Skip to content

Commit 3af12d0

Browse files
author
hzq
committed
Reject impossible tool plans before dispatch
Preserve completed model usage and output without handing out tools whose empty replies cannot fit. Continue accepting the results of calls already issued. Improvement-Round: 2/10 after v0.0.73
1 parent 8a2b1c2 commit 3af12d0

8 files changed

Lines changed: 716 additions & 59 deletions

File tree

‎docs/harness.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ Key points:
163163
- For kernel agents, each result written to the model conversation is limited to **1 MiB of encoded JSON (UTF-8)**. An API may impose a smaller input limit. Caller text that parses as an object or array is measured after normalization; other text is returned unquoted but measured with JSON quotes and escapes. An oversized result fails the run with `payload_too_large` before another model call. None of that batch's tool replies are appended to the conversation; completed tool steps remain recorded.
164164
- The kernel also checks the batch against the **2,000,000-byte conversation limit** before saving it. This includes the existing history, escaped replies, and the pinned system prompt or its mandatory prefix. A batch that cannot fit is not appended. When available tools or files change the final prompt, the exact request is checked again before dispatch.
165165
- The final check includes the actual system prompt for that route. If the request does not fit, already completed steps remain recorded, but no new model attempt is saved or sent. At handoff the worker request must still match the admitted conversation; the byte count and digest used for that check are not recorded in public run events.
166+
- A newly returned tool plan must also leave room for the assistant message and **one empty reply per call**, including the call IDs. If even this minimum cannot fit, the kernel does not run a tool, ask for approval, or hand the call to a client. The model turn, its reported usage and already produced output are retained; its rejected arguments are not saved as pending work. A plan that fits can still receive a larger result later. Already accepted calls, including those restored after an upgrade, follow the normal result and recovery paths. A final answer without tools needs no further turn.
166167
- 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.
167168
- 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.
168169
- 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.

‎docs/zh-CN/harness.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ Responses(`/v1/compat/responses`)与 Gemini(`tools[].functionDeclarations`
163163
- 对内核智能体,写回模型对话的每条工具结果最多为 **1 MiB 的 UTF-8 编码 JSON**,各协议入口可能还有更小的输入上限。调用方文本能解析成对象或数组时,按规范化后的大小计算;其他文本不加引号写回,但计量时包含 JSON 引号与转义。超限会在下一次模型调用前以 `payload_too_large` 终结运行。同批结果都不会追加到模型对话;已完成的工具步骤仍有记录,不会被撤销。
164164
- 保存整批回复前,内核还会检查 **2,000,000 字节的对话上限**,计入既有历史、转义后的回复,以及已固定的系统提示或其必含前缀。确定放不下就不追加。可用工具和文件可能改变最终提示,派发前仍按实际请求复核。
165165
- 最终检查计入本条路由实际使用的系统提示。如果放不下,已完成的工具步骤照常保留,但不会新增模型尝试记录,也不会派发。交给执行节点的对话仍须与已通过检查的对话相符;用于核对的字节数和摘要不会写入公开运行事件。
166+
- 模型新提出工具计划时,还必须放得下这条助手消息,以及**每个调用带原 ID 的一条空回复**。连这个下限都超出时,内核不会运行工具、发起审批或将调用交给客户端。已发生的模型轮次、已上报用量和已产生的输出仍保留;拒绝的参数不会存为待执行工作。计划放得下,不代表实际返回的大结果一定放得下。已经受理的调用(包括升级后恢复的调用)仍按原流程接收结果;不再调用工具的最终答案无需预留下一轮。
166167
- 只有包含新结果的有效回传才能把原运行改为 `tool_choice: "none"`。无效批次和只读重试都不会更改选项或输出位置。存储暂时不能确认回传时,请按原运行 ID 检查,不要重新执行调用方工具。
167168
- 流式(`stream: true`):停车时依次发出角色帧(之前没发过时,`content: null`)、每个调用一帧 `tool_calls` 增量(`index` 从 0 起)、`finish_reason: "tool_calls"` 收尾帧、(请求了 `include_usage` 时)用量帧与 `[DONE]`;续接后的流从上次之后开始,不重放之前的文本。
168169
- 模型给出的参数不符合调用方的 schema 时,这次调用不会交给调用方,而是把 `{"error":"invalid_arguments","detail":...}` 作为工具结果交回模型,让它改了再调。这与已发布工具的参数错误(`invalid_tool_arguments`,运行直接失败)不同:调用方的 schema 不受发布者控制。

‎src/kernel/execute.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { ElapsedRunDeadline, Fault, checkAbort, faultOf, id } from '../core/util
1515
import { isWriteUnavailable, isCheckpointUnavailable } from '../store/checkpoint.js';
1616
import { hasA2ATaskReceipt } from '../store/a2a-task-receipts.js';
1717
import { commitTerminal } from './terminal-checkpoint.js';
18+
import { RejectedToolPlan } from './model-context.js';
1819
import { UnconfirmedRunCommit } from '../store/run-creation.js';
1920
import { hasUnconfirmedSteps, UnconfirmedStepCommit } from '../store/step-commit.js';
2021
import { DispatchStateConflict, UnprovedDispatch } from '../store/step-preparation.js';
@@ -426,14 +427,19 @@ export async function execute(rt: KernelRuntime, run: Run, bundle: AgentBundle):
426427
return;
427428
if (modelPending) run.metadata['oaa.usage_complete'] = 'false';
428429
releaseCommitted = false;
430+
const rejected = error instanceof RejectedToolPlan && fault === error ? error : undefined;
431+
const closing = rt.closing();
432+
// Shutdown does not turn a definitive, undispatched plan rejection into replayable work.
429433
const failure = {
430-
closing: rt.closing(),
434+
closing: closing && !rejected,
431435
timedOut,
432-
aborted: controller.signal.aborted,
436+
aborted: controller.signal.aborted && !(closing && rejected),
433437
hadEventError: Boolean(eventError),
434438
};
435439
delete run.checkpoint.suspension;
436-
const finalEvents = stepIssue ? [] : await writer.finish('incomplete');
440+
const finalEvents = stepIssue
441+
? []
442+
: (rejected?.outputEvents ?? (await writer.finish('incomplete')));
437443
releaseCommitted = await commitTerminal(
438444
rt,
439445
run,

‎src/kernel/model-answer.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import type { ModelResult, Usage } from '../core/contracts.js';
2+
import { Fault, RunErrorFault } from '../core/util.js';
3+
import { validateProviderState } from '../providers/provider-state.js';
4+
import type { ModelContextWitness } from '../store/model-turns.js';
5+
import { prepareToolPlan, type ToolPlanMessage } from './model-context.js';
6+
7+
type Decision =
8+
| { kind: 'invalid'; fault: Fault }
9+
| { kind: 'refused'; fault: Fault }
10+
| { kind: 'accepted'; message: ToolPlanMessage };
11+
12+
/** Detach the plan while the returned model result is in hand, before output or checkpoint writes can wait. */
13+
export function captureModelAnswer(
14+
answer: ModelResult,
15+
admitted: ModelContextWitness,
16+
system: string,
17+
minimumSystem: () => string,
18+
): { text: string; calls: number; usage: Usage | null; decision: Decision } {
19+
if (!answer || typeof answer.text !== 'string' || !Array.isArray(answer.calls))
20+
throw new Fault('invalid_model_result', 'Worker returned an invalid model result.', 502);
21+
const { text, calls, providerState, finish } = answer;
22+
const facts = { text, calls: calls.length, usage: answer.usage ? { ...answer.usage } : null };
23+
const message: ToolPlanMessage = {
24+
role: 'assistant',
25+
content: text,
26+
tool_calls: calls,
27+
providerItems: providerState ? undefined : answer.providerItems,
28+
...(providerState ? { providerState } : {}),
29+
};
30+
let decision: Decision;
31+
if (finish === 'length') {
32+
decision = {
33+
kind: 'invalid',
34+
fault: new RunErrorFault('max_output_tokens', 'Model output was truncated.'),
35+
};
36+
} else if (
37+
calls.some(
38+
(c) => !c || typeof c.id !== 'string' || !c.id || typeof c.name !== 'string' || !c.name,
39+
) ||
40+
new Set(calls.map((c) => c.id)).size !== calls.length
41+
) {
42+
decision = {
43+
kind: 'invalid',
44+
fault: new Fault(
45+
'invalid_tool_calls',
46+
'Model returned duplicate or invalid tool call IDs.',
47+
502,
48+
),
49+
};
50+
} else if (calls.length) {
51+
try {
52+
decision = {
53+
kind: 'accepted',
54+
message: prepareToolPlan(
55+
admitted,
56+
system,
57+
providerState ? system : minimumSystem(),
58+
message,
59+
),
60+
};
61+
} catch (error) {
62+
if (
63+
!(error instanceof Fault) ||
64+
!['context_limit', 'invalid_tool_calls', 'invalid_model_result'].includes(error.code)
65+
)
66+
throw error;
67+
decision = { kind: 'refused', fault: error };
68+
}
69+
} else decision = { kind: 'accepted', message };
70+
// Keep invalid provider state ahead of output/accounting, as before. Validate accepted calls against their snapshot.
71+
if (providerState) {
72+
const view = decision.kind === 'accepted' ? decision.message : message;
73+
view.providerState = validateProviderState(view.providerState, {
74+
text,
75+
calls: view.tool_calls,
76+
});
77+
}
78+
return { ...facts, decision };
79+
}

‎src/kernel/model-context.ts‎

Lines changed: 83 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { types } from 'node:util';
22
import { createHash } from 'node:crypto';
3-
import type { AgentDefinition, Checkpoint, ModelMessage, Run } from '../core/contracts.js';
3+
import type {
4+
AgentDefinition,
5+
Checkpoint,
6+
ModelMessage,
7+
Run,
8+
ToolCall,
9+
} from '../core/contracts.js';
410
import {
511
JsonByteBudget,
612
chargeJson,
@@ -10,6 +16,7 @@ import {
1016
import { LIMITS } from '../core/limits.js';
1117
import { Fault, RunErrorFault, sha } from '../core/util.js';
1218
import type { ModelContextWitness } from '../store/model-turns.js';
19+
import type { EventInput } from '../store/output.js';
1320

1421
export const contextLimit = () =>
1522
new Fault(
@@ -145,6 +152,80 @@ export function baseModelInstructions(text: string): string {
145152
// The preceding comma and static fields, excluding the two separately charged quoted strings.
146153
const replyFrame = 1 + '{"role":"tool","tool_call_id":"","content":""}'.length - 4;
147154

155+
function chargeReply(bytes: JsonByteBudget, id: string, text: string): void {
156+
bytes.charge(replyFrame);
157+
chargeQuoted(id, bytes);
158+
chargeQuoted(text, bytes);
159+
}
160+
161+
export type ToolPlanMessage = ModelMessage & { role: 'assistant'; tool_calls: ToolCall[] };
162+
163+
/** The model returned, but no tool from its proposed batch was admitted. */
164+
export class RejectedToolPlan extends Fault {
165+
constructor(
166+
reason: Fault,
167+
readonly outputEvents: EventInput[],
168+
) {
169+
super(reason.code, reason.text ?? reason.message, reason.status);
170+
}
171+
}
172+
173+
/** A fresh plan needs the assistant message and one reply envelope per call, even for empty results. */
174+
export function prepareToolPlan(
175+
admitted: ModelContextWitness,
176+
sentSystem: string,
177+
minimumSystem: string,
178+
assistant: ToolPlanMessage,
179+
): ToolPlanMessage {
180+
const bytes = new JsonByteBudget(LIMITS.contextBytes, contextLimit);
181+
if (sentSystem === minimumSystem) {
182+
bytes.charge(admitted.bytes);
183+
} else {
184+
// Reuse the admitted history. Files and tool availability may change, so replace only the system string.
185+
const system = new JsonByteBudget(admitted.bytes, contextLimit);
186+
chargeQuoted(sentSystem, system);
187+
bytes.charge(system.remainingBytes);
188+
chargeQuoted(minimumSystem, bytes);
189+
}
190+
bytes.charge(1);
191+
const identities: Pick<ToolCall, 'id' | 'name'>[] = [];
192+
for (const { id, name } of assistant.tool_calls) {
193+
chargeReply(bytes, id, '');
194+
identities.push({ id, name });
195+
}
196+
const room = bytes.remainingBytes;
197+
let encoded: string;
198+
try {
199+
const wire = stringifyBounded(assistant, bytes);
200+
if (wire === undefined) throw new TypeError();
201+
encoded = wire;
202+
} catch (error) {
203+
if (error instanceof Fault && error.code === 'context_limit') throw error;
204+
throw new Fault('invalid_model_result', 'The model tool plan is not JSON.', 502);
205+
}
206+
const stable = JSON.parse(encoded) as ToolPlanMessage | null;
207+
if (
208+
stable?.role !== 'assistant' ||
209+
stable.content !== assistant.content ||
210+
Boolean(stable.providerState) !== Boolean(assistant.providerState) ||
211+
!Array.isArray(stable.tool_calls) ||
212+
stable.tool_calls.length !== identities.length ||
213+
!stable.tool_calls.every(
214+
(c, i) => c?.id === identities[i]!.id && c?.name === identities[i]!.name,
215+
)
216+
)
217+
throw new Fault(
218+
'invalid_tool_calls',
219+
'The model tool plan changed identity while being encoded.',
220+
502,
221+
);
222+
// Parsing raw JSON numbers can expand their next wire representation. Tiny native JSON snapshots
223+
// fit even with that expansion; otherwise measure the detached value, not the producer's hooks again.
224+
if (encoded.length * 32 > room || 'toJSON' in Object.prototype || 'toJSON' in Array.prototype)
225+
chargeJson(stable, new JsonByteBudget(room, contextLimit));
226+
return stable;
227+
}
228+
148229
export function toolReplyContext(
149230
checkpoint: Pick<Checkpoint, 'messages' | 'modelInstructions'>,
150231
instructions: string,
@@ -154,9 +235,5 @@ export function toolReplyContext(
154235
// Placement and files can change between turns. Only the pinned prompt or its mandatory prefix is known.
155236
const content = checkpoint.modelInstructions ?? baseModelInstructions(instructions);
156237
chargeJson([{ role: 'system', content }, ...checkpoint.messages], bytes);
157-
return (id, text) => {
158-
bytes.charge(replyFrame);
159-
chargeQuoted(id, bytes);
160-
chargeQuoted(text, bytes);
161-
};
238+
return (id, text) => chargeReply(bytes, id, text);
162239
}

‎src/kernel/model-turn.ts‎

Lines changed: 45 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,18 @@ import type {
1111
Work,
1212
} from '../core/contracts.js';
1313
import { bindModelRequest } from './model-request.js';
14-
import { baseModelInstructions, modelContextWitness, modelTurnLimit } from './model-context.js';
14+
import {
15+
baseModelInstructions,
16+
RejectedToolPlan,
17+
modelContextWitness,
18+
modelTurnLimit,
19+
} from './model-context.js';
1520
import type { NodeHub } from '../fabric/network.js';
1621
import { asRoutingStrategy } from './routing.js';
17-
import { Fault, RunErrorFault, checkAbort, faultOf, id } from '../core/util.js';
22+
import { Fault, checkAbort, faultOf, id } from '../core/util.js';
1823
import type { ModelPermit } from '../store/model-turns.js';
1924
import type { EventInput } from '../store/output.js';
20-
import { validateProviderState } from '../providers/provider-state.js';
25+
import { captureModelAnswer } from './model-answer.js';
2126
import { addUsage } from './run-state.js';
2227
import { outputTokenCap } from './invocation.js';
2328
import { LIMITS } from '../core/limits.js';
@@ -116,7 +121,8 @@ export async function runModelTurn(
116121
let mark: ModelMark | undefined;
117122
let permit: ModelPermit;
118123
let routeEvent: EventInput | undefined;
119-
let requestInstructions: string | undefined;
124+
let requestInstructions: string;
125+
let pinnedAtHandoff: boolean;
120126
let work: Awaited<ReturnType<NodeHub['execute']>>;
121127
for (let routeAttempt = 0; ; routeAttempt++) {
122128
const availability = rt.hub.availability(
@@ -188,6 +194,7 @@ export async function runModelTurn(
188194
mark = run.checkpoint.marks!.at(-1)!;
189195
// Waiting for the writer can replace the live checkpoint. The handoff must verify this view.
190196
requestInstructions = currentInstructions();
197+
pinnedAtHandoff = run.checkpoint.modelInstructions !== undefined;
191198
const messages = [
192199
{
193200
role: 'system' as const,
@@ -352,13 +359,14 @@ export async function runModelTurn(
352359
};
353360
}
354361
}
355-
const answer = work.result as ModelResult;
356362
checkAbort(signal);
357-
if (!answer || typeof answer.text !== 'string' || !Array.isArray(answer.calls))
358-
throw new Fault('invalid_model_result', 'Worker returned an invalid model result.', 502);
359-
const providerState = answer.providerState
360-
? validateProviderState(answer.providerState, { text: answer.text, calls: answer.calls })
361-
: undefined;
363+
const answer = captureModelAnswer(
364+
work.result as ModelResult,
365+
permit.admittedContext,
366+
requestInstructions,
367+
() =>
368+
pinnedAtHandoff ? requestInstructions : baseModelInstructions(bundle.agent.instructions),
369+
);
362370
// 流式路径攒下的增量按流式的错误语义落盘;整段补发的文本保持原有的直接报错语义。
363371
if (!session.writer.open && answer.text) {
364372
session.writer.emit(answer.text);
@@ -371,48 +379,38 @@ export async function runModelTurn(
371379
else view.metadata['oaa.usage_complete'] = 'false';
372380
view.checkpoint.turn++;
373381
};
374-
if (
375-
answer.finish === 'length' ||
376-
new Set(answer.calls.map((c) => c.id)).size !== answer.calls.length ||
377-
answer.calls.some((c) => !c.id || !c.name)
378-
) {
382+
const decision = answer.decision;
383+
if (decision.kind === 'invalid') {
379384
// The rejected answer still consumed this turn and its reported tokens.
380385
account(run);
381386
session.pending(false);
382-
if (answer.finish === 'length')
383-
throw new RunErrorFault('max_output_tokens', 'Model output was truncated.');
384-
throw new Fault(
385-
'invalid_tool_calls',
386-
'Model returned duplicate or invalid tool call IDs.',
387-
502,
388-
);
387+
throw decision.fault;
389388
}
390-
await rt.store.modelTurns.finish(
391-
run,
392-
permit,
393-
await session.writer.finish('completed'),
394-
(next) => {
395-
account(next);
396-
next.checkpoint.messages.push({
397-
role: 'assistant',
398-
content: answer.text,
399-
tool_calls: answer.calls,
400-
providerItems: providerState ? undefined : answer.providerItems,
401-
...(providerState ? { providerState } : {}),
402-
});
403-
if (providerState) next.checkpoint.modelInstructions ??= requestInstructions;
404-
next.checkpoint.pending = answer.calls;
405-
next.checkpoint.phase = answer.calls.length ? 'tools' : 'done';
406-
const completed = next.checkpoint.marks!.at(-1)!;
407-
Object.assign(completed, {
408-
dispatched: mark?.dispatched,
409-
end: mark?.end,
410-
status: 'completed',
411-
calls: answer.calls.length,
412-
});
413-
},
414-
);
389+
const outputEvents = await session.writer.finish('completed');
390+
const rejected = await rt.store.modelTurns.finish(run, permit, outputEvents, (next) => {
391+
account(next);
392+
const completed = next.checkpoint.marks!.at(-1)!;
393+
Object.assign(completed, {
394+
dispatched: mark?.dispatched,
395+
end: mark?.end,
396+
status: 'completed',
397+
calls: answer.calls,
398+
});
399+
if (decision.kind === 'refused') {
400+
next.checkpoint.pending = [];
401+
return decision.fault.code === 'context_limit'
402+
? (modelTurnLimit(next, agent.limits) ?? decision.fault)
403+
: decision.fault;
404+
}
405+
const message = decision.message;
406+
next.checkpoint.messages.push(message);
407+
if (message.providerState) next.checkpoint.modelInstructions ??= requestInstructions;
408+
next.checkpoint.pending = message.tool_calls;
409+
next.checkpoint.phase = message.tool_calls.length ? 'tools' : 'done';
410+
return undefined;
411+
});
415412
session.pending(false);
413+
if (rejected) throw new RejectedToolPlan(rejected, outputEvents);
416414
session.writer.close();
417415
checkAbort(signal);
418416
slice.progressed = true;

0 commit comments

Comments
 (0)