dsh-plugin-doubao 0.0.0-stage → 0.2.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.
package/lib/client.js ADDED
@@ -0,0 +1,171 @@
1
+ // The remaining Doubao credit, beside the composer.
2
+ //
3
+ // Mirrors what the WorkBuddy plugin does for its own accounts: the readout sits
4
+ // in `conversation.input.right`, so it is only as far from the send button as
5
+ // the model name is. The number itself cannot be computed here — it is an
6
+ // upstream fact — so the component asks the host's own route
7
+ // (`/plugins/dsh-plugin-doubao/credits`, registered by lib/index.js) and shows
8
+ // an em dash when that read fails. A dash is the honest rendering of "could not
9
+ // read it", which is a different fact from "you have none left".
10
+ //
11
+ // Every hook runs before the provider test, because the slot renders for every
12
+ // provider: the readout is drawn for `doubao` rows only, but bailing out before
13
+ // the hooks would break React's ordering the moment the user switches models.
14
+ window.__ModuleLoader__.load({
15
+ id: 'dsh-plugin-doubao',
16
+ factory: (require) => {
17
+ const React = require('react')
18
+ const h = React.createElement
19
+
20
+ const PROVIDER_ID = 'doubao'
21
+ const CREDITS_PATH = '/plugins/dsh-plugin-doubao/credits'
22
+ /** How often an open composer re-reads the balance. */
23
+ const REFRESH_MS = 60_000
24
+
25
+ const CSS = `
26
+ .dsh-doubao-credits{display:inline-flex;align-items:center;min-width:0}
27
+ .dsh-doubao-credits-trigger{
28
+ appearance:none;display:inline-flex;align-items:center;align-self:stretch;
29
+ padding:2px 6px;border:0;border-radius:6px;background:transparent;
30
+ font-size:12px;line-height:18px;
31
+ color:var(--dsw-alias-label-tertiary,#999);
32
+ white-space:nowrap;cursor:pointer;
33
+ font-variant-numeric:tabular-nums;
34
+ }
35
+ .dsh-doubao-credits-trigger:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14))}
36
+ .dsh-doubao-credits-trigger:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
37
+ `
38
+
39
+ /** The provider the session is pointing at, or undefined before one is picked. */
40
+ function providerOf(projection) {
41
+ const provider = (projection?.next ?? projection?.lastUsed)?.provider
42
+ return typeof provider === 'string' && provider !== '' ? provider : undefined
43
+ }
44
+
45
+ /** `9,793` — the same thousand-separated spelling the official client uses. */
46
+ function formatAmount(value) {
47
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
48
+ return Math.round(value).toLocaleString('en-US')
49
+ }
50
+
51
+ /** One line per quota group, for the tooltip: what the total is made of. */
52
+ function describe(credits) {
53
+ if (!credits) return undefined
54
+ const rows = (credits.groups ?? []).map(
55
+ (group) => `${group.label} ${formatAmount(group.remaining)} / ${formatAmount(group.limit)}`,
56
+ )
57
+ if (rows.length === 0) rows.push(`${formatAmount(credits.remaining)} / ${formatAmount(credits.limit)}`)
58
+ return rows.join(' · ')
59
+ }
60
+
61
+ async function readCredits(signal) {
62
+ const response = await fetch(CREDITS_PATH, { headers: { Accept: 'application/json' }, signal, cache: 'no-store' })
63
+ if (!response.ok) throw new Error(`credits read returned HTTP ${response.status}`)
64
+ const payload = await response.json()
65
+ return payload?.credits ?? null
66
+ }
67
+
68
+ function CreditsPill(props) {
69
+ const { t, useProjection } = props
70
+ const projection = typeof useProjection === 'function' ? useProjection('modelSelection') : undefined
71
+ const provider = providerOf(projection)
72
+ const owned = provider === PROVIDER_ID
73
+ const [credits, setCredits] = React.useState(undefined)
74
+ const [failed, setFailed] = React.useState(false)
75
+
76
+ React.useEffect(() => {
77
+ if (!owned) return undefined
78
+ let alive = true
79
+ let timer
80
+ const read = async () => {
81
+ try {
82
+ const next = await readCredits()
83
+ if (!alive) return
84
+ setCredits(next)
85
+ setFailed(false)
86
+ } catch {
87
+ if (!alive) return
88
+ setFailed(true)
89
+ }
90
+ }
91
+ read()
92
+ timer = setInterval(read, REFRESH_MS)
93
+ return () => {
94
+ alive = false
95
+ clearInterval(timer)
96
+ }
97
+ }, [owned])
98
+
99
+ if (!owned) return null
100
+
101
+ const label = t === undefined ? '积分' : t('label')
102
+ const text =
103
+ credits === undefined
104
+ ? `${label} …`
105
+ : credits === null
106
+ ? `${label} —`
107
+ : `${label} ${formatAmount(credits.remaining)}`
108
+ const title = failed
109
+ ? t === undefined ? '无法读取豆包剩余积分' : t('failed')
110
+ : describe(credits)
111
+
112
+ return h(
113
+ 'div',
114
+ { className: 'dsh-doubao-credits' },
115
+ h(
116
+ 'button',
117
+ {
118
+ type: 'button',
119
+ className: 'dsh-doubao-credits-trigger',
120
+ title,
121
+ onClick: async () => {
122
+ try {
123
+ const next = await readCredits()
124
+ setCredits(next)
125
+ setFailed(false)
126
+ } catch {
127
+ setFailed(true)
128
+ }
129
+ },
130
+ },
131
+ text,
132
+ ),
133
+ )
134
+ }
135
+
136
+ const zh = {
137
+ label: '积分',
138
+ failed: '无法读取豆包剩余积分',
139
+ }
140
+ const en = {
141
+ label: 'Credits',
142
+ failed: 'Could not read the Doubao credit balance',
143
+ }
144
+
145
+ return {
146
+ inject: ['slots', 'locale'],
147
+ apply(ctx) {
148
+ const namespace = 'doubaoCredits'
149
+ ctx.effect(() => {
150
+ const style = document.createElement('style')
151
+ style.dataset.dshPluginDoubaoCredits = ''
152
+ style.textContent = CSS
153
+ document.head.appendChild(style)
154
+ return () => style.remove()
155
+ }, 'doubao: credits styles')
156
+ ctx.effect(() => ctx.locale.register(namespace, { zh, en }), 'doubao: credits dictionaries')
157
+ ctx.slots.inject('conversation.input.right', () =>
158
+ ctx.slots.register(
159
+ {
160
+ name: 'conversation.input.right',
161
+ id: 'dsh-plugin-doubao-credits',
162
+ order: 4,
163
+ locale: namespace,
164
+ },
165
+ CreditsPill,
166
+ ),
167
+ )
168
+ },
169
+ }
170
+ },
171
+ })
package/lib/credits.js ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The credits the Doubao account has left.
3
+ *
4
+ * Like the model rates, this is not a documented API: the number the client
5
+ * prints in its own account panel comes from
6
+ * `/alice/commerce/sale/subscription/quota/summary/`, which the web client calls
7
+ * when that panel opens. It answers with the account's quota groups — the
8
+ * activity-granted allowance (`活动赠送额度`) and the monthly plan allowance
9
+ * (`monthly_quota`) — each carrying `total_amount` and `used_amount` as
10
+ * thousand-separated *strings* (`"9,000"`). Remaining credit is therefore a
11
+ * subtraction, not a field; publishing a number the upstream does not send
12
+ * would drift the moment the plan changes.
13
+ *
14
+ * `POST` only. A `GET` on the same path is a 404 with an empty body, which is
15
+ * how this endpoint announced itself while it was being found.
16
+ *
17
+ * Failures resolve to `undefined`, never to zero: "we could not read it" and
18
+ * "you have none left" are different answers, and the readout says `—` for the
19
+ * first while only the second should look like an empty balance.
20
+ */
21
+ import { DEFAULT_UA, buildQuery } from './doubao.js'
22
+
23
+ const QUOTA_URL = 'https://www.doubao.com/alice/commerce/sale/subscription/quota/summary/'
24
+
25
+ /** Group keys whose upstream label is blank, mapped to what the user calls them. */
26
+ const GROUP_LABELS = Object.freeze({
27
+ monthly_quota: '月度额度',
28
+ doubao_activity_reward_quota: '活动赠送额度',
29
+ })
30
+
31
+ /**
32
+ * Read one `total_amount` / `used_amount` string as a number.
33
+ *
34
+ * The upstream format is `"1,200"`; anything unparsable is treated as absent
35
+ * rather than as zero, so a shape change degrades the readout instead of
36
+ * silently reporting an empty balance.
37
+ */
38
+ export function amountOf(value) {
39
+ if (typeof value === 'number' && Number.isFinite(value)) return value
40
+ if (typeof value !== 'string') return undefined
41
+ const digits = value.replace(/[,\s_]/g, '')
42
+ if (!/^-?\d+(?:\.\d+)?$/.test(digits)) return undefined
43
+ const parsed = Number(digits)
44
+ return Number.isFinite(parsed) ? parsed : undefined
45
+ }
46
+
47
+ /** Turn one upstream window into the row the readout shows. */
48
+ function windowOf(group, limit) {
49
+ const total = amountOf(limit?.total_amount)
50
+ const used = amountOf(limit?.used_amount)
51
+ if (total === undefined && used === undefined) return undefined
52
+ const limitAmount = total ?? 0
53
+ const usedAmount = used ?? 0
54
+ return {
55
+ key: String(group?.feature_group ?? ''),
56
+ label: String(group?.feature_group_name ?? '').trim() || GROUP_LABELS[group?.feature_group] || String(group?.feature_group ?? '额度'),
57
+ limit: limitAmount,
58
+ used: usedAmount,
59
+ // A negative remainder would mean the upstream counted more usage than
60
+ // allowance; clamp it so the readout cannot print a negative balance.
61
+ remaining: Math.max(0, limitAmount - usedAmount),
62
+ percent: typeof limit?.used_percent === 'number' ? limit.used_percent : undefined,
63
+ endTime: typeof limit?.end_time === 'number' ? limit.end_time : undefined,
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Flatten a `quota/summary` answer into the one shape the UI renders.
69
+ *
70
+ * Both sections are walked the same way — the activity allowance and the plan
71
+ * allowance are the same kind of fact, so they are summed rather than
72
+ * special-cased, and a future third section needs no code change.
73
+ */
74
+ export function creditsFromSummary(payload) {
75
+ const data = payload?.data
76
+ if (!data || typeof data !== 'object') return undefined
77
+ const groups = []
78
+ for (const section of [data.incentive_quota_section, data.window_limit_section]) {
79
+ for (const group of section?.window_limit_groups ?? []) {
80
+ for (const limit of group?.window_limits ?? []) {
81
+ const row = windowOf(group, limit)
82
+ if (row !== undefined) groups.push(row)
83
+ }
84
+ }
85
+ }
86
+ const sum = (pick) => groups.reduce((total, row) => total + pick(row), 0)
87
+ // No parsable window means the answer did not carry a balance, which is not
88
+ // the same fact as "nothing left" — the readout must not print 0 for it.
89
+ if (groups.length === 0) return undefined
90
+ const subscription = data.current_subscription ?? {}
91
+ return {
92
+ groups,
93
+ limit: sum((row) => row.limit),
94
+ used: sum((row) => row.used),
95
+ remaining: sum((row) => row.remaining),
96
+ plan: String(subscription.display?.short_name ?? '').trim() || undefined,
97
+ planEndTime: typeof subscription.end_time === 'number' ? subscription.end_time : undefined,
98
+ }
99
+ }
100
+
101
+ /** `9,793` — the same thousand-separated spelling the client uses. */
102
+ export function formatAmount(value) {
103
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
104
+ return Math.round(value).toLocaleString('en-US')
105
+ }
106
+
107
+ /**
108
+ * Fetch the live balance. Never throws: `undefined` means "could not read it",
109
+ * which the caller renders as an em dash rather than as an empty balance.
110
+ */
111
+ export async function fetchCredits({ identity, cookies, signal, timeoutMs = 5_000, logger } = {}) {
112
+ if (!identity?.deviceId || !cookies) return undefined
113
+ const query = new URLSearchParams(buildQuery(identity))
114
+ try {
115
+ const response = await fetch(`${QUOTA_URL}?${query}`, {
116
+ method: 'POST',
117
+ headers: {
118
+ 'Content-Type': 'application/json',
119
+ Accept: 'application/json, text/plain, */*',
120
+ 'Agw-Js-Conv': 'str',
121
+ 'User-Agent': DEFAULT_UA,
122
+ Origin: 'https://www.doubao.com',
123
+ Referer: 'https://www.doubao.com/chat/',
124
+ Cookie: cookies,
125
+ },
126
+ body: '{}',
127
+ signal: signal ?? AbortSignal.timeout(timeoutMs),
128
+ })
129
+ if (!response.ok) {
130
+ logger?.warn?.(`doubao: credit lookup returned HTTP ${response.status}`)
131
+ return undefined
132
+ }
133
+ const credits = creditsFromSummary(await response.json())
134
+ if (credits === undefined) {
135
+ logger?.warn?.('doubao: credit lookup carried no quota groups')
136
+ return undefined
137
+ }
138
+ return { ...credits, fetchedAt: Date.now() }
139
+ } catch (error) {
140
+ logger?.warn?.(`doubao: credit lookup failed (${error?.message ?? error})`)
141
+ return undefined
142
+ }
143
+ }