Skip to content

Commit 40692e2

Browse files
author
hzq
committed
Keep A2A receipts recoverable after output write failures
1 parent 87963fe commit 40692e2

8 files changed

Lines changed: 277 additions & 26 deletions

File tree

‎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+
- A saved A2A task receipt remains usable for readback after a local output write failure. A task already known to be terminal is not cancelled again.
78
- 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.
89
- 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.
910
- 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.

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

‎docs/architecture.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,8 @@ If a new A2A task was acknowledged by a matching JSON-RPC response and the strea
228228

229229
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.
230230

231+
If output publication fails while a side-effecting A2A step with a saved receipt is still unresolved, the run stays interrupted and the step keeps the local error. The receipt can still be queried; a remote terminal result does not make local publication successful. The A2A worker skips cancellation when it already received a matching terminal task state, while live tasks remain eligible for normal cancellation.
232+
231233
ACP approval is an application-layer decision, not an OS sandbox. A binary approval can authorize only one unambiguous `allow_once` option; multiple choices are cancelled, not answered on the user's behalf. Native/ACP launches exclude `OAA_*` environment variables. Environment allowlisting and OS-level containment are separate controls; the default inherit mode passes other variables.
232234

233235
**Model drivers do not depend on vendor SDKs.** The OpenAI Responses / Chat Completions driver (`OpenAIModel`) sends requests directly with `fetch` and parses streams with this project's SSE reader, consistent with the Anthropic and Gemini drivers: no automatic retries, no following redirects, the request body contains only the fields written explicitly in code, and upstream error bodies are not passed through to the caller. The connect timeout covers only up to receiving the response headers (consistent with the earlier SDK behavior), so a long answer that has already started is not cut off by the timeout. When replaying the previous round's Responses items it strips output-only fields itself, and still reports `invalid_provider_state` for item types it does not recognize. The `openai` package is used only in tests to verify the compatibility endpoints and is in `devDependencies`; `eventsource-parser` is no longer referenced by this project's code and has been removed from the direct dependencies (it still exists as an indirect dependency of the MCP SDK).

‎docs/zh-CN/architecture.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,8 @@ JSON-RPC 回包先核对本次请求 ID,再允许交付文本或接受终态
228228

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

231+
有副作用的 A2A 步骤已保存回执,但本地输出写入失败时,运行保持中断,步骤保留本地错误。回执仍可查询;远端终态不会被当作本地交付成功。执行节点已经收到匹配的终态时不再取消对端任务,尚未结束的任务仍可按正常流程取消。
232+
231233
ACP 审批是应用层决策,不等于操作系统沙箱。二选一的批准仅能授予唯一、无歧义的 `allow_once`;遇到多个选项会取消,不代替用户选答案。原生与 ACP 子进程不会继承 `OAA_*` 环境变量;环境变量白名单和操作系统隔离是另外两项控制。默认继承模式仍会传递其他变量。
232234

233235
**模型驱动不依赖厂商 SDK**。OpenAI Responses / Chat Completions 驱动(`OpenAIModel`)直接用 `fetch` 发请求、用本项目的 SSE 读取器解析流,与 Anthropic、Gemini 驱动一致:不自动重试、不跟随重定向,请求体里只有代码里明确写出的字段,上游错误正文不会透传给调用方。连接超时只覆盖到收到响应头为止(与此前 SDK 的行为一致),已经开始的长回答不会被超时掐断。重放上一轮 Responses 条目时自行去掉输出专有字段,遇到不认识的条目类型仍报 `invalid_provider_state`。`openai` 包只在测试里用来验证兼容入口,在 `devDependencies`;`eventsource-parser` 不再被本项目代码引用,已从直接依赖里移除(它仍作为 MCP SDK 的间接依赖存在)。

‎src/engines/a2a.ts‎

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,8 @@ export type A2AAdapterConfig = Extract<WorkerConfig['adapters'][string], { trans
4141
export type FetchLike = typeof fetch;
4242
const MAX_TEXT = AGENT_IO_LIMITS.textChars;
4343
const MAX_STREAM_BYTES = AGENT_IO_LIMITS.frameBytes;
44-
/** Terminal and interrupted states: the turn ends (and a 1.0 stream closes) on any of them. */
45-
const TERMINAL = new Set([
46-
'completed',
47-
'failed',
48-
'rejected',
49-
'canceled',
50-
'input-required',
51-
'auth-required',
52-
]);
44+
const FINISHED_TASK = new Set(['completed', 'failed', 'rejected', 'canceled']);
45+
const TURN_END = new Set([...FINISHED_TASK, 'input-required', 'auth-required']);
5346

5447
function headers(
5548
adapter: A2AAdapterConfig,
@@ -211,6 +204,7 @@ export async function runA2A(
211204
let acknowledged: A2ATaskReceipt | undefined;
212205
let sendAttempted = false;
213206
let outcomeConfirmed = false;
207+
let peerFinished = false;
214208
const prompt = agent.instructions ? `${agent.instructions}\n\n${input}` : input;
215209
const controller = new AbortController();
216210
const rpc = rpcFor(peer, fetchImpl);
@@ -228,11 +222,9 @@ export async function runA2A(
228222
text += delta;
229223
await emit({ type: 'text', data: { delta } });
230224
};
231-
const status = async (raw: unknown, final: boolean) => {
232-
const value = record(raw);
233-
const current = stateName(value.state) ?? 'unknown';
234-
const said = partsText(record(value.message).parts);
235-
if (TERMINAL.has(current)) {
225+
const status = async (value: Json | undefined, current: string, final: boolean) => {
226+
const said = partsText(record(value?.message).parts);
227+
if (TURN_END.has(current)) {
236228
if (!observedTask)
237229
throw invalidA2AReply('A2A terminal status has no confirmed task identity.');
238230
finalState = current;
@@ -263,6 +255,8 @@ export async function runA2A(
263255
const value = event.value;
264256
const seenId = exactA2APeerId(event.type === 'task' ? value.id : value.taskId);
265257
const seenContext = exactA2APeerId(value.contextId);
258+
if (event.type === 'task' && !seenId)
259+
throw invalidA2AReply('A2A task reply did not identify its task.');
266260
if (
267261
(taskId && seenId && taskId !== seenId) ||
268262
(observedContext && seenContext && observedContext !== seenContext)
@@ -272,9 +266,14 @@ export async function runA2A(
272266
}
273267
observedContext ??= seenContext;
274268
contextId = observedContext ?? contextId;
269+
const taskStatus =
270+
event.type === 'task' || event.type === 'status' ? record(value.status) : undefined;
271+
const current = stateName(taskStatus?.state) ?? 'unknown';
275272
if (event.type !== 'message') {
276273
observedTask ??= seenId;
277274
taskId ??= seenId;
275+
// Remember the peer's terminal state before a local receipt/output callback can abort.
276+
if (observedTask && FINISHED_TASK.has(current)) peerFinished = true;
278277
if (remember && !continuingTask && !acknowledged && seenId && seenContext) {
279278
const proof = a2aTaskReceipt.safeParse({
280279
adapter: name,
@@ -295,34 +294,34 @@ export async function runA2A(
295294
await append(partsText(value.parts));
296295
finalState ??= 'completed';
297296
} else if (event.type === 'task') {
298-
if (!seenId) throw invalidA2AReply('A2A task reply did not identify its task.');
299297
if (!text)
300298
for (const artifact of Array.isArray(value.artifacts) ? value.artifacts : [])
301299
await append(partsText(record(artifact).parts));
302-
await status(value.status, false);
300+
await status(taskStatus, current, false);
303301
} else if (event.type === 'artifact') {
304302
if (!observedTask) throw invalidA2AReply('A2A artifact has no confirmed task identity.');
305303
await append(partsText(record(value.artifact).parts));
306304
} else {
307-
await status(value.status, event.final);
305+
await status(taskStatus, current, event.final);
308306
}
309307
};
310308
const readBack = async (): Promise<boolean> => {
311309
// An inherited task ID cannot by itself prove delivery of this continuation.
312310
if (continuingTask || !observedTask) return false;
313311
const recovered = await taskSnapshot(rpc, version, observedTask, contextId, controller.signal);
312+
const taskStatus = record(recovered?.status);
313+
const current = stateName(taskStatus.state);
314+
if (current && FINISHED_TASK.has(current)) peerFinished = true;
314315
checkAbort(signal);
315-
if (!recovered) return false;
316-
const current = stateName(record(recovered.status).state);
317-
if (!current || !TERMINAL.has(current)) return false;
316+
if (!recovered || !current || !TURN_END.has(current)) return false;
318317
const completeText = snapshotText(recovered);
319318
if (current === 'completed' || current === 'input-required' || current === 'auth-required') {
320319
// Already delivered bytes are immutable. Never concatenate an unrelated or reordered snapshot.
321320
if (!completeText.startsWith(text) || completeText.length > MAX_TEXT) return false;
322321
await append(completeText.slice(text.length));
323322
}
324323
contextId = exactA2APeerId(recovered.contextId) ?? contextId;
325-
await status(recovered.status, true);
324+
await status(taskStatus, current, true);
326325
return true;
327326
};
328327
try {
@@ -411,7 +410,7 @@ export async function runA2A(
411410
}
412411
checkAbort(signal);
413412
// A stream marked final in a non-terminal state (or `unknown`) is not a completed turn.
414-
if ((!finalState || !TERMINAL.has(finalState)) && !(await readBack())) {
413+
if ((!finalState || !TURN_END.has(finalState)) && !(await readBack())) {
415414
checkAbort(signal);
416415
throw new Fault(
417416
'native_incomplete',
@@ -420,8 +419,10 @@ export async function runA2A(
420419
true,
421420
);
422421
}
423-
if ((finalState === 'input-required' || finalState === 'auth-required') && !text)
422+
if ((finalState === 'input-required' || finalState === 'auth-required') && !text) {
424423
await append(question);
424+
checkAbort(signal);
425+
}
425426
outcomeConfirmed = true;
426427
if (finalState === 'failed' || finalState === 'rejected')
427428
throw new Fault(
@@ -447,7 +448,7 @@ export async function runA2A(
447448
};
448449
} catch (error) {
449450
if (signal.aborted) {
450-
if (sendAttempted && taskId)
451+
if (sendAttempted && taskId && !peerFinished)
451452
await rpc(
452453
v1 ? 'CancelTask' : 'tasks/cancel',
453454
{ id: taskId },

‎src/kernel/execute.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { permits } from '../fabric/network.js';
1313
import { responseObject } from './response-object.js';
1414
import { ElapsedRunDeadline, Fault, checkAbort, faultOf, id } from '../core/util.js';
1515
import { isWriteUnavailable, isCheckpointUnavailable } from '../store/checkpoint.js';
16+
import { hasA2ATaskReceipt } from '../store/a2a-task-receipts.js';
1617
import { commitTerminal } from './terminal-checkpoint.js';
1718
import { UnconfirmedRunCommit } from '../store/run-creation.js';
1819
import { hasUnconfirmedSteps, UnconfirmedStepCommit } from '../store/step-commit.js';
@@ -450,9 +451,11 @@ export async function execute(rt: KernelRuntime, run: Run, bundle: AgentBundle):
450451
!!unconfirmed ||
451452
!!fault.uncertain ||
452453
(fault.code === 'persistence_failed' &&
453-
(sawStorageOutage || isWriteUnavailable(error)) &&
454454
step?.status === 'running' &&
455-
step.effect !== 'read');
455+
step.effect !== 'read' &&
456+
(sawStorageOutage ||
457+
isWriteUnavailable(error) ||
458+
(!!eventError && step.runId === run.id && hasA2ATaskReceipt(rt.store, step))));
456459
const classification = classifyFailure({
457460
...failure,
458461
fault: { code: fault.code, message: fault.message, uncertain },

‎src/store/a2a-task-receipts.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,17 @@ export function recordA2ATaskReceipt(
103103
});
104104
}
105105

106+
export function hasA2ATaskReceipt(store: Pick<Storage, 'prepare'>, step: ExecutionStep): boolean {
107+
return (
108+
step.callId === 'native' &&
109+
step.name.startsWith('adapter/') &&
110+
Number.isSafeInteger(step.startedAt) &&
111+
!!store
112+
.prepare('SELECT 1 FROM a2a_task_receipts WHERE step_id=? AND valid=1 AND started_at=?')
113+
.get(step.id, step.startedAt!)
114+
);
115+
}
116+
106117
export function recoverableA2ATask(store: Pick<Storage, 'prepare'>, runId: string, stepId: string) {
107118
const unavailable = () =>
108119
new Fault(

0 commit comments

Comments
 (0)