dsh-workbuddy-free 1.0.0 → 1.1.0

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 (4) hide show
  1. package/README.md +3 -4
  2. package/client.js +20 -21
  3. package/index.js +105 -74
  4. package/package.json +49 -47
package/README.md CHANGED
@@ -45,11 +45,10 @@ install_bundle(target: "<本包目录的绝对路径>")
45
45
 
46
46
  需要一台运行 **WorkBuddy 桌面版**(CodeBuddy 分支)的电脑。首次登录:
47
47
 
48
- 1. 打开 WorkBuddy 桌面版, 在任意对话里发一条消息 — hook 会把最新 JWT 写到 `%TEMP%\wb-auth.json`
49
- 2. 打开 DSH 设置 → WorkBuddy Free → 点「从应用刷新」
50
- 3. 完成。JWT 有效期 28 天
48
+ 1. DSH 设置 → WorkBuddy Free → 点「浏览器登录」— 自动打开登录页, 登录后 token 自动保存
49
+ 2. 完成。
50
+ JWT 有效期 28 天, 带 refresh_token 可静默续期
51
51
 
52
- 也可以在设置页直接粘贴 JWT(从 `%TEMP%\wb-auth.json` 的 `authorization` 字段复制)。
53
52
 
54
53
  ## 工作原理
55
54
 
package/client.js CHANGED
@@ -142,7 +142,6 @@ window.__ModuleLoader__.load({
142
142
 
143
143
  function App({ t, localeTag, ctx }) {
144
144
  const [status, setStatus] = useState(null)
145
- const [pasteToken, setPasteToken] = useState('')
146
145
  const [toast, setToast] = useState('')
147
146
  const [probing, setProbing] = useState(false)
148
147
  const [probeResult, setProbeResult] = useState(null)
@@ -170,7 +169,7 @@ window.__ModuleLoader__.load({
170
169
  h('style', null, CSS),
171
170
  toast && h('div', { className: 'wbf_card', style: { borderColor: '#10b981' } }, toast),
172
171
 
173
- // ---- login ----
172
+ // ---- login (browser login only) ----
174
173
  h('div', { className: 'wbf_card' },
175
174
  h('h3', { className: 'wbf_title' }, t('auth.title')),
176
175
  h('p', { className: 'wbf_desc' }, t('auth.desc')),
@@ -183,6 +182,7 @@ window.__ModuleLoader__.load({
183
182
  : h('span', { className: 'wbf_badge warn' }, t('auth.none')),
184
183
  ts.account && h('span', { className: 'wbf_label' }, t('auth.account') + ': ' + ts.account),
185
184
  ts.expiresAt && h('span', { className: 'wbf_label' }, t('auth.expiresAt') + ': ' + new Date(ts.expiresAt).toLocaleString()),
185
+ ),
186
186
  status.lastQuota && h('div', { className: 'wbf_row' },
187
187
  h('span', { className: 'wbf_label' }, '额度'),
188
188
  h('span', { className: 'wbf_badge ' + (status.lastQuota.percent >= 90 ? 'bad' : status.lastQuota.percent >= 70 ? 'warn' : 'ok') },
@@ -191,32 +191,31 @@ window.__ModuleLoader__.load({
191
191
  '重置: ' + new Date(Number(status.lastQuota.reset_at) * 1000).toLocaleString() +
192
192
  (status.lastQuota.shared_models?.length ? ' · 共享: ' + status.lastQuota.shared_models.join(', ') : '')),
193
193
  ),
194
- ),
195
194
  h('div', { className: 'wbf_row' },
196
- h('input', {
197
- className: 'wbf_input', placeholder: t('auth.pastePlaceholder'),
198
- value: pasteToken, onChange: e => setPasteToken(e.target.value), type: 'password',
199
- }),
200
195
  h('button', {
201
196
  className: 'wbf_btn primary',
202
197
  onClick: async () => {
203
- const r = await api('POST', '/token', { token: pasteToken })
204
- showToast(r.ok ? t('status.tokenSaved') : (r.error || t('status.tokenBad')))
205
- if (r.ok) { setPasteToken(''); refresh() }
198
+ const r = await api('POST', '/login')
199
+ if (!r.ok || !r.session?.authUrl) { showToast('启动登录失败: ' + (r.session?.error || '?')); return }
200
+ window.open(r.session.authUrl, '_blank')
201
+ showToast('浏览器已打开, 登录后自动完成…')
202
+ const poll = setInterval(async () => {
203
+ const s = await api('GET', '/login')
204
+ if (!s.ok || !s.session) { clearInterval(poll); return }
205
+ if (s.session.status === 'ok') {
206
+ clearInterval(poll)
207
+ showToast('登录成功! Token 已保存')
208
+ refresh()
209
+ } else if (s.session.status === 'failed' || s.session.status === 'expired' || s.session.status === 'cancelled') {
210
+ clearInterval(poll)
211
+ showToast('登录未完成: ' + (s.session.error || s.session.status))
212
+ }
213
+ }, 1500)
206
214
  },
207
- }, t('auth.pasteBtn')),
208
- h('button', {
209
- className: 'wbf_btn',
210
- onClick: async () => { await api('POST', '/refresh'); refresh(); showToast('done') },
211
- }, t('auth.refresh')),
212
- ts.state !== 'none' && h('button', {
213
- className: 'wbf_btn',
214
- onClick: async () => { await api('POST', '/clear'); refresh() },
215
- }, t('auth.clear')),
215
+ }, '浏览器登录'),
216
216
  ),
217
- h('div', { className: 'wbf_hint' }, t('auth.how')),
217
+ h('div', { className: 'wbf_hint' }, '点击按钮会在浏览器打开 WorkBuddy 登录页, 登录成功后 token 自动保存。无需手动粘贴。'),
218
218
  ),
219
-
220
219
  // ---- probe ----
221
220
  h('div', { className: 'wbf_card' },
222
221
  h('h3', { className: 'wbf_title' }, t('status.title')),
package/index.js CHANGED
@@ -74,83 +74,107 @@ const NSFW_VERDICTS = {
74
74
  }
75
75
 
76
76
  /** Extra models discovered from the WorkBuddy product config (spill). */
77
- let discoveredModels = []
77
+
78
78
 
79
79
  /**
80
80
  * Extract the chat-capable model set from a spill config, mirroring what the
81
81
  * WorkBuddy UI shows: excludes image/video generators, completion helpers,
82
82
  * codewise internals and craft-tagged duplicates of the same lineup.
83
83
  */
84
- function extractChatModels(config) {
85
- const out = []
86
- for (const m of config?.models || []) {
87
- if (!m.id || m.id.startsWith('custom-local')) continue
88
- const tags = Array.isArray(m.tags) ? m.tags : []
89
- if (tags.includes('text-to-image') || tags.includes('image-to-image')) continue
90
- if (tags.includes('text-to-video') || tags.includes('image-to-video')) continue
91
- if (/completion|codewise|embed|rerank|turing|asdf/i.test(m.id)) continue
92
- // internal variants that duplicate the main lineup under different endpoints
93
- if (/-ctrl$|-exp$|-exp\d$|-x$|-lkeap$|-volc$|-taiji$|-gf$|-b$|-c$|-0324$|-0528$/i.test(m.id)) continue
94
- // models the WorkBuddy UI does not expose in its picker (internal/legacy/hidden)
95
- if (/^(hunyuan-3b|hunyuan-7b-dense|hunyuan-2.0-instruct|hunyuan-chat|default-1\.[12]|deepseek-r1-0528|deepseek-v3-0324|glm-4\.6v|glm-4\.6|minimax-m2\.5|hy3-b|hy3-c)$/i.test(m.id)) continue
96
- if (m.id === 'fast-model' || m.id === 'balanced-model' || m.id === 'deep-model') continue
97
- if (out.some(e => e.id === m.id)) continue
98
- out.push({
99
- id: m.id,
100
- name: m.name || m.id,
101
- credits: parseFloat(String(m.credits || '0').replace('x', '')) || 0,
102
- nsfw: NSFW_VERDICTS[m.id] ?? false,
103
- contextWindow: m.contextWindow?.defaultLength || m.maxInputTokens || 128000,
104
- maxOutput: m.maxOutputTokens || 64000,
105
- supportsImages: m.supportsImages === true,
106
- })
107
- }
108
- return out
109
- }
84
+ // ---------------------------------------------------------------------------
85
+ // browser login (EAC-style): POST auth/state -> open authUrl -> poll auth/token
86
+ // ---------------------------------------------------------------------------
87
+ const LOGIN_BASE = 'https://www.workbuddy.cn'
88
+ const LOGIN_UA = 'WorkBuddy/5.5.2 WorkBuddy/5.5.2 CLI/5.5.2'
89
+ let loginSession = null // { state, authUrl, status, startedAt, timer, abort }
110
90
 
111
- function rescanModels() {
112
- try {
113
- const tmp = os.tmpdir()
114
- const spills = fs.readdirSync(tmp).filter(d => d.startsWith('workbuddy-product-spill-'))
115
- .map(d => ({ dir: d, at: fs.statSync(path.join(tmp, d)).mtimeMs }))
116
- .sort((a, b) => b.at - a.at)
117
- const seen = new Set()
118
- const merged = []
119
- for (const sp of spills) {
120
- const cfgPath = path.join(tmp, sp.dir, 'acc-product-config-v3.json')
121
- if (!fs.existsSync(cfgPath)) continue
122
- let j
123
- try { j = JSON.parse(fs.readFileSync(cfgPath, 'utf8')) } catch { continue }
124
- for (const m of extractChatModels(j)) {
125
- if (seen.has(m.id)) continue
126
- seen.add(m.id)
127
- merged.push(m)
128
- }
91
+ function loginFetch(path, { method = 'GET', body } = {}) {
92
+ return new Promise((resolve, reject) => {
93
+ const u = new URL(LOGIN_BASE + path)
94
+ const headers = {
95
+ 'User-Agent': LOGIN_UA,
96
+ 'X-No-Authorization': 'true',
97
+ 'X-No-User-Id': 'true',
98
+ 'X-No-Enterprise-Id': 'true',
99
+ 'X-No-Department-Info': 'true',
100
+ accept: 'application/json',
129
101
  }
130
- if (merged.length) {
131
- discoveredModels = merged.filter(m => !BASE_MODELS.some(b => b.id === m.id))
132
- loggerInfo('[wb-free] model rescan: total ' + (BASE_MODELS.length + discoveredModels.length) + ' chat models')
102
+ if (body !== undefined) {
103
+ headers['content-type'] = 'application/json'
104
+ headers['content-length'] = Buffer.byteLength(body)
133
105
  }
134
- } catch (e) {
135
- loggerWarn('[wb-free] model rescan failed:', e.message)
136
- }
106
+ const req = https.request({ host: u.host, path: u.pathname + u.search, method, headers }, res => {
107
+ let buf = []
108
+ res.on('data', c => buf.push(c))
109
+ res.on('end', () => resolve({ status: res.statusCode, raw: Buffer.concat(buf).toString('utf8') }))
110
+ })
111
+ req.on('error', reject)
112
+ req.setTimeout(15000, () => { req.destroy(); reject(new Error('timeout')) })
113
+ if (body !== undefined) req.write(body)
114
+ req.end()
115
+ })
137
116
  }
138
117
 
139
- const DEFAULTS = {
140
- effort: 'balanced',
141
- contextWindow: 128000,
142
- maxTokens: 64000,
143
- sanitizer: true,
144
- keepalive: false,
145
- keepaliveMinutes: 30,
118
+ function startLoginSession() {
119
+ if (loginSession && loginSession.status === 'pending') {
120
+ return loginSession // reuse the pending session
121
+ }
122
+ loginSession = { state: '', authUrl: '', status: 'starting', startedAt: Date.now(), timer: null }
123
+ ;(async () => {
124
+ try {
125
+ const { status, raw } = await loginFetch('/v2/plugin/auth/state?platform=workbuddy-ai', { method: 'POST' })
126
+ const j = JSON.parse(raw)
127
+ if (status !== 200 || j.code !== 0 || !j.data?.state) throw new Error(j.msg || `auth/state HTTP ${status}`)
128
+ loginSession.state = j.data.state
129
+ loginSession.authUrl = String(j.data.authUrl || '').replace(/\\u0026/g, '&')
130
+ loginSession.status = 'pending'
131
+ // poll auth/token until the browser login completes (5 min deadline)
132
+ loginSession.timer = setInterval(async () => {
133
+ if (!loginSession || loginSession.status !== 'pending') return
134
+ if (Date.now() - loginSession.startedAt > 5 * 60000) {
135
+ clearInterval(loginSession.timer)
136
+ loginSession.status = 'expired'
137
+ return
138
+ }
139
+ try {
140
+ const { status: st, raw: r2 } = await loginFetch(`/v2/plugin/auth/token?state=${encodeURIComponent(loginSession.state)}`)
141
+ const j2 = JSON.parse(r2)
142
+ if (st === 200 && j2.code === 0 && j2.data) {
143
+ const d = j2.data
144
+ const access = d.access_token ?? d.accessToken ?? ''
145
+ const refresh = d.refresh_token ?? d.refreshToken ?? ''
146
+ const domain = d.domain ?? 'www.workbuddy.cn'
147
+ if (access) {
148
+ clearInterval(loginSession.timer)
149
+ // build authData in the hook-dump compatible shape so the whole
150
+ // request path keeps working unchanged
151
+ const headers = { ...(dumpData?.headers || {}) }
152
+ headers.authorization = 'Bearer ' + access
153
+ authData = { time: new Date().toISOString(), headers, token: access, refreshToken: refresh, domain, loginSession: true }
154
+ loginSession.status = 'ok'
155
+ loggerInfo('[wb-free] browser login success, token captured')
156
+ }
157
+ }
158
+ // 11217 = not ready; anything else non-zero fails the session
159
+ else if (st !== 200 || (j2.code !== 0 && j2.code !== 11217)) {
160
+ clearInterval(loginSession.timer)
161
+ loginSession.status = 'failed'
162
+ loginSession.error = j2.msg || `auth/token HTTP ${st}`
163
+ }
164
+ } catch { /* transient poll errors: keep polling */ }
165
+ }, 1200)
166
+ } catch (e) {
167
+ loginSession.status = 'failed'
168
+ loginSession.error = e.message
169
+ }
170
+ })()
171
+ return loginSession
146
172
  }
147
173
 
148
- let settings = { ...DEFAULTS }
149
- let authData = null
150
- let dumpData = null
151
- let keepaliveTimer = null
152
- let keepaliveLog = []
153
- let lastQuota = null
174
+ function stopLoginSession() {
175
+ if (loginSession?.timer) clearInterval(loginSession.timer)
176
+ if (loginSession && loginSession.status === 'pending') loginSession.status = 'cancelled'
177
+ }
154
178
  let ctxRef = null
155
179
  let loggerWarn = console.warn
156
180
  let loggerInfo = console.info
@@ -537,7 +561,7 @@ class WorkBuddyAdapter {
537
561
  }
538
562
 
539
563
  async listModels(provider) {
540
- const all = [...BASE_MODELS, ...discoveredModels]
564
+ const all = BASE_MODELS
541
565
  return all.map(entry => ({
542
566
  provider,
543
567
  id: entry.id,
@@ -548,7 +572,7 @@ class WorkBuddyAdapter {
548
572
  }
549
573
 
550
574
  async resolveModel(provider, model) {
551
- const all = [...BASE_MODELS, ...discoveredModels]
575
+ const all = BASE_MODELS
552
576
  const entry = all.find(c => c.id === model)
553
577
  // Kernel validation (INVALID_MODEL_REASONING): every effort needs {id, name}
554
578
  // (id unique, name string), and defaultEffort must be one of the ids.
@@ -569,7 +593,7 @@ class WorkBuddyAdapter {
569
593
  }
570
594
 
571
595
  async prepareCall(provider, model) {
572
- const all = [...BASE_MODELS, ...discoveredModels]
596
+ const all = BASE_MODELS
573
597
  const entry = all.find(c => c.id === model) ?? null
574
598
  return {
575
599
  model: await this.resolveModel(provider, model),
@@ -744,17 +768,14 @@ export async function apply(ctx, config) {
744
768
  authData = loadAuthFromDisk()
745
769
  dumpData = loadDumpFromDisk()
746
770
 
747
- rescanModels()
748
- // auto-rescan every 10 min so new models appear without restart
749
- setInterval(rescanModels, 10 * 60000)
750
-
771
+ // model list = fixed allowlist mirroring the WorkBuddy picker`n
751
772
  const adapter = new WorkBuddyAdapter({})
752
773
  ctx.llm.registerAdapter([ROUTE], adapter)
753
774
  ctx.llm.registerConfigurableProviders?.([
754
775
  { provider: ROUTE, displayName: ROUTE_LABEL, settingsNs: name, settingsPath: [] },
755
776
  ])
756
777
  ctx.llm.registerModelDiscovery?.(name, async () => {
757
- return [...BASE_MODELS, ...discoveredModels].map(entry => ({
778
+ return BASE_MODELS.map(entry => ({
758
779
  id: entry.id,
759
780
  name: entry.name,
760
781
  contextWindow: entry.contextWindow,
@@ -780,7 +801,7 @@ export async function apply(ctx, config) {
780
801
  settings,
781
802
  keepaliveLog: keepaliveLog.slice(0, 10),
782
803
  keepaliveRunning: !!keepaliveTimer,
783
- models: [...BASE_MODELS, ...discoveredModels],
804
+ models: BASE_MODELS,
784
805
  dumpPresent: !!dumpData,
785
806
  }),
786
807
  'POST /token': (body) => {
@@ -819,6 +840,16 @@ export async function apply(ctx, config) {
819
840
  return { ok: status === 200, status, answer: text.slice(0, 200) }
820
841
  },
821
842
  'POST /keepalive': () => keepaliveTick().then(() => ({ ok: true, log: keepaliveLog.slice(0, 10) })),
843
+ 'POST /login': () => {
844
+ const s = startLoginSession()
845
+ return { ok: true, session: { status: s.status, authUrl: s.authUrl, state: s.state, startedAt: s.startedAt, error: s.error ?? null } }
846
+ },
847
+ 'GET /login': () => {
848
+ const s = loginSession
849
+ if (!s) return { ok: true, session: { status: 'none' } }
850
+ return { ok: true, session: { status: s.status, authUrl: s.authUrl, state: s.state, startedAt: s.startedAt, error: s.error ?? null } }
851
+ },
852
+ 'POST /login/cancel': () => { stopLoginSession(); return { ok: true } },
822
853
  }
823
854
 
824
855
  ctx.inject?.(['webServer'], scoped => {
@@ -858,7 +889,7 @@ export async function apply(ctx, config) {
858
889
  loggerInfo('[wb-free] settings API mounted at /api/workbuddy-free')
859
890
  })
860
891
 
861
- loggerInfo('[wb-free] adapter registered, models:', BASE_MODELS.length + discoveredModels.length)
892
+ loggerInfo('[wb-free] adapter registered, models:', BASE_MODELS.length)
862
893
 
863
894
  return () => {
864
895
  stopKeepalive()
package/package.json CHANGED
@@ -1,47 +1,49 @@
1
- {
2
- "name": "dsh-workbuddy-free",
3
- "version": "1.0.0",
4
- "type": "module",
5
- "description": "WorkBuddy Free — use your WorkBuddy desktop account quota in DSH: Tencent Hunyuan Hy4, Xiaomi MiMo, GLM, Kimi, DeepSeek and more. Hook-token login, live thinking, tool calling, quota display, fingerprint sanitizer.",
6
- "main": "./index.js",
7
- "exports": {
8
- ".": "./index.js",
9
- "./client": "./client.js",
10
- "./package.json": "./package.json",
11
- "./locale/*.json": "./locale/*.json"
12
- },
13
- "files": [
14
- "index.js",
15
- "client.js",
16
- "locale",
17
- "icon.svg",
18
- "cordis.patch.yml",
19
- "docs",
20
- "README.md"
21
- ],
22
- "keywords": [
23
- "dsh",
24
- "dsh-plugin",
25
- "deepseek-harness",
26
- "workbuddy",
27
- "free-model",
28
- "llm-provider",
29
- "hunyuan",
30
- "mimo"
31
- ],
32
- "author": "xifengwuyuan",
33
- "engines": {
34
- "node": "^22.19.0 || >=24.0.0"
35
- },
36
- "dsh": {
37
- "bundle": {
38
- "patch": "./cordis.patch.yml"
39
- },
40
- "client": {
41
- "platform": "web",
42
- "immediately": true,
43
- "inject": []
44
- }
45
- },
46
- "license": "MIT"
47
- }
1
+ {
2
+ "name": "dsh-workbuddy-free",
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "description": "WorkBuddy Free 鈥?use your WorkBuddy desktop account quota in DSH: Tencent Hunyuan Hy4, Xiaomi MiMo, GLM, Kimi, DeepSeek and more. Hook-token login, live thinking, tool calling, quota display, fingerprint sanitizer.",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./package.json": "./package.json",
11
+ "./locale/*.json": "./locale/*.json"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "client.js",
16
+ "locale",
17
+ "icon.svg",
18
+ "cordis.patch.yml",
19
+ "docs",
20
+ "README.md"
21
+ ],
22
+ "keywords": [
23
+ "dsh",
24
+ "dsh-plugin",
25
+ "deepseek-harness",
26
+ "workbuddy",
27
+ "free-model",
28
+ "llm-provider",
29
+ "hunyuan",
30
+ "mimo"
31
+ ],
32
+ "author": "xifengwuyuan",
33
+ "engines": {
34
+ "node": "^22.19.0 || \u003e=24.0.0"
35
+ },
36
+ "dsh": {
37
+ "bundle": {
38
+ "patch": "./cordis.patch.yml"
39
+ },
40
+ "client": {
41
+ "platform": "web",
42
+ "immediately": true,
43
+ "inject": [
44
+
45
+ ]
46
+ }
47
+ },
48
+ "license": "MIT"
49
+ }