workbuddy 0.2.31: a WorkBuddy AI chat carries the client's chat_request_send growth event (#691)
WorkBuddy AI has no check-in; its daily credit follows a finished chat in the official client. The reporters' capture shows the official chat body carries extra_vars.growthEvent, a JSON string array holding one chat_request_send event (conversation id, input length, model id and name, mode "craft"), and initiator "user". The WorkBuddy AI CLI 5.6.2 builds the same event in reportChatRequestSendTelemetry/appendGrowthEvent. The plugin now adds that event to every WorkBuddy AI chat (the CN site is unchanged), keeps any events and initiator the caller already sent, gives the event the retrying account's conversation on a retry, and inserts extra_vars into the body as text so the rest of it goes as written (#461). initiator comes from the 5.9.4 capture; the 5.6.2 CLI doesn't set it. Run (WSL, Bun 1.4.2, temp HOME): - bun test packages: 366 pass, 0 fail (6 new in growth.test.mjs). - bun scripts/check.mjs workbuddy: ok. Broken by hand on a separate test Mac: dropping the event, the initiator, the retry rewrite or the text insert: 6 fail, then restored. Not tried: a real WorkBuddy AI account. Whether the next day's credit lands is unproven, so #691 stays open for the reporters. Reported-by: xxhhlk Reported-by: dgqyushen
This commit is contained in:
@@ -174,6 +174,15 @@ Not sent: `X-Device-Token`, which the desktop app gets from Tencent's
|
||||
native device SDK before each prompt, and a `traceparent`, which the CLI
|
||||
adds only while its server-side tracing is on.
|
||||
|
||||
A WorkBuddy AI chat also carries, in its body, the `extra_vars` its own
|
||||
client sends (#691): `initiator: "user"` and `growthEvent`, a JSON string
|
||||
holding a `chat_request_send` event for the chat's `X-Conversation-ID`, with
|
||||
the user's last message's length, the model's id and name, `mode: "craft"`
|
||||
and no command. WorkBuddy AI's CLI sends this event in the chat itself
|
||||
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.
|
||||
|
||||
A chat that doesn't open with a system message is given WorkBuddy's
|
||||
default one, as the app does.
|
||||
|
||||
|
||||
@@ -119,7 +119,13 @@ test("a chat goes gzipped, as WorkBuddy's client sends it, on both builds", asyn
|
||||
expect(c.headers.get("content-encoding")).toBe("gzip")
|
||||
expect(c.headers.has("content-length")).toBe(false)
|
||||
expect(typeof c.wire).not.toBe("string")
|
||||
expect(JSON.parse(c.text)).toEqual(JSON.parse(body))
|
||||
// WorkBuddy AI's chat carries its growth event too (growth.test.mjs)
|
||||
const got = JSON.parse(c.text)
|
||||
if (plugin === WorkBuddyAIAuthPlugin) {
|
||||
expect(got.extra_vars.initiator).toBe("user")
|
||||
delete got.extra_vars
|
||||
}
|
||||
expect(got).toEqual(JSON.parse(body))
|
||||
expect(c.wire.byteLength * 5).toBeLessThan(Buffer.byteLength(body))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// WorkBuddy AI's client sends, in a chat's own body, extra_vars.growthEvent:
|
||||
// a JSON string of growth events holding a chat_request_send for the
|
||||
// conversation, and initiator "user" (magpie-community/plugins#691). The
|
||||
// China build's chats go as before. Nothing leaves the machine.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs"
|
||||
import { unz } from "./testdata/unz.mjs"
|
||||
|
||||
const { withGrowth, inputLengthOf, SITES } = _internal
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
|
||||
async function ask(body, { plugin = WorkBuddyAIAuthPlugin, url = "https://www.workbuddy.ai/v2/chat/completions" } = {}) {
|
||||
let sent
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
sent = { headers: new Headers(init?.headers), body: JSON.parse(unz(init.body)) }
|
||||
return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
const hooks = await plugin({ client: {} })
|
||||
const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", uid: "u1", expires: Date.now() + 3600_000 }))
|
||||
const res = await l.fetch(url, { method: "POST", body: JSON.stringify(body) })
|
||||
expect(res.status).toBe(200)
|
||||
return sent
|
||||
}
|
||||
|
||||
const call = { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{}" } }] }
|
||||
const result = { role: "tool", tool_call_id: "c1", content: "a long tool result that is not the user's input" }
|
||||
|
||||
test("a WorkBuddy AI chat carries the client's chat_request_send growth event and initiator", async () => {
|
||||
const sent = await ask({
|
||||
model: "gpt-5.5",
|
||||
stream: true,
|
||||
messages: [{ role: "system", content: "be brief" }, { role: "user", content: "hello" }, { role: "assistant", content: "hi" }, { role: "user", content: "跑一下测试" }],
|
||||
})
|
||||
const vars = sent.body.extra_vars
|
||||
expect(vars.initiator).toBe("user")
|
||||
expect(typeof vars.growthEvent).toBe("string")
|
||||
const events = JSON.parse(vars.growthEvent)
|
||||
expect(events).toEqual([{
|
||||
eventCode: "chat_request_send",
|
||||
id: sent.headers.get("x-conversation-id"),
|
||||
extra: { inputLength: 5, requestModelId: "gpt-5.5", requestModelName: "GPT-5.5", mode: "craft", command: "" },
|
||||
}])
|
||||
expect(events[0].id).toBeTruthy()
|
||||
})
|
||||
|
||||
test("a tool step's event counts the user's message, not the tool's result", async () => {
|
||||
const sent = await ask({ model: "custom-x", stream: true, messages: [{ role: "user", content: [{ type: "text", text: "run" }, { type: "text", text: " it" }] }, call, result] })
|
||||
const [e] = JSON.parse(sent.body.extra_vars.growthEvent)
|
||||
expect(e.extra.inputLength).toBe(6)
|
||||
// a model the table doesn't name goes by its id
|
||||
expect(e.extra.requestModelName).toBe("custom-x")
|
||||
})
|
||||
|
||||
test("the caller's extra_vars and events are kept", async () => {
|
||||
const own = { eventCode: "expert_actual_use", id: "e1" }
|
||||
const sent = await ask({ model: "gpt-5.5", stream: true, extra_vars: { a: 1, initiator: "agent", growthEvent: JSON.stringify([own]) }, messages: [{ role: "user", content: "hi" }] })
|
||||
const vars = sent.body.extra_vars
|
||||
expect(vars.a).toBe(1)
|
||||
expect(vars.initiator).toBe("agent")
|
||||
const events = JSON.parse(vars.growthEvent)
|
||||
expect(events[0]).toEqual(own)
|
||||
expect(events[1].eventCode).toBe("chat_request_send")
|
||||
})
|
||||
|
||||
test("the China build's chat and a non-chat go without it", async () => {
|
||||
const cn = await ask({ model: "glm-5.3", stream: true, messages: [{ role: "user", content: "hi" }] }, { plugin: WorkBuddyAuthPlugin, url: "https://copilot.tencent.com/v2/chat/completions" })
|
||||
expect(cn.body.extra_vars).toBeUndefined()
|
||||
const chat = { model: "gpt-5.5", messages: [{ role: "user", content: "hi" }] }
|
||||
expect(withGrowth(SITES["workbuddy-ai"], chat, "")).toBe(false)
|
||||
expect(chat.extra_vars).toBeUndefined()
|
||||
})
|
||||
|
||||
test("sent as another account, the event is that conversation's alone", () => {
|
||||
const chat = { model: "gpt-5.5", messages: [{ role: "user", content: "hi" }] }
|
||||
withGrowth(SITES["workbuddy-ai"], chat, "conv-a")
|
||||
withGrowth(SITES["workbuddy-ai"], chat, "conv-b", "conv-a")
|
||||
expect(JSON.parse(chat.extra_vars.growthEvent).map((e) => e.id)).toEqual(["conv-b"])
|
||||
expect(inputLengthOf([])).toBe(0)
|
||||
})
|
||||
|
||||
test("a chat nothing else changes keeps its own bytes, the vars set before its closing brace", async () => {
|
||||
const body = `{"model": "gpt-5.5", "stream": true, "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}], "reasoning_effort": "low"}`
|
||||
let text
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
text = unz(init.body)
|
||||
return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
const hooks = await WorkBuddyAIAuthPlugin({ client: {} })
|
||||
const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", uid: "u1", expires: Date.now() + 3600_000 }))
|
||||
await l.fetch("https://www.workbuddy.ai/v2/chat/completions", { method: "POST", body })
|
||||
expect(text.startsWith(body.slice(0, -1) + ',"extra_vars":{"growthEvent":')).toBe(true)
|
||||
expect(JSON.parse(text).extra_vars.initiator).toBe("user")
|
||||
})
|
||||
@@ -1504,6 +1504,90 @@ function fitted(body) {
|
||||
}
|
||||
}
|
||||
|
||||
// GROWTH_SEND is the growth event WorkBuddy's client puts in a chat's own
|
||||
// body for the user's send (Events.ChatRequestSend).
|
||||
const GROWTH_SEND = "chat_request_send"
|
||||
|
||||
// withGrowth gives a WorkBuddy AI chat the extra_vars its own client sends
|
||||
// (magpie-community/plugins#691): `growthEvent`, a JSON string holding an
|
||||
// array of growth events, and `initiator: "user"`. WorkBuddy AI 5.6.2's CLI
|
||||
// (codebuddy-lite-wb.mjs, reportChatRequestSendTelemetry) builds the
|
||||
// chat_request_send event as {eventCode, id: the conversation's id, extra:
|
||||
// {inputLength, requestModelId, requestModelName, mode, command, expertId}}
|
||||
// and, when its growth flag is on, sends it in the chat body
|
||||
// (appendGrowthEvent into providerData.extra_vars) instead of reporting it
|
||||
// on /v2/report; a 5.9.4 capture (#691) carries it there, with initiator
|
||||
// "user". Nothing proves WorkBuddy reads it for the daily credit; it is the
|
||||
// only per-chat activity mark the client sends with the chat itself.
|
||||
//
|
||||
// Built from the chat alone: inputLength is the length of the user's last
|
||||
// own message (its text, as the CLI's getInputLength counts it), the model
|
||||
// is the chat's, its name the site's table's (else the id), mode "craft"
|
||||
// (the X-Agent-Intent it is sent with) and no command. conv is the chat's
|
||||
// X-Conversation-ID; with none, nothing is added. An event the caller put
|
||||
// there is kept; was is the conversation id an earlier call gave the event
|
||||
// for, whose event this one replaces (the chat sent as another account).
|
||||
// true when the chat changed.
|
||||
function withGrowth(site, chat, conv, was = "") {
|
||||
if (!site.ai || !conv || !chat || typeof chat !== "object" || !Array.isArray(chat.messages)) return false
|
||||
const vars = chat.extra_vars !== null && typeof chat.extra_vars === "object" && !Array.isArray(chat.extra_vars) ? chat.extra_vars : {}
|
||||
let events = []
|
||||
if (typeof vars.growthEvent === "string" && vars.growthEvent.trim()) {
|
||||
try {
|
||||
const v = JSON.parse(vars.growthEvent)
|
||||
events = Array.isArray(v) ? v : [v]
|
||||
} catch {}
|
||||
}
|
||||
if (was) events = events.filter((e) => !(e?.eventCode === GROWTH_SEND && e?.id === was))
|
||||
const model = typeof chat.model === "string" ? chat.model : ""
|
||||
const event = {
|
||||
eventCode: GROWTH_SEND,
|
||||
id: conv,
|
||||
extra: {
|
||||
inputLength: inputLengthOf(chat.messages),
|
||||
requestModelId: model,
|
||||
requestModelName: site.models.find((m) => m[0] === model)?.[1] ?? model,
|
||||
mode: "craft",
|
||||
command: "",
|
||||
},
|
||||
}
|
||||
if (!events.some((e) => e?.eventCode === GROWTH_SEND && e?.id === conv)) events.push(event)
|
||||
chat.extra_vars = { ...vars, growthEvent: JSON.stringify(events), initiator: vars.initiator ?? "user" }
|
||||
return true
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const chat = chatOf(typeof b === "string" ? b : bodyString(b))
|
||||
return chat && withGrowth(site, chat, conv, was) ? JSON.stringify(chat) : null
|
||||
}
|
||||
|
||||
// withVars is a chat body, as text, with extra_vars set as its last field
|
||||
// and every byte it had kept: the vars go in before the object's closing
|
||||
// brace. For a chat that names no extra_vars of its own (withGrowth).
|
||||
function withVars(body, vars) {
|
||||
if (typeof body !== "string") return body
|
||||
const i = body.lastIndexOf("}")
|
||||
if (i < 0) return body
|
||||
const open = /\{\s*$/.test(body.slice(0, i))
|
||||
return body.slice(0, i) + (open ? "" : ",") + '"extra_vars":' + JSON.stringify(vars) + "}" + body.slice(i + 1)
|
||||
}
|
||||
|
||||
// inputLengthOf is the length of the chat's last user message that is the
|
||||
// user's own (not a tool's result): its text, as WorkBuddy's CLI counts a
|
||||
// user input (TelemetryUtils.getInputLength); 0 when there is none.
|
||||
function inputLengthOf(msgs) {
|
||||
for (let i = msgs.length - 1; i >= 0; i--) {
|
||||
if (msgs[i]?.role !== "user" || answeredBefore(msgs, i)) continue
|
||||
const c = msgs[i].content
|
||||
if (typeof c === "string") return c.length
|
||||
if (!Array.isArray(c)) return 0
|
||||
return c.reduce((n, p) => n + ((p?.type ?? "text") === "text" && typeof p?.text === "string" ? p.text.length : 0), 0)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// gzipped is a chat's body compressed, as WorkBuddy's own client sends its
|
||||
// model requests: its CLI's GzipRequestProcessor (WorkBuddy 5.9.3, CLI
|
||||
// 2.165.0, on both builds) gzips each POST's body and sets
|
||||
@@ -4033,7 +4117,22 @@ function makePlugin(site) {
|
||||
chatHeaders(site, headers)
|
||||
let who = scopeOf(a)
|
||||
let ids = attendChat(headers, chat, session, who)
|
||||
// the growth event WorkBuddy AI's client sends with a chat (#691),
|
||||
// for the conversation id the chat goes with
|
||||
let grownFor = ""
|
||||
// a chat nothing else changes has the vars set into its own
|
||||
// bytes (withVars), so it isn't written out again whole for
|
||||
// them (plugins#461); one that named extra_vars is written out
|
||||
const hadVars = !!chat && typeof chat === "object" && Object.hasOwn(chat, "extra_vars")
|
||||
if (completion && withGrowth(site, chat, headers.get("X-Conversation-ID") ?? "")) {
|
||||
if (hadVars) changed = true
|
||||
grownFor = headers.get("X-Conversation-ID")
|
||||
}
|
||||
const post = (b) => {
|
||||
// sent as another account (reattend), the chat's conversation
|
||||
// id is that account's, and so is its growth event's
|
||||
const conv = headers.get("X-Conversation-ID") ?? ""
|
||||
if (grownFor && conv && conv !== grownFor) b = regrown(site, b, grownFor, conv) ?? b
|
||||
// a chat goes gzipped, as WorkBuddy's client sends it
|
||||
// (gzipped); its size on the wire is what unanswered weighs
|
||||
const z = gzipped(completion, b)
|
||||
@@ -4103,6 +4202,7 @@ function makePlugin(site) {
|
||||
const shaped = (b) => (!native && endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b)
|
||||
if (!native && endsAfterTools.has(model) && replyAfterToolsOn(chat)) changed = true
|
||||
if (changed) body = JSON.stringify(chat)
|
||||
else if (grownFor) body = withVars(body, chat.extra_vars)
|
||||
chat = null
|
||||
let res = await send(body)
|
||||
// a signature WorkBuddy's own signing didn't make — a session
|
||||
@@ -4408,4 +4508,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
|
||||
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
|
||||
|
||||
// for tests
|
||||
export const _internal = { 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 }
|
||||
export const _internal = { 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 }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-workbuddy-auth",
|
||||
"version": "0.2.30",
|
||||
"version": "0.2.31",
|
||||
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
Vendored
+17
-2
@@ -56,6 +56,10 @@ export const CHATS = [
|
||||
["not json", "https://www.workbuddy.ai/v2/chat/completions", "{not json"],
|
||||
]
|
||||
|
||||
// GROWN is the extra_vars a WorkBuddy AI chat is sent with (withGrowth),
|
||||
// set before the body's closing brace
|
||||
const GROWN = /,"extra_vars":(\{"growthEvent":"(?:[^"\\]|\\.)*","initiator":"user"\})(?=\}\s*$)/
|
||||
|
||||
const sha = (s) => createHash("sha256").update(s ?? "").digest("hex")
|
||||
|
||||
// sentBy(mod, freeOnly) is what mod's WorkBuddy AI plugin sent for CHATS,
|
||||
@@ -68,8 +72,19 @@ export async function sentBy(mod, freeOnly = false) {
|
||||
if (u.endsWith("/v3/config")) return Response.json(CONFIG)
|
||||
const h = new Headers(init?.headers)
|
||||
const text = unz(init?.body)
|
||||
const s = typeof text === "string" ? text : new TextDecoder().decode(text)
|
||||
sent.push({ url: u, encoding: h.get("content-encoding"), body: sha(s), conversation: h.get("x-conversation-id"), turn: h.get("x-conversation-request-id") })
|
||||
let s = typeof text === "string" ? text : new TextDecoder().decode(text)
|
||||
// the growth event a WorkBuddy AI chat carries since 0.2.31 (#691) is
|
||||
// set as the body's last field; what is left is held to 0.1.43's bytes,
|
||||
// and the event to the conversation the request went as
|
||||
const grown = GROWN.exec(s)
|
||||
const row = { url: u, encoding: h.get("content-encoding"), body: "", conversation: h.get("x-conversation-id"), turn: h.get("x-conversation-request-id") }
|
||||
if (grown) {
|
||||
s = s.slice(0, grown.index) + s.slice(grown.index + grown[0].length)
|
||||
const ev = JSON.parse(JSON.parse(grown[1]).growthEvent)
|
||||
if (ev.length !== 1 || ev[0].eventCode !== "chat_request_send" || ev[0].id !== row.conversation) row.growth = ev
|
||||
}
|
||||
row.body = sha(s)
|
||||
sent.push(row)
|
||||
if (s.includes("REFUSE-461") && s.includes('"role":"system","content":"REFUSE-461')) return new Response(REFUSAL, { status: 400, headers: { "content-type": "application/json" } })
|
||||
if (s.includes('"gemini-sent-461"')) {
|
||||
const m = JSON.parse(s).messages
|
||||
|
||||
Reference in New Issue
Block a user