dsh-model-allowance 0.0.0-stage → 1.0.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/status.js ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Provider platform status.
3
+ *
4
+ * The four sources this plugin reads are public pages, not authenticated
5
+ * APIs: a Statuspage JSON document, OpenCode's own status endpoint, and the
6
+ * server-rendered DeepSeek page. None of them needs a credential, so this
7
+ * service owns no secrets and can be reached from anywhere — but it is still
8
+ * Host-only, because the browser should not have to know four different
9
+ * response formats.
10
+ *
11
+ * A reading is cached per source, not per route: the two DeepSeek routes share
12
+ * one status page, and asking twice must not mean fetching twice.
13
+ */
14
+
15
+ import { findAdapter } from './providers.js'
16
+
17
+ /** Status pages refresh on the order of a minute; more often buys nothing. */
18
+ const DEFAULT_TTL_MS = 60 * 1000
19
+
20
+ /**
21
+ * How long a failed status fetch is remembered.
22
+ *
23
+ * Without a negative cache, a down source is fetched again on every badge
24
+ * mount, every 60-second dot refresh, and every manual refresh. A short
25
+ * failure window keeps the source from being hammered while still letting a
26
+ * recovered page show up promptly.
27
+ */
28
+ const DEFAULT_FAILURE_TTL_MS = 30 * 1000
29
+
30
+ /** A status page that does not answer quickly is as good as unknown. */
31
+ const DEFAULT_TIMEOUT_MS = 8 * 1000
32
+
33
+ /** A page larger than this is not a status page this plugin understands. */
34
+ const MAX_PAGE_BYTES = 2 * 1024 * 1024
35
+
36
+ /**
37
+ * @typedef {object} StatusView
38
+ * @property {string} provider Route the reading belongs to.
39
+ * @property {string} state One of the shared states in `providers/status.js`.
40
+ * @property {string} [summary] What the source says is wrong, when it says.
41
+ * @property {string} [url] The provider's status page.
42
+ * @property {number} [updatedAt] Epoch milliseconds of the reading.
43
+ * @property {string} [error] Why the reading failed, for `state === 'unknown'`.
44
+ */
45
+
46
+ /**
47
+ * @typedef {object} StatusServiceOptions
48
+ * @property {number} [ttlMs] Lifetime of one successful reading.
49
+ * @property {number} [failureTtlMs] Lifetime of one failed reading.
50
+ * @property {number} [timeoutMs] Timeout for one status request.
51
+ */
52
+
53
+ /**
54
+ * @typedef {object} StatusSource
55
+ * @property {string} endpoint Machine-readable status endpoint.
56
+ * @property {string} url Human-readable status page.
57
+ * @property {(env: {text?: string, json?: unknown, response?: unknown}) => {state: string, summary?: string}} parse Projection.
58
+ */
59
+
60
+ /**
61
+ * @typedef {object} StatusReading
62
+ * @property {string} state One of the shared states in `providers/status.js`.
63
+ * @property {string} [summary] What the source says is wrong, when it says.
64
+ * @property {string} [url] The provider's status page.
65
+ * @property {number} [updatedAt] Epoch milliseconds of the reading.
66
+ * @property {string} [error] Why the reading failed, for `state === 'unknown'`.
67
+ */
68
+
69
+ /**
70
+ * Host-side status readings, keyed by source endpoint.
71
+ */
72
+ export class StatusService {
73
+ /**
74
+ * @param {object} deps Injected dependencies.
75
+ * @param {import('@deepseek-ai/cordis').Context} deps.ctx Cordis context.
76
+ * @param {StatusServiceOptions} [deps.options] Service options.
77
+ */
78
+ constructor({ ctx, options = {} }) {
79
+ this.ctx = ctx
80
+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
81
+ this.failureTtlMs = options.failureTtlMs ?? DEFAULT_FAILURE_TTL_MS
82
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
83
+ /** @type {Map<string, {view: StatusReading, at: number, failed: boolean}>} */
84
+ this.cache = new Map()
85
+ /** @type {Map<string, Promise<StatusReading>>} */
86
+ this.inflight = new Map()
87
+ }
88
+
89
+ /**
90
+ * Read one provider's platform status.
91
+ *
92
+ * A route whose vendor publishes no status page answers `unknown` without
93
+ * touching the network: the browser hides the row, and a route that later
94
+ * gains a source starts working without any other change.
95
+ *
96
+ * @param {string} provider Provider route.
97
+ * @returns {Promise<StatusView>} The reading.
98
+ */
99
+ async read(provider) {
100
+ const source = findAdapter(provider)?.status
101
+ if (source === undefined) return { provider, state: 'unknown' }
102
+ try {
103
+ const view = await this.#readSource(source)
104
+ return { ...view, provider }
105
+ } catch (error) {
106
+ const reason = error instanceof Error ? error.message : String(error)
107
+ return { provider, state: 'unknown', url: source.url, error: reason }
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Read one source, reusing a fresh cached reading.
113
+ *
114
+ * Successful readings live for `ttlMs`; failures for `failureTtlMs`. A
115
+ * failure is cached as an `unknown` reading rather than thrown, so every
116
+ * route sharing the source gets the same answer without another request.
117
+ *
118
+ * @param {StatusSource} source The source.
119
+ * @returns {Promise<StatusReading>} The reading without its provider.
120
+ */
121
+ async #readSource(source) {
122
+ const cached = this.cache.get(source.endpoint)
123
+ if (cached) {
124
+ const ttl = cached.failed ? this.failureTtlMs : this.ttlMs
125
+ if (Date.now() - cached.at < ttl) return cached.view
126
+ }
127
+ const pending = this.inflight.get(source.endpoint)
128
+ if (pending) return await pending
129
+ const request = this.#query(source)
130
+ .then((view) => {
131
+ this.cache.set(source.endpoint, { view, at: Date.now(), failed: false })
132
+ return view
133
+ })
134
+ .catch((error) => {
135
+ const reason = error instanceof Error ? error.message : String(error)
136
+ const view = {
137
+ state: 'unknown',
138
+ url: source.url,
139
+ error: reason,
140
+ updatedAt: Date.now(),
141
+ }
142
+ this.cache.set(source.endpoint, { view, at: Date.now(), failed: true })
143
+ return view
144
+ })
145
+ .finally(() => {
146
+ this.inflight.delete(source.endpoint)
147
+ })
148
+ this.inflight.set(source.endpoint, request)
149
+ return await request
150
+ }
151
+
152
+ /**
153
+ * Fetch and project one source.
154
+ * @param {StatusSource} source The source.
155
+ * @returns {Promise<StatusReading>} The reading without its provider.
156
+ */
157
+ async #query(source) {
158
+ const timeout = AbortSignal.timeout(this.timeoutMs)
159
+ const response = await fetch(source.endpoint, {
160
+ headers: { accept: 'application/json, text/html;q=0.9' },
161
+ signal: timeout,
162
+ })
163
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
164
+ // Check the declared size before reading the body: a status page that is
165
+ // not a status page (a captive portal, an error page) should not be read
166
+ // into memory in full.
167
+ const declared = Number(response.headers?.get?.('content-length'))
168
+ if (Number.isFinite(declared) && declared > MAX_PAGE_BYTES) {
169
+ throw new Error('status page too large')
170
+ }
171
+ const text = await response.text()
172
+ if (text.length > MAX_PAGE_BYTES) throw new Error('status page too large')
173
+ let json
174
+ const contentType = response.headers?.get?.('content-type') ?? ''
175
+ if (contentType.includes('json')) {
176
+ try {
177
+ json = JSON.parse(text)
178
+ } catch {
179
+ // A body that claims JSON and is not: the parser decides what that
180
+ // means, and most will answer unknown.
181
+ }
182
+ }
183
+ const parsed = source.parse({ text, json, response })
184
+ if (parsed === null || typeof parsed !== 'object' || typeof parsed.state !== 'string') {
185
+ throw new Error('status source returned no state')
186
+ }
187
+ return {
188
+ state: parsed.state,
189
+ ...(typeof parsed.summary === 'string' && parsed.summary !== ''
190
+ ? { summary: parsed.summary }
191
+ : {}),
192
+ url: source.url,
193
+ updatedAt: Date.now(),
194
+ }
195
+ }
196
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Model Allowance",
4
+ "description": "Shows the current conversation model's provider balance or remaining allowance in the composer."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "模型额度",
4
+ "description": "在输入框显示当前会话所用模型的厂商余额或剩余额度。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
2
  "name": "dsh-model-allowance",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Shows the current conversation model's provider balance or remaining allowance in the composer.",
6
+ "license": "MIT",
7
+ "author": "MeiK2333",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/MeiK2333/dsh-model-allowance.git"
11
+ },
12
+ "homepage": "https://github.com/MeiK2333/dsh-model-allowance#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/MeiK2333/dsh-model-allowance/issues"
15
+ },
16
+ "keywords": [
17
+ "deepseek-harness",
18
+ "dsh",
19
+ "dsh-plugin",
20
+ "balance",
21
+ "quota",
22
+ "allowance",
23
+ "composer"
24
+ ],
25
+ "exports": {
26
+ ".": "./index.js",
27
+ "./client": "./client.js",
28
+ "./package.json": "./package.json",
29
+ "./locale/*.json": "./locale/*.json",
30
+ "./icon": "./icon.svg"
31
+ },
32
+ "files": [
33
+ "index.js",
34
+ "client.js",
35
+ "cordis.patch.yml",
36
+ "lib/*.js",
37
+ "lib/providers/*.js",
38
+ "locale/*.json",
39
+ "icon.svg",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "dsh": {
44
+ "bundle": {
45
+ "patch": "./cordis.patch.yml"
46
+ },
47
+ "client": {
48
+ "platform": "web",
49
+ "immediately": true,
50
+ "inject": [
51
+ "@deepseek-ai/dsh-client-ui-conversation"
52
+ ]
53
+ }
54
+ },
55
+ "engines": {
56
+ "dsh": ">=0.2.1-rc.5 <0.3.0"
57
+ },
58
+ "scripts": {
59
+ "build": "node tools/build-client.mjs",
60
+ "check:dist": "node tools/build-client.mjs --check",
61
+ "lint": "biome check .",
62
+ "format": "biome format --write .",
63
+ "pretest": "npm run check:dist",
64
+ "test": "npm run test:unit && npm run test:integration",
65
+ "test:unit": "node --test \"test/*.test.mjs\"",
66
+ "test:integration": "node tools/verify-all.mjs",
67
+ "typecheck": "tsc --noEmit",
68
+ "prepack": "npm run build"
69
+ },
70
+ "devDependencies": {
71
+ "@biomejs/biome": "^2.6.5",
72
+ "@deepseek-ai/cordis": "^4.1.0",
73
+ "@deepseek-ai/dsh-typert-protocol": "^0.2.2-rc.1",
74
+ "@deepseek-ai/schemastery": "^3.19.0",
75
+ "@types/node": "^26.6.6",
76
+ "@types/react": "^18.3.28",
77
+ "@types/react-dom": "^18.3.7",
78
+ "esbuild": "^0.28.2",
79
+ "react": "^18.3.1",
80
+ "react-dom": "^18.3.1",
81
+ "typescript": "^7.0.2",
82
+ "zod": "^4.6.7"
83
+ }
84
+ }