catpaw 0.2.0: tools over the flattened prompt, parsed back into tool_calls, one forced retry (#697)
catpaw 0.2.0 (gcdong, #697): the conversation protocol takes one flattened
text prompt, so a request with tools was refused with 400. Tools now ride as
an injected instruction and the reply is parsed back into OpenAI tool_calls:
only a reply that is wholly the call JSON (bare object or one fenced block)
counts, unknown names and calls missing a required arg are dropped, a
drifted name case is matched back. A forced tool_choice (required / named)
gets one retry with the failed reply in the prompt; streaming holds the
whole reply in that case, otherwise only a JSON-shaped head is held and
prose streams live. Tool results ride as text. Images are still refused.
The keep-alive interval is cleared wherever the stream closes.
Run at the reviewed head f72226f2, on mote:
- bun test packages/catpaw: 53 pass.
- Squashed onto origin/main 075cd237: HOME=$(mktemp -d) bun test, 5418
pass, 19 skip, 0 fail across 403 files; bun scripts/check.mjs, 43 ok.
- CI run 41780109549: attempt 1 was the fork approval gate (action_required),
attempt 2 after approval: test and on-npm pass.
Broken by hand: deciding prose per chunk instead of holding the JSON head
turns "a call JSON split across cumulative frames" red (only it); dropping
halt() from push's catch turns the keep-alive teardown test red (only it).
Earlier rounds broke the forced hold, the whole-reply parse, the retry's
assistant turn and the required-arg check, each red.
Probed (throwaway tests, not committed): tool names like
mcp__srv__do.thing-x; fenced and bare-array forms; null, [], 42, a
non-array tool_calls, nulls in tool_calls, string arguments that aren't
JSON, a lone "{", a truncated fenced block and a call followed by prose all
come back as the literal text with finish stop, streamed or not; a forced
choice failing twice makes exactly 2 rounds; a forced streaming call split
over frames comes out as tool_calls with no content; tool_choice required
with no tools takes the plain path; the prompt names no magpie, plugin,
proxy or gateway.
Not tried: a real CatPaw account (the model's actual adherence to the JSON
instruction is unmeasured). The forced streaming retry's reasoning is not
emitted (the first turn's is); minor.
This commit is contained in:
@@ -20,7 +20,7 @@ magpie plugin login catpaw # 选「网页登录」/「妙手桌面端登录
|
||||
- **无续期接口**:token 过期后 401,网页登录重新发起一次即可;桌面端登录态则在妙手里重新登录(下一请求自动读新 token)。
|
||||
- **聊天**:`round → event → turn` 三步会话机;上游 SSE 帧为累积式,插件做差分转 OpenAI delta(`content` + `reasoning_content`),流式与非流式都支持。
|
||||
- **模型**:妙手桌面端的 9 个模型(longcat-2.0 / glm-5.3 系列 / deepseek-v4 系列 / minimax-m3 / kimi-k3 / auto),静态表打底,再按妙手桌面端的做法向网关取账号的模型清单(`POST /api/agent/maas/model-types`,缓存 5 分钟),官方新增的模型(如 LongCat 2.5)无需发版即出现;取不到清单时用静态表。不声明各模型的上下文/输出窗口(客户端未公布,不编造数字),也不声明图片输入(见下)。
|
||||
- **工具与图片**:会话协议只收一段扁平文本 prompt,工具定义、工具结果与图片都无法送达——带这些的请求以 **400 明确拒绝**(而不是悄悄丢掉后答错)。
|
||||
- **工具与图片**:会话协议只收一段扁平文本 prompt,图片无法送达——带图片的请求以 **400 明确拒绝**。工具以 **JSON 协议适配**支持:工具定义注入系统指令,模型按 `{"tool_calls":[…]}` 严格 JSON 回复,插件解析回 OpenAI `tool_calls`。只有整条回复就是调用 JSON(裸对象或单个 fence 块)才算调用——散文里引用的示例不会误判;工具名大小写漂移会匹配回声明名;未声明的工具名、缺必需参数的调用会被丢弃。流式:普通回复**边出边流**,仅 JSON 开头短暂扣留;`tool_choice=required`/指定工具时整条回复扣住(SSE 心跳保活),保证未拿到调用时能带上下文重试一次;`tool_choice=none` 保持原样透传。
|
||||
- **余额(usage)**:`GET https://catx.nocode.cn/api/gateway/credit/balance`,鉴权头是 **`X-Auth-Token: <accessToken>`**。
|
||||
- ⚠️ 这个接口与聊天网关**不是同一个鉴权头**:它只认 `X-Auth-Token`,把聊天用的 `Cookie: X-Passport-Token` 发到这里会稳定 401(body `code 4010`)。magpie 把 usage 的 401 当作「登录态失效」,所以鉴权头必须分开核对。
|
||||
- 读成功后**不带 `signIn` 字段**:magpie 以此把「已退出登录」的标记撤掉。
|
||||
|
||||
@@ -18,6 +18,13 @@ export function fakeCatPaw() {
|
||||
events: 0,
|
||||
turns: 0,
|
||||
turnError: null, // "sse-error" makes the turn stream send an error frame
|
||||
// per-turn frame scripts: each shift() plays one entry as the turn's
|
||||
// cumulative frames (the tools tests use it to script a reply, then a
|
||||
// forced-retry reply); empty → the default 你好 frames
|
||||
turnFramesQueue: [],
|
||||
// per-turn delay before the SSE starts (the keep-alive teardown test
|
||||
// uses it to keep the stream open while the agent cancels)
|
||||
turnDelayMs: 0,
|
||||
// sources the gateway has turned off: it answers them HTTP 200 with
|
||||
// {code: 400, msg: "source 不存在或未启用: <source>"}, the body behind
|
||||
// plugins#605. CatPawCLI was turned off by 2026-11-01.
|
||||
@@ -42,6 +49,8 @@ export function fakeCatPaw() {
|
||||
state.events = 0
|
||||
state.turns = 0
|
||||
state.turnError = null
|
||||
state.turnFramesQueue = []
|
||||
state.turnDelayMs = 0
|
||||
state.disabledSources = new Set(["CatPawCLI"])
|
||||
state.turnBodies = []
|
||||
state.balanceCalls = 0
|
||||
@@ -133,8 +142,11 @@ export function fakeCatPaw() {
|
||||
if (body.conversationId !== conv?.id) return json(400, { code: 400, msg: "turn for unknown conversation" })
|
||||
if (state.turnError === "sse-error")
|
||||
return new Response(`data: ${JSON.stringify({ error: { code: 500, message: "vendor broke" } })}\n\n`, { headers: { "content-type": "text/event-stream" } })
|
||||
if (state.turnDelayMs) await new Promise((r) => setTimeout(r, state.turnDelayMs))
|
||||
// cumulative frames: each carries the whole text so far (as the real gateway does)
|
||||
const frames = [
|
||||
const frames = state.turnFramesQueue.length
|
||||
? state.turnFramesQueue.shift()
|
||||
: [
|
||||
{ message: { content: [{ type: "text", text: "你", reasoningContent: "思" }] } },
|
||||
{ message: { content: [{ type: "text", text: "你好", reasoningContent: "思考" }] } },
|
||||
{ message: { content: [{ type: "text", text: "你好,", reasoningContent: "思考" }] } },
|
||||
|
||||
+398
-9
@@ -277,6 +277,205 @@ function buildPrompt(messages) {
|
||||
return parts.join("\n\n")
|
||||
}
|
||||
|
||||
// ── tools over the flattened prompt ──────────────────────────────────────
|
||||
//
|
||||
// The conversation protocol carries one text prompt and returns text, so
|
||||
// tool definitions travel as instructions and the model's reply is parsed
|
||||
// back into OpenAI tool_calls. The model can ignore the instruction — every
|
||||
// path answers with what actually came back, and a forced tool_choice gets
|
||||
// one explicit retry before giving up (no silent success).
|
||||
|
||||
function normalizeToolChoice(toolChoice) {
|
||||
if (toolChoice === undefined || toolChoice === null) return { mode: "auto" }
|
||||
if (typeof toolChoice === "string") {
|
||||
if (toolChoice === "none") return { mode: "none" }
|
||||
if (toolChoice === "required" || toolChoice === "any") return { mode: "required" }
|
||||
if (toolChoice === "auto") return { mode: "auto" }
|
||||
return { mode: "named", name: toolChoice }
|
||||
}
|
||||
if (typeof toolChoice === "object") {
|
||||
const type = toolChoice.type || "auto"
|
||||
if (type === "none") return { mode: "none" }
|
||||
if (type === "required" || type === "any") return { mode: "required" }
|
||||
if (type === "tool" || type === "function") {
|
||||
const name = toolChoice.name || toolChoice.function?.name || ""
|
||||
return name ? { mode: "named", name } : { mode: "required" }
|
||||
}
|
||||
return { mode: "auto" }
|
||||
}
|
||||
return { mode: "auto" }
|
||||
}
|
||||
|
||||
const isToolChoiceRequired = (toolChoice) => ["required", "named"].includes(normalizeToolChoice(toolChoice).mode)
|
||||
|
||||
function toolNameOf(tool) {
|
||||
return tool?.function?.name || tool?.name || ""
|
||||
}
|
||||
|
||||
function toolParamsOf(tool) {
|
||||
return tool?.function?.parameters || tool?.input_schema || tool?.parameters || {}
|
||||
}
|
||||
|
||||
function summarizeTool(tool) {
|
||||
const schema = toolParamsOf(tool)
|
||||
const props = schema?.properties && typeof schema.properties === "object" ? schema.properties : {}
|
||||
const required = new Set(Array.isArray(schema?.required) ? schema.required : [])
|
||||
const names = Object.keys(props).slice(0, 12)
|
||||
const params = names.length
|
||||
? `args: ${names.map((n) => `${n}: ${props[n]?.type ?? "?"}${required.has(n) ? "*" : ""}`).join(", ")}`
|
||||
: "args: object"
|
||||
const desc = String(tool?.function?.description || tool?.description || "").replace(/\s+/g, " ").trim()
|
||||
return `- ${toolNameOf(tool) || "tool"}: ${desc ? desc.slice(0, 120) : "No description"} (${params})`
|
||||
}
|
||||
|
||||
function buildToolInstruction(tools, toolChoice) {
|
||||
const choice = normalizeToolChoice(toolChoice)
|
||||
const lines = [
|
||||
"You can call tools, but this API only accepts a strict JSON tool-call response.",
|
||||
"When a tool is needed, respond with JSON only and no prose.",
|
||||
"For any file, code, shell, workspace, search, read, edit, write, or project task, you MUST call tools instead of describing the change.",
|
||||
"Never claim that you changed, read, searched, or executed anything unless you returned a tool call for it.",
|
||||
"Use exactly this shape:",
|
||||
'{"tool_calls":[{"name":"ToolName","arguments":{"arg":"value"}}]}',
|
||||
"Required argument names are marked with *.",
|
||||
]
|
||||
if (choice.mode === "required") lines.push("tool_choice=required: you MUST return a JSON tool_calls payload now. Plain text answers are forbidden.")
|
||||
else if (choice.mode === "named") lines.push(`tool_choice forces tool "${choice.name}": return JSON tool_calls that call ONLY this tool. Plain text answers are forbidden.`)
|
||||
else lines.push("Only answer normally for pure explanation or conversation tasks that do not need workspace access.")
|
||||
lines.push("Available tools:", ...tools.map(summarizeTool))
|
||||
return lines.join("\n")
|
||||
}
|
||||
|
||||
function forcedToolRetryMessage(toolChoice) {
|
||||
const choice = normalizeToolChoice(toolChoice)
|
||||
if (choice.mode === "named")
|
||||
return [
|
||||
"Your previous reply did not include a valid tool call.",
|
||||
`Return ONLY JSON tool_calls that invoke "${choice.name}". No markdown, no explanation.`,
|
||||
`{"tool_calls":[{"name":"${choice.name}","arguments":{...}}]}`,
|
||||
].join("\n")
|
||||
return [
|
||||
"Your previous reply did not include a valid tool call.",
|
||||
"Return ONLY a JSON tool_calls payload now. No markdown, no explanation.",
|
||||
'{"tool_calls":[{"name":"ToolName","arguments":{"arg":"value"}}]}',
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
function textOfContent(content) {
|
||||
if (typeof content === "string") return content
|
||||
return Array.isArray(content)
|
||||
? content
|
||||
.map((c) => (typeof c === "string" ? c : c?.type === "text" ? c.text || "" : ""))
|
||||
.join("")
|
||||
: ""
|
||||
}
|
||||
|
||||
// tool results become user text and assistant tool calls become their text
|
||||
// record — the roles buildPrompt would otherwise skip entirely (a silent
|
||||
// drop)
|
||||
function flattenMessagesForPrompt(messages) {
|
||||
const out = []
|
||||
for (const msg of messages) {
|
||||
if (msg.role === "tool") {
|
||||
out.push({ role: "user", content: `Tool result${msg.tool_call_id ? ` for ${msg.tool_call_id}` : ""}:\n${textOfContent(msg.content)}` })
|
||||
continue
|
||||
}
|
||||
const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : []
|
||||
if (calls.length) {
|
||||
const content = textOfContent(msg.content)
|
||||
const callText = calls
|
||||
.map((call) => {
|
||||
const name = call?.function?.name || call?.name || "tool"
|
||||
const args = call?.function?.arguments ?? call?.arguments ?? "{}"
|
||||
return `Tool call requested: ${name} ${typeof args === "string" ? args : JSON.stringify(args)}`
|
||||
})
|
||||
.join("\n")
|
||||
out.push({ role: msg.role || "assistant", content: content ? `${content}\n${callText}` : callText })
|
||||
continue
|
||||
}
|
||||
out.push({ role: msg.role || "user", content: textOfContent(msg.content) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function messagesWithToolInstruction(messages, tools, toolChoice) {
|
||||
const instruction = buildToolInstruction(tools, toolChoice)
|
||||
return [{ role: "system", content: instruction }, ...flattenMessagesForPrompt(messages), { role: "system", content: instruction }]
|
||||
}
|
||||
|
||||
const parseJsonLoose = (text) => {
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// the reply text → OpenAI tool_calls. The whole reply must be the call
|
||||
// JSON — a bare object or a single fenced block; an example quoted inside
|
||||
// prose is not a call. Unknown names are dropped; a drifted name case is
|
||||
// matched back to the declaration; a call missing a required arg is dropped
|
||||
// too (half a call fails at the agent anyway, and a forced tool_choice gets
|
||||
// its retry)
|
||||
function toolCallsFromText(text, tools, toolChoice) {
|
||||
if (normalizeToolChoice(toolChoice).mode === "none") return []
|
||||
if (!Array.isArray(tools) || tools.length === 0) return []
|
||||
const raw = String(text ?? "").trim()
|
||||
if (!raw) return []
|
||||
const fenced = raw.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)
|
||||
const candidate = fenced ? fenced[1].trim() : raw
|
||||
const parsed = parseJsonLoose(candidate)
|
||||
if (!parsed || typeof parsed !== "object") return []
|
||||
let items = Array.isArray(parsed)
|
||||
? parsed
|
||||
: Array.isArray(parsed.tool_calls)
|
||||
? parsed.tool_calls
|
||||
: Array.isArray(parsed.tool_uses)
|
||||
? parsed.tool_uses
|
||||
: []
|
||||
// a bare object is one call only when it actually carries arguments —
|
||||
// {"name":"Read"} alone reads like an answer, not a call
|
||||
if (!items.length) {
|
||||
const bare = parsed.function?.name
|
||||
? { name: parsed.function.name, arguments: parsed.function.arguments }
|
||||
: parsed
|
||||
if ((bare.name || bare.tool) && bare.arguments !== undefined) items = [bare]
|
||||
}
|
||||
const known = new Map(tools.map((t) => [toolNameOf(t).toLowerCase(), toolNameOf(t)]).filter(([k]) => k))
|
||||
const choice = normalizeToolChoice(toolChoice)
|
||||
const out = []
|
||||
for (const call of items) {
|
||||
const rawName = call?.name || call?.tool || call?.function?.name || ""
|
||||
const name = known.get(String(rawName).toLowerCase())
|
||||
if (!name) continue
|
||||
if (choice.mode === "named" && name !== choice.name) continue
|
||||
let args = call?.arguments ?? call?.input ?? call?.parameters ?? call?.function?.arguments ?? {}
|
||||
if (typeof args === "string") {
|
||||
const p = parseJsonLoose(args)
|
||||
args = p && typeof p === "object" ? p : { value: args }
|
||||
}
|
||||
if (!args || typeof args !== "object") args = {}
|
||||
const schema = toolParamsOf(tools.find((t) => toolNameOf(t) === name))
|
||||
const required = Array.isArray(schema?.required) ? schema.required : []
|
||||
if (required.some((k) => args[k] === undefined)) continue
|
||||
out.push({
|
||||
id: `call_${Date.now().toString(36)}_${out.length}`,
|
||||
type: "function",
|
||||
function: { name, arguments: JSON.stringify(args) },
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// the gateway sometimes answers with an HTML page (a WAF or a rate limit);
|
||||
// surface that as what it is instead of a bare JSON parse error
|
||||
function friendlyUpstreamMessage(e) {
|
||||
const m = String(e?.message ?? e)
|
||||
return /JSON Parse error|Unrecognized token|Unexpected token '<'/i.test(m) || /^\s*</.test(m)
|
||||
? m + "(妙手网关返回了非 JSON 页面 —— 多为限流或临时故障;超大 prompt 也可能触发,稍等重试)"
|
||||
: m
|
||||
}
|
||||
|
||||
// runConversation: round → event(running) → turn(SSE), yielding OpenAI-shaped
|
||||
// deltas from the cumulative frames (the proxy's catpawComplete, as a stream)
|
||||
async function* runConversation(token, chat, signal, modelType = modelTypeOf(chat.model)) {
|
||||
@@ -430,15 +629,14 @@ export async function CatPawAuthPlugin({ client } = {}) {
|
||||
}
|
||||
if (!Array.isArray(chat.messages) || chat.messages.length === 0)
|
||||
return errorResponse(400, "messages is required")
|
||||
// the flattened one-text prompt the conversation protocol carries
|
||||
// has no room for tool schemas, tool results or image parts: a
|
||||
// request carrying any of them would get an answer that never
|
||||
// calls a tool and never sees the image, with nothing saying why
|
||||
// — refuse it instead (tool continuation is a later phase)
|
||||
if (Array.isArray(chat.tools) && chat.tools.length > 0)
|
||||
return errorResponse(400, "this provider cannot run tools: the conversation protocol takes one flattened text prompt, so tool definitions would be silently dropped (refused rather than answered wrongly)")
|
||||
if (chat.messages.some((m) => m.role === "tool" || (Array.isArray(m.content) && m.content.some((c) => c?.type === "tool_call" || c?.type === "tool_use" || c?.type === "tool_result"))))
|
||||
return errorResponse(400, "this provider cannot continue a tool call: the conversation protocol takes one flattened text prompt, so tool results would be silently dropped (refused rather than answered wrongly)")
|
||||
// tools ride as instructions over the flattened text prompt and
|
||||
// the reply is parsed back into OpenAI tool_calls (see
|
||||
// messagesWithToolInstruction / toolCallsFromText); a forced
|
||||
// tool_choice gets one explicit retry. Images still cannot ride
|
||||
// along a text-only prompt: refuse them instead of dropping them.
|
||||
const toolChoiceMode = normalizeToolChoice(chat.tool_choice).mode
|
||||
const wantsTools = toolChoiceMode !== "none" && Array.isArray(chat.tools) && chat.tools.length > 0
|
||||
const hasToolParts = chat.messages.some((m) => m.role === "tool" || (Array.isArray(m.content) && m.content.some((c) => c?.type === "tool_call" || c?.type === "tool_use" || c?.type === "tool_result")))
|
||||
// image_url is what @ai-sdk/openai-compatible actually sends
|
||||
// ({"type":"image_url","image_url":{…}}); input_image is the
|
||||
// responses-API shape some clients carry over
|
||||
@@ -483,6 +681,197 @@ export async function CatPawAuthPlugin({ client } = {}) {
|
||||
const id = `chatcmpl-${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`
|
||||
const created = Math.floor(Date.now() / 1000)
|
||||
|
||||
// tools: inject the instruction, run the conversation, parse the
|
||||
// reply back into tool_calls. Streaming holds the reply back only
|
||||
// while it still reads as the strict JSON a tool call must be —
|
||||
// the moment it reads as prose it flushes and streams live, so
|
||||
// agents see bytes during long turns. Tool results without a
|
||||
// tools array still ride along (as text); they are just
|
||||
// flattened, with nothing to parse.
|
||||
if (wantsTools || hasToolParts) {
|
||||
const baseMessages = wantsTools
|
||||
? messagesWithToolInstruction(chat.messages ?? [], chat.tools, chat.tool_choice)
|
||||
: flattenMessagesForPrompt(chat.messages ?? [])
|
||||
const runTurn = async (messages) => {
|
||||
let text = ""
|
||||
let reasoning = ""
|
||||
for await (const ev of runConversation(token, { ...chat, messages }, init.signal, spec?.type)) {
|
||||
if (ev.delta) text += ev.delta
|
||||
if (ev.reasoningDelta) reasoning += ev.reasoningDelta
|
||||
if (ev.done) {
|
||||
text = ev.text
|
||||
reasoning = ev.reasoning
|
||||
}
|
||||
}
|
||||
return { text, reasoning }
|
||||
}
|
||||
if (!chat.stream) {
|
||||
// buffered: collect the whole turn, parse, retry once if a
|
||||
// forced tool_choice went unanswered
|
||||
let text = ""
|
||||
let reasoning = ""
|
||||
let calls = []
|
||||
try {
|
||||
const out = await runTurn(baseMessages)
|
||||
text = out.text
|
||||
reasoning = out.reasoning
|
||||
if (wantsTools) {
|
||||
calls = toolCallsFromText(text, chat.tools, chat.tool_choice)
|
||||
if (!calls.length && isToolChoiceRequired(chat.tool_choice)) {
|
||||
// one explicit retry: the failed reply rides along as
|
||||
// an assistant turn, since the retry line alone refers
|
||||
// to something the model cannot see
|
||||
const retried = await runTurn([
|
||||
...baseMessages,
|
||||
{ role: "assistant", content: text },
|
||||
{ role: "user", content: forcedToolRetryMessage(chat.tool_choice) },
|
||||
])
|
||||
text = retried.text
|
||||
reasoning = retried.reasoning
|
||||
calls = toolCallsFromText(text, chat.tools, chat.tool_choice)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
const message = friendlyUpstreamMessage(e)
|
||||
return errorResponse(message.includes("401") ? 401 : 502, message)
|
||||
}
|
||||
const message = {
|
||||
role: "assistant",
|
||||
content: calls.length ? null : text,
|
||||
...(calls.length ? { tool_calls: calls } : {}),
|
||||
...(reasoning ? { reasoning_content: reasoning } : {}),
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
id,
|
||||
object: "chat.completion",
|
||||
created,
|
||||
model,
|
||||
choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : "stop" }],
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
)
|
||||
}
|
||||
|
||||
// streaming: for a forced tool_choice the whole reply is held
|
||||
// (keep-alives feed the idle timeout) so the promised retry is
|
||||
// always possible; otherwise only the JSON-shaped head is held
|
||||
// and prose flushes and streams live. The hold matters because
|
||||
// a tool call split into content deltas can't be un-sent.
|
||||
const forced = wantsTools && isToolChoiceRequired(chat.tool_choice)
|
||||
const encoder = new TextEncoder()
|
||||
const sse = (delta, finish, reasoningDelta) => {
|
||||
const choices = [{ index: 0, delta: {}, finish_reason: finish ?? null }]
|
||||
if (delta) choices[0].delta.content = delta
|
||||
if (reasoningDelta) choices[0].delta.reasoning_content = reasoningDelta
|
||||
return encoder.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices })}\n\n`)
|
||||
}
|
||||
const toolChunk = (part, finish) =>
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { tool_calls: [part] }, finish_reason: finish ?? null }] })}\n\n`,
|
||||
)
|
||||
const doneFrame = encoder.encode("data: [DONE]\n\n")
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
let closed = false
|
||||
let ka = null
|
||||
const halt = () => {
|
||||
if (ka) {
|
||||
clearInterval(ka)
|
||||
ka = null
|
||||
}
|
||||
}
|
||||
const push = (bytes) => {
|
||||
if (closed) return
|
||||
try {
|
||||
controller.enqueue(bytes)
|
||||
} catch {
|
||||
closed = true
|
||||
halt()
|
||||
}
|
||||
}
|
||||
const stop = () => {
|
||||
halt()
|
||||
if (!closed) {
|
||||
try {
|
||||
controller.close()
|
||||
} catch {}
|
||||
closed = true
|
||||
}
|
||||
}
|
||||
// the gateway can think a long while before the first
|
||||
// frame; SSE comments keep the agent's idle timeout fed
|
||||
ka = setInterval(() => push(encoder.encode(": ka\n\n")), 3_000)
|
||||
init.signal?.addEventListener("abort", () => stop())
|
||||
push(sse(null, null)) // the role frame
|
||||
let pending = "" // held back: still could be the tool JSON
|
||||
let committed = false // decided prose — streaming live from here
|
||||
let fullText = ""
|
||||
let calls = []
|
||||
try {
|
||||
for await (const ev of runConversation(token, { ...chat, messages: baseMessages }, init.signal, spec?.type)) {
|
||||
if (closed) return
|
||||
if (ev.reasoningDelta) push(sse(null, null, ev.reasoningDelta))
|
||||
if (ev.delta) {
|
||||
fullText += ev.delta
|
||||
if (committed || !wantsTools) push(sse(ev.delta))
|
||||
else if (forced) {
|
||||
// held whole: the promised retry must stay possible
|
||||
pending += ev.delta
|
||||
} else {
|
||||
pending += ev.delta
|
||||
const head = pending.trimStart()
|
||||
if (head !== "" && !head.startsWith("{") && !head.startsWith("```")) {
|
||||
// reads as prose: flush everything and go live
|
||||
committed = true
|
||||
push(sse(pending))
|
||||
pending = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ev.done) fullText = ev.text
|
||||
}
|
||||
if (wantsTools && !committed) {
|
||||
calls = toolCallsFromText(fullText, chat.tools, chat.tool_choice)
|
||||
if (!calls.length && forced) {
|
||||
// nothing streamed yet, so a retry is invisible to
|
||||
// the agent; the failed reply rides along as an
|
||||
// assistant turn, since the retry line alone refers
|
||||
// to something the model cannot see
|
||||
const retried = await runTurn([
|
||||
...baseMessages,
|
||||
{ role: "assistant", content: fullText },
|
||||
{ role: "user", content: forcedToolRetryMessage(chat.tool_choice) },
|
||||
])
|
||||
fullText = retried.text
|
||||
calls = toolCallsFromText(fullText, chat.tools, chat.tool_choice)
|
||||
}
|
||||
}
|
||||
if (calls.length) {
|
||||
calls.forEach((call, index) => {
|
||||
push(toolChunk({ index, id: call.id, type: "function", function: { name: call.function.name, arguments: "" } }))
|
||||
push(toolChunk({ index, function: { arguments: call.function.arguments } }))
|
||||
})
|
||||
push(sse(null, "tool_calls"))
|
||||
} else {
|
||||
// prose that was held (it started JSON-shaped but never
|
||||
// parsed) still goes out — answering beats silence
|
||||
if (!committed && fullText) push(sse(fullText))
|
||||
push(sse(null, "stop"))
|
||||
}
|
||||
} catch (e) {
|
||||
push(encoder.encode(`data: ${JSON.stringify({ error: { message: friendlyUpstreamMessage(e) } })}\n\n`))
|
||||
push(doneFrame)
|
||||
stop()
|
||||
return
|
||||
}
|
||||
push(doneFrame)
|
||||
stop()
|
||||
},
|
||||
})
|
||||
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
|
||||
if (chat.stream) {
|
||||
const encoder = new TextEncoder()
|
||||
const chunk = (delta, finish, reasoningDelta) => {
|
||||
|
||||
@@ -202,25 +202,414 @@ describe("chat", () => {
|
||||
expect(text).toContain("vendor broke")
|
||||
})
|
||||
|
||||
test("a request carrying tools is refused with a clear 400", async () => {
|
||||
test("a tool request is answered with parsed tool_calls (non-stream)", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: { command: "ls" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: callText }] } },
|
||||
{ message: { content: [{ type: "text", text: callText }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "longcat-2.0", messages: [{ role: "user", content: "hi" }], tools: [{ type: "function", function: { name: "f" } }] }),
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "list the files" }],
|
||||
tools: [{ type: "function", function: { name: "Bash", description: "run a shell command", parameters: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } } }],
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.error.message).toContain("cannot run tools")
|
||||
expect(body.choices[0].finish_reason).toBe("tool_calls")
|
||||
expect(body.choices[0].message.tool_calls[0].function.name).toBe("Bash")
|
||||
expect(JSON.parse(body.choices[0].message.tool_calls[0].function.arguments)).toEqual({ command: "ls" })
|
||||
// the instruction rode in the flattened prompt
|
||||
expect(fake.state.conversations.at(-1).prompt).toContain("Bash")
|
||||
expect(fake.state.rounds).toBe(1)
|
||||
})
|
||||
|
||||
test("a request carrying tool results is refused, images are refused", async () => {
|
||||
test("tool results ride as text instead of a 400", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [
|
||||
{ role: "user", content: "list the files" },
|
||||
{ role: "assistant", tool_calls: [{ id: "c1", function: { name: "Bash", arguments: "{\"command\":\"ls\"}" } }] },
|
||||
{ role: "tool", tool_call_id: "c1", content: "a.txt" },
|
||||
],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].message.content).toBeTruthy()
|
||||
expect(fake.state.conversations.at(-1).prompt).toContain("Tool result")
|
||||
})
|
||||
|
||||
test("tool_choice=required retries once when the reply has no call", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: { command: "ls" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[{ message: { content: [{ type: "text", text: "我直接说明一下" }] }, finished: true }],
|
||||
[{ message: { content: [{ type: "text", text: callText }] }, finished: true }],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "run ls" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
tool_choice: "required",
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(fake.state.rounds).toBe(2)
|
||||
expect(body.choices[0].message.tool_calls[0].function.name).toBe("Bash")
|
||||
})
|
||||
|
||||
test("tool_choice none keeps the plain passthrough", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
tool_choice: "none",
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(fake.state.rounds).toBe(1)
|
||||
expect(fake.state.conversations.at(-1).prompt).not.toContain("Available tools")
|
||||
})
|
||||
|
||||
test("a streaming tool request synthesizes tool_calls deltas", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: { command: "ls" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: callText }] } },
|
||||
{ message: { content: [{ type: "text", text: callText }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "list the files" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const text = await res.text()
|
||||
expect(text).toContain('"tool_calls"')
|
||||
expect(text).toContain('"finish_reason":"tool_calls"')
|
||||
expect(text.endsWith("data: [DONE]\n\n")).toBe(true)
|
||||
})
|
||||
|
||||
test("a streaming tool request with a prose reply streams content, not tool_calls", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const text = await res.text()
|
||||
// deltas流式逐字输出,逐字断言而不是拼好的整句
|
||||
expect(text).toContain("收到")
|
||||
expect(text).toContain('"finish_reason":"stop"')
|
||||
expect(text).not.toContain('"tool_calls"')
|
||||
})
|
||||
|
||||
test("streaming + tool_choice=required + prose twice: the retry runs, then text goes out as text", async () => {
|
||||
fake.state.turnFramesQueue = [
|
||||
[{ message: { content: [{ type: "text", text: "我直接说明" }] }, finished: true }],
|
||||
[{ message: { content: [{ type: "text", text: "我还是直接说明吧" }] }, finished: true }],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "run ls" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
stream: true,
|
||||
tool_choice: "required",
|
||||
}),
|
||||
})
|
||||
const text = await res.text()
|
||||
expect(fake.state.rounds).toBe(2)
|
||||
expect(text).toContain("我还是直接说明吧")
|
||||
expect(text).toContain('"finish_reason":"stop"')
|
||||
expect(text).not.toContain('"tool_calls"')
|
||||
// the failed first reply rides along so the retry can refer to it
|
||||
const second = fake.state.conversations.at(-1).prompt
|
||||
expect(second).toContain("我直接说明")
|
||||
expect(second).toContain("did not include a valid tool call")
|
||||
})
|
||||
|
||||
test("a truncated JSON head in streaming still flushes as content", async () => {
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: '{"tool_calls":[{"name":"Bash"' }] } },
|
||||
{ message: { content: [{ type: "text", text: '{"tool_calls":[{"name":"Bash"' }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "list files" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
const text = await res.text()
|
||||
expect(res.status).toBe(200)
|
||||
expect(text).toContain('"finish_reason":"stop"')
|
||||
expect(text).not.toContain('"finish_reason":"tool_calls"')
|
||||
})
|
||||
|
||||
test("multiple calls in one reply all come out", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: { command: "ls" } }, { name: "Bash", arguments: { command: "pwd" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: callText }] } },
|
||||
{ message: { content: [{ type: "text", text: callText }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "ls and pwd" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].message.tool_calls.length).toBe(2)
|
||||
expect(JSON.parse(body.choices[0].message.tool_calls[1].function.arguments)).toEqual({ command: "pwd" })
|
||||
})
|
||||
|
||||
test("an unknown tool name is dropped, not answered as text", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "TotallyUnknown", arguments: {} }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: callText }] } },
|
||||
{ message: { content: [{ type: "text", text: callText }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].finish_reason).toBe("stop")
|
||||
expect(body.choices[0].message.content).toContain("TotallyUnknown")
|
||||
})
|
||||
|
||||
test("a drifted name case is matched back to the declaration", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "bash", arguments: { command: "ls" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: callText }] } },
|
||||
{ message: { content: [{ type: "text", text: callText }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "ls" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].message.tool_calls[0].function.name).toBe("Bash")
|
||||
})
|
||||
|
||||
test("a named tool_choice whose reply calls another tool gets the retry", async () => {
|
||||
const wrongText = JSON.stringify({ tool_calls: [{ name: "Unknown", arguments: {} }] })
|
||||
const rightText = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: { command: "ls" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[{ message: { content: [{ type: "text", text: wrongText }] } }, { message: { content: [{ type: "text", text: wrongText }] }, finished: true }],
|
||||
[{ message: { content: [{ type: "text", text: rightText }] } }, { message: { content: [{ type: "text", text: rightText }] }, finished: true }],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "run ls" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
tool_choice: { type: "function", function: { name: "Bash" } },
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(fake.state.rounds).toBe(2)
|
||||
expect(body.choices[0].message.tool_calls[0].function.name).toBe("Bash")
|
||||
})
|
||||
|
||||
test("a bare object without arguments is an answer, not a call", async () => {
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: '{"name":"Bash"}' }] } },
|
||||
{ message: { content: [{ type: "text", text: '{"name":"Bash"}' }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].finish_reason).toBe("stop")
|
||||
expect(body.choices[0].message.content).toContain('"name":"Bash"')
|
||||
})
|
||||
|
||||
test("a quoted example inside prose is not a call", async () => {
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: '可以用 Bash,例如 {"name":"Bash","arguments":{"command":"rm -rf x"}} 之类' }] } },
|
||||
{ message: { content: [{ type: "text", text: '可以用 Bash,例如 {"name":"Bash","arguments":{"command":"rm -rf x"}} 之类' }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].finish_reason).toBe("stop")
|
||||
expect(body.choices[0].message.content).toContain("例如")
|
||||
})
|
||||
|
||||
test("a call missing a required arg is dropped", async () => {
|
||||
const callText = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: {} }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: callText }] } },
|
||||
{ message: { content: [{ type: "text", text: callText }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash", parameters: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } } }],
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.choices[0].finish_reason).toBe("stop")
|
||||
expect(body.choices[0].message.content).toContain("tool_calls")
|
||||
})
|
||||
|
||||
test("a call JSON split across cumulative frames still becomes a call", async () => {
|
||||
// frame 1 cuts mid-token — the head-hold in the streaming tool path
|
||||
// exists for exactly this shape
|
||||
const whole = JSON.stringify({ tool_calls: [{ name: "Bash", arguments: { command: "ls" } }] })
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: whole.slice(0, 19) }] } },
|
||||
{ message: { content: [{ type: "text", text: whole }] }, finished: true },
|
||||
],
|
||||
]
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "list files" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const text = await res.text()
|
||||
expect(text).toContain('"finish_reason":"tool_calls"')
|
||||
expect(text).toContain('"name":"Bash"')
|
||||
expect(text.endsWith("data: [DONE]\n\n")).toBe(true)
|
||||
})
|
||||
|
||||
test("the keep-alive interval is torn down when the agent cancels mid-turn", async () => {
|
||||
fake.state.turnFramesQueue = [
|
||||
[
|
||||
{ message: { content: [{ type: "text", text: "你" }] } },
|
||||
{ message: { content: [{ type: "text", text: "你好" }] }, finished: true },
|
||||
],
|
||||
]
|
||||
fake.state.turnDelayMs = 400
|
||||
let created = 0
|
||||
let cleared = 0
|
||||
const origSet = globalThis.setInterval
|
||||
const origClear = globalThis.clearInterval
|
||||
globalThis.setInterval = (fn, ms) => {
|
||||
created++
|
||||
return origSet(fn, ms)
|
||||
}
|
||||
globalThis.clearInterval = (t) => {
|
||||
cleared++
|
||||
return origClear(t)
|
||||
}
|
||||
try {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "longcat-2.0",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash" } }],
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
const reader = res.body.getReader()
|
||||
await reader.read() // the role frame, then cancel mid-turn
|
||||
await reader.cancel()
|
||||
// the next delta arrives after the fake's delay; the push that hits a
|
||||
// cancelled stream is where the interval must be cleared
|
||||
await new Promise((r) => setTimeout(r, 800))
|
||||
expect(created).toBeGreaterThanOrEqual(1)
|
||||
expect(cleared).toBeGreaterThanOrEqual(created)
|
||||
} finally {
|
||||
globalThis.setInterval = origSet
|
||||
globalThis.clearInterval = origClear
|
||||
}
|
||||
})
|
||||
|
||||
test("tool results ride as text, images are refused", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const toolRes = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "longcat-2.0", messages: [{ role: "user", content: "hi" }, { role: "tool", content: "result" }] }),
|
||||
})
|
||||
expect(toolRes.status).toBe(400)
|
||||
expect((await toolRes.json()).error.message).toContain("cannot continue a tool call")
|
||||
expect(toolRes.status).toBe(200)
|
||||
const imgRes = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "longcat-2.0", messages: [{ role: "user", content: [{ type: "image", image_url: { url: "data:image/png;base64,AAAA" } }] }] }),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-catpaw-auth",
|
||||
"version": "0.1.4",
|
||||
"version": "0.2.0",
|
||||
"description": "OpenCode & Magpie provider plugin for Meituan's 妙手 CatPaw (ai.catpaw.meituan.com): web sign-in or the desktop client's saved credentials, chat through the round/event/turn protocol, models and credit balance",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
Reference in New Issue
Block a user