#38 (deepseek-v4.1-flash on trae-cn): 64 of 3112 turns came back with the model's text-form <tool_call> block as the answer, no call made, as a 200 with a normal finish, so the gateway had nothing to fail over on. ARNO (trae-cn, Discord) sent two more: a write whose JSON is whole but has no </tool_call> (the stream ended), and a closed write block. ARNO's two replies, as sent (content redacted to xxxx), are read as calls by 0.2.4 too, whole or one character at a time, with the tool declared as write or Write; prose before the block and arguments as an object don't matter. What breaks the closed one is in its content: a written-out analysis with a quote left unescaped ("官方"), a backslash JSON doesn't know (\| \_ C:\Users) or a JSON sample of its own makes JSON.parse fail, and 0.2.4 then printed the block as text. Those are the fixtures here. TextTools now: - reads a block as models get its JSON wrong: every quote escaped ({\"name\":…}, #38's most common shape), unknown backslash escapes doubled, and quotes inside a string escaped unless they end it (a key's before its colon, a value's before closing braces and the end or a comma and the next key); - takes an opener with attributes, <tool_call name="bash"> with <parameter name="k">v</parameter>, and DeepSeek's {"name":"x"}> head with parameters (magpie's paramCall, #917), its values typed by the tool's schema; - when a block is closed but can't be read, or is cut short at the end (JSON not whole, a parameter not closed), returns an error instead of the text: parts() yields it, so a stream ends with the error event and [DONE] and no finish, and a body is a 502; - leaves a <tool_call> in backticks or a code fence, or named in prose with no JSON after it, as text. Not done: #38's fourth point (text on done/response_done events): there is no raw event showing Trae puts text there, and reading it blind could send a whole reply twice. textcall.test.mjs builds from ARNO's literal bytes and #38's repro cases. Against 0.2.4's index.mjs 4 of its 6 tests fail (the two that pass are ARNO's literal replies, which 0.2.4 already reads). HOME=$(mktemp -d) bun test: 870 pass, 0 fail; bun scripts/check.mjs passes. Not tried with a real Trae CN account.
173 lines
8.8 KiB
JavaScript
173 lines
8.8 KiB
JavaScript
// plugins#38: a tool call the model wrote into its text that wasn't read
|
|
// went out as the answer, the call lost, with a 200 nothing could fail
|
|
// over on. The shapes are the issue's (deepseek-v4.1-flash on trae-cn) and
|
|
// ARNO's on Discord (trae-cn, content redacted by them as xxxx).
|
|
import "./nonet.mjs"
|
|
import { afterEach, expect, test } from "bun:test"
|
|
import { TraeCNAuthPlugin, _internal } from "./index.mjs"
|
|
import { fakeTrae, signedIn, sse } from "./fake.mjs"
|
|
|
|
let f
|
|
afterEach(() => f?.close())
|
|
|
|
async function ask(body, auth = signedIn()) {
|
|
const hooks = await TraeCNAuthPlugin({ client: {} })
|
|
const opts = await hooks.auth.loader(async () => auth)
|
|
return opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(body) })
|
|
}
|
|
|
|
async function chunks(res) {
|
|
const out = []
|
|
for (const line of (await res.text()).split("\n")) {
|
|
if (!line.startsWith("data: ")) continue
|
|
const d = line.slice(6)
|
|
out.push(d === "[DONE]" ? d : JSON.parse(d))
|
|
}
|
|
return out
|
|
}
|
|
|
|
const deltasOf = (c) => c.filter((x) => x !== "[DONE]" && x.choices?.length).map((x) => x.choices[0].delta)
|
|
const callsOf = (c) => deltasOf(c).flatMap((d) => d.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)])
|
|
const textOf = (c) => deltasOf(c).map((d) => d.content ?? "").join("")
|
|
const finishOf = (c) => c.filter((x) => x !== "[DONE]" && x.choices?.[0]?.finish_reason).map((x) => x.choices[0].finish_reason)
|
|
|
|
const TOOLS = [
|
|
{ type: "function", function: { name: "bash", parameters: { type: "object", properties: { command: { type: "string" } } } } },
|
|
{ type: "function", function: { name: "write", parameters: { type: "object", properties: { content: { type: "string" }, filePath: { type: "string" } } } } },
|
|
]
|
|
|
|
// what TextTools makes of s given whole, and given a piece at a time
|
|
function read(s, size = 0, tools = TOOLS) {
|
|
const t = new _internal.TextTools(tools)
|
|
const pieces = size ? Array.from({ length: Math.ceil(s.length / size) }, (_, k) => s.slice(k * size, (k + 1) * size)) : [s]
|
|
const out = { text: "", calls: [], error: null }
|
|
for (const [k, p] of [...pieces, ""].entries()) {
|
|
const r = t.push(p, k === pieces.length)
|
|
out.text += r.text
|
|
out.calls.push(...r.calls.map((c) => [c.name, JSON.parse(c.arguments)]))
|
|
if (r.error) {
|
|
out.error = r.error
|
|
break
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// ARNO's two replies, as sent
|
|
const ARNO_1 = '官方资料齐了。我把完整分析写成文件,聊天里给你重点。\n<tool_call>{"name":"write","arguments":{"content":"xxxxxxxx"}}'
|
|
const ARNO_2 = '文件确实丢了(可能是之前写入没成功),我重写完整版。\n<tool_call>{"name":"write","arguments":{"content":"xxxxxx"}}</tool_call>'
|
|
|
|
test("ARNO's two replies are calls: a block closed, and one whose JSON is whole when the stream ends", () => {
|
|
for (const size of [0, 1, 7]) {
|
|
expect(read(ARNO_1, size)).toEqual({ text: "官方资料齐了。我把完整分析写成文件,聊天里给你重点。\n", calls: [["write", { content: "xxxxxxxx" }]], error: null })
|
|
expect(read(ARNO_2, size)).toEqual({ text: "文件确实丢了(可能是之前写入没成功),我重写完整版。\n", calls: [["write", { content: "xxxxxx" }]], error: null })
|
|
}
|
|
})
|
|
|
|
test("a write's content as models get its JSON wrong is still the call: quotes left unescaped, backslashes JSON doesn't know", () => {
|
|
// ARNO's second reply, its redacted content as a written-out analysis
|
|
// may have it
|
|
const contents = [
|
|
'# 分析\n他说"官方"的资料齐了',
|
|
"| 列 | a \\| b |\n| --- | --- |",
|
|
"snake\\_case 和 \\*强调\\*",
|
|
"路径 C:\\Users\\arno\\x",
|
|
"```json\n{\"a\": 1, \"b\": \"c\"}\n```\n完",
|
|
]
|
|
const want = [
|
|
'# 分析\n他说"官方"的资料齐了',
|
|
"| 列 | a \\| b |\n| --- | --- |",
|
|
"snake\\_case 和 \\*强调\\*",
|
|
"路径 C:\\Users\\arno\\x",
|
|
'```json\n{"a": 1, "b": "c"}\n```\n完',
|
|
]
|
|
contents.forEach((c, k) => {
|
|
const s = '文件确实丢了(可能是之前写入没成功),我重写完整版。\n<tool_call>{"name":"write","arguments":{"content":"' + c + '"}}</tool_call>'
|
|
for (const size of [0, 5]) {
|
|
const r = read(s, size)
|
|
expect(r.error).toBe(null)
|
|
expect(r.text).toBe("文件确实丢了(可能是之前写入没成功),我重写完整版。\n")
|
|
expect(r.calls).toEqual([["write", { content: want[k] }]])
|
|
}
|
|
})
|
|
})
|
|
|
|
test("#38's shapes: escaped quotes and an attribute-framed opener are calls; a block cut short is an error, never text", () => {
|
|
// the issue's repro, case by case
|
|
expect(read('Sure. <tool_call>{"name":"bash","arguments":{"command":"ls"}}</tool_call>')).toEqual({ text: "Sure. ", calls: [["bash", { command: "ls" }]], error: null })
|
|
for (const size of [0, 3]) {
|
|
expect(read('<tool_call>{\\"name\\":\\"bash\\",\\"arguments\\":{\\"command\\":\\"ls\\"}}</tool_call>', size)).toEqual({ text: "", calls: [["bash", { command: "ls" }]], error: null })
|
|
expect(read('<tool_call name="bash">\n<parameter name="command">ls</parameter>\n</tool_call>', size)).toEqual({ text: "", calls: [["bash", { command: "ls" }]], error: null })
|
|
// the name as JSON, then its parameters (magpie#917's shape)
|
|
expect(read('<tool_call>{"name":"bash"}>\n<parameter name="command">ls -la</parameter>\n</tool_call>', size)).toEqual({ text: "", calls: [["bash", { command: "ls -la" }]], error: null })
|
|
}
|
|
// a quote in a command escaped as a whole block's are
|
|
expect(read('<tool_call>{\\"name\\":\\"bash\\",\\"arguments\\":{\\"command\\":\\"echo \\\\\\"hi\\\\\\"\\"}}</tool_call>').calls).toEqual([["bash", { command: 'echo "hi"' }]])
|
|
for (const cut of [
|
|
'<tool_call>{"name":"bash","arguments":{"command":"cd "C:/x"',
|
|
'<tool_call>{"name":"bash","arguments":{"command":"ls"}',
|
|
'<tool_call>{"name":"write","arguments":{"content":"## 结论\\n1. 先',
|
|
'<tool_call name="bash">\n<parameter name="command">ls -',
|
|
]) {
|
|
for (const size of [0, 4]) {
|
|
const r = read("Running it.\n" + cut, size)
|
|
expect(r.error).toContain("cut short")
|
|
expect(r.text).toBe("Running it.\n")
|
|
expect(r.calls).toEqual([])
|
|
}
|
|
}
|
|
// closed, but not JSON however read
|
|
const bad = read('<tool_call>{"name":"bash","arguments":{"command":}}</tool_call>')
|
|
expect(bad.error).toContain("can't be read")
|
|
expect(bad.text).toBe("")
|
|
})
|
|
|
|
test("prose that mentions <tool_call> stays text: in backticks, in a code fence, or a tag named in passing", () => {
|
|
for (const s of [
|
|
'Write `<tool_call>{"name":"bash","arguments":{}}</tool_call>` to call a tool.',
|
|
"Each call goes in a `<tool_call>` block.",
|
|
'Example:\n```\n<tool_call>{"name":"bash","arguments":{"command":"ls"}}</tool_call>\n```\nThat is all.',
|
|
"The <tool_call> tag wraps a call; </tool_call> ends it.",
|
|
"<tool_call>hello</tool_call> ok",
|
|
]) {
|
|
for (const size of [0, 1, 6]) expect(read(s, size)).toEqual({ text: s, calls: [], error: null })
|
|
}
|
|
})
|
|
|
|
test("a stream whose call is cut short ends with an error, not a finish, and the block isn't the answer", async () => {
|
|
f = fakeTrae()
|
|
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([
|
|
["output", { response: "Running it.\n<tool_call>" }],
|
|
["output", { response: '{"name":"bash","arguments":{"command":"cd "C:/x"' }],
|
|
["done", { finish_reason: "stop" }],
|
|
]))
|
|
const res = await ask({ model: "deepseek-v4.1-flash", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] })
|
|
const c = await chunks(res)
|
|
expect(textOf(c)).toBe("Running it.\n")
|
|
expect(textOf(c)).not.toContain("<tool_call")
|
|
expect(finishOf(c)).toEqual([])
|
|
expect(c.find((x) => x !== "[DONE]" && x.error).error.message).toContain("cut short")
|
|
expect(c.at(-1)).toBe("[DONE]")
|
|
|
|
// asked without a stream, it is a failure the gateway can fail over on
|
|
const res2 = await ask({ model: "deepseek-v4.1-flash", tools: TOOLS, messages: [{ role: "user", content: "hi" }] })
|
|
expect(res2.status).toBe(502)
|
|
expect((await res2.json()).error.message).toContain("cut short")
|
|
})
|
|
|
|
test("ARNO's second reply through the plugin: a write call, the reply finished as one that called tools", async () => {
|
|
f = fakeTrae()
|
|
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([
|
|
["output", { response: ARNO_2.slice(0, 30) }],
|
|
["output", { response: ARNO_2.slice(30, 60) }],
|
|
["output", { response: ARNO_2.slice(60) }],
|
|
["done", { finish_reason: "stop" }],
|
|
]))
|
|
// the agent declared the tool as Write
|
|
const tools = [{ type: "function", function: { name: "Write", parameters: { type: "object", properties: { content: { type: "string" } } } } }]
|
|
const c = await chunks(await ask({ model: "deepseek-v4.1-flash", stream: true, tools, messages: [{ role: "user", content: "hi" }] }))
|
|
expect(textOf(c)).toBe("文件确实丢了(可能是之前写入没成功),我重写完整版。\n")
|
|
expect(callsOf(c)).toEqual([["Write", { content: "xxxxxx" }]])
|
|
expect(finishOf(c)).toEqual(["tool_calls"])
|
|
})
|