fix(cursor): preserve assistant reasoning across tool continuations (#82)
Co-authored-by: luolingpeng <luolingpeng@lovart.ai>
This commit is contained in:
@@ -63,7 +63,11 @@ plugin's `fetch` answers them on Cursor's agent API:
|
||||
so subagents under one session are conversations of their own. With
|
||||
nothing naming the session, each Run has a new one.
|
||||
- Text, thinking (`reasoning_content`) and token usage come back streamed
|
||||
or not. Cursor's `input_tokens` counts the cached prompt too: the cache
|
||||
or not. Replayed assistant `reasoning_content` (or `reasoning`) is kept as
|
||||
AI SDK reasoning parts in the next Run's transcript, including when a
|
||||
caller splits parallel tool calls across assistant messages. It stays
|
||||
separate from reply text; no thinking signature is invented.
|
||||
Cursor's `input_tokens` counts the cached prompt too: the cache
|
||||
read and written is taken out of it, and given as `cached_tokens` and
|
||||
`cache_write_tokens`, so it is counted once; its reasoning tokens are
|
||||
`reasoning_tokens`. A step that calls tools gets no usage in its Run
|
||||
|
||||
@@ -1081,6 +1081,10 @@ function statusOf(status, code, msg) {
|
||||
const textOf = (c) =>
|
||||
typeof c === "string" ? c : Array.isArray(c) ? c.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("") : ""
|
||||
|
||||
// Chat clients replay thinking beside content. Cursor's transcript blobs
|
||||
// use AI SDK reasoning parts; putting it in text would change its role.
|
||||
const reasoningOf = (m) => [m.reasoning_content, m.reasoning].find((s) => typeof s === "string" && s.trim()) ?? ""
|
||||
|
||||
// joinSplitCalls joins an assistant message onto the assistant message
|
||||
// before it when that one made tool calls: Anthropic takes consecutive
|
||||
// assistant messages as one turn, and an agent can send a turn's parallel
|
||||
@@ -1093,7 +1097,8 @@ function joinSplitCalls(msgs) {
|
||||
const prev = out.at(-1)
|
||||
if (m?.role === "assistant" && prev?.role === "assistant" && prev.tool_calls?.length) {
|
||||
const content = [textOf(prev.content), textOf(m.content)].filter(Boolean).join("\n\n")
|
||||
out[out.length - 1] = { ...prev, content, tool_calls: [...prev.tool_calls, ...(m.tool_calls ?? [])] }
|
||||
const reasoning_content = [reasoningOf(prev), reasoningOf(m)].filter(Boolean).join("\n\n")
|
||||
out[out.length - 1] = { ...prev, content, reasoning_content, tool_calls: [...prev.tool_calls, ...(m.tool_calls ?? [])] }
|
||||
continue
|
||||
}
|
||||
out.push(m)
|
||||
@@ -1198,9 +1203,11 @@ function conversation(chat, tools) {
|
||||
if (m.role === "assistant") {
|
||||
answer()
|
||||
const content = []
|
||||
const reasoning = reasoningOf(m)
|
||||
if (reasoning) content.push({ type: "reasoning", text: reasoning })
|
||||
const text = textOf(m.content)
|
||||
if (text) content.push({ type: "text", text })
|
||||
size += text.length
|
||||
size += reasoning.length + text.length
|
||||
for (const c of m.tool_calls ?? []) {
|
||||
if (c?.type && c.type !== "function") continue
|
||||
const args = parseArgs(c.function?.arguments)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// Tool continuations replay the assistant's reasoning as AI SDK reasoning
|
||||
// parts, rather than discarding it when a new Run is built. No request leaves
|
||||
// this machine; fixtures contain no real conversation or account data.
|
||||
import "./nonet.mjs"
|
||||
import { expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const call = (id) => ({ id, type: "function", function: { name: "read", arguments: '{"path":"a"}' } })
|
||||
const messages = (assistant) => [
|
||||
{ role: "user", content: "fix the bug" },
|
||||
{ role: "assistant", content: null, tool_calls: [call("toolu_a")], ...assistant },
|
||||
{ role: "tool", tool_call_id: "toolu_a", content: "the source" },
|
||||
]
|
||||
const convert = (msgs) => _internal.conversation({ messages: msgs }, [])
|
||||
const parts = (conv) => conv.msgs.map((b) => JSON.parse(b.toString())).filter((m) => m.role === "assistant")
|
||||
|
||||
test("reasoning_content survives a tool continuation and the Run's transcript blobs", () => {
|
||||
const conv = convert(messages({ reasoning_content: "The branch needs a null check.", content: "Reading the source." }))
|
||||
expect(parts(conv)[0].content).toEqual([
|
||||
{ type: "reasoning", text: "The branch needs a null check." },
|
||||
{ type: "text", text: "Reading the source." },
|
||||
{ type: "tool-call", toolCallId: "toolu_a", toolName: "CallDynamicTool", args: { namespace: "magpie", toolName: "read", arguments: { path: "a" } } },
|
||||
])
|
||||
const run = _internal.buildRun(conv.msgs, conv.last, [], "grok-4.7-fast")
|
||||
const transcript = [...run.blobs.values()].map((b) => b.toString())
|
||||
expect(transcript).toContain(JSON.stringify(parts(conv)[0]))
|
||||
expect(JSON.stringify(conv.msgs.map((b) => JSON.parse(b.toString())))).toContain("the source")
|
||||
})
|
||||
|
||||
test("reasoning is accepted as the alternate Chat field, without duplicating both fields", () => {
|
||||
expect(parts(convert(messages({ reasoning: "Keep the existing interface." })))[0].content[0]).toEqual({ type: "reasoning", text: "Keep the existing interface." })
|
||||
expect(parts(convert(messages({ reasoning_content: "Canonical", reasoning: "Alias" })))[0].content.filter((p) => p.type === "reasoning")).toEqual([{ type: "reasoning", text: "Canonical" }])
|
||||
})
|
||||
|
||||
test("split tool calls retain reasoning from both assistant messages in order", () => {
|
||||
const msgs = [
|
||||
{ role: "user", content: "read a and b" },
|
||||
{ role: "assistant", content: null, reasoning_content: "Check a first.", tool_calls: [call("toolu_a")] },
|
||||
{ role: "assistant", content: "Reading both.", reasoning: "Then check b.", tool_calls: [call("toolu_b")] },
|
||||
{ role: "tool", tool_call_id: "toolu_a", content: "A" },
|
||||
{ role: "tool", tool_call_id: "toolu_b", content: "B" },
|
||||
]
|
||||
const before = JSON.stringify(msgs)
|
||||
const conv = convert(msgs)
|
||||
expect(parts(conv)[0].content.filter((p) => p.type === "reasoning")).toEqual([{ type: "reasoning", text: "Check a first.\n\nThen check b." }])
|
||||
expect(parts(conv)[0].content.filter((p) => p.type === "tool-call")).toHaveLength(2)
|
||||
const results = conv.msgs.map((b) => JSON.parse(b.toString())).find((m) => m.role === "tool").content
|
||||
expect(results.map((p) => p.experimental_content[0].text)).toEqual(["A", "B"])
|
||||
expect(JSON.stringify(msgs)).toBe(before)
|
||||
})
|
||||
|
||||
test("reasoning-only history is preserved as reasoning, not ordinary assistant text", () => {
|
||||
expect(parts(convert([{ role: "user", content: "continue" }, { role: "assistant", content: null, reasoning_content: "An unfinished plan." }]))).toEqual([
|
||||
{ role: "assistant", content: [{ type: "reasoning", text: "An unfinished plan." }] },
|
||||
])
|
||||
})
|
||||
|
||||
test("blank or non-string reasoning fields do not create empty or invalid parts", () => {
|
||||
for (const value of [undefined, null, "", " ", {}, [], 42]) {
|
||||
const got = parts(convert(messages({ reasoning_content: value })))[0].content
|
||||
expect(got.filter((p) => p.type === "reasoning")).toEqual([])
|
||||
expect(got.filter((p) => p.type === "tool-call")).toHaveLength(1)
|
||||
}
|
||||
expect(parts(convert(messages({ reasoning_content: "", reasoning: "Fallback" })))[0].content[0]).toEqual({ type: "reasoning", text: "Fallback" })
|
||||
})
|
||||
|
||||
test("the input estimate includes replayed reasoning exactly once", () => {
|
||||
const baseline = convert(messages({}))
|
||||
const reasoning = "x".repeat(400)
|
||||
const conv = convert(messages({ reasoning_content: reasoning, reasoning }))
|
||||
expect(conv.estimate - baseline.estimate).toBe(100)
|
||||
})
|
||||
Reference in New Issue
Block a user