diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index adb46e7..9ccfb04 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -205,6 +205,21 @@ instead of on `/v2/report`; whether WorkBuddy reads it for the daily credit is not known. Anything the caller put in `extra_vars` is kept. The China build's chats go without it. +Since 0.2.35 a WorkBuddy AI chat is also reported on `POST /v2/report`, as +WorkBuddy AI 5.9.4's client reports one (#691): once the reply has been +read to its end, `chat_message_send`, then `chat_message_response` and +`chat_message_status` (with `chat_request_send` first when the user's own +message opened the step, and `chat_request_response` last when the step +ends the turn), then `agent_task_completed` and `chat_response_complete` +for a step that ends it. They carry the chat's ids, model, token counts and +finish reason, and the client's common fields: the account's id and name, +WorkBuddy's version, this computer's OS, CPU and memory, and a machine id +that is a hash of the host's and user's names. Only the user's own chats +are reported, never a message of the plugin's own; a reply cut off, a +refusal, a key account and the China build send none, and a report that +fails is dropped. Whether the daily credit reads these reports is not +known yet. + A chat that doesn't open with a system message is given WorkBuddy's default one, as the app does. diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 582524c..fe6061a 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -11,7 +11,7 @@ import { createHash, randomBytes } from "node:crypto" import { closeSync, createReadStream, openSync, readFileSync, readdirSync, readSync, statSync } from "node:fs" -import { homedir } from "node:os" +import { arch, cpus, homedir, hostname, release, totalmem, userInfo } from "node:os" import { dirname, isAbsolute, join } from "node:path" import { createGunzip, gzipSync } from "node:zlib" @@ -1602,6 +1602,214 @@ function withGrowth(site, chat, conv, was = "") { return true } +// ---- activity reports (magpie-community/plugins#691) ---- +// +// WorkBuddy AI's desktop client reports each chat on POST /v2/report, an +// array of events, and xxhhlk's capture of WorkBuddy AI 5.9.4 shows three +// such calls around one user send: chat_message_send; then +// chat_request_send, chat_message_response, chat_message_status and +// chat_request_response; then agent_task_completed and +// chat_response_complete. Each answered 200 {"code":0,"msg":"OK"}. On the +// same day the client's account was granted its daily credit and three +// accounts chatting through the plugin, which sent the growth event in the +// chat body alone (withGrowth), were not. Whether the credit reads these +// reports isn't known; they are what the official client sends for the +// user's own chat, so the plugin sends them for the user's own chats too, +// and never a chat of its own. +// +// Sent once the reply has been read to its end (reporting), with the token +// counts and the finish reason the reply gave. A step that ends in tool +// calls reports its message only; the request's events (chat_request_*, +// agent_task_completed, chat_response_complete) go with the step that +// ends the turn. chat_request_send goes with the step the user's own +// message opened. Best effort: a report that fails is dropped, and the +// chat's answer never waits on it. + +// reportSession is this process's session id, as the client's is its own +// run's. +const reportSession = randomBytes(16).toString("hex") + +// machineOf is a stable id for this computer, as the client sends one: a +// hash, so neither the host's name nor the user's is sent. +let machine +function machineOf() { + if (machine) return machine + let user = "" + try { + user = userInfo().username + } catch {} + return (machine = createHash("sha256").update(`magpie-workbuddy|${hostname()}|${user}`).digest("hex")) +} + +// reportBase is the fields every event carries (the capture's common set). +function reportBase(site, a, code) { + const cpu = cpus() + return { + eventCode: code, + buddyId: "", + buddyName: "", + timezone: Intl.DateTimeFormat().resolvedOptions().timeZone ?? "", + userId: a.uid ?? "", + username: a.name ?? "", + userNickname: a.name ?? "", + product: "SaaS", + commit: "", + ideName: "WorkBuddy", + ideType: "WorkBuddy", + ideVersion: site.app, + machineId: machineOf(), + sessionId: reportSession, + extName: site.appName, + extVersion: site.cli, + os: process.platform, + arch: arch(), + osVersion: release(), + cpuModel: cpu[0]?.model ?? "", + timestamp: Date.now(), + reportDelay: 0, + releaseDate: 0, + cpuCores: cpu.length, + memorySize: totalmem(), + } +} + +// replyFacts reads the token counts and the finish reason off the end of a +// reply, streamed or whole: the last usage object and the last +// finish_reason it names. +function replyFacts(tail) { + const out = { finish: "", input: 0, output: 0, total: 0, cached: 0 } + const reasons = [...tail.matchAll(/"finish_reason"\s*:\s*"([^"]+)"/g)] + if (reasons.length) out.finish = reasons.at(-1)[1] + const num = (k) => { + const m = [...tail.matchAll(new RegExp(`"${k}"\\s*:\\s*(\\d+)`, "g"))] + return m.length ? Number(m.at(-1)[1]) : 0 + } + out.input = num("prompt_tokens") + out.output = num("completion_tokens") + out.total = num("total_tokens") || out.input + out.output + out.cached = num("cached_tokens") + return out +} + +// reportEvents is the three /v2/report bodies for one step of a chat. +// t holds the step's ids, model, input length and whether the user's own +// message opened it; f is replyFacts of its reply; at its start and end +// times. +function reportEvents(site, a, t, f, start, end) { + const base = (code) => reportBase(site, a, code) + const name = site.models.find((m) => m[0] === t.model)?.[1] ?? t.model + const ids = { + conversationId: t.conv, + requestId: t.turn, + traceId: t.message, + rootRequestId: t.turn, + parentConversationId: "", + agentName: "", + agentType: "main", + "codebuddy.session_id": t.conv, + "codebuddy.conversation_request_id": t.turn, + } + const model = { requestModelId: t.model, requestModelName: name } + const tokens = { inputToken: f.input, outputToken: f.output, totalToken: f.total, cachedTokens: f.cached, cachedWriteTokens: 0, cachedMissTokens: Math.max(0, f.input - f.cached) } + const last = f.finish !== "tool_calls" + const ok = { isSuccessful: true, messageErrorCode: "", finishReason: f.finish || "stop" } + const first = [{ ...base("chat_message_send"), ...ids, messageId: t.message, ...model, historyCount: t.history, currentStepCount: t.step, totalStepCount: t.step, compactionCount: 0, presentAt: start, isContextTruncated: false }] + const second = [] + if (t.userSend) { + second.push({ + ...base("chat_request_send"), mode: "craft", source: "work", command: "", ...ids, ...model, + inputLength: t.input, mentionContextCount: 0, presentAt: start, + isPlan: false, isAutoExecuteTerminal: false, isAutoModify: false, codebaseEnable: false, isMaxMode: true, + mentionContexts: [], knowledgeId: [], knowledgeName: [], + codebaseId: "", inputAttemptId: "", recommendId: "", skillId: "", + vcsType: "", vcsRepo: "", vcsBranchName: "", vcsRevId: "", + }) + } + second.push({ ...base("chat_message_response"), ...ids, messageId: t.message, ...model, responseModelId: t.model, totalStepCount: t.step, ...tokens, firstTokenAt: start, presentAt: end, ...ok }) + second.push({ ...base("chat_message_status"), ...ids, messageId: t.message, ...model, messageErrorCode: "0" }) + const third = [] + if (last) { + const { traceId, ...noTrace } = ids + second.push({ ...base("chat_request_response"), mode: "craft", ...noTrace, ...model, toolCallCount: t.toolCalls, ...tokens, presentAt: end, ...ok }) + third.push({ ...base("agent_task_completed"), mode: "LOCAL", task_id: t.turn, duration_ms: Math.max(0, end - start), total_steps: t.step }) + third.push({ ...base("chat_response_complete"), conversationId: t.conv, requestId: t.turn, artifactType: "", source: "work" }) + } + return [first, second, third].filter((e) => e.length) +} + +// sendReports posts each body to /v2/report in turn, with the headers the +// client sends there; failures are dropped. +async function sendReports(site, a, bodies) { + for (const body of bodies) { + try { + const res = await fetch(endpointOf(site, a) + "/v2/report", { + method: "POST", + headers: { + Accept: "application/json, text/plain, */*", "Content-Type": "application/json", "User-Agent": cliAgent(site), + "X-Request-ID": hex(), "X-Product": "SaaS", Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", + "X-Domain": domainOf(site, a), "X-Requested-With": "XMLHttpRequest", ...enterpriseHeaders(a), + }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(15000), + }) + await res.body?.cancel().catch(() => {}) + } catch {} + } +} + +// TAIL is how much of a reply's end replyFacts reads: the usage chunk and +// the last finish_reason are in its last few events. +const TAIL = 16384 + +// reporting is res with the step's reports sent once its body has been +// read to the end. A reply cut off before its end, or not read, sends +// none: the client reports a send it saw answered. +function reporting(site, a, t, res) { + if (!res.body || !res.ok || a.source === "key") return res + const start = Date.now() + const dec = new TextDecoder() + let tail = "" + const body = res.body.pipeThrough( + new TransformStream({ + transform(chunk, ctl) { + tail = (tail + dec.decode(chunk, { stream: true })).slice(-TAIL) + ctl.enqueue(chunk) + }, + flush() { + tail = (tail + dec.decode()).slice(-TAIL) + sendReports(site, a, reportEvents(site, a, t, replyFacts(tail), start, Date.now())) + }, + }), + ) + return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers }) +} + +// stepOf is what reportEvents needs of a chat, read before it is sent: +// the model, the user's input length, whether the user's own message +// opened this step, the turn's step count and tool calls so far, and the +// history's length. +function stepOf(chat) { + const msgs = chat.messages + let step = 1 + let toolCalls = 0 + for (let i = msgs.length - 1; i >= 0; i--) { + const m = msgs[i] + if (m?.role === "user") break + if (m?.role === "assistant") { + step++ + toolCalls += Array.isArray(m.tool_calls) ? m.tool_calls.length : 0 + } + } + return { + model: typeof chat.model === "string" ? chat.model : "", + input: inputLengthOf(msgs), + userSend: msgs.at(-1)?.role === "user", + step, + toolCalls, + history: msgs.filter((m) => m?.role === "user" || m?.role === "assistant").length, + } +} + // regrown is a chat body given for conversation was given its growth event // for conv instead (withGrowth); null when it can't be read or isn't one. function regrown(site, b, was, conv) { @@ -4389,6 +4597,9 @@ function makePlugin(site) { if (hadVars) changed = true grownFor = headers.get("X-Conversation-ID") } + // what the step's activity reports (#691) need of the chat, + // read now: the chat is let go before it is sent + const step = completion && site.ai && Array.isArray(chat?.messages) ? stepOf(chat) : null const post = (b) => { // sent as another account (reattend), the chat's conversation // id is that account's, and so is its growth event's @@ -4521,7 +4732,12 @@ function makePlugin(site) { } if (ours.has(res)) return res // renewed here: a mark the account had comes off - return res.status >= 400 ? explained(res) : kept(native ? res : unsaid(await renamed(res, names)), renewed ? "renewed" : "kept") + if (res.status >= 400) return explained(res) + const told = native ? res : unsaid(await renamed(res, names)) + // the ids are the ones the chat went with, after any renewal + const conv = headers.get("X-Conversation-ID") ?? "" + const t = step && conv ? { ...step, conv, turn: headers.get("X-Conversation-Request-ID") ?? "", message: headers.get("X-Conversation-Message-ID") ?? "" } : null + return kept(t ? reporting(site, a, t, told) : told, renewed ? "renewed" : "kept") }, } }, @@ -4773,4 +4989,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { endpointOf, moved, at, signInsIn, importSignIns, importFrom, otherSite, withGrowth, inputLengthOf, HIDE_DSH, hideDsh, dshHidden, planCodes, listedExtra, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, freeWindowRouting, routingRefusalRows, readRoutingRefusals, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, CN_ESTIMATED_WINDOWS, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM, routingReads, routingParsed, restIdentity, routingLines, ROUTING_LINE_MAX } +export const _internal = { replyFacts, reportEvents, stepOf, reporting, machineOf, endpointOf, moved, at, signInsIn, importSignIns, importFrom, otherSite, withGrowth, inputLengthOf, HIDE_DSH, hideDsh, dshHidden, planCodes, listedExtra, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, freeWindowRouting, routingRefusalRows, readRoutingRefusals, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, CN_ESTIMATED_WINDOWS, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM, routingReads, routingParsed, restIdentity, routingLines, ROUTING_LINE_MAX } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 9836424..6f7088f 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.2.34", + "version": "0.2.35", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./opencode.mjs", diff --git a/packages/workbuddy/report.test.mjs b/packages/workbuddy/report.test.mjs new file mode 100644 index 0000000..0efcf12 --- /dev/null +++ b/packages/workbuddy/report.test.mjs @@ -0,0 +1,92 @@ +// WorkBuddy AI's client reports each chat on /v2/report (plugins#691); the +// plugin sends the same reports for the user's own chats, once the reply +// has been read to its end. Nothing leaves the machine. +import { afterEach, expect, test } from "bun:test" +import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs" + +const { replyFacts, stepOf } = _internal +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const SSE_STOP = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":120,"completion_tokens":8,"total_tokens":128,"prompt_tokens_details":{"cached_tokens":100}}}\n\ndata: [DONE]\n\n' +const SSE_TOOLS = 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":50,"completion_tokens":5,"total_tokens":55}}\n\ndata: [DONE]\n\n' + +async function chatThrough(plugin, body, reply, { read = true, status = 200, source } = {}) { + const sent = [] + const reports = [] + let done + const all = new Promise((r) => (done = r)) + globalThis.fetch = async (url, init) => { + const u = String(url) + if (u.endsWith("/v2/report")) { + reports.push({ url: u, headers: new Headers(init.headers), body: JSON.parse(init.body) }) + if (reports.length === 3 || reports.some((r) => r.body.some((e) => e.eventCode === "chat_response_complete")) || (reports.length === 2 && !reports[1].body.some((e) => e.eventCode === "chat_request_response"))) done() + return Response.json({ code: 0, msg: "OK" }) + } + sent.push(u) + return new Response(reply, { status, headers: { "content-type": "text/event-stream" } }) + } + const hooks = await plugin({ client: {} }) + const auth = source === "key" ? { type: "api", key: "sk-test" } : { type: "oauth", access: "tok", uid: "u1", name: "小明", expires: Date.now() + 3600_000 } + const l = await hooks.auth.loader(async () => auth) + const res = await l.fetch("https://www.workbuddy.ai/v2/chat/completions", { method: "POST", headers: new Headers(), body: JSON.stringify(body) }) + if (read) await res.text() + await Promise.race([all, new Promise((r) => setTimeout(r, 300))]) + return { res, sent, reports } +} + +const send = { model: "glm-5.3", stream: true, messages: [{ role: "system", content: "s" }, { role: "user", content: "你好呀" }] } +const call = { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{}" } }] } + +test("a user's send answered to its end is reported as the client reports it", async () => { + const { reports } = await chatThrough(WorkBuddyAIAuthPlugin, send, SSE_STOP) + expect(reports.map((r) => r.body.map((e) => e.eventCode))).toEqual([ + ["chat_message_send"], + ["chat_request_send", "chat_message_response", "chat_message_status", "chat_request_response"], + ["agent_task_completed", "chat_response_complete"], + ]) + const [first, second] = reports + expect(first.url).toBe("https://www.workbuddy.ai/v2/report") + expect(first.headers.get("authorization")).toBe("Bearer tok") + expect(first.headers.get("x-user-id")).toBe("u1") + expect(first.headers.get("x-product")).toBe("SaaS") + const msg = first.body[0] + expect(msg.userId).toBe("u1") + expect(msg.username).toBe("小明") + expect(msg.machineId).toMatch(/^[0-9a-f]{64}$/) + expect(msg.conversationId).toMatch(/^[0-9a-f]{32}$/) + const req = second.body[0] + expect(req.inputLength).toBe(3) + expect(req.requestModelId).toBe("glm-5.3") + const resp = second.body[1] + expect([resp.inputToken, resp.outputToken, resp.totalToken, resp.cachedTokens]).toEqual([120, 8, 128, 100]) + expect(resp.finishReason).toBe("stop") + // one conversation, one turn across every event + const all = reports.flatMap((r) => r.body) + expect(new Set(all.filter((e) => e.conversationId).map((e) => e.conversationId)).size).toBe(1) +}) + +test("a step that ends in tool calls reports its message only", async () => { + const { reports } = await chatThrough(WorkBuddyAIAuthPlugin, { ...send, messages: [...send.messages, call, { role: "tool", tool_call_id: "c1", content: "x" }] }, SSE_TOOLS) + expect(reports.map((r) => r.body.map((e) => e.eventCode))).toEqual([["chat_message_send"], ["chat_message_response", "chat_message_status"]]) +}) + +test("nothing is reported for a reply not read to its end, a refusal, the China build or a key", async () => { + expect((await chatThrough(WorkBuddyAIAuthPlugin, send, SSE_STOP, { read: false })).reports).toEqual([]) + expect((await chatThrough(WorkBuddyAIAuthPlugin, send, '{"error":{"message":"no"}}', { status: 400 })).reports).toEqual([]) + expect((await chatThrough(WorkBuddyAuthPlugin, send, SSE_STOP)).reports).toEqual([]) + expect((await chatThrough(WorkBuddyAIAuthPlugin, send, SSE_STOP, { source: "key" })).reports).toEqual([]) +}) + +test("the reply passes through unchanged", async () => { + const { res } = await chatThrough(WorkBuddyAIAuthPlugin, send, SSE_STOP, { read: false }) + expect(await res.text()).toBe(SSE_STOP) +}) + +test("replyFacts reads the last usage and finish reason; stepOf counts the turn's steps", () => { + expect(replyFacts('{"choices":[{"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}')).toEqual({ finish: "stop", input: 3, output: 2, total: 5, cached: 0 }) + expect(replyFacts("")).toEqual({ finish: "", input: 0, output: 0, total: 0, cached: 0 }) + const s = stepOf({ model: "m", messages: [{ role: "user", content: "ab" }, call, { role: "tool", content: "x" }, call, { role: "tool", content: "y" }] }) + expect(s).toMatchObject({ model: "m", input: 2, userSend: false, step: 3, toolCalls: 2 }) + expect(stepOf(send).userSend).toBe(true) +}) diff --git a/packages/workbuddy/testdata/sent.mjs b/packages/workbuddy/testdata/sent.mjs index a9bad17..e5e50d6 100644 --- a/packages/workbuddy/testdata/sent.mjs +++ b/packages/workbuddy/testdata/sent.mjs @@ -70,6 +70,9 @@ export async function sentBy(mod, freeOnly = false) { globalThis.fetch = async (url, init) => { const u = String(url) if (u.endsWith("/v3/config")) return Response.json(CONFIG) + // the activity reports a WorkBuddy AI chat is followed by since 0.2.35 + // (#691) aren't the chat; report.test.mjs holds them + if (u.endsWith("/v2/report")) return Response.json({ code: 0, msg: "OK" }) const h = new Headers(init?.headers) const text = unz(init?.body) let s = typeof text === "string" ? text : new TextDecoder().decode(text)