@jianmu-plugins/opencode-workbuddy-auth 0.2.34 → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +16 -1
  2. package/index.mjs +237 -10
  3. package/package.json +3 -5
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @magpie-community/opencode-workbuddy-auth
1
+ # @jianmu-plugins/opencode-workbuddy-auth
2
2
 
3
3
  Signs in to the plans of WorkBuddy, Tencent's desktop agent from CodeBuddy.
4
4
  It has one provider for each of WorkBuddy's two builds:
@@ -205,6 +205,21 @@ instead of on `/v2/report`; whether WorkBuddy reads it for the daily credit
205
205
  is not known. Anything the caller put in `extra_vars` is kept. The China
206
206
  build's chats go without it.
207
207
 
208
+ Since 0.2.35 a WorkBuddy AI chat is also reported on `POST /v2/report`, as
209
+ WorkBuddy AI 5.9.4's client reports one (#691): once the reply has been
210
+ read to its end, `chat_message_send`, then `chat_message_response` and
211
+ `chat_message_status` (with `chat_request_send` first when the user's own
212
+ message opened the step, and `chat_request_response` last when the step
213
+ ends the turn), then `agent_task_completed` and `chat_response_complete`
214
+ for a step that ends it. They carry the chat's ids, model, token counts and
215
+ finish reason, and the client's common fields: the account's id and name,
216
+ WorkBuddy's version, this computer's OS, CPU and memory, and a machine id
217
+ that is a hash of the host's and user's names. Only the user's own chats
218
+ are reported, never a message of the plugin's own; a reply cut off, a
219
+ refusal, a key account and the China build send none, and a report that
220
+ fails is dropped. Whether the daily credit reads these reports is not
221
+ known yet.
222
+
208
223
  A chat that doesn't open with a system message is given WorkBuddy's
209
224
  default one, as the app does.
210
225
 
package/index.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { createHash, randomBytes } from "node:crypto"
13
13
  import { closeSync, createReadStream, openSync, readFileSync, readdirSync, readSync, statSync } from "node:fs"
14
- import { homedir } from "node:os"
14
+ import { arch, cpus, homedir, hostname, release, totalmem, userInfo } from "node:os"
15
15
  import { dirname, isAbsolute, join } from "node:path"
16
16
  import { createGunzip, gzipSync } from "node:zlib"
17
17
 
@@ -1602,6 +1602,214 @@ function withGrowth(site, chat, conv, was = "") {
1602
1602
  return true
1603
1603
  }
1604
1604
 
1605
+ // ---- activity reports (magpie-community/plugins#691) ----
1606
+ //
1607
+ // WorkBuddy AI's desktop client reports each chat on POST /v2/report, an
1608
+ // array of events, and xxhhlk's capture of WorkBuddy AI 5.9.4 shows three
1609
+ // such calls around one user send: chat_message_send; then
1610
+ // chat_request_send, chat_message_response, chat_message_status and
1611
+ // chat_request_response; then agent_task_completed and
1612
+ // chat_response_complete. Each answered 200 {"code":0,"msg":"OK"}. On the
1613
+ // same day the client's account was granted its daily credit and three
1614
+ // accounts chatting through the plugin, which sent the growth event in the
1615
+ // chat body alone (withGrowth), were not. Whether the credit reads these
1616
+ // reports isn't known; they are what the official client sends for the
1617
+ // user's own chat, so the plugin sends them for the user's own chats too,
1618
+ // and never a chat of its own.
1619
+ //
1620
+ // Sent once the reply has been read to its end (reporting), with the token
1621
+ // counts and the finish reason the reply gave. A step that ends in tool
1622
+ // calls reports its message only; the request's events (chat_request_*,
1623
+ // agent_task_completed, chat_response_complete) go with the step that
1624
+ // ends the turn. chat_request_send goes with the step the user's own
1625
+ // message opened. Best effort: a report that fails is dropped, and the
1626
+ // chat's answer never waits on it.
1627
+
1628
+ // reportSession is this process's session id, as the client's is its own
1629
+ // run's.
1630
+ const reportSession = randomBytes(16).toString("hex")
1631
+
1632
+ // machineOf is a stable id for this computer, as the client sends one: a
1633
+ // hash, so neither the host's name nor the user's is sent.
1634
+ let machine
1635
+ function machineOf() {
1636
+ if (machine) return machine
1637
+ let user = ""
1638
+ try {
1639
+ user = userInfo().username
1640
+ } catch {}
1641
+ return (machine = createHash("sha256").update(`magpie-workbuddy|${hostname()}|${user}`).digest("hex"))
1642
+ }
1643
+
1644
+ // reportBase is the fields every event carries (the capture's common set).
1645
+ function reportBase(site, a, code) {
1646
+ const cpu = cpus()
1647
+ return {
1648
+ eventCode: code,
1649
+ buddyId: "",
1650
+ buddyName: "",
1651
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone ?? "",
1652
+ userId: a.uid ?? "",
1653
+ username: a.name ?? "",
1654
+ userNickname: a.name ?? "",
1655
+ product: "SaaS",
1656
+ commit: "",
1657
+ ideName: "WorkBuddy",
1658
+ ideType: "WorkBuddy",
1659
+ ideVersion: site.app,
1660
+ machineId: machineOf(),
1661
+ sessionId: reportSession,
1662
+ extName: site.appName,
1663
+ extVersion: site.cli,
1664
+ os: process.platform,
1665
+ arch: arch(),
1666
+ osVersion: release(),
1667
+ cpuModel: cpu[0]?.model ?? "",
1668
+ timestamp: Date.now(),
1669
+ reportDelay: 0,
1670
+ releaseDate: 0,
1671
+ cpuCores: cpu.length,
1672
+ memorySize: totalmem(),
1673
+ }
1674
+ }
1675
+
1676
+ // replyFacts reads the token counts and the finish reason off the end of a
1677
+ // reply, streamed or whole: the last usage object and the last
1678
+ // finish_reason it names.
1679
+ function replyFacts(tail) {
1680
+ const out = { finish: "", input: 0, output: 0, total: 0, cached: 0 }
1681
+ const reasons = [...tail.matchAll(/"finish_reason"\s*:\s*"([^"]+)"/g)]
1682
+ if (reasons.length) out.finish = reasons.at(-1)[1]
1683
+ const num = (k) => {
1684
+ const m = [...tail.matchAll(new RegExp(`"${k}"\\s*:\\s*(\\d+)`, "g"))]
1685
+ return m.length ? Number(m.at(-1)[1]) : 0
1686
+ }
1687
+ out.input = num("prompt_tokens")
1688
+ out.output = num("completion_tokens")
1689
+ out.total = num("total_tokens") || out.input + out.output
1690
+ out.cached = num("cached_tokens")
1691
+ return out
1692
+ }
1693
+
1694
+ // reportEvents is the three /v2/report bodies for one step of a chat.
1695
+ // t holds the step's ids, model, input length and whether the user's own
1696
+ // message opened it; f is replyFacts of its reply; at its start and end
1697
+ // times.
1698
+ function reportEvents(site, a, t, f, start, end) {
1699
+ const base = (code) => reportBase(site, a, code)
1700
+ const name = site.models.find((m) => m[0] === t.model)?.[1] ?? t.model
1701
+ const ids = {
1702
+ conversationId: t.conv,
1703
+ requestId: t.turn,
1704
+ traceId: t.message,
1705
+ rootRequestId: t.turn,
1706
+ parentConversationId: "",
1707
+ agentName: "",
1708
+ agentType: "main",
1709
+ "codebuddy.session_id": t.conv,
1710
+ "codebuddy.conversation_request_id": t.turn,
1711
+ }
1712
+ const model = { requestModelId: t.model, requestModelName: name }
1713
+ const tokens = { inputToken: f.input, outputToken: f.output, totalToken: f.total, cachedTokens: f.cached, cachedWriteTokens: 0, cachedMissTokens: Math.max(0, f.input - f.cached) }
1714
+ const last = f.finish !== "tool_calls"
1715
+ const ok = { isSuccessful: true, messageErrorCode: "", finishReason: f.finish || "stop" }
1716
+ 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 }]
1717
+ const second = []
1718
+ if (t.userSend) {
1719
+ second.push({
1720
+ ...base("chat_request_send"), mode: "craft", source: "work", command: "", ...ids, ...model,
1721
+ inputLength: t.input, mentionContextCount: 0, presentAt: start,
1722
+ isPlan: false, isAutoExecuteTerminal: false, isAutoModify: false, codebaseEnable: false, isMaxMode: true,
1723
+ mentionContexts: [], knowledgeId: [], knowledgeName: [],
1724
+ codebaseId: "", inputAttemptId: "", recommendId: "", skillId: "",
1725
+ vcsType: "", vcsRepo: "", vcsBranchName: "", vcsRevId: "",
1726
+ })
1727
+ }
1728
+ second.push({ ...base("chat_message_response"), ...ids, messageId: t.message, ...model, responseModelId: t.model, totalStepCount: t.step, ...tokens, firstTokenAt: start, presentAt: end, ...ok })
1729
+ second.push({ ...base("chat_message_status"), ...ids, messageId: t.message, ...model, messageErrorCode: "0" })
1730
+ const third = []
1731
+ if (last) {
1732
+ const { traceId, ...noTrace } = ids
1733
+ second.push({ ...base("chat_request_response"), mode: "craft", ...noTrace, ...model, toolCallCount: t.toolCalls, ...tokens, presentAt: end, ...ok })
1734
+ third.push({ ...base("agent_task_completed"), mode: "LOCAL", task_id: t.turn, duration_ms: Math.max(0, end - start), total_steps: t.step })
1735
+ third.push({ ...base("chat_response_complete"), conversationId: t.conv, requestId: t.turn, artifactType: "", source: "work" })
1736
+ }
1737
+ return [first, second, third].filter((e) => e.length)
1738
+ }
1739
+
1740
+ // sendReports posts each body to /v2/report in turn, with the headers the
1741
+ // client sends there; failures are dropped.
1742
+ async function sendReports(site, a, bodies) {
1743
+ for (const body of bodies) {
1744
+ try {
1745
+ const res = await fetch(endpointOf(site, a) + "/v2/report", {
1746
+ method: "POST",
1747
+ headers: {
1748
+ Accept: "application/json, text/plain, */*", "Content-Type": "application/json", "User-Agent": cliAgent(site),
1749
+ "X-Request-ID": hex(), "X-Product": "SaaS", Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "",
1750
+ "X-Domain": domainOf(site, a), "X-Requested-With": "XMLHttpRequest", ...enterpriseHeaders(a),
1751
+ },
1752
+ body: JSON.stringify(body),
1753
+ signal: AbortSignal.timeout(15000),
1754
+ })
1755
+ await res.body?.cancel().catch(() => {})
1756
+ } catch {}
1757
+ }
1758
+ }
1759
+
1760
+ // TAIL is how much of a reply's end replyFacts reads: the usage chunk and
1761
+ // the last finish_reason are in its last few events.
1762
+ const TAIL = 16384
1763
+
1764
+ // reporting is res with the step's reports sent once its body has been
1765
+ // read to the end. A reply cut off before its end, or not read, sends
1766
+ // none: the client reports a send it saw answered.
1767
+ function reporting(site, a, t, res) {
1768
+ if (!res.body || !res.ok || a.source === "key") return res
1769
+ const start = Date.now()
1770
+ const dec = new TextDecoder()
1771
+ let tail = ""
1772
+ const body = res.body.pipeThrough(
1773
+ new TransformStream({
1774
+ transform(chunk, ctl) {
1775
+ tail = (tail + dec.decode(chunk, { stream: true })).slice(-TAIL)
1776
+ ctl.enqueue(chunk)
1777
+ },
1778
+ flush() {
1779
+ tail = (tail + dec.decode()).slice(-TAIL)
1780
+ sendReports(site, a, reportEvents(site, a, t, replyFacts(tail), start, Date.now()))
1781
+ },
1782
+ }),
1783
+ )
1784
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
1785
+ }
1786
+
1787
+ // stepOf is what reportEvents needs of a chat, read before it is sent:
1788
+ // the model, the user's input length, whether the user's own message
1789
+ // opened this step, the turn's step count and tool calls so far, and the
1790
+ // history's length.
1791
+ function stepOf(chat) {
1792
+ const msgs = chat.messages
1793
+ let step = 1
1794
+ let toolCalls = 0
1795
+ for (let i = msgs.length - 1; i >= 0; i--) {
1796
+ const m = msgs[i]
1797
+ if (m?.role === "user") break
1798
+ if (m?.role === "assistant") {
1799
+ step++
1800
+ toolCalls += Array.isArray(m.tool_calls) ? m.tool_calls.length : 0
1801
+ }
1802
+ }
1803
+ return {
1804
+ model: typeof chat.model === "string" ? chat.model : "",
1805
+ input: inputLengthOf(msgs),
1806
+ userSend: msgs.at(-1)?.role === "user",
1807
+ step,
1808
+ toolCalls,
1809
+ history: msgs.filter((m) => m?.role === "user" || m?.role === "assistant").length,
1810
+ }
1811
+ }
1812
+
1605
1813
  // regrown is a chat body given for conversation was given its growth event
1606
1814
  // for conv instead (withGrowth); null when it can't be read or isn't one.
1607
1815
  function regrown(site, b, was, conv) {
@@ -2594,6 +2802,8 @@ const CN_ESTIMATED_WINDOWS = [
2594
2802
  aliases: ["deepseek-v4.1-flash-sg"],
2595
2803
  cap: 2e8,
2596
2804
  name: "deepseek-v4.1-flash tokens (est.)",
2805
+ // the card WorkBuddy's refusal makes: nothing in it is estimated
2806
+ refusedName: "deepseek-v4.1-flash tokens",
2597
2807
  short: "~200M",
2598
2808
  // no unit: the name already says tokens, and magpie's narrow account
2599
2809
  // cards cut a unit short ("tok…") beside the nine-digit numbers
@@ -2758,12 +2968,21 @@ function freeWindowOf(rows, account, now = Date.now(), win = FREE_WINDOW_AI) {
2758
2968
  if (now >= end) return null // lapsed: nothing is exhausted, a new window opens on the next request
2759
2969
 
2760
2970
  const card = (amount, resetsAt, refused) => ({
2761
- name: win.name,
2762
- used: Math.min(100, (100 * amount) / win.cap),
2763
- amount,
2764
- limit: win.cap,
2765
- unit: win.unit,
2766
- display: `${tokensShort(amount)} / ${win.short}`,
2971
+ name: (refused && win.refusedName) || win.name,
2972
+ // A refusal is the vendor's word that the window is spent, and says
2973
+ // nothing of a count: the card says 100% used and when WorkBuddy said it
2974
+ // resets, with no tokens. It used to say the cap as its count,
2975
+ // "200,000,000 / 200,000,000" under "(est.)", a number nothing measured,
2976
+ // which read as magpie's estimate gone wrong (wsyfree on X).
2977
+ ...(refused
2978
+ ? { used: 100, display: "" }
2979
+ : {
2980
+ used: Math.min(100, (100 * amount) / win.cap),
2981
+ amount,
2982
+ limit: win.cap,
2983
+ unit: win.unit,
2984
+ display: `${tokensShort(amount)} / ${win.short}`,
2985
+ }),
2767
2986
  resetsAt: new Date(resetsAt).toISOString(),
2768
2987
  span: FREE_WINDOW_SPAN / 1000,
2769
2988
  // the window's own model and the ids that share it, so magpie's exact
@@ -2785,7 +3004,7 @@ function freeWindowOf(rows, account, now = Date.now(), win = FREE_WINDOW_AI) {
2785
3004
  if (!Number.isFinite(t) || t <= now || t <= start) continue
2786
3005
  if (live === null || t > live) live = t
2787
3006
  }
2788
- if (live !== null) return card(win.cap, live, true)
3007
+ if (live !== null) return card(0, live, true)
2789
3008
 
2790
3009
  return card(used, end, false)
2791
3010
  }
@@ -4389,6 +4608,9 @@ function makePlugin(site) {
4389
4608
  if (hadVars) changed = true
4390
4609
  grownFor = headers.get("X-Conversation-ID")
4391
4610
  }
4611
+ // what the step's activity reports (#691) need of the chat,
4612
+ // read now: the chat is let go before it is sent
4613
+ const step = completion && site.ai && Array.isArray(chat?.messages) ? stepOf(chat) : null
4392
4614
  const post = (b) => {
4393
4615
  // sent as another account (reattend), the chat's conversation
4394
4616
  // id is that account's, and so is its growth event's
@@ -4521,7 +4743,12 @@ function makePlugin(site) {
4521
4743
  }
4522
4744
  if (ours.has(res)) return res
4523
4745
  // renewed here: a mark the account had comes off
4524
- return res.status >= 400 ? explained(res) : kept(native ? res : unsaid(await renamed(res, names)), renewed ? "renewed" : "kept")
4746
+ if (res.status >= 400) return explained(res)
4747
+ const told = native ? res : unsaid(await renamed(res, names))
4748
+ // the ids are the ones the chat went with, after any renewal
4749
+ const conv = headers.get("X-Conversation-ID") ?? ""
4750
+ const t = step && conv ? { ...step, conv, turn: headers.get("X-Conversation-Request-ID") ?? "", message: headers.get("X-Conversation-Message-ID") ?? "" } : null
4751
+ return kept(t ? reporting(site, a, t, told) : told, renewed ? "renewed" : "kept")
4525
4752
  },
4526
4753
  }
4527
4754
  },
@@ -4773,4 +5000,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
4773
5000
  export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
4774
5001
 
4775
5002
  // for tests
4776
- 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 }
5003
+ 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 }
package/package.json CHANGED
@@ -1,12 +1,10 @@
1
1
  {
2
2
  "name": "@jianmu-plugins/opencode-workbuddy-auth",
3
- "version": "0.2.34",
3
+ "version": "0.2.36",
4
4
  "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",
7
- "exports": {
8
- ".": "./opencode2.mjs"
9
- },
7
+ "exports": { ".": "./opencode2.mjs" },
10
8
  "files": [
11
9
  "index.mjs",
12
10
  "opencode.mjs",
@@ -22,7 +20,7 @@
22
20
  "license": "MIT",
23
21
  "repository": {
24
22
  "type": "git",
25
- "url": "git+https://github.com/TopoReduce/plugins.git",
23
+ "url": "git+https://github.com/magpie-community/plugins.git",
26
24
  "directory": "packages/workbuddy"
27
25
  }
28
26
  }