diff --git a/README.md b/README.md index c3463f5..e70c48b 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ vendor service and makes its requests. The packages work in OpenCode and in | [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` | | [cline](packages/cline) | Cline (cline.bot): usage-billed models, ClinePass's and Cline's free ones, with Cline's device sign-in or an API key | `cline` | | [codearts](packages/codearts) | Huawei Cloud CodeArts (码道) coding plans (Trial, personal and enterprise credits), with Huawei Cloud OAuth sign-in (unofficial) | `codearts` | +| [comate](packages/comate) | Baidu's 文心快码 Comate (comate.baidu.com), with the Comate CLI's browser sign-in or a pasted license: live models and chat as a Comate agent turn (unofficial, not yet tried with a real account) | `comate` | | [commandcode](packages/commandcode) | Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams Pro) | `commandcode-plan` | | [copilot](packages/copilot) | GitHub Copilot on GitHub.com or GitHub Enterprise, with premium request or credit quotas | `github-copilot` | | [cursor](packages/cursor) | Cursor subscriptions (Pro, Pro+, Ultra, Teams), on the API cursor-agent talks to | `cursor` | diff --git a/packages/comate/README.md b/packages/comate/README.md new file mode 100644 index 0000000..c0f0972 --- /dev/null +++ b/packages/comate/README.md @@ -0,0 +1,52 @@ +# @magpie-community/opencode-comate-auth + +[OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider 插件:**文心快码(Baidu Comate,`comate.baidu.com`)**——登录、模型清单、聊天转发。 + +请求形态按文心快码 VS Code 扩展 `BaiduComate.comate` 4.14.1 内置的 Comate CLI(`@comate/zulu` 1.7.16)源码移植,插件以该 CLI 的身份(`zulucli` 1.7.16)发请求。 + +> ⚠️ **尚未用真实账号验证。** 登录、模型清单与聊天三条链路都是读官方客户端代码写成的,测试打的是本地假上游。遇到问题请把报错发到 magpie 的 Discord。 + +## 安装 + +``` +magpie plugin add @magpie-community/opencode-comate-auth +magpie plugin login comate # 选「网页登录」或「粘贴 License」 +``` + +## 能力 + +- **登录**: + - `网页登录`:与 Comate CLI 相同。插件生成一个 clientId,打开 `comate.baidu.com/zh/login?track=COMATE_CLI&clientId=…`,在浏览器里登录并授权后,插件每 2 秒轮询 `/api/client/generate/token`(3 分钟内),拿到 token 再换出账号的 **License**(`/api/client/key`)。无监听端口。 + - `粘贴 License`:comate.baidu.com/user 页面上的 License,插件先用 `/api/key/valid/` 校验一次。 + - License 就是凭据,没有续期;失效后请求返回 401,重新登录即可。 +- **模型**:按 CLI 的做法读账号的模型清单(`POST /api/v2/api/models/available`,缓存 5 分钟),模型 id 即清单里的 `modelId`。取不到清单时只有 `auto`(文心快码的默认模式)。支持思考的模型打开 `thinkingEnabled`,支持思考档的模型透传 `reasoning_effort`。 +- **聊天**:每个请求是一次 Comate 智能体回合:`conversation → task → execute(SSE)`。插件用 CLI 自带的「自定义智能体」形态(`isProjectAgent: true`、`agentPrompt`、`tools: []`):请求的 system 提示作为智能体提示词,不带文心快码的服务端工具。整段对话写进本回合的 query,不复用跨请求会话。`ANSWER` 帧的 `delta` / `reasoningDelta` 转成 OpenAI 的 `content` / `reasoning_content`,`TOKEN_USAGE` 转成 `usage`。流式与非流式都支持。 +- **工具与图片**:工具以 JSON 文本协议适配(与 catpaw 插件相同):工具定义写进提示词,模型按 `{"tool_calls":[…]}` 回复,插件解析回 OpenAI `tool_calls`;`tool_choice=required` / 指定工具时,未拿到调用会带上下文重试一次。图片无法经文本送达,带图片的请求以 **400 明确拒绝**。 +- **错误**:`code 401` → 401(License 失效);`code 429`、`QUOTA_EXCEED`、`DOWNGRADE` → 429(用量超限,原文透出,不编造重置时间);`EXCEPTION` → 错误。 +- **用量(usage)**:文心快码对外没有可按 License 读取的额度接口(客户端自己的额度查询在百度内网域名上),卡片只显示 License 是否有效。 + +## 协议细节 + +- 请求头(CLI 原样):`login-name` / `Uuap-login-name: encodeURIComponent(license)`、`X-Source: COMATE`、`plugin-version: zulucli-1.7.16`、`x-skip-fcnap: yes`、`Accept-Language: zh-CN,zh`、`X-Trace-Id`(execute 另带 `x-query-id`)。 +- 请求体都带 `{username: license, ide: "zulucli", ideVersion, pluginVersion}`;execute 带 `agentVersion: 12`、`modelKey`、`modelProvider`。 +- 智能体接口前缀:`/api/aidevops/autocomate/rest/autowork/v2`。 + +未经真实账号确认的部分:服务端是否对顶层自定义智能体采用 `agentPrompt` 且不附加内置工具与提示;conversation / task 需要的字段是否齐全;`thinkingEnabled` / `effort` / `contextWindow` 是否被接受;真实模型 id;限额帧的确切形态。 + +## 环境变量(测试 / 镜像用) + +| 变量 | 默认 | +|---|---| +| `COMATE_ORIGIN` | `https://comate.baidu.com` | + +## 测试 + +``` +bun test packages/comate +``` + +测试打到进程内的假上游(替换 `fetch`),不触网、不使用真实 License。 + +## 许可 + +MIT。 diff --git a/packages/comate/index.mjs b/packages/comate/index.mjs new file mode 100644 index 0000000..6a8c6c2 --- /dev/null +++ b/packages/comate/index.mjs @@ -0,0 +1,794 @@ +// @magpie-community/opencode-comate-auth — the 文心快码 (Baidu Comate) +// provider plugin for OpenCode and magpie. +// +// Signs in the way Comate's own CLI (@comate/zulu 1.7.16, bundled in the VS +// Code extension BaiduComate.comate 4.14.1) does: a browser page binds a +// fresh clientId to the account, and polling hands back the account's +// license, which is the credential every later request carries. A license +// copied from https://comate.baidu.com/user can be pasted instead. +// +// Each chat completion runs as one Zulu agent turn: conversation → task → +// execute (SSE). The agent is a custom one in the client's own shape +// ({isProjectAgent: true, agentPrompt, tools: []}, as the client's retrieval +// planner sends it), so the request's system prompt is the agent's prompt +// and Comate's server-side tools stay out. Tools ride as JSON text over the +// prompt, as in the catpaw plugin. Read from the extension's code; not run +// against a real account (see README). + +const ID = "comate" +const NAME = "文心快码 Comate" + +const origin = () => process.env.COMATE_ORIGIN || "https://comate.baidu.com" +const AGENT_BASE = "/api/aidevops/autocomate/rest/autowork/v2" + +// the client this plugin speaks as: Comate's own CLI +const CLI = Object.freeze({ ide: "zulucli", version: "1.7.16" }) + +// what the vendor answers before a list can be read: its own default mode +const MODELS = { auto: { name: "Auto", provider: null } } + +// ── small helpers ────────────────────────────────────────────────────────── + +const errorResponse = (status, message, fields = {}, headers = {}) => + new Response(JSON.stringify({ error: { message, ...fields } }), { status, headers: { "content-type": "application/json", ...headers } }) + +// a failure with the status the agent should see +class Refused extends Error { + constructor(status, message, fields = {}, headers = {}) { + super(message) + this.status = status + this.fields = fields + this.headers = headers + } +} + +const expiredLicense = (said) => + new Refused(401, `文心快码 license 无效或已失效${said ? `:${said}` : ""}。请在 magpie 里重新登录文心快码`, { type: "authentication_error" }) + +// over the account's limit: the vendor's own words, as a 429 (it names no +// reset, so no retry-after is made up) +const overLimit = (said) => + new Refused(429, `文心快码用量已超限${said ? `:${said}` : ""}`, { type: "rate_limit_error", code: "quota_exceeded" }) + +function failResponse(e) { + if (e instanceof Refused) return errorResponse(e.status, e.message, e.fields, e.headers) + return errorResponse(502, String(e?.message ?? e)) +} + +// primed waits for a turn's first event, up to ms, before the agent is +// answered: a refusal there goes out as its own status instead of an error +// inside a 200 stream +const PRIME_MS = 10_000 +async function primed(gen, ms = PRIME_MS) { + const first = gen.next().then( + (v) => ({ v }), + (e) => ({ e }), + ) + let timer + const won = await Promise.race([first, new Promise((r) => (timer = setTimeout(() => r(null), ms)))]) + clearTimeout(timer) + if (won?.e) throw won.e + return (async function* () { + const r = won ?? (await first) + if (r.e) throw r.e + if (r.v.done) return + yield r.v.value + yield* gen + })() +} + +async function bodyText(input, init) { + const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined) + return typeof b === "string" ? b : new TextDecoder().decode(b) +} + +const licenseOf = (auth) => (auth?.type === "oauth" && typeof auth.access === "string" ? auth.access.trim() : "") + +// ── the wire: what the client puts on every request ─────────────────────── + +// getRequestUserHeader in the client: the license is the user's name +function headers(license, extra = {}) { + const who = encodeURIComponent(license) + return { + "Content-Type": "application/json", + "Accept-Language": "zh-CN,zh", + "login-name": who, + "Uuap-login-name": who, + "X-Source": "COMATE", + "plugin-version": `${CLI.ide}-${CLI.version}`, + "x-skip-fcnap": "yes", + ...extra, + } +} + +// getRequestClienInfo in the client: spread into every agent body +const clientInfo = (license) => ({ username: license, ide: CLI.ide, ideVersion: CLI.version, pluginVersion: CLI.version }) + +async function postJSON(url, body, license, extra, signal) { + const res = await fetch(url, { method: "POST", headers: headers(license, extra), body: JSON.stringify(body), signal: signal ?? AbortSignal.timeout(30_000) }) + const text = await res.text() + let json = null + try { + json = JSON.parse(text) + } catch {} + return { status: res.status, text, json } +} + +// ── models ───────────────────────────────────────────────────────────────── + +// the account's list as the CLI reads it (POST /api/v2/api/models/available, +// {data: {reason, models: [...]}}); a row's modelId is the id the agent +// turn's modelKey takes +function liveModels(rows) { + const out = {} + for (const r of Array.isArray(rows) ? rows : []) { + const id = typeof r?.modelId === "string" ? r.modelId.trim() : "" + if (!id) continue + const prev = out[id] + out[id] = { + name: (typeof r.displayName === "string" && r.displayName.trim()) || prev?.name || id, + provider: r.provider ?? prev?.provider ?? null, + image: r.supportImage === true || prev?.image === true, + thinking: r.supportThinking === true || prev?.thinking === true, + effort: r.supportEffort === true || prev?.effort === true, + ...(Number.isFinite(r.maxContextWindow) && r.maxContextWindow > 0 ? { context: r.maxContextWindow } : prev?.context ? { context: prev.context } : {}), + ...(Number.isFinite(r.ratio) && r.ratio >= 0 ? { rate: r.ratio } : prev?.rate !== undefined ? { rate: prev.rate } : {}), + } + } + return out +} + +const LIVE_TTL = 5 * 60_000 +const liveLists = new Map() // license -> { at, models } + +async function fetchLiveModels(license, signal) { + const r = await postJSON( + origin() + "/api/v2/api/models/available", + { username: license, type: "ZULU", rootRepo: "", submodules: [], zuluVersion: CLI.version, source: "cli", ideType: CLI.ide }, + license, + {}, + signal ?? AbortSignal.timeout(15_000), + ) + if (r.status !== 200 || r.json?.status !== "OK") throw new Error(`文心快码模型列表返回 HTTP ${r.status} ${r.json?.message ?? ""}`.trim()) + const rows = Array.isArray(r.json.data) ? r.json.data : r.json.data?.models + if (!Array.isArray(rows)) throw new Error("文心快码模型列表无法解析") + return liveModels(rows) +} + +async function liveListFor(license, signal) { + const hit = liveLists.get(license) + if (hit && Date.now() - hit.at < LIVE_TTL) return hit.models + try { + const models = await fetchLiveModels(license, signal) + liveLists.set(license, { at: Date.now(), models }) + return models + } catch { + return hit?.models ?? null + } +} + +async function specOf(license, id, signal) { + const live = await liveListFor(license, signal) + return live?.[id] ?? MODELS[id] ?? null +} + +// the vendor's context window when it gives one; no output limit is made up +const configModel = (m) => ({ + name: m.name, + ...(m.rate !== undefined ? { rate: m.rate } : {}), +}) + +// ── prompt and tools over text ───────────────────────────────────────────── + +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("") : "" +} + +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" } +} + +const isToolChoiceRequired = (toolChoice) => ["required", "named"].includes(normalizeToolChoice(toolChoice).mode) +const toolNameOf = (tool) => tool?.function?.name || tool?.name || "" +const toolParamsOf = (tool) => 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") +} + +// the request's messages as the agent's prompt and the turn's query. System +// messages become the agent's prompt; the rest is one text, each turn +// labelled, tool calls and results written out (never dropped). +function buildTurn(messages, tools, toolChoice) { + const system = [] + const parts = [] + for (const msg of messages) { + const role = msg.role || "user" + const text = textOfContent(msg.content) + if (role === "system" || role === "developer") { + if (text) system.push(text) + continue + } + if (role === "tool") { + parts.push(`[Tool result${msg.tool_call_id ? ` for ${msg.tool_call_id}` : ""}]\n${text}`) + continue + } + const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [] + 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") + const body = [text, callText].filter(Boolean).join("\n") + parts.push(role === "assistant" ? `[Assistant]\n${body}` : `[User]\n${body}`) + } + const wantsTools = normalizeToolChoice(toolChoice).mode !== "none" && Array.isArray(tools) && tools.length > 0 + if (wantsTools) { + const instruction = buildToolInstruction(tools, toolChoice) + system.push(instruction) + parts.push(`[System]\n${instruction}`) + } + // a lone user message goes as itself, the way the client sends a query + const rest = messages.filter((m) => m.role !== "system" && m.role !== "developer") + const lone = !wantsTools && rest.length === 1 && (rest[0].role || "user") === "user" + const query = lone ? textOfContent(rest[0].content) : parts.join("\n\n") + return { prompt: system.join("\n\n"), query } +} + +const parseJsonLoose = (text) => { + try { + return JSON.parse(text) + } catch { + return null + } +} + +// the reply → OpenAI tool_calls; the whole reply must be the call JSON +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 parsed = parseJsonLoose(fenced ? fenced[1].trim() : raw) + 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 : [] + 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 name = known.get(String(call?.name || call?.tool || call?.function?.name || "").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 +} + +// ── one agent turn ───────────────────────────────────────────────────────── + +// the custom agent each turn runs as: the client's own shape for an agent +// whose prompt it supplies, with none of Comate's tools +const AGENT_NAME = "assistant" +const agentInfo = (prompt) => ({ agentName: AGENT_NAME, isProjectAgent: true, agentPrompt: prompt, tools: [] }) + +// an agent step's JSON answer: {code, message, data}; HTTP 200 carries the +// refusals too +function stepData(step, r) { + const code = r.json?.code + const said = String(r.json?.message ?? "").trim() + if (r.status === 401 || code === 401) throw expiredLicense(said) + if (r.status === 429 || code === 429) throw overLimit(r.json?.data ? JSON.stringify(r.json.data) : said) + if (r.status !== 200 || !r.json) throw new Error(`文心快码 ${step} 失败:HTTP ${r.status} ${r.text.slice(0, 300)}`.trim()) + if (code !== 200) throw new Error(`文心快码 ${step} 失败:code=${code ?? "?"} ${said}`.trim()) + return r.json.data +} + +// runTurn: conversation → task → execute, yielding {delta}, {reasoningDelta}, +// {usage} and finally {done, text, reasoning}. A fresh conversation each +// time: the whole history rides in the query. +async function* runTurn(license, { prompt, query, spec, effort }, signal) { + const traceId = crypto.randomUUID() + const info = agentInfo(prompt) + const conv = stepData( + "conversation", + await postJSON(origin() + AGENT_BASE + "/conversation", { agentId: 1, ...clientInfo(license) }, license, { "X-Trace-Id": traceId }, signal), + ) + const conversationId = conv?.id + if (conversationId == null) throw new Error("文心快码 conversation 没有返回 id") + const task = stepData( + "task", + await postJSON( + origin() + AGENT_BASE + "/task", + { agentInfo: { isProjectAgent: true, agentName: AGENT_NAME }, conversationId, ...clientInfo(license) }, + license, + { "X-Trace-Id": traceId }, + signal, + ), + ) + const taskId = task?.taskId + if (taskId == null) throw new Error("文心快码 task 没有返回 taskId") + + const body = { + ...clientInfo(license), + taskId, + conversationId, + query, + modelKey: spec.id, + ...(spec.provider ? { modelProvider: spec.provider } : {}), + thinkingEnabled: !!spec.thinking, + ...(spec.effort && effort ? { effort } : {}), + ...(spec.context ? { contextWindow: spec.context } : {}), + sysInfo: { os: process.platform, defaultShell: "", homeDir: "", installedCommands: [], notInstalledCommands: [], workspacePath: "", workspaceRoots: [] }, + skillInfos: [], + hasMcp: false, + isUserQuery: true, + contexts: [], + toolUseResults: [], + subAgents: [], + agentInfo: info, + agentVersion: 12, + isFirstQuery: true, + systemReminder: "", + extendUserQueryInfo: { commands: [], skills: [], subagents: [], rules: [] }, + extend: { isMultiWorkspace: false, useWorkflow: true }, + } + const res = await fetch(origin() + AGENT_BASE + "/execute", { + method: "POST", + headers: headers(license, { Accept: "text/event-stream", "X-Trace-Id": traceId, "x-query-id": crypto.randomUUID() }), + body: JSON.stringify(body), + signal: signal ?? AbortSignal.timeout(60 * 60_000), + }) + // a refusal comes as JSON, not a stream + if (!String(res.headers.get("content-type") ?? "").includes("text/event-stream")) { + const text = await res.text().catch(() => "") + let json = null + try { + json = JSON.parse(text) + } catch {} + stepData("execute", { status: res.status, text, json }) + throw new Error(`文心快码 execute 没有返回事件流:HTTP ${res.status} ${text.slice(0, 300)}`.trim()) + } + if (!res.body) throw new Error("文心快码 execute 返回了空流") + + const decoder = new TextDecoder() + const reader = res.body.getReader() + let buffered = "" + let text = "" + let reasoning = "" + let frames = 0 + const handle = function* (data) { + let frame + try { + frame = JSON.parse(data) + } catch { + return + } + const content = frame?.content + if (!content || typeof content !== "object") return + frames++ + const detail = content.detail ?? {} + switch (content.type) { + case "ANSWER": + if (typeof detail.reasoningDelta === "string" && detail.reasoningDelta) { + reasoning += detail.reasoningDelta + yield { reasoningDelta: detail.reasoningDelta } + } + if (typeof detail.delta === "string" && detail.delta) { + // the client trims the answer's leading newlines + const d = text === "" ? detail.delta.replace(/^(\r?\n)+/, "") : detail.delta + if (d) { + text += d + yield { delta: d } + } + } + return + case "TOKEN_USAGE": + if (detail.usage) yield { usage: detail.usage } + return + case "EXCEPTION": + throw new Error(`文心快码执行异常:${detail.exceptionMsg ?? "后端未返回详细信息"}`) + case "QUOTA_EXCEED": + case "DOWNGRADE": + throw overLimit(String(detail.message ?? detail.msg ?? detail.exceptionMsg ?? "").trim()) + case "NEED_RETRY_EXCEPTION": + throw new Error(`文心快码要求重试:${detail.exceptionMsg ?? ""}`.trim()) + } + } + const lineOf = function* (line) { + if (!line.startsWith("data:")) return + yield* handle(line.slice(5).trim()) + } + for (;;) { + const { done, value } = await reader.read() + if (done) break + buffered += decoder.decode(value, { stream: true }) + const lines = buffered.split("\n") + buffered = lines.pop() ?? "" + for (const line of lines) yield* lineOf(line.replace(/\r$/, "")) + } + if (buffered) yield* lineOf(buffered.replace(/\r$/, "")) + if (frames === 0) throw new Error("文心快码事件流结束但没有任何帧") + yield { done: true, text, reasoning } +} + +// TOKEN_USAGE's {inputTokens, cachedInputTokens, outputTokens} as OpenAI's +function openaiUsage(u) { + if (!u) return undefined + const prompt = Number(u.inputTokens) || 0 + const cached = Number(u.cachedInputTokens) || 0 + const completion = Number(u.outputTokens) || 0 + return { prompt_tokens: prompt, completion_tokens: completion, total_tokens: prompt + completion, ...(cached ? { prompt_tokens_details: { cached_tokens: cached } } : {}) } +} + +// ── sign-in ──────────────────────────────────────────────────────────────── + +const apiGet = (pathname, extra = {}, signal) => + fetch(origin() + "/api" + pathname, { headers: { Accept: "application/json", ...extra }, signal: signal ?? AbortSignal.timeout(10_000) }) + +async function checkLicense(license) { + const res = await apiGet(`/key/valid/${encodeURIComponent(license)}`) + const json = await res.json().catch(() => null) + if (json?.status === "OK" && json.data === true) return { ok: true } + if (json && json.data === false) return { ok: false, message: String(json.message ?? "license 无效") } + return { ok: null, message: `HTTP ${res.status}` } +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const POLL_MS = 2_000 +const POLL_FOR_MS = 180_000 + +// the CLI's device label: "user host (OS arch release)" +async function deviceLabel() { + try { + const os = await import("node:os") + return `${os.userInfo().username} ${os.hostname()} (${os.type()} ${os.arch()} ${os.release()})` + } catch { + return "magpie" + } +} + +// ── the plugin ───────────────────────────────────────────────────────────── + +export async function ComateAuthPlugin() { + return { + auth: { + provider: ID, + async loader(getAuth) { + const serve = async (chat, signal) => { + const license = licenseOf(await getAuth()) + if (!license) return errorResponse(401, "文心快码未登录:请在 magpie 里登录文心快码") + const id = String(chat.model ?? "").trim() || "auto" + const found = await specOf(license, id, signal) + if (!found) { + const known = Object.keys({ ...MODELS, ...(liveLists.get(license)?.models ?? {}) }) + return errorResponse(400, `unknown model "${id}" (known: ${known.join(", ")})`) + } + const spec = { id, ...found } + const effort = typeof chat.reasoning_effort === "string" ? chat.reasoning_effort : undefined + const tools = chat.tools + const wantsTools = normalizeToolChoice(chat.tool_choice).mode !== "none" && Array.isArray(tools) && tools.length > 0 + const forced = wantsTools && isToolChoiceRequired(chat.tool_choice) + const turnOf = (messages) => ({ ...buildTurn(messages, tools, chat.tool_choice), spec, effort }) + const collect = async (messages) => { + let out = { text: "", reasoning: "", usage: undefined } + for await (const ev of runTurn(license, turnOf(messages), signal)) { + if (ev.usage) out.usage = ev.usage + if (ev.done) out = { ...out, text: ev.text, reasoning: ev.reasoning } + } + return out + } + const retryMessages = (failed) => [...chat.messages, { role: "assistant", content: failed }, { role: "user", content: forcedToolRetryMessage(chat.tool_choice) }] + + const cid = `chatcmpl-${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}` + const created = Math.floor(Date.now() / 1000) + + if (!chat.stream) { + let out + let calls = [] + try { + out = await collect(chat.messages) + if (wantsTools) { + calls = toolCallsFromText(out.text, tools, chat.tool_choice) + if (!calls.length && forced) { + out = await collect(retryMessages(out.text)) + calls = toolCallsFromText(out.text, tools, chat.tool_choice) + } + } + } catch (e) { + return failResponse(e) + } + const message = { + role: "assistant", + content: calls.length ? null : out.text, + ...(calls.length ? { tool_calls: calls } : {}), + ...(out.reasoning ? { reasoning_content: out.reasoning } : {}), + } + const usage = openaiUsage(out.usage) + return new Response( + JSON.stringify({ id: cid, object: "chat.completion", created, model: id, choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : "stop" }], ...(usage ? { usage } : {}) }), + { status: 200, headers: { "content-type": "application/json" } }, + ) + } + + let events + try { + events = await primed(runTurn(license, turnOf(chat.messages), signal)) + } catch (e) { + return failResponse(e) + } + const encoder = new TextEncoder() + const frame = (obj) => encoder.encode(`data: ${JSON.stringify(obj)}\n\n`) + const chunk = (delta, finish, extra = {}) => frame({ id: cid, object: "chat.completion.chunk", created, model: id, choices: [{ index: 0, delta, finish_reason: finish ?? null }], ...extra }) + const stream = new ReadableStream({ + async start(controller) { + let closed = false + const push = (bytes) => { + if (closed) return + try { + controller.enqueue(bytes) + } catch { + closed = true + } + } + // the agent can think a while before its first frame + const ka = setInterval(() => push(encoder.encode(": ka\n\n")), 3_000) + const stop = () => { + clearInterval(ka) + if (!closed) { + closed = true + try { + controller.close() + } catch {} + } + } + signal?.addEventListener("abort", stop) + push(chunk({ role: "assistant" })) + // with tools, a JSON-shaped head is held until it reads as + // prose (a forced tool_choice holds all of it, for the retry) + let pending = "" + let live = !wantsTools + let text = "" + let usage + try { + for await (const ev of events) { + if (closed) return + if (ev.reasoningDelta) push(chunk({ reasoning_content: ev.reasoningDelta })) + if (ev.usage) usage = ev.usage + if (ev.delta) { + text += ev.delta + if (live) push(chunk({ content: ev.delta })) + else { + pending += ev.delta + const head = pending.trimStart() + if (!forced && head !== "" && !head.startsWith("{") && !head.startsWith("```")) { + live = true + push(chunk({ content: pending })) + pending = "" + } + } + } + if (ev.done) text = ev.text + } + let calls = [] + if (wantsTools && !live) { + calls = toolCallsFromText(text, tools, chat.tool_choice) + if (!calls.length && forced) { + const out = await collect(retryMessages(text)) + text = out.text + usage = out.usage ?? usage + calls = toolCallsFromText(text, tools, chat.tool_choice) + } + } + if (calls.length) { + calls.forEach((call, index) => { + push(chunk({ tool_calls: [{ index, id: call.id, type: "function", function: { name: call.function.name, arguments: "" } }] })) + push(chunk({ tool_calls: [{ index, function: { arguments: call.function.arguments } }] })) + }) + } else if (!live && text) push(chunk({ content: text })) + const u = openaiUsage(usage) + push(chunk({}, calls.length ? "tool_calls" : "stop", u ? { usage: u } : {})) + } catch (e) { + push(frame({ error: { message: String(e?.message ?? e), ...(e instanceof Refused ? e.fields : {}) } })) + } + push(encoder.encode("data: [DONE]\n\n")) + stop() + }, + }) + return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } }) + } + return { + baseURL: origin(), + apiKey: "comate", + async fetch(input, init = {}) { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + if (!/\/chat\/completions$/.test(new URL(url).pathname)) return errorResponse(404, "only chat completions are served") + let chat + try { + chat = JSON.parse(await bodyText(input, init)) + } catch { + return errorResponse(400, "a request that isn't JSON") + } + if (!Array.isArray(chat.messages) || chat.messages.length === 0) return errorResponse(400, "messages is required") + if (chat.messages.some((m) => Array.isArray(m.content) && m.content.some((c) => c?.type === "image" || c?.type === "image_url" || c?.type === "input_image"))) + return errorResponse(400, "this provider cannot take images through the text prompt (refused rather than silently dropped)") + return serve(chat, init.signal) + }, + } + }, + // Comate's SaaS shows no quota a license can read (the client's own + // quota read is on Baidu's internal host), so the card says whether + // the license still holds and nothing more + async usage(getAuth) { + const license = licenseOf(await getAuth()) + if (!license) return { error: "文心快码未登录", signIn: "expired" } + let r + try { + r = await checkLicense(license) + } catch (e) { + return { error: String(e?.message ?? e), signIn: "kept" } + } + if (r.ok === false) return { error: r.message, signIn: "expired" } + if (r.ok === null) return { error: `文心快码 license 校验失败:${r.message}`, signIn: "kept" } + return { plan: NAME, windows: [] } + }, + methods: [ + { + type: "oauth", + label: "网页登录(文心快码官方登录页)", + authorize: async () => { + const clientId = crypto.randomUUID() + // the CLI unbinds the id first; best effort, as there + try { + await apiGet(`/client/logout?clientId=${clientId}`) + } catch {} + const url = `${origin()}/zh/login?track=COMATE_CLI&clientId=${clientId}&device=${encodeURIComponent(await deviceLabel())}` + return { + url, + instructions: "在浏览器打开的文心快码页面登录并确认授权,完成后会自动回到 magpie。", + method: "auto", + callback: async () => { + const deadline = Date.now() + POLL_FOR_MS + while (Date.now() < deadline) { + await sleep(POLL_MS) + try { + // not bound yet: {status: "BAD_REQUEST", message: "未找到客户端信息"} + const res = await apiGet(`/client/generate/token?clientId=${clientId}`) + const json = await res.json().catch(() => null) + if (json?.status !== "OK" || !json.data) continue + const keyRes = await apiGet(`/client/key?clientId=${clientId}`, { token: String(json.data) }) + const key = await keyRes.json().catch(() => null) + const license = typeof key?.data?.key === "string" ? key.data.key.trim() : "" + if (key?.status !== "OK" || !license) return { type: "failed", error: "获取文心快码 license 失败,请重试" } + const name = typeof key.data.displayName === "string" && key.data.displayName.trim() ? key.data.displayName.trim() : "文心快码账号" + return { type: "success", refresh: "", access: license, expires: 0, accountId: name, source: "web" } + } catch { + // one failed poll is skipped, as the CLI does + } + } + return { type: "failed", error: "登录超时(3 分钟内未完成授权),请重试" } + }, + } + }, + }, + { + type: "oauth", + label: "粘贴 License", + prompts: [{ type: "text", key: "license", message: "License(comate.baidu.com/user 页面上的 License)", validate: (v) => (v && v.trim() ? undefined : "必填") }], + authorize: async (inputs) => { + const license = String(inputs?.license ?? "").trim() + if (!license) return { type: "failed", error: "License 必填" } + return { + url: "", + instructions: "正在校验 License。", + method: "auto", + callback: async () => { + try { + const r = await checkLicense(license) + if (r.ok === false) return { type: "failed", error: r.message } + } catch {} + return { type: "success", refresh: "", access: license, expires: 0, accountId: "文心快码 License", source: "manual" } + }, + } + }, + }, + ], + }, + provider: { + id: ID, + async models(provider, { auth } = {}) { + const have = provider?.models ?? {} + const license = licenseOf(auth) + if (!license) return have + const live = await liveListFor(license) + if (!live) return have + return { ...have, ...Object.fromEntries(Object.entries(live).filter(([id]) => !(id in have)).map(([id, m]) => [id, configModel(m)])) } + }, + }, + async config(config) { + config.provider ??= {} + const was = config.provider[ID] ?? {} + config.provider[ID] = { + name: NAME, + npm: "@ai-sdk/openai-compatible", + api: origin(), + ...was, + models: { ...Object.fromEntries(Object.entries(MODELS).map(([id, m]) => [id, configModel(m)])), ...(was.models ?? {}) }, + } + }, + } +} + +// for tests +export const _internal = { ID, CLI, MODELS, headers, clientInfo, liveModels, buildTurn, toolCallsFromText, openaiUsage, runTurn, agentInfo, forgetLive: () => liveLists.clear() } diff --git a/packages/comate/index.test.mjs b/packages/comate/index.test.mjs new file mode 100644 index 0000000..77dc377 --- /dev/null +++ b/packages/comate/index.test.mjs @@ -0,0 +1,327 @@ +import { describe, test, expect, beforeEach, afterEach } from "bun:test" +import { ComateAuthPlugin, _internal } from "./index.mjs" + +// Every test runs against an in-process fake of comate.baidu.com: global +// fetch is swapped for a router, so nothing reaches the network. The shapes +// are the ones the Comate extension's code reads (BaiduComate.comate 4.14.1: +// comate-engine/server.js and zulu-cli/bundle/index.js). + +const LICENSE = "lic-abc+/=1" +let realFetch +let calls +let upstream + +const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) +const sse = (frames) => + new Response(frames.map((f) => (typeof f === "string" ? f : `data:${JSON.stringify(f)}`) + "\n\n").join(""), { + status: 200, + headers: { "content-type": "text/event-stream" }, + }) +const answer = (detail) => ({ content: { type: "ANSWER", detail } }) + +function defaults() { + return { + models: [ + { modelId: "auto", displayName: "Auto", provider: null, requestType: "COMATE_DEFAULT_MODE" }, + { modelId: "ernie-x", displayName: "ERNIE X", provider: "BAIDU", supportThinking: true, supportEffort: true, maxContextWindow: 128000, ratio: 1 }, + ], + conversation: () => json({ code: 200, data: { id: 41 } }), + task: () => json({ code: 200, data: { taskId: 42 } }), + execute: () => sse([":heartbeat", answer({ reasoningDelta: "想" }), answer({ delta: "\n你好" }), answer({ delta: ",世界" }), { content: { type: "TOKEN_USAGE", detail: { usage: { inputTokens: 10, cachedInputTokens: 4, outputTokens: 3 } } } }, answer({ delta: "", end: true })]), + valid: () => json({ status: "OK", data: true }), + } +} + +beforeEach(() => { + _internal.forgetLive() + calls = [] + upstream = defaults() + realFetch = globalThis.fetch + globalThis.fetch = async (input, init = {}) => { + const url = new URL(typeof input === "string" ? input : input.url) + const body = init.body ? JSON.parse(init.body) : undefined + calls.push({ path: url.pathname, search: url.search, headers: init.headers ?? {}, body }) + expect(url.origin).toBe("https://comate.baidu.com") + const p = url.pathname + if (p === "/api/v2/api/models/available") return json({ status: "OK", data: { reason: "PASS", models: upstream.models } }) + if (p === "/api/aidevops/autocomate/rest/autowork/v2/conversation") return upstream.conversation(body) + if (p === "/api/aidevops/autocomate/rest/autowork/v2/task") return upstream.task(body) + if (p === "/api/aidevops/autocomate/rest/autowork/v2/execute") return upstream.execute(body) + if (p.startsWith("/api/key/valid/")) return upstream.valid(decodeURIComponent(p.slice("/api/key/valid/".length))) + if (upstream.route) return upstream.route(url, init) + return json({ status: "NOT_FOUND" }, 404) + } +}) + +afterEach(() => { + globalThis.fetch = realFetch +}) + +async function provider(auth = { type: "oauth", access: LICENSE, refresh: "", expires: 0 }) { + const plugin = await ComateAuthPlugin() + return plugin.auth.loader(async () => auth) +} + +const chat = (p, body) => p.fetch("https://comate.baidu.com/chat/completions", { method: "POST", body: JSON.stringify(body) }) + +async function readSSE(res) { + const text = await res.text() + return text + .split("\n\n") + .filter((l) => l.startsWith("data: ")) + .map((l) => l.slice(6)) + .map((d) => (d === "[DONE]" ? d : JSON.parse(d))) +} + +describe("the wire", () => { + test("every agent request carries the license the way the client does", async () => { + const p = await provider() + const res = await chat(p, { model: "ernie-x", messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(200) + const steps = calls.filter((c) => c.path.includes("/autowork/")) + expect(steps.map((c) => c.path.split("/").pop())).toEqual(["conversation", "task", "execute"]) + for (const c of steps) { + expect(c.headers["login-name"]).toBe(encodeURIComponent(LICENSE)) + expect(c.headers["Uuap-login-name"]).toBe(encodeURIComponent(LICENSE)) + expect(c.headers["X-Source"]).toBe("COMATE") + expect(c.headers["plugin-version"]).toBe("zulucli-1.7.16") + expect(c.headers["x-skip-fcnap"]).toBe("yes") + expect(c.body).toMatchObject({ username: LICENSE, ide: "zulucli", ideVersion: "1.7.16", pluginVersion: "1.7.16" }) + } + // one trace id across the turn's three steps + expect(new Set(steps.map((c) => c.headers["X-Trace-Id"])).size).toBe(1) + }) + + test("execute names the task, the model and a custom agent with no Comate tools", async () => { + const p = await provider() + await chat(p, { + model: "ernie-x", + reasoning_effort: "high", + messages: [ + { role: "system", content: "Be brief." }, + { role: "user", content: "hi" }, + ], + }) + const task = calls.find((c) => c.path.endsWith("/task")).body + expect(task).toMatchObject({ conversationId: 41, agentInfo: { isProjectAgent: true } }) + const ex = calls.find((c) => c.path.endsWith("/execute")).body + expect(ex).toMatchObject({ + conversationId: 41, + taskId: 42, + query: "hi", + modelKey: "ernie-x", + modelProvider: "BAIDU", + thinkingEnabled: true, + effort: "high", + contextWindow: 128000, + isUserQuery: true, + isFirstQuery: true, + agentVersion: 12, + agentInfo: { isProjectAgent: true, agentPrompt: "Be brief.", tools: [] }, + }) + // a project agent goes without an agentId, as the client sends it + expect("agentId" in ex).toBe(false) + }) + + test("the prompt sent upstream names neither magpie nor the vendor", async () => { + const p = await provider() + await chat(p, { model: "auto", messages: [{ role: "user", content: "hi" }, { role: "assistant", content: "yo" }, { role: "user", content: "again" }], tools: [{ type: "function", function: { name: "Read", parameters: { type: "object", properties: { path: { type: "string" } }, required: ["path"] } } }] }) + const ex = calls.find((c) => c.path.endsWith("/execute")).body + const sent = JSON.stringify({ q: ex.query, a: ex.agentInfo }) + expect(sent).not.toMatch(/magpie|comate|文心|baidu/i) + }) +}) + +describe("answers", () => { + test("non-streaming: deltas joined, leading newlines trimmed, reasoning and usage kept", async () => { + const p = await provider() + const res = await chat(p, { model: "ernie-x", messages: [{ role: "user", content: "hi" }] }) + const body = await res.json() + expect(body.choices[0].message).toEqual({ role: "assistant", content: "你好,世界", reasoning_content: "想" }) + expect(body.choices[0].finish_reason).toBe("stop") + expect(body.usage).toEqual({ prompt_tokens: 10, completion_tokens: 3, total_tokens: 13, prompt_tokens_details: { cached_tokens: 4 } }) + }) + + test("streaming: OpenAI chunks, then stop and [DONE]", async () => { + const p = await provider() + const res = await chat(p, { model: "ernie-x", stream: true, messages: [{ role: "user", content: "hi" }] }) + expect(res.headers.get("content-type")).toBe("text/event-stream") + const frames = await readSSE(res) + expect(frames.at(-1)).toBe("[DONE]") + const content = frames.filter((f) => f !== "[DONE]").map((f) => f.choices[0].delta.content ?? "").join("") + expect(content).toBe("你好,世界") + const reasoning = frames.filter((f) => f !== "[DONE]").map((f) => f.choices[0].delta.reasoning_content ?? "").join("") + expect(reasoning).toBe("想") + expect(frames.at(-2).choices[0].finish_reason).toBe("stop") + expect(frames.at(-2).usage.total_tokens).toBe(13) + }) + + test("a JSON tool-call reply becomes OpenAI tool_calls", async () => { + upstream.execute = () => sse([answer({ delta: '{"tool_calls":[{"name":"read","arguments":{"path":"a.txt"}}]}' })]) + const p = await provider() + const tools = [{ type: "function", function: { name: "Read", parameters: { type: "object", properties: { path: { type: "string" } }, required: ["path"] } } }] + const res = await chat(p, { model: "auto", messages: [{ role: "user", content: "read a.txt" }], tools }) + const body = await res.json() + expect(body.choices[0].finish_reason).toBe("tool_calls") + expect(body.choices[0].message.tool_calls[0].function).toEqual({ name: "Read", arguments: '{"path":"a.txt"}' }) + // the instruction rides in the agent's prompt and the query both + const ex = calls.find((c) => c.path.endsWith("/execute")).body + expect(ex.agentInfo.agentPrompt).toContain('{"tool_calls"') + expect(ex.query).toContain("[User]\nread a.txt") + }) + + test("a forced tool_choice gets one retry with the failed reply in view", async () => { + let n = 0 + upstream.execute = () => sse([answer({ delta: n++ === 0 ? "I will read it." : '{"tool_calls":[{"name":"Read","arguments":{"path":"a"}}]}' })]) + const p = await provider() + const tools = [{ type: "function", function: { name: "Read", parameters: { type: "object", properties: { path: { type: "string" } } } } }] + const res = await chat(p, { model: "auto", stream: true, tool_choice: "required", messages: [{ role: "user", content: "go" }], tools }) + const frames = (await readSSE(res)).filter((f) => f !== "[DONE]") + expect(frames.some((f) => f.choices[0].delta.tool_calls)).toBe(true) + expect(frames.some((f) => f.choices[0].delta.content)).toBe(false) + const second = calls.filter((c) => c.path.endsWith("/execute"))[1].body + expect(second.query).toContain("[Assistant]\nI will read it.") + }) + + test("tool results and earlier calls are written into the query, not dropped", () => { + const { query } = _internal.buildTurn( + [ + { role: "user", content: "go" }, + { role: "assistant", content: null, tool_calls: [{ id: "c1", function: { name: "Read", arguments: '{"path":"a"}' } }] }, + { role: "tool", tool_call_id: "c1", content: "file body" }, + ], + undefined, + undefined, + ) + expect(query).toContain('Tool call requested: Read {"path":"a"}') + expect(query).toContain("[Tool result for c1]\nfile body") + }) + + test("images are refused, not dropped", async () => { + const p = await provider() + const res = await chat(p, { model: "auto", messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "data:image/png;base64,AA" } }] }] }) + expect(res.status).toBe(400) + expect(calls.length).toBe(0) + }) +}) + +describe("refusals", () => { + test("code 401 is a lost sign-in (401), before any stream", async () => { + upstream.conversation = () => json({ code: 401, message: "当前License信息无效" }) + const p = await provider() + const res = await chat(p, { model: "auto", stream: true, messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(401) + expect((await res.json()).error.message).toContain("当前License信息无效") + }) + + test("code 429 at conversation is over the limit (429)", async () => { + upstream.conversation = () => json({ code: 429, message: "资源使用超过限制" }) + const p = await provider() + const res = await chat(p, { model: "auto", messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(429) + }) + + test("QUOTA_EXCEED in the stream is a 429 when it comes first", async () => { + upstream.execute = () => sse([{ content: { type: "QUOTA_EXCEED", detail: { message: "今日额度已用完" } } }]) + const p = await provider() + const res = await chat(p, { model: "auto", stream: true, messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(429) + expect((await res.json()).error.message).toContain("今日额度已用完") + }) + + test("EXCEPTION after text is an error frame, then [DONE]", async () => { + upstream.execute = () => sse([answer({ delta: "半句" }), { content: { type: "EXCEPTION", detail: { exceptionMsg: "boom" } } }]) + const p = await provider() + const res = await chat(p, { model: "auto", stream: true, messages: [{ role: "user", content: "hi" }] }) + const frames = await readSSE(res) + expect(frames.at(-1)).toBe("[DONE]") + expect(frames.at(-2).error.message).toContain("boom") + }) + + test("execute answering JSON instead of a stream is read as its refusal", async () => { + upstream.execute = () => json({ code: 401, message: "当前License信息无效" }) + const p = await provider() + const res = await chat(p, { model: "auto", messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(401) + }) + + test("an unknown model is a 400 naming the known ones", async () => { + const p = await provider() + const res = await chat(p, { model: "nope", messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain("ernie-x") + }) + + test("no license is a 401 with no request made", async () => { + const p = await provider({}) + const res = await chat(p, { model: "auto", messages: [{ role: "user", content: "hi" }] }) + expect(res.status).toBe(401) + expect(calls.length).toBe(0) + }) +}) + +describe("models", () => { + test("the account's list, read the way the CLI reads it", async () => { + const plugin = await ComateAuthPlugin() + const models = await plugin.provider.models({ models: {} }, { auth: { type: "oauth", access: LICENSE } }) + expect(models).toEqual({ auto: { name: "Auto" }, "ernie-x": { name: "ERNIE X", rate: 1 } }) + const c = calls.find((x) => x.path === "/api/v2/api/models/available") + expect(c.body).toEqual({ username: LICENSE, type: "ZULU", rootRepo: "", submodules: [], zuluVersion: "1.7.16", source: "cli", ideType: "zulucli" }) + }) + + test("a failed list leaves the configured models", async () => { + upstream.models = null + const plugin = await ComateAuthPlugin() + expect(await plugin.provider.models({ models: { auto: { name: "Auto" } } }, { auth: { type: "oauth", access: LICENSE } })).toEqual({ auto: { name: "Auto" } }) + }) + + test("config adds the provider with Auto and keeps the user's own models", async () => { + const plugin = await ComateAuthPlugin() + const config = { provider: { comate: { models: { mine: { name: "Mine" } } } } } + await plugin.config(config) + expect(config.provider.comate.models).toEqual({ auto: { name: "Auto" }, mine: { name: "Mine" } }) + expect(config.provider.comate.api).toBe("https://comate.baidu.com") + }) +}) + +describe("sign-in and usage", () => { + test("web sign-in: the CLI's login page, then token, then license", async () => { + let polls = 0 + upstream.route = (url, init) => { + if (url.pathname === "/api/client/logout") return json({ status: "OK" }) + if (url.pathname === "/api/client/generate/token") return ++polls < 2 ? json({ status: "BAD_REQUEST", message: "未找到客户端信息" }, 400) : json({ status: "OK", data: "tok-1" }) + if (url.pathname === "/api/client/key") { + expect(init.headers.token).toBe("tok-1") + return json({ status: "OK", data: { key: LICENSE, displayName: "张三" } }) + } + } + const plugin = await ComateAuthPlugin() + const flow = await plugin.auth.methods[0].authorize() + const u = new URL(flow.url) + expect(u.origin + u.pathname).toBe("https://comate.baidu.com/zh/login") + expect(u.searchParams.get("track")).toBe("COMATE_CLI") + const clientId = u.searchParams.get("clientId") + expect(clientId).toMatch(/^[0-9a-f-]{36}$/) + const done = await flow.callback() + expect(done).toEqual({ type: "success", refresh: "", access: LICENSE, expires: 0, accountId: "张三", source: "web" }) + expect(calls.filter((c) => c.path === "/api/client/generate/token").every((c) => c.search === `?clientId=${clientId}`)).toBe(true) + }, 15_000) + + test("a pasted license is checked first", async () => { + upstream.valid = () => json({ status: "FORBIDDEN", message: "当前license无效", data: false }) + const plugin = await ComateAuthPlugin() + const flow = await plugin.auth.methods[1].authorize({ license: " bad " }) + expect(await flow.callback()).toEqual({ type: "failed", error: "当前license无效" }) + expect(calls[0].path).toBe("/api/key/valid/bad") + }) + + test("usage: a refused license is expired, a held one has no sign-in mark", async () => { + const plugin = await ComateAuthPlugin() + const auth = async () => ({ type: "oauth", access: LICENSE }) + expect(await plugin.auth.usage(auth)).toEqual({ plan: "文心快码 Comate", windows: [] }) + upstream.valid = () => json({ status: "FORBIDDEN", message: "当前license无效", data: false }) + expect((await plugin.auth.usage(auth)).signIn).toBe("expired") + upstream.valid = () => json({ status: "ERROR" }, 503) + expect((await plugin.auth.usage(auth)).signIn).toBe("kept") + }) +}) diff --git a/packages/comate/opencode.mjs b/packages/comate/opencode.mjs new file mode 100644 index 0000000..7aec02e --- /dev/null +++ b/packages/comate/opencode.mjs @@ -0,0 +1,5 @@ +// The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host +// load them: its plugin functions and nothing else (1.x refuses a +// package whose exports include anything but plugins). OpenCode 2.x +// loads opencode2.mjs, which runs these. +export { ComateAuthPlugin } from "./index.mjs" diff --git a/packages/comate/opencode2.mjs b/packages/comate/opencode2.mjs new file mode 100644 index 0000000..b939308 --- /dev/null +++ b/packages/comate/opencode2.mjs @@ -0,0 +1,620 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required, and + // neither can one whose own validate() accepts an empty answer (the + // browser sign-in's optional API key) + if (!p.condition && p.required !== false) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + // A plugin still reading its list in the background when the first read + // returned (agy-cli: `agy models` and a session probe take seconds, and + // the first read gets its static list) says so through + // provider.warming(): the list is read once more when that ends, once, + // and no later than a minute on. + const warmed = async () => { + let w + try { + w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null + } catch { + return + } + if (!w || typeof w.then !== "function") return + let timer + await Promise.race([ + Promise.resolve(w).catch(() => {}), + new Promise((r) => { + timer = setTimeout(r, 60_000) + timer.unref?.() + }), + ]) + clearTimeout(timer) + if (live.on) await refresh() + } + void refresh().then(warmed, () => {}) +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/comate/package.json b/packages/comate/package.json new file mode 100644 index 0000000..0878f5b --- /dev/null +++ b/packages/comate/package.json @@ -0,0 +1,31 @@ +{ + "name": "@magpie-community/opencode-comate-auth", + "version": "0.1.0", + "description": "OpenCode & Magpie provider plugin for Baidu's 文心快码 Comate (comate.baidu.com): the Comate CLI's browser sign-in or a pasted license, chat through its Zulu agent protocol, and the account's model list", + "type": "module", + "main": "./opencode.mjs", + "exports": { ".": "./opencode2.mjs" }, + "scripts": { + "test": "bun test" + }, + "files": [ + "index.mjs", + "opencode.mjs", + "opencode2.mjs", + "README.md" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "comate", + "baidu", + "文心快码" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/comate" + } +} diff --git a/registry.json b/registry.json index ffad0c2..3ac0583 100644 --- a/registry.json +++ b/registry.json @@ -68,6 +68,9 @@ { "package": "@magpie-community/opencode-catpaw-auth", "name": "CatPaw", "providers": ["catpaw"], "community": true, "summary": { "en": "Meituan's 妙手 CatPaw (ai.catpaw.meituan.com): a browser web sign-in or the desktop client's saved credentials, chat through its round/event/turn conversation protocol, models and credit balance.", "zh": "美团妙手 CatPaw(ai.catpaw.meituan.com):浏览器网页登录或妙手桌面端已保存的登录态,经其 round/event/turn 会话协议对话,含模型与积分余额。" } }, + { "package": "@magpie-community/opencode-comate-auth", "name": "文心快码 Comate", "providers": ["comate"], "community": true, + "summary": { "en": "Baidu's 文心快码 Comate (comate.baidu.com): the Comate CLI's browser sign-in or a pasted license, the account's live models, and chat as a Comate agent turn (conversation, task, execute). Not yet tried with a real account; unofficial.", + "zh": "百度文心快码 Comate(comate.baidu.com):Comate CLI 同款网页登录或粘贴 License,读取账号的模型清单,以 Comate 智能体回合(conversation、task、execute)对话。尚未用真实账号验证;非官方。" } }, { "package": "@magpie-community/opencode-loomy-auth", "name": "Loomy", "providers": ["loomy"], "community": true, "summary": { "en": "iFlytek's Loomy (loomyad.xunfei.cn): SMS sign-in, OpenAI-compatible chat with reasoning-effort folding and image markers, the live model catalog, two point wallets and the daily first-login grant.", "zh": "讯飞 Loomy(loomyad.xunfei.cn):短信验证码登录,OpenAI 兼容对话(思考档折叠与图片标记适配),实时模型目录、双积分钱包与每日首登赠送。" } },