Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

ACP: fail a turn that ends on tool-call markup no tool ran

erywim7d44583f84bf
diff --git a/server/chat-notices.ts b/server/chat-notices.ts
index 6c4d588472..c98fa2a715 100644
--- a/server/chat-notices.ts
+++ b/server/chat-notices.ts
@@ -91,6 +91,7 @@ export const CHAT_NOTICE = {
"chat.notice.phone.write.PHONE_SEND_WHATSAPP": "Send whatsapp on {phone}",
"chat.notice.acpEmpty": "{provider} finished without replying.",
"chat.notice.acpEndedAfterTools": "{provider} thought right past the last tool, then finished the turn without a last reply. Ask it to continue or summarize what it did.",
+ "chat.notice.acpToolCallFragment": "{provider}'s reply ended on a tool call it never ran, so the turn was not completed.",
"chat.notice.acpNoReason": "{provider} stopped without saying why.",
"chat.notice.acpNodeTooOld": "{provider} needs Node.js {needed} or newer, but this computer has Node.js {found}. Update Node.js from nodejs.org, then send your message again.",
"chat.notice.acpMcpAppsFailed": "Connected apps couldn't be set up, so {provider} couldn't start this reply. Try again, or switch this bot to another AI.",
diff --git a/server/drivers/acp/turn-state.test.ts b/server/drivers/acp/turn-state.test.ts
index 9acecc7d54..587e57037a 100644
--- a/server/drivers/acp/turn-state.test.ts
+++ b/server/drivers/acp/turn-state.test.ts
@@ -7,11 +7,13 @@ const ERROR_BODY = '403 {"type":"error","error":{"type":"permission_error","mess
/** A turn whose buffered text is `text`, flushed as core.ts does: a non-blank text becomes a reply. */
function turnWith(
text: string,
- state: { stopped?: boolean; replied?: string; toolsEnded?: boolean; thoughtAfterTools?: boolean; replyAfterTools?: string } = {},
+ state: { stopped?: boolean; replied?: string; toolsEnded?: boolean; toolRunning?: boolean; thoughtAfterTools?: boolean; replyAfterTools?: string } = {},
) {
const replies: string[] = [];
const current = {
state: { text: state.replied ?? "", stopped: false, producedItem: false, repliedText: false, toolsSinceShown: false, thoughtSinceTool: false },
+ runningTools: new Set<string>(state.toolRunning ? ["call"] : []),
+ endedToolIds: new Set<string>(state.toolsEnded ? ["call"] : []),
flushAssistantText() {
const said = current.state.text;
current.state.text = "";
@@ -112,3 +114,43 @@ describe("endTurn on a turn that goes wordless after its tools", () => {
expect(endTurn(current, true, null, "omp")).toEqual({ ok: true, stopReason: "cancelled" });
});
});
+
+describe("endTurn on a reply that ends on tool-call markup", () => {
+ it.each([
+ ["a closing parameter tag", 'Opening src/app.ts now.\n<parameter name="path">src/app.ts\n</parameter>'],
+ ["a closing invoke tag", "Applying the edit.\n</invoke>"],
+ ["a tool_call tag", "Reading the file.\n<tool_call>"],
+ ["an unclosed parameter tag", 'Creating the file.\n<parameter name="path"'],
+ ])("fails the turn on %s and still shows the text", (_name, text) => {
+ const { current, replies } = turnWith(text);
+ expect(endTurn(current, true, null, "Grok")).toMatchObject({
+ ok: false,
+ stopReason: "tool_call_fragment",
+ error: { text: { key: "chat.notice.acpToolCallFragment", params: { provider: "Grok" } } },
+ });
+ expect(replies).toEqual([text]);
+ });
+
+ it("leaves prose that ends on plain JSON alone", () => {
+ const { current, replies } = turnWith('The answer is:\n{"ok":true}');
+ expect(endTurn(current, true, null, "Grok")).toEqual({ ok: true, stopReason: null });
+ expect(replies).toEqual(['The answer is:\n{"ok":true}']);
+ });
+
+ it("leaves an ordinary announcement alone", () => {
+ const { current } = turnWith("I'll keep that in mind.");
+ expect(endTurn(current, true, null, "Grok")).toEqual({ ok: true, stopReason: null });
+ });
+
+ it("leaves a turn that ran a tool alone", () => {
+ const running = turnWith("</parameter>", { toolRunning: true });
+ expect(endTurn(running.current, true, null, "Grok")).toEqual({ ok: true, stopReason: null });
+ const ended = turnWith("</parameter>", { toolsEnded: true });
+ expect(endTurn(ended.current, true, null, "Grok")).toEqual({ ok: true, stopReason: null });
+ });
+
+ it("leaves a cut-off fenced example alone", () => {
+ const { current } = turnWith('Here is the shape:\n```xml\n<tool_call>\n<parameter name="path">src/a.ts</parameter>');
+ expect(endTurn(current, true, null, "Grok")).toEqual({ ok: true, stopReason: null });
+ });
+});
diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.ts
index 1670755a03..52a08804d9 100644
--- a/server/drivers/acp/turn-state.ts
+++ b/server/drivers/acp/turn-state.ts
@@ -136,6 +136,17 @@ export interface AcpTurnEnd {
error?: Omit<ErrorReplyFailure, "stopReason">;
}
+const TOOL_CALL_TAIL = ["</parameter>", "</invoke>", "<tool_call>"];
+
+/** A reply whose tail is tool-call markup no tool ran: the model wrote the call as text. A tag inside an unclosed ```
+ * example block is a cut-off sample, not a leak. */
+export function endsOnToolCallMarkup(text: string): boolean {
+ const trimmed = text.trimEnd();
+ if (!trimmed || (trimmed.match(/```/g)?.length ?? 0) % 2 === 1) return false;
+ const tail = trimmed.slice(-64).toLowerCase();
+ return TOOL_CALL_TAIL.some((tag) => tail.endsWith(tag)) || /<parameter(?:\s[^<>]*)?>?$/i.test(trimmed);
+}
+
/** How a settling turn ends, once its last text is out. A Stop the agent answers with end_turn (OpenCode does) is the
* person's stop. A reply that is only a provider's error body fails the turn in plain words. Otherwise `end_turn` with
* nothing to show is a lost turn: a provider may cut a reasoning-only stream and still answer end_turn, and a turn that
@@ -144,12 +155,15 @@ export interface AcpTurnEnd {
export function endTurn(current: AcpTurn, ok: boolean, stopReason: string | null, ai: string): AcpTurnEnd {
const ended = ok && stopReason === null;
const errorReply = ended && !current.state.stopped && !current.state.repliedText ? errorReplyFailure(ai, current.state.text) : null;
+ const toolCallTail = ended && !current.state.stopped && !errorReply && current.runningTools.size === 0 && current.endedToolIds.size === 0
+ && endsOnToolCallMarkup(current.state.text);
if (!errorReply) current.flushAssistantText();
if (ended && current.state.stopped) return { ok, stopReason: "cancelled" };
if (errorReply) {
const { stopReason: failed, ...error } = errorReply;
return { ok: false, stopReason: failed, error };
}
+ if (toolCallTail) return { ok: false, stopReason: "tool_call_fragment", error: noticeFailure("chat.notice.acpToolCallFragment", { provider: ai }) };
if (ended && !current.state.producedItem) return { ok: false, stopReason: "empty_turn", error: noticeFailure("chat.notice.acpEmpty", { provider: ai }) };
if (ended && current.state.repliedText && current.state.thoughtSinceTool) return { ok: false, stopReason: "ended_after_tools", error: noticeFailure("chat.notice.acpEndedAfterTools", { provider: ai }) };
return { ok, stopReason };
diff --git a/src/locales/en.json b/src/locales/en.json
index cf38252006..c3e3e41764 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10277,6 +10277,7 @@
"serverError.engineCheck.timeout": "{name} didn't answer within {seconds} seconds.",
"chat.notice.acpEmpty": "{provider} finished without replying.",
"chat.notice.acpEndedAfterTools": "{provider} thought right past the last tool, then finished the turn without a last reply. Ask it to continue or summarize what it did.",
+ "chat.notice.acpToolCallFragment": "{provider}'s reply ended on a tool call it never ran, so the turn was not completed.",
"chat.notice.acpNoReason": "{provider} stopped without saying why.",
"chat.notice.acpNodeTooOld": "{provider} needs Node.js {needed} or newer, but this computer has Node.js {found}. Update Node.js from nodejs.org, then send your message again.",
"chat.notice.acpMcpAppsFailed": "Connected apps couldn't be set up, so {provider} couldn't start this reply. Try again, or switch this bot to another AI.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 0dd3959498..9caac4d209 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10200,6 +10200,7 @@
"serverError.engineCheck.timeout": "{name} não respondeu em {seconds} segundos.",
"chat.notice.acpEmpty": "{provider} terminou sem responder.",
"chat.notice.acpEndedAfterTools": "{provider} ficou pensando após a última ferramenta e terminou a sessão sem dar a resposta final. Peça para continuar ou resumir o que fez.",
+ "chat.notice.acpToolCallFragment": "A resposta de {provider} terminou em uma chamada de ferramenta que ela nunca executou, então a sessão não foi concluída.",
"chat.notice.acpNoReason": "{provider} parou sem informar o motivo.",
"chat.notice.acpNodeTooOld": "{provider} precisa do Node.js {needed} ou mais recente, mas este computador tem o Node.js {found}. Atualize o Node.js em nodejs.org e envie sua mensagem de novo.",
"chat.notice.acpMcpAppsFailed": "Não foi possível configurar os apps conectados, então {provider} não conseguiu começar esta resposta. Tente de novo ou troque a IA deste bot.",