dsh-continue-cost 0.0.0-stage → 1.3.1
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/LICENSE +21 -0
- package/README.md +177 -2
- package/client.js +1724 -0
- package/cordis.patch.yml +9 -0
- package/host-1.2.0.js +512 -0
- package/host.js +6 -0
- package/icon.svg +8 -0
- package/index.js +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +65 -4
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# dsh-continue-cost —— bundle patch
|
|
2
|
+
#
|
|
3
|
+
# The client half owns the composer chip and all cost arithmetic. The Host
|
|
4
|
+
# half adds two optional routes that fetch DeepSeek's public pricing Markdown
|
|
5
|
+
# and the State Council holiday notices; it never receives Session content or
|
|
6
|
+
# credentials. Thresholds live in this browser's localStorage.
|
|
7
|
+
- insert:
|
|
8
|
+
- id: dsh-continue-cost
|
|
9
|
+
name: 'dsh-continue-cost'
|
package/host-1.2.0.js
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of `dsh-continue-cost`.
|
|
3
|
+
*
|
|
4
|
+
* The client's arithmetic is local. This half adds optional network
|
|
5
|
+
* capabilities: it fetches DeepSeek's public Chinese pricing Markdown and the
|
|
6
|
+
* State Council holiday notices, then serves validated tables to the page at
|
|
7
|
+
*
|
|
8
|
+
* GET /plugins/dsh-continue-cost/prices
|
|
9
|
+
* GET /plugins/dsh-continue-cost/holidays
|
|
10
|
+
*
|
|
11
|
+
* Only the public documentation URL is requested. No Session content, token
|
|
12
|
+
* usage, credential, or API key is ever sent. If the fetch or parse fails, the
|
|
13
|
+
* client keeps its built-in table. The route caches one successful result for
|
|
14
|
+
* six hours so a page reload does not hammer the docs site.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-continue-cost
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Route prefix; the client fetches `${BASE_PATH}/prices`. */
|
|
20
|
+
export const BASE_PATH = '/plugins/dsh-continue-cost'
|
|
21
|
+
|
|
22
|
+
/** The Host service needed to mount the route. */
|
|
23
|
+
export const inject = ['webServer']
|
|
24
|
+
|
|
25
|
+
/** Official Chinese pricing page, Markdown form (CNY values). */
|
|
26
|
+
const PRICING_URL = 'https://api-docs.deepseek.com/zh-cn/quick_start/pricing.md'
|
|
27
|
+
|
|
28
|
+
/** Official State Council "latest documents" page used to discover a new notice. */
|
|
29
|
+
const HOLIDAY_INDEX_URL = 'https://www.gov.cn/pushinfo/v150203/index.htm?aisiteOutPageId=543406643'
|
|
30
|
+
|
|
31
|
+
/** Known official notices for years whose URL can be pinned. */
|
|
32
|
+
const KNOWN_HOLIDAY_NOTICES = {
|
|
33
|
+
2026: 'https://www.gov.cn/zhengce/content/202511/content_7047090.htm',
|
|
34
|
+
2027: 'https://www.gov.cn/zhengce/content/202611/content_7085101.htm',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A successful holiday parse is reused by the Host for one day. */
|
|
38
|
+
const HOLIDAY_CACHE_MS = 24 * 60 * 60 * 1000
|
|
39
|
+
|
|
40
|
+
/** How long one successful fetch is reused by the Host. */
|
|
41
|
+
const CACHE_MS = 6 * 60 * 60 * 1000
|
|
42
|
+
|
|
43
|
+
/** Per-request upstream timeout. */
|
|
44
|
+
const REQUEST_TIMEOUT_MS = 10_000
|
|
45
|
+
|
|
46
|
+
/** The three model-price buckets. */
|
|
47
|
+
const BUCKETS = ['cacheHit', 'cacheMiss', 'output']
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse one price cell such as `0.02元` or `4.5元`.
|
|
51
|
+
* @param text - table cell.
|
|
52
|
+
* @returns the number, or undefined when the cell is not a price.
|
|
53
|
+
*/
|
|
54
|
+
function parsePrice(text) {
|
|
55
|
+
const match = /(\d+(?:\.\d+)?)/u.exec(String(text).replace(/,/gu, ''))
|
|
56
|
+
if (match === null) return undefined
|
|
57
|
+
const value = Number(match[1])
|
|
58
|
+
return Number.isFinite(value) && value >= 0 ? value : undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Parse the official Markdown table into the client's price shape.
|
|
63
|
+
*
|
|
64
|
+
* The table header names the model columns; each `价格` row names the bucket
|
|
65
|
+
* (cache hit / cache miss / output) and the tariff (off-peak / peak), with the
|
|
66
|
+
* model prices as the last N cells. Any missing or unreadable value throws so
|
|
67
|
+
* the caller falls back to the built-in table instead of publishing a partial
|
|
68
|
+
* table.
|
|
69
|
+
*
|
|
70
|
+
* @param markdown - the fetched `pricing.md` body.
|
|
71
|
+
* @returns `{ modelId: { off: {...}, peak: {...} } }` with CNY per 1M tokens.
|
|
72
|
+
*/
|
|
73
|
+
export function parsePricing(markdown) {
|
|
74
|
+
const source = String(markdown)
|
|
75
|
+
// The Chinese page is billed in CNY. Refuse an English/USD fallback rather
|
|
76
|
+
// than silently pricing yuan as dollars.
|
|
77
|
+
if (!/元|¥/u.test(source)) throw new Error('pricing page is not in CNY')
|
|
78
|
+
const lines = source.split(/\r?\n/u)
|
|
79
|
+
const header = lines.find((line) => line.includes('|')
|
|
80
|
+
&& /deepseek-[a-z0-9-]+/iu.test(line)
|
|
81
|
+
&& /模型|model/iu.test(line))
|
|
82
|
+
if (header === undefined) throw new Error('pricing header not found')
|
|
83
|
+
const models = [...new Set([...header.matchAll(/deepseek-[a-z0-9-]+/giu)].map((match) => match[0].toLowerCase()))]
|
|
84
|
+
if (models.length === 0) throw new Error('pricing model columns not found')
|
|
85
|
+
|
|
86
|
+
const table = Object.fromEntries(models.map((model) => [model, { off: {}, peak: {} }]))
|
|
87
|
+
for (const line of lines) {
|
|
88
|
+
if (!line.trim().startsWith('|')) continue
|
|
89
|
+
const cells = line.split('|').slice(1, -1).map((cell) => cell.trim())
|
|
90
|
+
if (cells.length < models.length + 2) continue
|
|
91
|
+
const prefix = cells.slice(0, -models.length).join(' ')
|
|
92
|
+
let bucket
|
|
93
|
+
if (/缓存命中|CACHE HIT/iu.test(prefix)) bucket = 'cacheHit'
|
|
94
|
+
else if (/缓存未命中|CACHE MISS/iu.test(prefix)) bucket = 'cacheMiss'
|
|
95
|
+
else if (/输出|OUTPUT/iu.test(prefix)) bucket = 'output'
|
|
96
|
+
else continue
|
|
97
|
+
let tariff
|
|
98
|
+
if (/空闲时段|OFF-PEAK/iu.test(prefix)) tariff = 'off'
|
|
99
|
+
else if (/高峰时段/iu.test(prefix)) tariff = 'peak'
|
|
100
|
+
else continue
|
|
101
|
+
const values = cells.slice(-models.length).map(parsePrice)
|
|
102
|
+
if (values.some((value) => value === undefined)) {
|
|
103
|
+
throw new Error(`unreadable pricing row: ${line}`)
|
|
104
|
+
}
|
|
105
|
+
models.forEach((model, index) => {
|
|
106
|
+
table[model][tariff][bucket] = values[index]
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
for (const model of models) {
|
|
111
|
+
for (const tariff of ['off', 'peak']) {
|
|
112
|
+
for (const bucket of BUCKETS) {
|
|
113
|
+
const value = table[model][tariff][bucket]
|
|
114
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
115
|
+
throw new Error(`incomplete pricing for ${model} ${tariff} ${bucket}`)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return table
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Read one optional Host service without letting a missing one throw.
|
|
125
|
+
* @param ctx - plugin context.
|
|
126
|
+
* @param name - service key.
|
|
127
|
+
* @returns the service, or undefined.
|
|
128
|
+
*/
|
|
129
|
+
function service(ctx, name) {
|
|
130
|
+
try {
|
|
131
|
+
return ctx.get(name)
|
|
132
|
+
} catch {
|
|
133
|
+
return undefined
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @param value - HTML/XML text. @returns common entities decoded. */
|
|
138
|
+
function decodeEntities(value) {
|
|
139
|
+
return String(value)
|
|
140
|
+
.replace(/ /gu, ' ')
|
|
141
|
+
.replace(/&/gu, '&')
|
|
142
|
+
.replace(/</gu, '<')
|
|
143
|
+
.replace(/>/gu, '>')
|
|
144
|
+
.replace(/"/gu, '"')
|
|
145
|
+
.replace(/'/gu, "'")
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Turn a government HTML page into compact plain text for clause parsing.
|
|
150
|
+
* @param html - page body.
|
|
151
|
+
* @returns whitespace-normalized text.
|
|
152
|
+
*/
|
|
153
|
+
function extractText(html) {
|
|
154
|
+
return decodeEntities(
|
|
155
|
+
String(html)
|
|
156
|
+
.replace(/<script[\s\S]*?<\/script>/giu, ' ')
|
|
157
|
+
.replace(/<style[\s\S]*?<\/style>/giu, ' ')
|
|
158
|
+
.replace(/<[^>]+>/gu, ' '),
|
|
159
|
+
).replace(/\s+/gu, ' ')
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Parse the State Council notice body into off-peak holiday dates.
|
|
164
|
+
*
|
|
165
|
+
* This is deliberately deterministic text parsing, not a model call. It reads
|
|
166
|
+
* the seven festival clauses and takes the first date or date range in each;
|
|
167
|
+
* later dates in the same clause are make-up workdays, which are already
|
|
168
|
+
* off-peak because they fall on a weekend.
|
|
169
|
+
*
|
|
170
|
+
* @param htmlOrText - fetched notice page or plain notice text.
|
|
171
|
+
* @param year - schedule year.
|
|
172
|
+
* @returns sorted `YYYY-MM-DD` dates.
|
|
173
|
+
*/
|
|
174
|
+
export function parseHolidayNotice(htmlOrText, year) {
|
|
175
|
+
const compact = extractText(htmlOrText).replace(/\s+/gu, '')
|
|
176
|
+
const names = '元旦|春节|清明节|劳动节|端午节|中秋节|国庆节'
|
|
177
|
+
const clauses = [...compact.matchAll(new RegExp(`(${names})[::]([^。]+)。`, 'gu'))]
|
|
178
|
+
const dates = new Set()
|
|
179
|
+
const add = (month, day) => {
|
|
180
|
+
const date = new Date(Date.UTC(year, month - 1, day))
|
|
181
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return
|
|
182
|
+
dates.add(`${String(year)}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`)
|
|
183
|
+
}
|
|
184
|
+
for (const clause of clauses) {
|
|
185
|
+
const body = clause[2]
|
|
186
|
+
const range = /(\d{1,2})月(\d{1,2})日[^至。]*至(?:(\d{1,2})月)?(\d{1,2})日/u.exec(body)
|
|
187
|
+
if (range !== null) {
|
|
188
|
+
const startMonth = Number(range[1])
|
|
189
|
+
const startDay = Number(range[2])
|
|
190
|
+
const endMonth = range[3] === undefined ? startMonth : Number(range[3])
|
|
191
|
+
const endDay = Number(range[4])
|
|
192
|
+
let month = startMonth
|
|
193
|
+
let day = startDay
|
|
194
|
+
for (let index = 0; index < 400; index += 1) {
|
|
195
|
+
add(month, day)
|
|
196
|
+
if (month === endMonth && day === endDay) break
|
|
197
|
+
day += 1
|
|
198
|
+
if (day > 31) {
|
|
199
|
+
day = 1
|
|
200
|
+
month += 1
|
|
201
|
+
}
|
|
202
|
+
if (month > 12) break
|
|
203
|
+
}
|
|
204
|
+
} else {
|
|
205
|
+
const single = /(\d{1,2})月(\d{1,2})日/u.exec(body)
|
|
206
|
+
if (single !== null) add(Number(single[1]), Number(single[2]))
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (dates.size === 0) throw new Error(`holiday notice for ${String(year)} has no readable dates`)
|
|
210
|
+
return [...dates].sort()
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** @param html - government index page. @returns `{ title, link }[]`. */
|
|
214
|
+
function parseIndexLinks(html) {
|
|
215
|
+
const links = []
|
|
216
|
+
const pattern = /<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/giu
|
|
217
|
+
for (const match of String(html).matchAll(pattern)) {
|
|
218
|
+
const href = decodeEntities(match[1]).trim()
|
|
219
|
+
const title = decodeEntities(match[2].replace(/<[^>]+>/gu, '')).trim()
|
|
220
|
+
if (title === '' || href === '') continue
|
|
221
|
+
try {
|
|
222
|
+
links.push({ title, link: new URL(href, 'https://www.gov.cn/').href })
|
|
223
|
+
} catch {
|
|
224
|
+
/* ignore malformed href */
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return links
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Find the notice URL for one year from the official latest-documents page,
|
|
232
|
+
* with a known URL and a Bing RSS fallback for older/future years.
|
|
233
|
+
* @param year - schedule year.
|
|
234
|
+
* @returns `{ url, via }`.
|
|
235
|
+
*/
|
|
236
|
+
async function discoverHolidayNotice(year, includeKnown = true) {
|
|
237
|
+
const wanted = `国务院办公厅关于${String(year)}年部分节假日安排的通知`
|
|
238
|
+
const known = includeKnown ? KNOWN_HOLIDAY_NOTICES[year] : undefined
|
|
239
|
+
if (known !== undefined) return { url: known, via: 'known' }
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
const indexHtml = await fetchText(HOLIDAY_INDEX_URL, 'text/html')
|
|
243
|
+
const hit = parseIndexLinks(indexHtml).find((entry) => entry.title.includes(wanted)
|
|
244
|
+
&& /^https?:\/\/www\.gov\.cn\//u.test(entry.link))
|
|
245
|
+
if (hit !== undefined) return { url: hit.link, via: 'gov-index' }
|
|
246
|
+
} catch {
|
|
247
|
+
/* fall through to search */
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const query = encodeURIComponent(`site:gov.cn "${wanted}"`)
|
|
251
|
+
const rss = await fetchText(`https://cn.bing.com/search?q=${query}&format=rss`, 'application/rss+xml')
|
|
252
|
+
const item = [...String(rss).matchAll(/<item>([\s\S]*?)<\/item>/giu)]
|
|
253
|
+
.map((match) => {
|
|
254
|
+
const block = match[1]
|
|
255
|
+
const link = decodeEntities(/<link>([\s\S]*?)<\/link>/iu.exec(block)?.[1] ?? '').trim()
|
|
256
|
+
const description = decodeEntities(/<description>([\s\S]*?)<\/description>/iu.exec(block)?.[1] ?? '')
|
|
257
|
+
return { link, description }
|
|
258
|
+
})
|
|
259
|
+
.find((entry) => /^https?:\/\/www\.gov\.cn\//u.test(entry.link))
|
|
260
|
+
if (item === undefined) throw new Error(`no official holiday notice found for ${String(year)}`)
|
|
261
|
+
return { url: item.link, via: 'search', description: item.description }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** @param url - URL to fetch. @param accept - Accept header. @returns body text. */
|
|
265
|
+
async function fetchText(url, accept) {
|
|
266
|
+
const response = await fetch(url, {
|
|
267
|
+
headers: {
|
|
268
|
+
accept,
|
|
269
|
+
'user-agent': 'dsh-continue-cost',
|
|
270
|
+
},
|
|
271
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
272
|
+
})
|
|
273
|
+
if (!response.ok) throw new Error(`${url} returned HTTP ${String(response.status)}`)
|
|
274
|
+
return response.text()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Load and parse one year's official holiday notice.
|
|
279
|
+
* @param year - schedule year.
|
|
280
|
+
* @returns `{ dates, sourceUrl, via }`.
|
|
281
|
+
*/
|
|
282
|
+
async function loadHolidayYear(year) {
|
|
283
|
+
let discovered = await discoverHolidayNotice(year)
|
|
284
|
+
let body
|
|
285
|
+
try {
|
|
286
|
+
body = await fetchText(discovered.url, 'text/html')
|
|
287
|
+
} catch (error) {
|
|
288
|
+
if (discovered.via === 'known') {
|
|
289
|
+
discovered = await discoverHolidayNotice(year, false)
|
|
290
|
+
body = await fetchText(discovered.url, 'text/html')
|
|
291
|
+
} else if (typeof discovered.description === 'string') {
|
|
292
|
+
body = discovered.description
|
|
293
|
+
} else {
|
|
294
|
+
throw error
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
return { dates: parseHolidayNotice(body, year), sourceUrl: discovered.url, via: discovered.via }
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (discovered.via === 'known') {
|
|
301
|
+
discovered = await discoverHolidayNotice(year, false)
|
|
302
|
+
body = typeof discovered.description === 'string'
|
|
303
|
+
? discovered.description
|
|
304
|
+
: await fetchText(discovered.url, 'text/html')
|
|
305
|
+
return { dates: parseHolidayNotice(body, year), sourceUrl: discovered.url, via: discovered.via }
|
|
306
|
+
}
|
|
307
|
+
throw error
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Write one JSON response.
|
|
313
|
+
* @param res - the HTTP response to own.
|
|
314
|
+
* @param status - HTTP status code.
|
|
315
|
+
* @param payload - JSON-serializable body.
|
|
316
|
+
*/
|
|
317
|
+
function sendJson(res, status, payload) {
|
|
318
|
+
const text = JSON.stringify(payload)
|
|
319
|
+
res.statusCode = status
|
|
320
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
321
|
+
res.setHeader('cache-control', 'no-store')
|
|
322
|
+
res.end(text)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** @param ctx - the plugin's context. */
|
|
326
|
+
export function apply(ctx) {
|
|
327
|
+
/** Last successful table, reused for `CACHE_MS`. */
|
|
328
|
+
let cache
|
|
329
|
+
/** In-flight fetch, so concurrent readers share one upstream request. */
|
|
330
|
+
let inflight
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Read the price table, fetching only when missing, forced, or stale.
|
|
334
|
+
* @param force - true for an explicit refresh.
|
|
335
|
+
* @returns the JSON body the route answers with.
|
|
336
|
+
*/
|
|
337
|
+
const read = async (force) => {
|
|
338
|
+
const fresh = cache !== undefined && Date.now() - cache.fetchedAt < CACHE_MS
|
|
339
|
+
if (!force && fresh) return cache
|
|
340
|
+
if (inflight !== undefined) return inflight
|
|
341
|
+
inflight = (async () => {
|
|
342
|
+
const response = await fetch(PRICING_URL, {
|
|
343
|
+
headers: {
|
|
344
|
+
accept: 'text/markdown, text/plain;q=0.9, */*;q=0.8',
|
|
345
|
+
'user-agent': 'dsh-continue-cost',
|
|
346
|
+
},
|
|
347
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
348
|
+
})
|
|
349
|
+
if (!response.ok) throw new Error(`pricing page returned HTTP ${String(response.status)}`)
|
|
350
|
+
const markdown = await response.text()
|
|
351
|
+
const models = parsePricing(markdown)
|
|
352
|
+
cache = {
|
|
353
|
+
ok: true,
|
|
354
|
+
source: 'official',
|
|
355
|
+
url: PRICING_URL,
|
|
356
|
+
fetchedAt: Date.now(),
|
|
357
|
+
models,
|
|
358
|
+
}
|
|
359
|
+
return cache
|
|
360
|
+
})()
|
|
361
|
+
.catch((error) => {
|
|
362
|
+
if (cache !== undefined) {
|
|
363
|
+
return {
|
|
364
|
+
...cache,
|
|
365
|
+
stale: true,
|
|
366
|
+
error: error instanceof Error ? error.message : String(error),
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
ok: false,
|
|
371
|
+
reason: 'fetch-failed',
|
|
372
|
+
message: error instanceof Error ? error.message : String(error),
|
|
373
|
+
checkedAt: Date.now(),
|
|
374
|
+
}
|
|
375
|
+
})
|
|
376
|
+
.finally(() => {
|
|
377
|
+
inflight = undefined
|
|
378
|
+
})
|
|
379
|
+
return inflight
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
ctx.effect(() => {
|
|
383
|
+
const webServer = service(ctx, 'webServer')
|
|
384
|
+
if (webServer === undefined || typeof webServer.register !== 'function') {
|
|
385
|
+
ctx.logger.warn('dsh-continue-cost: no webServer service; price refresh is unavailable')
|
|
386
|
+
return () => {}
|
|
387
|
+
}
|
|
388
|
+
return webServer.register({
|
|
389
|
+
kind: 'exact',
|
|
390
|
+
path: `${BASE_PATH}/prices`,
|
|
391
|
+
handler: async (req, res) => {
|
|
392
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
393
|
+
res.writeHead(405)
|
|
394
|
+
res.end()
|
|
395
|
+
return
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
399
|
+
sendJson(res, 200, await read(url.searchParams.get('refresh') === '1'))
|
|
400
|
+
} catch (error) {
|
|
401
|
+
sendJson(res, 500, {
|
|
402
|
+
ok: false,
|
|
403
|
+
reason: 'internal',
|
|
404
|
+
message: error instanceof Error ? error.message : String(error),
|
|
405
|
+
checkedAt: Date.now(),
|
|
406
|
+
})
|
|
407
|
+
}
|
|
408
|
+
},
|
|
409
|
+
})
|
|
410
|
+
}, 'dsh-continue-cost: price route')
|
|
411
|
+
|
|
412
|
+
/** Parsed holiday years, keyed by year; reused for one day. */
|
|
413
|
+
const holidayCache = new Map()
|
|
414
|
+
/** In-flight holiday fetches, keyed by year. */
|
|
415
|
+
const holidayInflight = new Map()
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Load one year's holiday schedule, reusing a fresh parse or an in-flight
|
|
419
|
+
* request. A failed refresh with a previous value returns the stale value.
|
|
420
|
+
* @param year - schedule year.
|
|
421
|
+
* @param force - true for an explicit refresh.
|
|
422
|
+
* @returns `{ ok, dates?, error? }`.
|
|
423
|
+
*/
|
|
424
|
+
const readHolidayYear = async (year, force) => {
|
|
425
|
+
const cached = holidayCache.get(year)
|
|
426
|
+
if (!force && cached !== undefined && Date.now() - cached.fetchedAt < HOLIDAY_CACHE_MS) {
|
|
427
|
+
return cached
|
|
428
|
+
}
|
|
429
|
+
const existing = holidayInflight.get(year)
|
|
430
|
+
if (existing !== undefined) return existing
|
|
431
|
+
const pending = loadHolidayYear(year)
|
|
432
|
+
.then((result) => {
|
|
433
|
+
const record = {
|
|
434
|
+
ok: true,
|
|
435
|
+
dates: result.dates,
|
|
436
|
+
sourceUrl: result.sourceUrl,
|
|
437
|
+
via: result.via,
|
|
438
|
+
fetchedAt: Date.now(),
|
|
439
|
+
}
|
|
440
|
+
holidayCache.set(year, record)
|
|
441
|
+
return record
|
|
442
|
+
})
|
|
443
|
+
.catch((error) => {
|
|
444
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
445
|
+
if (cached !== undefined) return { ...cached, stale: true, error: message }
|
|
446
|
+
return { ok: false, error: message }
|
|
447
|
+
})
|
|
448
|
+
.finally(() => {
|
|
449
|
+
holidayInflight.delete(year)
|
|
450
|
+
})
|
|
451
|
+
holidayInflight.set(year, pending)
|
|
452
|
+
return pending
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Read current-year and next-year schedules.
|
|
457
|
+
* @param force - true for an explicit refresh.
|
|
458
|
+
* @returns the holiday route body.
|
|
459
|
+
*/
|
|
460
|
+
const readHolidays = async (force) => {
|
|
461
|
+
const beijing = new Date(Date.now() + 8 * 60 * 60 * 1000)
|
|
462
|
+
const currentYear = beijing.getUTCFullYear()
|
|
463
|
+
const years = [currentYear, currentYear + 1]
|
|
464
|
+
const records = await Promise.all(years.map((year) => readHolidayYear(year, force)))
|
|
465
|
+
const result = {}
|
|
466
|
+
const errors = {}
|
|
467
|
+
records.forEach((record, index) => {
|
|
468
|
+
const year = years[index]
|
|
469
|
+
if (record.ok) result[year] = record.dates
|
|
470
|
+
else errors[year] = record.error
|
|
471
|
+
})
|
|
472
|
+
const ok = Object.keys(result).length > 0
|
|
473
|
+
return {
|
|
474
|
+
ok,
|
|
475
|
+
source: 'official',
|
|
476
|
+
fetchedAt: Date.now(),
|
|
477
|
+
years: result,
|
|
478
|
+
...(ok ? {} : { reason: 'fetch-failed', message: 'no year could be loaded', errors }),
|
|
479
|
+
...(ok && Object.keys(errors).length > 0 ? { errors } : {}),
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
ctx.effect(() => {
|
|
484
|
+
const webServer = service(ctx, 'webServer')
|
|
485
|
+
if (webServer === undefined || typeof webServer.register !== 'function') {
|
|
486
|
+
ctx.logger.warn('dsh-continue-cost: no webServer service; holiday refresh is unavailable')
|
|
487
|
+
return () => {}
|
|
488
|
+
}
|
|
489
|
+
return webServer.register({
|
|
490
|
+
kind: 'exact',
|
|
491
|
+
path: `${BASE_PATH}/holidays`,
|
|
492
|
+
handler: async (req, res) => {
|
|
493
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
494
|
+
res.writeHead(405)
|
|
495
|
+
res.end()
|
|
496
|
+
return
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
500
|
+
sendJson(res, 200, await readHolidays(url.searchParams.get('refresh') === '1'))
|
|
501
|
+
} catch (error) {
|
|
502
|
+
sendJson(res, 500, {
|
|
503
|
+
ok: false,
|
|
504
|
+
reason: 'internal',
|
|
505
|
+
message: error instanceof Error ? error.message : String(error),
|
|
506
|
+
checkedAt: Date.now(),
|
|
507
|
+
})
|
|
508
|
+
}
|
|
509
|
+
},
|
|
510
|
+
})
|
|
511
|
+
}, 'dsh-continue-cost: holiday route')
|
|
512
|
+
}
|
package/host.js
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
|
|
2
|
+
<g fill="none" stroke="#2E6FB7" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
|
|
3
|
+
<path d="M27.5 13.2A10.5 10.5 0 1 0 28 21.5"/>
|
|
4
|
+
<path d="M28.2 8.9v5.2h-5.2"/>
|
|
5
|
+
</g>
|
|
6
|
+
<circle cx="24.2" cy="25.4" r="6" fill="#E8A93C"/>
|
|
7
|
+
<path d="M24.2 22.4v5.9M21.9 24h4.6M21.9 26.3h4.6" fill="none" stroke="#754A00" stroke-width="1.35" stroke-linecap="round"/>
|
|
8
|
+
</svg>
|
package/index.js
ADDED
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Turn count & carry-over delta",
|
|
4
|
+
"description": "Shows the completed turn count at the right of the composer, or switches to the extra cost of continuing this conversation instead of starting a fresh one. A small badge on the chip names the tariff in force and flips automatically across the official peak boundaries (09:00–12:00 and 14:00–18:00 Beijing time on workdays). Hover for the estimate; click the chip to pin the panel, switch the display, and set green, yellow, and red thresholds for turns or cost. Price and Chinese holiday tables update daily from public DeepSeek and gov.cn pages, falling back to a local cache or built-in table; no conversation content is sent and no API key is read."
|
|
5
|
+
}
|
|
6
|
+
}
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "对话轮数与续聊差价",
|
|
4
|
+
"description": "在输入框右侧显示已完成的对话轮数,也可切换为显示继续当前对话比新开对话多花的金额;胶囊上直接标出当前是峰时还是谷时,跨过官方峰谷边界(工作日北京时间 9:00–12:00、14:00–18:00 为峰时)会自动切换。悬停查看估算明细,点击胶囊固定面板后切换显示并设置轮数或金额的绿、黄、红阈值。价格表和法定节假日表每天从 DeepSeek 与中国政府网的公开页面自动更新,失败时使用本地缓存或内置表;不发送会话内容,不读取 API Key。"
|
|
5
|
+
}
|
|
6
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-continue-cost",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.3.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"description": "DSH 插件:显示对话轮数与续聊差价 —— 继续当前对话比新开一次多花多少钱,按官方峰谷时段自动切换。Turn count and the extra context cost of continuing this chat instead of starting fresh, switching between peak and off-peak tariffs automatically.",
|
|
7
|
+
"author": {
|
|
8
|
+
"name": "0345-0433",
|
|
9
|
+
"url": "https://github.com/0345-0433"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"dsh",
|
|
13
|
+
"dsh-plugin",
|
|
14
|
+
"deepseek-harness",
|
|
15
|
+
"cost",
|
|
16
|
+
"token",
|
|
17
|
+
"pricing",
|
|
18
|
+
"turn-count",
|
|
19
|
+
"cache",
|
|
20
|
+
"plugin"
|
|
21
|
+
],
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/0345-0433/dsh-continue-cost.git"
|
|
25
|
+
},
|
|
26
|
+
"homepage": "https://github.com/0345-0433/dsh-continue-cost#readme",
|
|
27
|
+
"bugs": {
|
|
28
|
+
"url": "https://github.com/0345-0433/dsh-continue-cost/issues"
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"icon": "./icon.svg",
|
|
32
|
+
"main": "./host-1.2.0.js",
|
|
33
|
+
"scripts": {
|
|
34
|
+
"test": "node test/client.test.mjs"
|
|
35
|
+
},
|
|
36
|
+
"exports": {
|
|
37
|
+
".": "./host-1.2.0.js",
|
|
38
|
+
"./host": "./host-1.2.0.js",
|
|
39
|
+
"./client": "./client.js",
|
|
40
|
+
"./locale/*.json": "./locale/*.json",
|
|
41
|
+
"./icon": "./icon.svg",
|
|
42
|
+
"./package.json": "./package.json"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"host-1.2.0.js",
|
|
46
|
+
"host.js",
|
|
47
|
+
"index.js",
|
|
48
|
+
"client.js",
|
|
49
|
+
"cordis.patch.yml",
|
|
50
|
+
"locale/*.json",
|
|
51
|
+
"icon.svg",
|
|
52
|
+
"README.md",
|
|
53
|
+
"LICENSE"
|
|
54
|
+
],
|
|
55
|
+
"dsh": {
|
|
56
|
+
"bundle": {
|
|
57
|
+
"patch": "./cordis.patch.yml"
|
|
58
|
+
},
|
|
59
|
+
"client": {
|
|
60
|
+
"platform": "web",
|
|
61
|
+
"immediately": true,
|
|
62
|
+
"inject": [
|
|
63
|
+
"@deepseek-ai/dsh-client-ui-slots"
|
|
64
|
+
]
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|