codearts 0.2.2: tool names over 64 characters go cut and unique, and come back as the agent's own (#432)
CodeArts turned away ZCode's android emulator MCP tool, mcp__plugin_android-emulator_android-emulator__android_discover_project (71 characters), with "Function name [...] length over limit, maximum is 64 (InferHub.001001017.413)", so every ZCode chat with that MCP on failed. A name over 64 now goes as magpie's FlatName cuts one: its first 55 characters, "_" and 8 hex of its SHA-256 (64 in all). It is cut in every place the body names a tool: tools, functions, tool_choice, function_call, the history's tool_calls and a tool message's name, so the history keeps matching its tool on every turn. A cut that equals another tool's own name, or another cut, is cut again with a salt. The answer gets the agent's names back: in a folded (non-streaming) reply and in the stream, where a name the gateway sends whole, repeated in a later delta, or in pieces (the part past 55 held until the name is whole) is put back. Events that name no cut tool pass byte for byte, and a body whose names all fit is not touched at all. Run: packages/codearts `bun test` (114 pass) and `node --test index.test.mjs` (114 pass); `bun scripts/check.mjs` all green. New tests use the reporter's literal tool name, two names alike for 55 characters, a short tool named exactly like a long one's cut, a stream round trip through the loader's fetch (whole name, name in three pieces across the 55th character, a name that fits), a gateway repeating the name, and a folded reply. Broken by hand: restoreToolNamesInStream returning the stream as it came (stream and repeat tests red); no salt on a collision (collision test red); no shortening in prepareChatBody (4 tests red). Not tried: a real CodeArts account (its refresh token is single-use, so no live sign-in was copied into a sandbox); whether CodeArts ever sends a tool name in pieces (handled, not seen).
This commit is contained in:
@@ -66,6 +66,10 @@ signing in, a short built-in catalog stands in.
|
||||
- Errors the gateway puts inside a `200` stream (spent quota, unknown model) come back as
|
||||
`429` / `400` / `502` with the vendor's words. The `codearts/` prefix is stripped and output
|
||||
budgets are clamped to 65536.
|
||||
- CodeArts takes tool names of up to 64 characters. A longer one (an MCP tool such as
|
||||
`mcp__plugin_android-emulator_android-emulator__android_discover_project`) goes as its first
|
||||
55 characters, `_` and 8 hex of its SHA-256, and the tool calls in the answer, streamed or
|
||||
not, carry the agent's own name again.
|
||||
|
||||
## Usage and check-in
|
||||
|
||||
@@ -121,7 +125,8 @@ magpie 里使用其 GLM、DeepSeek、openPangu 等模型。provider id:`codear
|
||||
`opengw.developer.huaweicloud.com`),发往其他地址(如改过的 `api`)的请求在凭据发出前就被拒绝,签名请求和令牌请求都不跟随重定向;像客户端一样发送 `x-ot-session-id` 会话头(每账号一个会话),账号内
|
||||
在途请求不超过 3 个,`TM.00001041` 退避重试,网关排队时按客户端的方式等待;总是以流式请求上游(码道
|
||||
只对流式回答计量积分),调用方要非流式时折叠回 JSON;默认注入 `thinking: { type: "enabled" }`,思考与
|
||||
正文分开;200 里内嵌的错误换算为 `429` / `400` / `502` 并带厂商原话。
|
||||
正文分开;200 里内嵌的错误换算为 `429` / `400` / `502` 并带厂商原话;码道只接受不超过 64 个字符的工具名,
|
||||
更长的(如 MCP 工具名)发出时缩为前 55 个字符 + `_` + 8 位 SHA-256,回答(流式与非流式)里的工具调用再换回原名。
|
||||
- **用量与签到**:总积分决定账号是否可用,其余积分桶只做明细;另有每日免费额度窗口。各批积分的到期
|
||||
时间读自码道控制台同一批接口,读不到时退回插件的签到账本 `~/.config/magpie/codearts-checkins.json`
|
||||
(这部分仍在用更多账号验证,请以控制台为准)。`auth.checkin` 与客户端「限时福利 → 每日领取」一致
|
||||
|
||||
+218
-7
@@ -42,6 +42,7 @@
|
||||
// replaces its browser sign-in + bearer-token requests with CodeArts' OAuth +
|
||||
// signed-request flow. See README.md.
|
||||
|
||||
import { createHash } from "node:crypto"
|
||||
import { createServer } from "node:http"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
@@ -800,12 +801,15 @@ function isRegularModel(model, state) {
|
||||
* - the output budget inside the gateway's 65536;
|
||||
* - always `stream: true`. CodeArts meters only streamed answers — a
|
||||
* non-streaming 200 returns tokens yet leaves the credits untouched — so a
|
||||
* caller that asked for JSON gets the stream folded back (`fold`).
|
||||
* caller that asked for JSON gets the stream folded back (`fold`);
|
||||
* - tool names within the gateway's 64 characters (`names`, short → the
|
||||
* agent's own, to put back in the answer; null when none was cut).
|
||||
* A body that is not a chat (no `model` + `messages`) gives null.
|
||||
*/
|
||||
function prepareChatBody(parsed, { thinking = true } = {}) {
|
||||
if (!parsed || typeof parsed.model !== "string" || !Array.isArray(parsed.messages)) return null
|
||||
const body = { ...parsed, model: upstreamModelId(parsed.model) }
|
||||
const names = shortenToolNames(body)
|
||||
// `injected`: ours to take back should a model refuse the parameter.
|
||||
const injected = thinking && body.thinking === undefined
|
||||
if (injected) body.thinking = ENABLE_THINKING
|
||||
@@ -814,7 +818,208 @@ function prepareChatBody(parsed, { thinking = true } = {}) {
|
||||
}
|
||||
const fold = body.stream !== true
|
||||
body.stream = true
|
||||
return { body, fold, injected }
|
||||
return { body, fold, injected, names }
|
||||
}
|
||||
|
||||
// ---- tool names over the gateway's limit (#432) -----------------------------
|
||||
|
||||
/**
|
||||
* CodeArts turns away a function name over 64 characters ("Function name
|
||||
* […] length over limit, maximum is 64", InferHub.001001017.413), and an
|
||||
* agent's MCP tools are often longer: ZCode's android emulator tool is
|
||||
* `mcp__plugin_android-emulator_android-emulator__android_discover_project`,
|
||||
* 71. A longer name goes as magpie's FlatName cuts one: its first 55
|
||||
* characters, `_`, and 8 hex of its SHA-256, 64 in all. The same name is cut
|
||||
* the same way on every request, so a call in the history keeps matching its
|
||||
* tool, and two names that start alike differ in their hash.
|
||||
*/
|
||||
const TOOL_NAME_LIMIT = 64
|
||||
const TOOL_NAME_KEEP = 55
|
||||
|
||||
function cutToolName(name, salt) {
|
||||
let head = name.slice(0, TOOL_NAME_KEEP)
|
||||
// never half a surrogate pair
|
||||
if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1)
|
||||
const hex = createHash("sha256").update(salt ? `${name}\u0000${salt}` : name).digest("hex")
|
||||
return `${head}_${hex.slice(0, 8)}`
|
||||
}
|
||||
|
||||
/** Every place a body names a tool: its tools, its history's calls, tool_choice. */
|
||||
function toolNameSlots(body) {
|
||||
const slots = []
|
||||
const slot = (obj, key) => {
|
||||
if (obj && typeof obj === "object" && typeof obj[key] === "string") slots.push({ obj, key })
|
||||
}
|
||||
for (const t of Array.isArray(body.tools) ? body.tools : []) slot(t?.function, "name")
|
||||
for (const f of Array.isArray(body.functions) ? body.functions : []) slot(f, "name")
|
||||
const choice = body.tool_choice
|
||||
if (choice && typeof choice === "object") slot(choice.function, "name")
|
||||
if (body.function_call && typeof body.function_call === "object") slot(body.function_call, "name")
|
||||
for (const m of Array.isArray(body.messages) ? body.messages : []) {
|
||||
if (!m || typeof m !== "object") continue
|
||||
for (const c of Array.isArray(m.tool_calls) ? m.tool_calls : []) slot(c?.function, "name")
|
||||
slot(m.function_call, "name")
|
||||
if (m.role === "tool" || m.role === "function") slot(m, "name")
|
||||
}
|
||||
return slots
|
||||
}
|
||||
|
||||
/**
|
||||
* Cut every tool name over the limit in body, in place; the map of each cut
|
||||
* name to the agent's own, or null when every name fits. A cut name that is
|
||||
* another tool's own name, or another cut one's, is cut again with a salt,
|
||||
* so the map always leads back to one name.
|
||||
*/
|
||||
function shortenToolNames(body) {
|
||||
const slots = toolNameSlots(body)
|
||||
if (!slots.some((s) => s.obj[s.key].length > TOOL_NAME_LIMIT)) return null
|
||||
const taken = new Set(slots.map((s) => s.obj[s.key]).filter((n) => n.length <= TOOL_NAME_LIMIT))
|
||||
const short = new Map() // the agent's name → the one sent
|
||||
const names = new Map() // the one sent → the agent's name
|
||||
// In a fixed order, so the same names are cut alike on every request.
|
||||
const long = [...new Set(slots.map((s) => s.obj[s.key]).filter((n) => n.length > TOOL_NAME_LIMIT))].sort()
|
||||
for (const name of long) {
|
||||
let cut = cutToolName(name, 0)
|
||||
for (let salt = 1; taken.has(cut) || names.has(cut); salt += 1) cut = cutToolName(name, salt)
|
||||
short.set(name, cut)
|
||||
names.set(cut, name)
|
||||
}
|
||||
// In place: the body is signedFetch's own parse of the request.
|
||||
for (const s of slots) {
|
||||
const cut = short.get(s.obj[s.key])
|
||||
if (cut) s.obj[s.key] = cut
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
/** The agent's own names back in a whole completion's tool calls. */
|
||||
function restoreToolNames(completion, names) {
|
||||
if (!names) return completion
|
||||
for (const choice of Array.isArray(completion?.choices) ? completion.choices : []) {
|
||||
const msg = choice?.message
|
||||
if (!msg || typeof msg !== "object") continue
|
||||
for (const c of Array.isArray(msg.tool_calls) ? msg.tool_calls : []) {
|
||||
const name = c?.function?.name
|
||||
if (typeof name === "string" && names.has(name)) c.function.name = names.get(name)
|
||||
}
|
||||
if (msg.function_call && names.has(msg.function_call.name)) msg.function_call.name = names.get(msg.function_call.name)
|
||||
}
|
||||
return completion
|
||||
}
|
||||
|
||||
/**
|
||||
* A stream with the agent's own names back in its tool calls. A call's name
|
||||
* usually comes whole in one delta; should the gateway send it in pieces, the
|
||||
* pieces of a cut name past its first 55 characters (the part that differs
|
||||
* from the agent's) are held until the name is whole, then the rest of the
|
||||
* agent's name goes in their place. Events that name no cut tool pass as
|
||||
* they came, byte for byte.
|
||||
*/
|
||||
function restoreToolNamesInStream(stream, names) {
|
||||
if (!names) return stream
|
||||
const cuts = [...names.keys()]
|
||||
const calls = new Map() // `${choice}:${call}` → { got, sent }
|
||||
const enc = new TextEncoder()
|
||||
const dec = new TextDecoder()
|
||||
let pending = ""
|
||||
const named = (key, piece) => {
|
||||
const c = calls.get(key) ?? { got: "", sent: 0 }
|
||||
calls.set(key, c)
|
||||
// A whole cut name in one piece, the call's first or a gateway's repeat
|
||||
// of it in a later delta: the agent's name, whole.
|
||||
if (names.has(piece)) {
|
||||
const own = names.get(piece)
|
||||
c.got = own
|
||||
c.sent = own.length
|
||||
return own
|
||||
}
|
||||
c.got += piece
|
||||
let out
|
||||
if (names.has(c.got)) {
|
||||
const own = names.get(c.got)
|
||||
out = own.slice(c.sent)
|
||||
c.sent = own.length
|
||||
c.got = own // a whole name, matched once
|
||||
} else if (c.got.length < TOOL_NAME_LIMIT && cuts.some((cut) => cut.startsWith(c.got))) {
|
||||
const upTo = Math.min(c.got.length, TOOL_NAME_KEEP)
|
||||
out = upTo > c.sent ? c.got.slice(c.sent, upTo) : ""
|
||||
c.sent = Math.max(c.sent, upTo)
|
||||
} else {
|
||||
out = c.got.slice(c.sent)
|
||||
c.sent = c.got.length
|
||||
}
|
||||
return out
|
||||
}
|
||||
// what was held back of a name that never became whole
|
||||
const held = () => {
|
||||
const choices = []
|
||||
for (const [key, c] of calls) {
|
||||
if (c.sent >= c.got.length) continue
|
||||
const [ci, ti] = key.split(":").map(Number)
|
||||
choices.push({ index: ci, delta: { tool_calls: [{ index: ti, function: { name: c.got.slice(c.sent) } }] } })
|
||||
c.sent = c.got.length
|
||||
}
|
||||
return choices.length ? `data: ${JSON.stringify({ choices })}\n\n` : ""
|
||||
}
|
||||
const line = (l) => {
|
||||
const t = l.replace(/\r$/, "")
|
||||
if (!t.startsWith("data:")) return l
|
||||
const payload = t.slice(5).trim()
|
||||
if (payload === "[DONE]") return held() + l
|
||||
if (!payload.includes("tool_calls") && !payload.includes("function_call")) return l
|
||||
const ev = safeJson(payload)
|
||||
if (!ev || !Array.isArray(ev.choices)) return l
|
||||
let changed = false
|
||||
for (const [ci, choice] of ev.choices.entries()) {
|
||||
const delta = choice?.delta
|
||||
if (!delta || typeof delta !== "object") continue
|
||||
const index = Number.isInteger(choice.index) ? choice.index : ci
|
||||
for (const [k, call] of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []).entries()) {
|
||||
const fn = call?.function
|
||||
if (!fn || typeof fn.name !== "string") continue
|
||||
const out = named(`${index}:${Number.isInteger(call.index) ? call.index : k}`, fn.name)
|
||||
if (out !== fn.name) {
|
||||
fn.name = out
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (delta.function_call && typeof delta.function_call.name === "string") {
|
||||
const out = named(`${index}:fc`, delta.function_call.name)
|
||||
if (out !== delta.function_call.name) {
|
||||
delta.function_call.name = out
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed ? `data: ${JSON.stringify(ev)}${l.endsWith("\r") ? "\r" : ""}` : l
|
||||
}
|
||||
const reader = stream.getReader()
|
||||
return new ReadableStream({
|
||||
async pull(controller) {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) {
|
||||
let rest = pending + dec.decode()
|
||||
pending = ""
|
||||
if (rest) rest = line(rest)
|
||||
rest += held()
|
||||
if (rest) controller.enqueue(enc.encode(rest))
|
||||
controller.close()
|
||||
return
|
||||
}
|
||||
pending += dec.decode(value, { stream: true })
|
||||
const cut = pending.lastIndexOf("\n")
|
||||
if (cut < 0) continue
|
||||
const whole = pending.slice(0, cut)
|
||||
pending = pending.slice(cut + 1)
|
||||
controller.enqueue(enc.encode(whole.split("\n").map(line).join("\n") + "\n"))
|
||||
return
|
||||
}
|
||||
},
|
||||
cancel(reason) {
|
||||
return reader.cancel(reason)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ---- reading the gateway's answers -----------------------------------------
|
||||
@@ -1005,7 +1210,7 @@ function completionFromChunks(events) {
|
||||
}
|
||||
|
||||
/** Answer a caller that asked for JSON: read the whole stream, fold it. */
|
||||
async function foldAnswer(res, head) {
|
||||
async function foldAnswer(res, head, names = null) {
|
||||
let text = head.text
|
||||
if (head.reader) {
|
||||
for (;;) {
|
||||
@@ -1019,10 +1224,14 @@ async function foldAnswer(res, head) {
|
||||
headers.set("content-type", "application/json")
|
||||
const events = parseSseEvents(text)
|
||||
if (events.some((ev) => Array.isArray(ev.choices) && ev.choices.length > 0)) {
|
||||
return new Response(JSON.stringify(completionFromChunks(events)), { status: res.status, statusText: res.statusText, headers })
|
||||
return new Response(JSON.stringify(restoreToolNames(completionFromChunks(events), names)), { status: res.status, statusText: res.statusText, headers })
|
||||
}
|
||||
// The gateway answered JSON after all, or nothing at all.
|
||||
if (Array.isArray(safeJson(text)?.choices)) return new Response(text, { status: res.status, statusText: res.statusText, headers })
|
||||
const whole = safeJson(text)
|
||||
if (Array.isArray(whole?.choices)) {
|
||||
const body = names ? JSON.stringify(restoreToolNames(whole, names)) : text
|
||||
return new Response(body, { status: res.status, statusText: res.statusText, headers })
|
||||
}
|
||||
return errorResponse(502, errorCodeOf(text), firstOf(errorMessageOf(text), "the gateway returned an empty answer"))
|
||||
}
|
||||
|
||||
@@ -1352,9 +1561,10 @@ async function signedFetch(cred, input, init, context) {
|
||||
if (res.ok) {
|
||||
const head = await peekAnswer(res)
|
||||
if (!head.code) {
|
||||
if (chat.fold) return await foldAnswer(res, head)
|
||||
if (chat.fold) return await foldAnswer(res, head, chat.names)
|
||||
handedOver = true
|
||||
return new Response(replayBody(head, release), { status: res.status, statusText: res.statusText, headers: streamHeaders(res.headers) })
|
||||
const stream = restoreToolNamesInStream(replayBody(head, release), chat.names)
|
||||
return new Response(stream, { status: res.status, statusText: res.statusText, headers: streamHeaders(res.headers) })
|
||||
}
|
||||
text = head.text
|
||||
code = head.code
|
||||
@@ -2423,6 +2633,7 @@ export const _internal = {
|
||||
readGrants, recordGrant, readUnconfirmed, recordUnconfirmed, grantExpiry, grantBatches, soonestLapse, fetchCreditBatches,
|
||||
PACKAGE_CREDIT_PAGE_URL, OPS_CREDIT_OVERVIEW_URL, OPS_CREDIT_CAMPAIGN_URL,
|
||||
toBytes, isBenefitModel, prepareChatBody, signedFetch, signedGet,
|
||||
TOOL_NAME_LIMIT, cutToolName, shortenToolNames, restoreToolNames, restoreToolNamesInStream,
|
||||
parseSseEvents, errorCodeOf, errorMessageOf, isStaleCredential, isRateLimitCode, embeddedErrorStatus, classifyHead,
|
||||
peekAnswer, completionFromChunks, createConcurrencyGate, delay, retryDelayMs,
|
||||
isRegularModel, queueInfoOf, waitInQueue, TRACE_QUEUE_URL, SESSION_HEADER,
|
||||
|
||||
@@ -714,6 +714,133 @@ test("a folded answer keeps reasoning, tool calls and usage apart", async () =>
|
||||
assert.deepEqual(json.usage, { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 })
|
||||
})
|
||||
|
||||
// ---- tool names over CodeArts' 64 characters (#432) -------------------------
|
||||
|
||||
// The reporter's tool, word for word: ZCode's android emulator MCP, 71 long.
|
||||
const ANDROID_TOOL = "mcp__plugin_android-emulator_android-emulator__android_discover_project"
|
||||
const toolOf = (name) => ({ type: "function", function: { name, description: "d", parameters: { type: "object", properties: {} } } })
|
||||
const sentOf = (init) => JSON.parse(new TextDecoder().decode(init.body))
|
||||
|
||||
test("a tool name over 64 goes cut to 64: its first 55, _ and 8 hex of its SHA-256", async () => {
|
||||
assert.equal(ANDROID_TOOL.length, 71)
|
||||
const body = {
|
||||
model: "GLM-5.2",
|
||||
tools: [toolOf(ANDROID_TOOL), toolOf("read")],
|
||||
tool_choice: { type: "function", function: { name: ANDROID_TOOL } },
|
||||
messages: [
|
||||
{ role: "user", content: "find the project" },
|
||||
{ role: "assistant", content: "", tool_calls: [{ id: "c1", type: "function", function: { name: ANDROID_TOOL, arguments: "{}" } }] },
|
||||
{ role: "tool", tool_call_id: "c1", name: ANDROID_TOOL, content: "ok" },
|
||||
],
|
||||
}
|
||||
const { body: sent, names } = x.prepareChatBody(structuredClone(body))
|
||||
const hex = (await x.sha256Hex(new TextEncoder().encode(ANDROID_TOOL))).slice(0, 8)
|
||||
const cut = `${ANDROID_TOOL.slice(0, 55)}_${hex}`
|
||||
assert.equal(cut.length, 64)
|
||||
assert.equal(sent.tools[0].function.name, cut)
|
||||
assert.equal(sent.tools[1].function.name, "read")
|
||||
assert.equal(sent.tool_choice.function.name, cut)
|
||||
assert.equal(sent.messages[1].tool_calls[0].function.name, cut)
|
||||
assert.equal(sent.messages[2].name, cut)
|
||||
assert.deepEqual([...names], [[cut, ANDROID_TOOL]])
|
||||
// The same on the next request, so the history keeps matching its tool.
|
||||
assert.equal(x.prepareChatBody(structuredClone(body)).body.tools[0].function.name, cut)
|
||||
// Names that fit leave the body as it was, and nothing to put back.
|
||||
const fits = { model: "GLM-5.2", tools: [toolOf("read"), toolOf("x".repeat(64))], messages: [] }
|
||||
const plain = x.prepareChatBody(structuredClone(fits))
|
||||
assert.equal(plain.names, null)
|
||||
assert.deepEqual(plain.body.tools, fits.tools)
|
||||
})
|
||||
|
||||
test("cut names never collide: alike for 55, or the cut of one being another tool's own name", () => {
|
||||
const a = `${ANDROID_TOOL}_a_long_tail`
|
||||
const b = `${ANDROID_TOOL}_b_long_tail`
|
||||
const taken = x.cutToolName(a, 0) // a tool the agent itself calls by a's cut
|
||||
const { body, names } = x.prepareChatBody({ model: "GLM-5.2", tools: [toolOf(a), toolOf(b), toolOf(taken)], messages: [] })
|
||||
const sent = body.tools.map((t) => t.function.name)
|
||||
assert.equal(new Set(sent).size, 3)
|
||||
for (const n of sent) assert.ok(n.length <= x.TOOL_NAME_LIMIT, n)
|
||||
// the agent's own short name goes as it is; a's is cut again, with a salt
|
||||
assert.equal(sent[2], taken)
|
||||
assert.notEqual(sent[0], taken)
|
||||
assert.equal(sent[0].slice(0, 55), a.slice(0, 55))
|
||||
assert.equal(names.get(sent[0]), a)
|
||||
assert.equal(names.get(sent[1]), b)
|
||||
assert.equal(names.has(taken), false)
|
||||
})
|
||||
|
||||
test("a streamed tool call names the agent's tool again, whole or in pieces; other events pass byte for byte", async () => {
|
||||
const cred = await makeCred()
|
||||
const other = `${ANDROID_TOOL}_screenshot`
|
||||
const cutA = x.cutToolName(ANDROID_TOOL, 0)
|
||||
const cutB = x.cutToolName(other, 0)
|
||||
const sentBodies = []
|
||||
const head = sse({ id: "c3", model: "GLM-5.2", choices: [{ index: 0, delta: { role: "assistant", content: "" } }] })
|
||||
const stream = head + sse(
|
||||
// whole in one delta
|
||||
{ id: "c3", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_a", type: "function", function: { name: cutA, arguments: "" } }] } }] },
|
||||
{ id: "c3", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: '{"p":1}' } }] } }] },
|
||||
// in three pieces, one across the 55th character
|
||||
{ id: "c3", choices: [{ index: 0, delta: { tool_calls: [{ index: 1, id: "call_b", type: "function", function: { name: cutB.slice(0, 30) } }] } }] },
|
||||
{ id: "c3", choices: [{ index: 0, delta: { tool_calls: [{ index: 1, function: { name: cutB.slice(30, 60) } }] } }] },
|
||||
{ id: "c3", choices: [{ index: 0, delta: { tool_calls: [{ index: 1, function: { name: cutB.slice(60), arguments: "{}" } }] } }] },
|
||||
// a tool whose name fits
|
||||
{ id: "c3", choices: [{ index: 0, delta: { tool_calls: [{ index: 2, id: "call_c", type: "function", function: { name: "read", arguments: "{}" } }] } }] },
|
||||
{ id: "c3", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] },
|
||||
"[DONE]",
|
||||
)
|
||||
const fetcher = async (url, init) => {
|
||||
sentBodies.push(sentOf(init))
|
||||
return sseResponse(stream)
|
||||
}
|
||||
const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher })
|
||||
const loaded = await plugin.auth.loader(async () => makeAuth(cred))
|
||||
const res = await loaded.fetch(CHAT_URL, chatInit({
|
||||
model: "GLM-5.2", stream: true, tools: [toolOf(ANDROID_TOOL), toolOf(other), toolOf("read")], messages: [{ role: "user", content: "hi" }],
|
||||
}))
|
||||
// CodeArts was sent names it takes
|
||||
assert.deepEqual(sentBodies[0].tools.map((t) => t.function.name), [cutA, cutB, "read"])
|
||||
for (const t of sentBodies[0].tools) assert.ok(t.function.name.length <= 64)
|
||||
const text = await res.text()
|
||||
// what the agent's stream folds to: its own names
|
||||
const folded = x.completionFromChunks(x.parseSseEvents(text)).choices[0].message.tool_calls
|
||||
assert.deepEqual(folded.map((c) => c.function.name), [ANDROID_TOOL, other, "read"])
|
||||
assert.deepEqual(folded.map((c) => c.function.arguments), ['{"p":1}', "{}", "{}"])
|
||||
// no cut name reaches the agent; events naming no cut tool are unchanged
|
||||
assert.equal(text.includes(cutA) || text.includes(cutB), false)
|
||||
assert.ok(text.startsWith(head))
|
||||
assert.ok(text.endsWith('data: {"id":"c3","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\ndata: [DONE]\n\n'))
|
||||
})
|
||||
|
||||
test("a gateway that repeats a cut name in each delta still gives the agent's name", async () => {
|
||||
const cut = x.cutToolName(ANDROID_TOOL, 0)
|
||||
const names = new Map([[cut, ANDROID_TOOL]])
|
||||
const text = sse(
|
||||
{ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "c", function: { name: cut, arguments: "" } }] } }] },
|
||||
{ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { name: cut, arguments: "{}" } }] } }] },
|
||||
"[DONE]",
|
||||
)
|
||||
const out = await new Response(x.restoreToolNamesInStream(new Response(text).body, names)).text()
|
||||
const evs = x.parseSseEvents(out)
|
||||
assert.deepEqual(evs.map((e) => e.choices[0].delta.tool_calls[0].function.name), [ANDROID_TOOL, ANDROID_TOOL])
|
||||
})
|
||||
|
||||
test("a folded tool call names the agent's tool again", async () => {
|
||||
const cred = await makeCred()
|
||||
const cut = x.cutToolName(ANDROID_TOOL, 0)
|
||||
const stream = sse(
|
||||
{ id: "c4", model: "GLM-5.2", choices: [{ delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: cut, arguments: "{}" } }] } }] },
|
||||
{ id: "c4", choices: [{ delta: {}, finish_reason: "tool_calls" }] },
|
||||
"[DONE]",
|
||||
)
|
||||
let sent
|
||||
const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async (url, init) => { sent = sentOf(init); return sseResponse(stream) } })
|
||||
const loaded = await plugin.auth.loader(async () => makeAuth(cred))
|
||||
const json = await (await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", tools: [toolOf(ANDROID_TOOL)], messages: [] }))).json()
|
||||
assert.equal(sent.tools[0].function.name, cut)
|
||||
assert.deepEqual(json.choices[0].message.tool_calls, [{ id: "call_1", type: "function", function: { name: ANDROID_TOOL, arguments: "{}" } }])
|
||||
})
|
||||
|
||||
const capBody = JSON.stringify({ error_code: "TM.00001041", error_msg: "并发会话数已达上限(3个),请关闭部分会话后重试。" })
|
||||
|
||||
test("TM.00001041 as a 400 is retried, re-signed, until a session frees", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-codearts-auth",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"description": "Huawei Cloud CodeArts (码道) in OpenCode and magpie: its models through Huawei Cloud OAuth sign-in, signed requests, credit usage and the daily check-in (unofficial)",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user