feat(api): enforce OpenAI tool_choice contract (required/named/none)
build-and-push / build (push) Successful in 4m59s

- normalizeToolChoice maps OpenAI tool_choice values to internal shapes
- required/named: prepend a mandatory-tool directive block; buffer text
  deltas and only flush when a tool call actually arrives; on plain-text
  turn, retry in-process with a nudge block (max 2 retries) instead of
  emitting the violating text (streaming + non-streaming paths)
- none: prepend a no-tools directive
- unit tests for all new mapping/directive helpers (32 passing)

Verified live against cursor-agent ACP with model=auto: image+required
yields clean tool_calls chunks with no text pollution; follow-up turns
resolve parked MCP tool calls and retry on invalid observations.
This commit is contained in:
Ubuntu
2026-09-27 12:02:40 +00:00
parent 706733fed3
commit b467998ba4
3 changed files with 181 additions and 3 deletions
+68 -3
View File
@@ -28,6 +28,10 @@ import {
messageContentToText,
hasImageParts,
openAiMessagesToAcpBlocks,
normalizeToolChoice,
toolDirectiveBlock,
toolNudgeBlock,
noToolsDirectiveBlock,
} from "./message-converter.mjs";
import { textChunk, toolCallChunk, finishChunk, nonStreamResponse } from "./stream-translator.mjs";
@@ -167,6 +171,7 @@ async function handleChatCompletions(req, res) {
const stream = body.stream === true;
const model = normalizeModel(body.model);
const toolChoice = normalizeToolChoice(body.tool_choice);
const toolsCount = Array.isArray(body.tools) ? body.tools.length : 0;
const imageCount = hasImageParts(body.messages) ? body.messages.reduce((n, m) => {
if (!Array.isArray(m.content)) return n;
@@ -236,12 +241,27 @@ async function handleChatCompletions(req, res) {
return;
}
await streamSessionTurn({ res, session, requestId, stream, blocks });
// tool_choice enforcement: prepend directive blocks before user content.
if (toolChoice && toolChoice.kind !== "none" && (body.tools || []).length > 0) {
blocks.unshift(toolDirectiveBlock(toolChoice));
} else if (toolChoice && toolChoice.kind === "none") {
blocks.unshift(noToolsDirectiveBlock());
}
await streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice });
}
async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
async function streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice = null }) {
if (!stream) {
const result = await collectSessionTurn(session, blocks);
let result = await collectSessionTurn(session, blocks);
// tool_choice enforcement (non-streaming): retry internally when the
// model answered in plain text despite a required/named tool choice.
if (toolChoice && toolChoice.kind !== "none" && result.finishReason !== "tool_calls" && result.text.trim()) {
for (let attempt = 0; attempt < 2; attempt++) {
result = await collectSessionTurn(session, [toolNudgeBlock()]);
if (result.finishReason === "tool_calls") break;
}
}
if (!res.headersSent) {
res.setHeader("Content-Type", "application/json");
res.end(
@@ -272,10 +292,36 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
let isFirst = true;
let finished = false;
// tool_choice enforcement (streaming): buffer text deltas while a
// required/named choice is active; flush only when a tool call arrives or
// the turn finishes. On plain-text-only turn, retry with a nudge instead
// of emitting the violating text.
const enforceToolChoice = Boolean(toolChoice && toolChoice.kind !== "none");
let textBuffer = "";
let sawToolCall = false;
let enforcementRetries = 0;
const MAX_ENFORCEMENT_RETRIES = 2;
const flushText = () => {
if (!textBuffer) return;
const chunk = textChunk({
id: requestId,
model: session.detectedModel || "auto",
delta: textBuffer,
isFirst,
});
isFirst = false;
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
textBuffer = "";
};
const handlers = {
onAssistantDelta: (delta) => {
if (res.writableEnded || finished) return;
if (enforceToolChoice) {
textBuffer += delta;
return;
}
const chunk = textChunk({
id: requestId,
model: session.detectedModel || "auto",
@@ -287,6 +333,8 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
},
onToolCall: (call) => {
if (res.writableEnded || finished) return;
sawToolCall = true;
flushText();
const chunk = toolCallChunk({
id: requestId,
model: session.detectedModel || "auto",
@@ -298,8 +346,25 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
},
onFinish: async (reason, _usage) => {
if (finished) return;
// Enforcement retry: plain-text-only turn under required tool choice.
if (
enforceToolChoice &&
!sawToolCall &&
reason === "stop" &&
enforcementRetries < MAX_ENFORCEMENT_RETRIES &&
!res.writableEnded
) {
enforcementRetries += 1;
console.error(
`[chat] id=${requestId} tool_choice enforcement retry ${enforcementRetries}/${MAX_ENFORCEMENT_RETRIES}`
);
textBuffer = "";
session.runTurn([toolNudgeBlock()], handlers);
return;
}
finished = true;
if (!res.writableEnded) {
if (reason !== "error" || !enforceToolChoice) flushText();
const chunk = finishChunk({
id: requestId,
model: session.detectedModel || "auto",