Skip to content

Commit aa696f5

Browse files
author
hzq
committed
Confirm caller tool results before continuing the original run
Commit a returned batch, its audit, delivery cursor and tool option together. Verify the stored results before waking a parked run or delivering them to a native adapter. Replays retain the first outputs, and waiting on SQLite no longer stalls unrelated requests.
1 parent 6535116 commit aa696f5

31 files changed

Lines changed: 2003 additions & 316 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+
- Caller-tool continuations now commit a result batch, its audits, delivery cursor and tool option together. Losing the SQLite acknowledgement no longer strands the last batch; rejected or replayed returns cannot change an existing run's tool choice.
78
- Manual approvals and denials now confirm both the decision and its audit event before notifying waiters. Losing a SQLite acknowledgement no longer strands an already approved run or prompts the operator to vote again. Waiting for the writer does not block unrelated requests.
89
- An approved tool no longer stalls until timeout if SQLite commits its return to the queue but loses the acknowledgement. The gateway confirms the original wake before running the tool, without requesting approval again.
910
- Queued and readmitted runs now confirm the stored start event before dispatch. Waiting for SQLite no longer blocks the gateway or prevents cancelling an attached start.

‎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+
- 调用方工具回传的整批结果、审计事件、输出位置和工具选项现在一起提交。最后一批结果丢失提交回执也能继续原任务;被拒绝或重复的回传不会改变原运行的工具选择。
78
- 人工批准或拒绝后,网关核对决定和对应的审计事件再通知等待者。即使 SQLite 已提交但回执丢失,已批准的任务也能继续,不需要重新审批;等待写锁不会阻塞其他请求。
89
- 工具获批后,如果 SQLite 已将任务放回队列但提交回执丢失,网关会核对原记录并继续执行,不再卡到超时,也不要求重新审批。
910
- 排队运行首次启动或重新入场时,确认启动事件已落盘才派发;等 SQLite 写锁不会阻塞网关,也不会妨碍取消正在等锁的任务。

‎docs/harness.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ Key points:
160160
- Only the **consecutive** `role: "tool"` messages at the **end** of `messages` count as the results returned this time; earlier history is flattened into text as before.
161161
- The continuation credential is the `tool_call_id`. The gateway requires that it belong to the same owner and the same data partition (or an owner-level visible key), that the key have the `invoke` scope on the agent, and that all of them belong to the same run; if any condition fails (unknown, expired, belongs to someone else), the request is treated as new, the original run is not affected, and it is not revealed whether the ID exists.
162162
- Returning the same batch of results twice (a network retry) does not overwrite results already written; it attaches to the same run.
163+
- Only a valid return with new results can change the run to `tool_choice: "none"`. A bad batch or read-only replay leaves the option and output position unchanged. If storage cannot confirm a return, inspect the original run ID rather than executing the caller tools again.
163164
- Streaming (`stream: true`): when the run parks, the frames are sent in this order: the role frame (with `content: null`, if one has not been sent before), one `tool_calls` delta frame per call (`index` starting at 0), the closing frame with `finish_reason: "tool_calls"`, then (if `include_usage` was requested) the usage frame and `[DONE]`. After continuation, the stream starts from where the last one ended and does not replay earlier text.
164165
- When the arguments the model produces do not match the caller's schema, the call is not handed to the caller. Instead `{"error":"invalid_arguments","detail":...}` is returned to the model as the tool result so that it can fix the call and try again. This differs from argument errors of published tools (`invalid_tool_arguments`, where the run fails outright): the caller's schema is not under the publisher's control.
165166
- Names: must match `^[a-zA-Z0-9_-]{1,64}$`. The internal alias replaces `-` with `_` and prepends `t_` when the first character is not a letter; the original name is always used externally. A conflict with a published tool, workflow, delegate, `execute_graph`, or another caller tool returns `client_tool_conflict`; more than 100 published tools plus caller tools returns `client_tools_too_many`; a schema that cannot be compiled returns `invalid_client_tool`. All of these are checked before any execution. Caller tools cannot appear in `execute_graph` or in workflows.

‎docs/stability.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,16 @@ continues without another vote. A proven rollback leaves the action pending; the
341341
does not cast a vote in the background. New manual decisions also verify their audit
342342
before use after a restart; legacy decisions without a receipt retain their existing behavior.
343343

344+
A caller-tool return is a separate transaction: it saves all new outputs, their
345+
`approval.resolved` events, the delivery cursor and any requested tool disablement
346+
together. A replay attaches to the original run without overwriting accepted bytes.
347+
On a lost acknowledgement, the gateway checks the original batch before waking a
348+
parked run or delivering results to a live native adapter. While inconclusive, the
349+
API returns `effect_outcome_unknown` with the run ID; the inspector shows
350+
`caller_results_confirmed: false`. A proven rollback permits resending the existing
351+
outputs, not re-executing the caller's tools. This is a guarantee about gateway
352+
storage and delivery, not about how often an external caller performs its own work.
353+
344354
Kernel model turns use the same writer queue. Before sending, the gateway records the
345355
attempt and verifies that the durable run and the request handed to the worker still
346356
match. Cancellation while waiting prevents that send. Once a valid answer is ready

‎docs/zh-CN/harness.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ Responses(`/v1/compat/responses`)与 Gemini(`tools[].functionDeclarations`
160160
- 只有 `messages` **末尾连续的** `role: "tool"` 消息算本次回传的结果;更早的历史照旧压平成文本。
161161
- 续接凭据就是 `tool_call_id`。网关要求它属于同一 owner、同一数据分区(或 owner 级可见的密钥)、对该智能体有 `invoke` 权限,且全部属于同一个运行;任何一条不满足(不认识、过期、属于别人)都当作新请求处理,不影响原运行,也不会透露这个 ID 是否存在。
162162
- 同一批结果重复回传(网络重试)不会改写已写入的结果,会接到同一个运行上。
163+
- 只有包含新结果的有效回传才能把原运行改为 `tool_choice: "none"`。无效批次和只读重试都不会更改选项或输出位置。存储暂时不能确认回传时,请按原运行 ID 检查,不要重新执行调用方工具。
163164
- 流式(`stream: true`):停车时依次发出角色帧(之前没发过时,`content: null`)、每个调用一帧 `tool_calls` 增量(`index` 从 0 起)、`finish_reason: "tool_calls"` 收尾帧、(请求了 `include_usage` 时)用量帧与 `[DONE]`;续接后的流从上次之后开始,不重放之前的文本。
164165
- 模型给出的参数不符合调用方的 schema 时,这次调用不会交给调用方,而是把 `{"error":"invalid_arguments","detail":...}` 作为工具结果交回模型,让它改了再调。这与已发布工具的参数错误(`invalid_tool_arguments`,运行直接失败)不同:调用方的 schema 不受发布者控制。
165166
- 名字:须匹配 `^[a-zA-Z0-9_-]{1,64}$`;内部别名把 `-` 换成 `_`,首字符不是字母时加 `t_`,对外一律用原名。与已发布的工具、工作流、委托、`execute_graph` 或另一个调用方工具冲突报 `client_tool_conflict`;已发布工具加调用方工具超过 100 个报 `client_tools_too_many`;schema 无法编译报 `invalid_client_tool`。这些都在任何执行之前检查。调用方工具不能出现在 `execute_graph` 与工作流里。

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,8 @@ worker 已产出的文件共用同一个写锁探测器,按 owner 轮流取锁
145145

146146
人工批准或拒绝时,原待办和 `approval.resolved` 审计事件一起提交。等写锁期间会重新检查请求权限、连接、有效期和待办归属。若回执丢失,网关核对待办、运行、摘要和对应的审计事件后才通知等待者。尚不能确认时,响应接口返回 `effect_outcome_unknown`,运行检查接口标记 `approval_decision_confirmed: false`。证实已经提交就继续执行,不要求再批一次;证实回滚则待办仍可处理,网关不会在后台代为批准。重启后,新格式的人工决定在使用前也核对审计;没有回执的旧记录按原规则兼容。
147147

148+
调用方工具回传是另一笔事务:全部新结果、对应的 `approval.resolved` 审计事件、输出位置和本次请求禁用工具的选项一起保存。重复回传只接回原运行,不覆盖原结果。丢失提交回执后,网关先核实原批次,再唤醒停车任务或把结果交给仍在等待的原生适配器。查不清时返回 `effect_outcome_unknown` 和运行 ID,运行检查接口标记 `caller_results_confirmed: false`。证实回滚后可重发已有结果,无需重做调用方工具;网关不保证外部调用方自己的执行次数。
149+
148150
流式文本单独提交。创建输出消息和追加文本增量时异步等写锁;确认事件 ID、顺序和内容落盘后才通知订阅者。丢回执只读回核对,证明已回滚才重写原批次,不会重调模型。文本追加或单独结束输出消息的提交无法确认时,响应返回 `effect_outcome_unknown`,运行检查接口标记 `output_checkpoint_confirmed: false`。取消后不再接收新文本,终态等待已接收的文本处理完毕;进程崩溃仍可能丢掉尚未落盘的文本。
149151

150152
等锁的文本计入运行原有的输出上限;大批增量每写至多 1,024 条就让出事件循环,不合并对外事件。进度、审批和调用方工具帧等待前面的文本,单个运行最多缓冲 64 帧,JSON 合计不超过 1 MiB。超出任一限制以 `node_backpressure` 停止生产者;已经登记、正在等人决定的审批不占这个预算。

‎src/gateway/bridge.ts‎

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ import { Fault } from '../core/util.js';
77
import { nativeStepId } from '../kernel/native-turn.js';
88
import type { Invocation } from '../kernel/invocation.js';
99
import type { Kernel } from '../kernel/kernel.js';
10+
import { isUnknownCallerTarget } from '../kernel/client-tools.js';
11+
import type { UploadGuard } from '../store/file-writer.js';
1012
import type { Store } from '../store/store.js';
11-
import { pendingApprovals } from '../store/approval-rows.js';
13+
import { pendingApprovals, pendingWaiter } from '../store/approval-rows.js';
1214
import { chatObject, chatUsage, claudeMessageObject, responseObject } from './protocol.js';
1315
import { claudeDelta, claudeDeltaUsage, claudeMessage } from './claude.js';
1416
import { geminiResponseObject } from './uap.js';
@@ -55,15 +57,22 @@ export async function waitParkedOrTerminal(
5557
signal.addEventListener('abort', stop, { once: true });
5658
let onEvent: ((e: { type: string }) => void) | undefined;
5759
try {
58-
const parked = new Promise<Run>((resolve) => {
60+
const parked = new Promise<Run>((resolve, reject) => {
5961
const check = () => {
60-
const run = store.run(runId);
61-
if (
62-
terminal(run.status) ||
63-
(run.status === 'requires_action' && run.checkpoint.suspension?.kind === 'approval') ||
64-
awaitingCallerInProcess(store, run)
65-
)
66-
resolve(run);
62+
try {
63+
store.terminalPublications.requireConfirmed(runId);
64+
const run = store.run(runId);
65+
if (
66+
terminal(run.status) ||
67+
(run.status === 'requires_action' &&
68+
run.checkpoint.suspension?.kind === 'approval' &&
69+
pendingWaiter(store, runId)) ||
70+
awaitingCallerInProcess(store, run)
71+
)
72+
resolve(run);
73+
} catch (error) {
74+
reject(error);
75+
}
6776
};
6877
onEvent = (e) => {
6978
if (handOffEvent(e.type)) check();
@@ -174,16 +183,18 @@ export function resumeBridged(
174183
store: Store,
175184
principal: Principal,
176185
invocation: Invocation,
177-
): { run: Run; cursor: number } | undefined {
186+
grant?: UploadGuard,
187+
) {
178188
const results = invocation.client_results;
179189
if (!results?.length) return undefined;
180190
let prior: Run | undefined;
181191
try {
182192
const action = store.getApproval(results[0]!.call_id, principal.owner);
183193
prior = store.run(action.runId, principal.owner, visibleSubject(principal));
184194
kernel.authorize(principal, prior.agentId, 'invoke');
185-
} catch {
186-
return undefined;
195+
} catch (error) {
196+
if (isUnknownCallerTarget(error)) return undefined;
197+
throw error;
187198
}
188199
if (prior.metadata['oaa.tool_boundary']) {
189200
const boundary = invocation.metadata['oaa.tool_boundary'];
@@ -204,19 +215,13 @@ export function resumeBridged(
204215
409,
205216
);
206217
}
207-
if (invocation.previous_response_id) {
208-
try {
209-
const runId = store.getApproval(results[0]!.call_id, principal.owner).runId;
210-
if (runId !== invocation.previous_response_id) return undefined;
211-
} catch {
212-
return undefined;
213-
}
214-
}
215-
if (invocation.tool_choice?.mode === 'none' && prior.checkpoint.toolChoice?.mode !== 'none') {
216-
prior.checkpoint.toolChoice = { mode: 'none' };
217-
store.save(prior);
218-
}
219-
return kernel.resolveClientTools(principal, results);
218+
if (invocation.previous_response_id && prior.id !== invocation.previous_response_id)
219+
return undefined;
220+
return kernel.resolveClientTools(principal, results, {
221+
prior,
222+
disableTools: invocation.tool_choice?.mode === 'none',
223+
grant,
224+
});
220225
}
221226

222227
/** 停车的调用方调用(参数同时给 JSON 字符串与对象)。 */

‎src/gateway/protocol-routes.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export function registerProtocolRoutes(app: FastifyInstance, deps: ProtocolRoute
6868
// 流式请求先占事件流名额,超限时不创建运行。
6969
const release = invocation.stream ? streamSlots(store).acquire(req.principal) : undefined;
7070
let run: Run;
71-
let resumed: ReturnType<typeof resumeBridged>;
71+
let resumed: Awaited<ReturnType<typeof resumeBridged>>;
7272
try {
7373
invocation = applyConnectionDefaults(req, store, invocation);
7474
const publication = store.bundle(
@@ -92,7 +92,16 @@ export function registerProtocolRoutes(app: FastifyInstance, deps: ProtocolRoute
9292
requestGrant(auth, req, reply),
9393
deps.coldReads,
9494
);
95-
resumed = resumeBridged(kernel, store, req.principal, invocation);
95+
if (invocation.client_results?.length) {
96+
const attempt = resumeBridged(
97+
kernel,
98+
store,
99+
req.principal,
100+
invocation,
101+
requestGrant(auth, req, reply),
102+
);
103+
resumed = attempt instanceof Promise ? await attempt : attempt;
104+
}
96105
const trace = parseTraceHeaders(req.headers as Record<string, unknown>);
97106
run =
98107
resumed?.run ??

‎src/gateway/run-routes.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { cursor, streamEvents } from './compat-stream.js';
1010
import { outputPage } from '../store/inspection.js';
1111
import { observeAuthorization, revalidateObservation } from './streams.js';
1212
import { requestGrant } from './request-grant.js';
13+
import { isActionBoundary } from '../store/terminal-publication.js';
1314
import { etagMatches } from './overview.js';
1415
import { streamSlots } from './stream-slots.js';
1516
import { buildTimeline } from './timeline.js';
@@ -18,6 +19,7 @@ import { runImageSummary } from './image-summary.js';
1819
import { Fault, faultOf } from '../core/util.js';
1920

2021
const confirmationFlag = {
22+
caller: 'caller_results_confirmed',
2123
decision: 'approval_decision_confirmed',
2224
wake: 'approval_wake_confirmed',
2325
start: 'run_start_confirmed',
@@ -151,7 +153,7 @@ export function registerRunRoutes(app: FastifyInstance, context: RunRouteContext
151153
app.get('/v1/runs/:id/actions', async (req) => {
152154
const run = ownedIdentity(req);
153155
const issue = store.terminalPublications.issue(run.id);
154-
if (issue?.boundary === 'decision') throw issue;
156+
if (issue && isActionBoundary(issue.boundary)) throw issue;
155157
const q = actionsQuery.parse(req.query);
156158
return store.actionPage(run.id, run.owner, q.offset, q.limit);
157159
});
@@ -160,7 +162,7 @@ export function registerRunRoutes(app: FastifyInstance, context: RunRouteContext
160162
const action = store.getApproval((req.params as { action: string }).action, run.owner);
161163
if (action.runId !== run.id) throw new Fault('approval_not_found', 'Approval not found.', 404);
162164
const issue = store.terminalPublications.issue(run.id);
163-
if (issue?.boundary === 'decision') throw issue;
165+
if (issue && isActionBoundary(issue.boundary)) throw issue;
164166
reply.header('Content-Disposition', 'attachment; filename="approval.json"');
165167
return reply.type('application/json').send(JSON.stringify(action));
166168
});

‎src/kernel/admission.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { AgentBundle, Run } from '../core/contracts.js';
66
import { Fault } from '../core/util.js';
77
import type { Store } from '../store/store.js';
88
import { WebhookCaptureUnavailable, isWriteUnavailable } from '../store/checkpoint.js';
9-
import { PendingTerminalCommit } from '../store/terminal-publication.js';
9+
import { PendingTerminalCommit, isActionBoundary } from '../store/terminal-publication.js';
1010
import { parkedDecisions } from '../store/parked-decisions.js';
1111
import { ParkedWakes } from './parked-wakes.js';
1212
import type { NodeHub } from '../fabric/network.js';
@@ -310,7 +310,7 @@ export class Admission {
310310
);
311311
}
312312
scheduleParked(runId: string): boolean {
313-
if (this.rt.store.approvalDecisions.has(runId)) return false;
313+
if (this.rt.store.actionWrites.has(runId)) return false;
314314
if (this.rt.closing() || this.tasks.has(runId) || !this.parked.has(runId)) return true;
315315
if (this.retrying.get(runId) || this.wakes.has(runId)) return false;
316316
try {
@@ -325,7 +325,7 @@ export class Admission {
325325
void error.settlement.then((state) => {
326326
this.retrying.delete(runId);
327327
if (
328-
(state === 'absent' || (state === 'committed' && error.boundary === 'decision')) &&
328+
(state === 'absent' || (state === 'committed' && isActionBoundary(error.boundary))) &&
329329
!this.rt.closing() &&
330330
this.parked.has(runId)
331331
) {

0 commit comments

Comments
 (0)