dsh-opencode-status 0.1.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## 0.1.2
4
+
5
+ - 修复自定义 `keyRef` 配置下凭据读取、写入与清除目标不一致的问题
6
+ - 让 `OPENCODE_BASE_URL` 正确作为未配置 profile 的默认地址
7
+ - 实现 `/api/opencode-status/sync` 并让客户端通过该接口强制刷新
8
+ - 增加凭据引用、同步路由和环境变量默认值回归测试
9
+
10
+ ## 0.1.1
11
+
12
+ - 放大右上角设置(⚙)、刷新(↻)、关闭(✕)触控区域,提升交互手感与可点击性
13
+ - 统一侧栏状态指示灯对齐基准线与自适应弹性文本
14
+
15
+ ## 0.1.0
16
+
17
+ - 侧栏极简状态胶囊按钮(`● OpenCode · 月用量 58%`),异常自动变色,默认不打扰
18
+ - 点击弹出轻量悬浮面板,展示 Rolling (5h)、Weekly、Monthly 进度条与重置倒计时
19
+ - 支持直接在面板内配置 OpenCode API Key 与 Base URL,密钥安全保存在宿主凭据库
20
+ - 支持手动刷新与自动缓存
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # dsh-opencode-status
2
+
3
+ OpenCode GO 套餐用量与配额状态监控面板插件(DeepSeek Harness):侧栏常驻极简单行胶囊按钮,点开即看 5h 滑动窗口、周窗口、月窗口用量进度条与重置倒计时。
4
+
5
+ ## 功能特性
6
+
7
+ - **极简常驻态**:单行状态胶囊(`● OpenCode · 月用量 58%`),平时低调克制,超额预警时自动变色,默认不打扰。
8
+ - **3 维度用量进度条**:
9
+ - **滚动窗口 (5h)**:实时用量 % + 下次重置倒计时(如 `↻ 4h20m`)
10
+ - **周窗口 (Weekly)**:周额度消耗 % + 重置倒计时
11
+ - **月窗口 (Monthly)**:月额度消耗 % + 重置倒计时
12
+ - **内置安全配置卡片**:直接在弹窗内配置 API Key 与 Base URL,密钥仅存入宿主凭据库(`OPENCODE_GO_API_KEY`),API 响应不回传明文。
13
+ - **平滑交互**:悬浮面板智能定位,点击外部空白区域自动收起,用完即走。
14
+ - **多端同步与缓存**:服务端 30s 智能缓存,支持一键手动强制刷新。
15
+
16
+ ## 安装与更新
17
+
18
+ ### 1. 一键安装(自动拉取最新最新版)
19
+
20
+ ```sh
21
+ dsh plugin --profile web add github:j2st1n/dsh-opencode-status
22
+ ```
23
+
24
+ > **说明**:
25
+ > - 无需指定版本号,默认直接拉取 GitHub 上的**最新版本**(相当于 `@latest`);
26
+ > - 若需锁定特定稳定版本,可指定 Tag:`dsh plugin --profile web add github:j2st1n/dsh-opencode-status#v0.1.2`;
27
+ > - 安装后重启 `dsh web` 即可立即生效。
28
+
29
+ ### 2. 卸载
30
+
31
+ ```sh
32
+ dsh plugin --profile web remove dsh-opencode-status
33
+ ```
34
+
35
+ ## 配置
36
+
37
+ 点侧栏「连接 OpenCode」或弹窗右上角「⚙」配置:
38
+ - **Base URL**:默认 `https://opencode.ai/zen/go`
39
+ - **API Key**:粘贴你的 OpenCode API Key(亦可直接在环境变量中配置 `OPENCODE_GO_API_KEY`)
40
+
41
+ ## License
42
+
43
+ [Apache-2.0](./LICENSE)
package/SECURITY.md ADDED
@@ -0,0 +1,5 @@
1
+ # Security notes
2
+
3
+ - The OpenCode API key is stored only in the host credentials store (`OPENCODE_GO_API_KEY` or custom key ref); API responses never return the full key.
4
+ - Host routes are local to the DSH web server (`Cache-Control: no-store`) and return allowlisted usage fields only.
5
+ - Upstream requests use a 10-second `AbortController` timeout, and successful usage responses are cached for 30 seconds to reduce gateway load.
@@ -0,0 +1,4 @@
1
+ # dsh-opencode-status bundle patch
2
+ - insert:
3
+ - id: opencode-status
4
+ name: dsh-opencode-status
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "dsh-opencode-status",
3
+ "version": "0.1.2",
4
+ "description": "OpenCode GO quota and plan status panel for DeepSeek Harness: sidebar health light, quota bars, countdown timers, and in-app key management",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "keywords": [
8
+ "deepseek-harness",
9
+ "dsh",
10
+ "dsh-plugin",
11
+ "opencode",
12
+ "opencode-go",
13
+ "status-panel"
14
+ ],
15
+ "exports": {
16
+ ".": "./src/index.js",
17
+ "./client": "./src/client.js",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "files": [
21
+ "src",
22
+ "cordis.patch.yml",
23
+ "SECURITY.md",
24
+ "CHANGELOG.md",
25
+ "README.md"
26
+ ],
27
+ "dsh": {
28
+ "bundle": {
29
+ "patch": "./cordis.patch.yml"
30
+ },
31
+ "client": {
32
+ "platform": "web",
33
+ "inject": []
34
+ }
35
+ },
36
+ "dependencies": {
37
+ "@deepseek-ai/schemastery": "^3.18.1"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/j2st1n/dsh-opencode-status.git"
42
+ },
43
+ "homepage": "https://github.com/j2st1n/dsh-opencode-status#readme",
44
+ "bugs": "https://github.com/j2st1n/dsh-opencode-status/issues",
45
+ "engines": {
46
+ "node": ">=20"
47
+ },
48
+ "scripts": {
49
+ "test": "node --test"
50
+ }
51
+ }
package/src/client.js ADDED
@@ -0,0 +1,557 @@
1
+ /**
2
+ * dsh-opencode-status — Client half.
3
+ *
4
+ * 槽位:
5
+ * sidebar.footer.action 常驻极简单行按钮(状态灯 + 月用量 %;点击呼出详情面板)
6
+ * shell.overlay 轻量浮层面板(展示 Rolling 5h、Weekly、Monthly 进度条与重置倒计时)
7
+ */
8
+ window.__ModuleLoader__.load({
9
+ id: 'dsh-opencode-status',
10
+ factory: (require) => {
11
+ const module = { exports: {} }
12
+ const exports = module.exports
13
+ const React = require('react')
14
+ const h = React.createElement
15
+ const { useEffect, useState, useRef } = React
16
+
17
+ const CSS = `
18
+ div[class*="footerActions"] { display: flex !important; flex-direction: column !important; gap: 4px !important; width: 100% !important; }
19
+ @keyframes ocFadeSlideUp { from { opacity: 0; transform: translateY(8px) scale(.98) } to { opacity: 1; transform: translateY(0) scale(1) } }
20
+ @keyframes ocFadeSlideDown { from { opacity: 1; transform: translateY(0) scale(1) } to { opacity: 0; transform: translateY(8px) scale(.98) } }
21
+ @keyframes ocSpin { to { transform: rotate(360deg) } }
22
+ @keyframes ocPulse { 0% { box-shadow: 0 0 0 0 rgba(34,197,94,.45) } 70% { box-shadow: 0 0 0 5px rgba(34,197,94,0) } 100% { box-shadow: 0 0 0 0 rgba(34,197,94,0) } }
23
+ .oc-panel-enter { animation: ocFadeSlideUp .2s cubic-bezier(.2,.9,.3,1.2) both }
24
+ .oc-panel-exit { animation: ocFadeSlideDown .15s ease-in both; pointer-events: none !important }
25
+ .oc-btn { min-width: 0; transition: background .15s ease, border-color .15s ease, color .15s ease, transform .1s ease }
26
+ .oc-btn:hover:not(:disabled):not(.oc-btn-primary) { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-1)); border-color: var(--dsw-alias-border-l2) }
27
+ .oc-btn-primary:hover:not(:disabled) { filter: brightness(1.12) }
28
+ .oc-btn:active:not(:disabled) { transform: scale(.98) }
29
+ .oc-spin { display: inline-block; animation: ocSpin .8s linear infinite }
30
+ .oc-dot-live { animation: ocPulse 2.4s ease-out infinite }
31
+ @media (prefers-reduced-motion: reduce) {
32
+ .oc-panel-enter, .oc-panel-exit, .oc-spin, .oc-dot-live { animation: none !important }
33
+ }
34
+ `
35
+
36
+ const T = {
37
+ bg: 'var(--dsw-alias-bg-layer-2)',
38
+ layer1: 'var(--dsw-alias-bg-layer-1)',
39
+ border: 'var(--dsw-alias-border-l1)',
40
+ border2: 'var(--dsw-alias-border-l2)',
41
+ label: 'var(--dsw-alias-label-primary)',
42
+ secondary: 'var(--dsw-alias-label-secondary)',
43
+ brand: 'var(--dsw-alias-brand-primary)',
44
+ ok: 'var(--dsw-alias-state-success-primary)',
45
+ warn: 'var(--dsw-alias-state-warn-primary)',
46
+ err: 'var(--dsw-alias-state-error-primary)',
47
+ }
48
+
49
+ const dotStyle = (color) => ({
50
+ display: 'inline-block',
51
+ width: 7,
52
+ height: 7,
53
+ borderRadius: '50%',
54
+ background: color,
55
+ flexShrink: 0,
56
+ verticalAlign: 'middle',
57
+ })
58
+
59
+ const btnBase = {
60
+ display: 'flex',
61
+ alignItems: 'center',
62
+ gap: 6,
63
+ padding: '4px 8px',
64
+ border: `1px solid ${T.border}`,
65
+ borderRadius: 6,
66
+ background: 'transparent',
67
+ color: T.label,
68
+ fontSize: 12,
69
+ lineHeight: '18px',
70
+ height: 28,
71
+ boxSizing: 'border-box',
72
+ cursor: 'pointer',
73
+ whiteSpace: 'nowrap',
74
+ }
75
+
76
+ const inputStyle = {
77
+ width: '100%',
78
+ boxSizing: 'border-box',
79
+ padding: '6px 8px',
80
+ border: `1px solid ${T.border}`,
81
+ borderRadius: 6,
82
+ background: T.layer1,
83
+ color: T.label,
84
+ fontSize: 12,
85
+ outline: 'none',
86
+ }
87
+
88
+ function timeUntil(ts) {
89
+ if (!ts) return ''
90
+ const diff = ts - Date.now()
91
+ if (diff <= 0) return '即将重置'
92
+ const mins = Math.floor(diff / 60000)
93
+ if (mins < 60) return `${mins}m`
94
+ const hours = Math.floor(mins / 60)
95
+ if (hours < 24) return `${hours}h${mins % 60 ? `${mins % 60}m` : ''}`
96
+ return `${Math.floor(hours / 24)}d${hours % 24 ? `${hours % 24}h` : ''}`
97
+ }
98
+
99
+ function usageColor(percent) {
100
+ if (percent === null || percent === undefined) return T.secondary
101
+ if (percent >= 90) return T.err
102
+ if (percent >= 70) return T.warn
103
+ return T.ok
104
+ }
105
+
106
+ // ---------- Store ----------
107
+ const store = {
108
+ state: {
109
+ open: false,
110
+ editing: false,
111
+ status: null,
112
+ config: null,
113
+ refreshing: false,
114
+ error: null,
115
+ },
116
+ listeners: new Set(),
117
+ set(patch) {
118
+ store.state = { ...store.state, ...patch }
119
+ for (const fn of store.listeners) fn()
120
+ },
121
+ subscribe(fn) {
122
+ store.listeners.add(fn)
123
+ return () => store.listeners.delete(fn)
124
+ },
125
+ }
126
+
127
+ function useStore() {
128
+ return React.useSyncExternalStore(store.subscribe, () => store.state)
129
+ }
130
+
131
+ async function api(path, options) {
132
+ const res = await fetch(path, options)
133
+ const data = await res.json().catch(() => ({}))
134
+ if (!res.ok) throw Object.assign(new Error(data?.error?.message ?? `HTTP ${res.status}`), { data })
135
+ return data
136
+ }
137
+
138
+ async function refreshStatus(force = false) {
139
+ try {
140
+ const status = force
141
+ ? await api('/api/opencode-status/sync', { method: 'POST' })
142
+ : await api('/api/opencode-status')
143
+ store.set({ status, error: null })
144
+ } catch (err) {
145
+ store.set({ error: String(err?.message ?? err) })
146
+ }
147
+ }
148
+
149
+ async function refreshConfig() {
150
+ try {
151
+ const config = await api('/api/opencode-status/config')
152
+ store.set({ config })
153
+ } catch {}
154
+ }
155
+
156
+ // ---------- 常驻入口(上下结构单行按钮) ----------
157
+ function FooterEntry(props) {
158
+ const state = useStore()
159
+
160
+ useEffect(() => {
161
+ refreshStatus(false)
162
+ const timer = setInterval(() => refreshStatus(false), 30_000)
163
+ return () => clearInterval(timer)
164
+ }, [])
165
+
166
+ const st = state.status
167
+ let color = T.warn
168
+ let text = '连接 OpenCode'
169
+ let value = null
170
+
171
+ if (state.error) {
172
+ color = T.err
173
+ text = 'OpenCode ?'
174
+ } else if (st?.mode === 'ready') {
175
+ if (st.ok) {
176
+ const pct = st.monthlyUsedPct
177
+ color = usageColor(pct)
178
+ text = 'OpenCode'
179
+ value = pct !== null ? `月用量 ${pct}%` : '在线'
180
+ } else {
181
+ color = T.err
182
+ text = 'OpenCode'
183
+ value = '异常'
184
+ }
185
+ }
186
+
187
+ if (props?.wide === false) {
188
+ return h(
189
+ 'div',
190
+ {
191
+ className: 'oc-btn',
192
+ style: {
193
+ boxSizing: 'border-box',
194
+ width: 36,
195
+ height: 36,
196
+ display: 'flex',
197
+ alignItems: 'center',
198
+ justifyContent: 'center',
199
+ borderRadius: 8,
200
+ fontSize: 10,
201
+ fontWeight: 700,
202
+ color: T.label,
203
+ cursor: 'pointer',
204
+ margin: '2px auto',
205
+ },
206
+ title: st?.error?.message || `OpenCode GO ${value || ''}`,
207
+ onClick: () => store.set({ open: !state.open, editing: false }),
208
+ },
209
+ st?.monthlyUsedPct !== null && st?.monthlyUsedPct !== undefined ? `${st.monthlyUsedPct}%` : 'GO',
210
+ )
211
+ }
212
+
213
+ return h(
214
+ 'button',
215
+ {
216
+ className: 'oc-btn oc-footer-btn',
217
+ style: {
218
+ ...btnBase,
219
+ display: props?.wide === false ? 'inline-flex' : 'flex',
220
+ width: props?.wide === false ? undefined : '100%',
221
+ boxSizing: 'border-box',
222
+ justifyContent: props?.wide === false ? 'center' : 'flex-start',
223
+ margin: '2px 0',
224
+ minWidth: 0,
225
+ flexShrink: 0,
226
+ },
227
+ onClick: () => {
228
+ store.set({ open: !state.open, editing: false })
229
+ if (!state.open) {
230
+ refreshStatus(false)
231
+ refreshConfig()
232
+ }
233
+ },
234
+ title: st?.error?.message || `OpenCode GO · ${value || '点击查看详情'}`,
235
+ },
236
+ h('span', { className: color === T.ok ? 'oc-dot-live' : undefined, style: dotStyle(color) }),
237
+ h(
238
+ 'span',
239
+ { style: { display: 'inline-flex', alignItems: 'center', lineHeight: '18px', whiteSpace: 'nowrap', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } },
240
+ [
241
+ h('span', { key: 't', style: { color: T.label, flexShrink: 0 } }, text),
242
+ value
243
+ ? [
244
+ h('span', { key: 'sep', style: { color: T.secondary, margin: '0 5px', opacity: 0.7, flexShrink: 0 } }, '·'),
245
+ h('span', { key: 'v', style: { color, fontWeight: 500, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis' } }, value),
246
+ ]
247
+ : null,
248
+ ].flat().filter(Boolean),
249
+ ),
250
+ )
251
+ }
252
+
253
+ // ---------- 配额进度条 ----------
254
+ function QuotaRow(props) {
255
+ const w = props.window
256
+ const used = w.usedPct
257
+ const color = usageColor(used)
258
+ return h('div', { style: { marginBottom: 10 } }, [
259
+ h('div', { key: 'label', style: { display: 'flex', fontSize: 11, marginBottom: 3, fontVariantNumeric: 'tabular-nums' } }, [
260
+ h('span', { style: { color: T.label, fontWeight: 500 } }, w.label),
261
+ h('span', { style: { marginLeft: 'auto', color, fontWeight: 600 } }, used !== null ? `${used}%` : '—'),
262
+ w.resetAt ? h('span', { style: { color: T.secondary, marginLeft: 6 } }, `↻ ${timeUntil(w.resetAt)}`) : null,
263
+ ]),
264
+ h(
265
+ 'div',
266
+ {
267
+ key: 'track',
268
+ style: {
269
+ height: 6,
270
+ borderRadius: 3,
271
+ background: `color-mix(in srgb, ${color} 14%, transparent)`,
272
+ boxShadow: `inset 0 0 0 1px ${T.border}`,
273
+ overflow: 'hidden',
274
+ },
275
+ },
276
+ used === null
277
+ ? null
278
+ : h('div', {
279
+ style: {
280
+ height: '100%',
281
+ width: `${Math.max(0, Math.min(100, used))}%`,
282
+ background: color,
283
+ borderRadius: 3,
284
+ transition: 'width 0.4s ease',
285
+ },
286
+ }),
287
+ ),
288
+ ])
289
+ }
290
+
291
+ // ---------- 配置卡片 ----------
292
+ function ConfigCard() {
293
+ const state = useStore()
294
+ const cfg = state.config
295
+ const keyState = cfg?.apiKey ?? { configured: false, writable: true, hint: null }
296
+ const [baseUrl, setBaseUrl] = useState('')
297
+ const [apiKey, setApiKey] = useState('')
298
+ const [saving, setSaving] = useState(false)
299
+ const [error, setError] = useState(null)
300
+
301
+ useEffect(() => {
302
+ if (cfg) setBaseUrl(cfg.baseUrl ?? '')
303
+ }, [cfg])
304
+
305
+ async function save() {
306
+ setSaving(true)
307
+ setError(null)
308
+ try {
309
+ const result = await api('/api/opencode-status/config', {
310
+ method: 'PUT',
311
+ headers: { 'content-type': 'application/json' },
312
+ body: JSON.stringify({ baseUrl, ...(apiKey ? { apiKey } : {}) }),
313
+ })
314
+ store.set({ status: result.status, config: result.config, editing: false })
315
+ setApiKey('')
316
+ } catch (e) {
317
+ setError(e?.message ?? '保存失败')
318
+ } finally {
319
+ setSaving(false)
320
+ }
321
+ }
322
+
323
+ async function clearKey() {
324
+ if (!window.confirm('确定清除已保存的 OpenCode API Key?')) return
325
+ setSaving(true)
326
+ setError(null)
327
+ try {
328
+ const result = await api('/api/opencode-status/config', {
329
+ method: 'PUT',
330
+ headers: { 'content-type': 'application/json' },
331
+ body: JSON.stringify({ baseUrl, clearApiKey: true }),
332
+ })
333
+ store.set({ status: result.status, config: result.config, editing: false })
334
+ } catch (e) {
335
+ setError(e?.message ?? '清除失败')
336
+ } finally {
337
+ setSaving(false)
338
+ }
339
+ }
340
+
341
+ return h('div', null, [
342
+ h('div', { key: 'u', style: { marginBottom: 10 } }, [
343
+ h('label', { style: { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 } }, 'Base URL'),
344
+ h('input', {
345
+ style: inputStyle,
346
+ value: baseUrl,
347
+ placeholder: 'https://opencode.ai/zen/go',
348
+ onChange: (e) => setBaseUrl(e.target.value),
349
+ }),
350
+ ]),
351
+ h('div', { key: 'k', style: { marginBottom: 10 } }, [
352
+ h('label', { style: { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 } }, `API Key *${keyState.configured ? `(已保存 ${keyState.hint})` : ''}`),
353
+ h('input', {
354
+ style: { ...inputStyle, opacity: keyState.writable ? 1 : 0.6 },
355
+ type: 'password',
356
+ value: apiKey,
357
+ disabled: !keyState.writable,
358
+ placeholder: keyState.configured ? '留空表示不修改' : '粘贴 OpenCode API Key',
359
+ onChange: (e) => setApiKey(e.target.value),
360
+ }),
361
+ ]),
362
+ error ? h('div', { key: 'err', style: { fontSize: 11, color: T.err, marginBottom: 8 } }, error) : null,
363
+ h('div', { key: 'btns', style: { display: 'flex', gap: 8, marginTop: 12, alignItems: 'center' } }, [
364
+ h(
365
+ 'button',
366
+ { className: 'oc-btn oc-btn-primary', style: { ...btnBase, background: T.brand, borderColor: T.brand, color: '#fff' }, disabled: saving, onClick: save },
367
+ saving ? '保存中…' : '保存并连接',
368
+ ),
369
+ state.status?.mode === 'ready'
370
+ ? h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: () => store.set({ editing: false }) }, '取消')
371
+ : null,
372
+ keyState.configured && keyState.writable
373
+ ? h('button', { className: 'oc-btn', style: { ...btnBase, color: T.err, marginLeft: 'auto' }, disabled: saving, onClick: clearKey }, '清除')
374
+ : null,
375
+ ]),
376
+ ])
377
+ }
378
+
379
+ // ---------- 浮层面板 ----------
380
+ function OverlayPanel() {
381
+ const state = useStore()
382
+ const panelRef = useRef(null)
383
+ const [phase, setPhase] = useState('closed')
384
+
385
+ useEffect(() => {
386
+ if (state.open) setPhase('open')
387
+ else setPhase((p) => (p === 'open' ? 'closing' : p))
388
+ }, [state.open])
389
+
390
+ useEffect(() => {
391
+ if (phase !== 'closing') return
392
+ const timer = setTimeout(() => setPhase('closed'), 160)
393
+ return () => clearTimeout(timer)
394
+ }, [phase])
395
+
396
+ // 点击外部关闭
397
+ useEffect(() => {
398
+ if (!state.open) return
399
+ const handleClickOutside = (e) => {
400
+ if (panelRef.current && !panelRef.current.contains(e.target)) {
401
+ const isBtn = e.target.closest && e.target.closest('.oc-footer-btn')
402
+ if (!isBtn) store.set({ open: false, editing: false })
403
+ }
404
+ }
405
+ window.addEventListener('mousedown', handleClickOutside)
406
+ return () => window.removeEventListener('mousedown', handleClickOutside)
407
+ }, [state.open])
408
+
409
+ if (phase === 'closed') return null
410
+
411
+ const st = state.status
412
+ const showConfig = state.editing || !st || st.mode === 'needs_config'
413
+
414
+ return h(
415
+ 'div',
416
+ {
417
+ ref: panelRef,
418
+ className: phase === 'closing' ? 'oc-panel-exit' : 'oc-panel-enter',
419
+ style: {
420
+ position: 'fixed',
421
+ left: 12,
422
+ bottom: 52,
423
+ width: 320,
424
+ background: T.bg,
425
+ border: `1px solid ${T.border}`,
426
+ borderRadius: 16,
427
+ boxShadow: 'var(--dsw-shadow-lv3, 0 10px 32px rgba(0,0,0,0.4))',
428
+ padding: '14px 16px 12px',
429
+ zIndex: 60,
430
+ pointerEvents: phase === 'closing' ? 'none' : 'auto',
431
+ },
432
+ },
433
+ [
434
+ // 头部
435
+ h('div', { key: 'hd', style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, borderBottom: `1px solid ${T.border}`, paddingBottom: 8 } }, [
436
+ h('span', { style: { fontSize: 13, fontWeight: 600, color: T.label } }, showConfig ? '配置 OpenCode' : 'OpenCode GO 用量'),
437
+ h('div', { style: { display: 'flex', gap: 4, alignItems: 'center' } }, [
438
+ !showConfig
439
+ ? h(
440
+ 'button',
441
+ {
442
+ className: 'oc-btn',
443
+ style: {
444
+ width: 26,
445
+ height: 26,
446
+ padding: 0,
447
+ display: 'inline-flex',
448
+ alignItems: 'center',
449
+ justifyContent: 'center',
450
+ fontSize: 14,
451
+ border: 'none',
452
+ borderRadius: 6,
453
+ cursor: 'pointer',
454
+ color: T.secondary,
455
+ background: 'transparent',
456
+ },
457
+ onClick: async () => {
458
+ store.set({ refreshing: true })
459
+ await refreshStatus(true)
460
+ store.set({ refreshing: false })
461
+ },
462
+ title: '刷新用量',
463
+ },
464
+ state.refreshing ? h('span', { className: 'oc-spin' }, '↻') : '↻',
465
+ )
466
+ : null,
467
+ !showConfig
468
+ ? h(
469
+ 'button',
470
+ {
471
+ className: 'oc-btn',
472
+ style: {
473
+ width: 26,
474
+ height: 26,
475
+ padding: 0,
476
+ display: 'inline-flex',
477
+ alignItems: 'center',
478
+ justifyContent: 'center',
479
+ fontSize: 15,
480
+ border: 'none',
481
+ borderRadius: 6,
482
+ cursor: 'pointer',
483
+ color: T.secondary,
484
+ background: 'transparent',
485
+ },
486
+ onClick: () => {
487
+ store.set({ editing: true })
488
+ refreshConfig()
489
+ },
490
+ title: '更新配置',
491
+ },
492
+ '⚙',
493
+ )
494
+ : null,
495
+ h(
496
+ 'button',
497
+ {
498
+ className: 'oc-btn',
499
+ style: {
500
+ width: 26,
501
+ height: 26,
502
+ padding: 0,
503
+ display: 'inline-flex',
504
+ alignItems: 'center',
505
+ justifyContent: 'center',
506
+ fontSize: 13,
507
+ border: 'none',
508
+ borderRadius: 6,
509
+ cursor: 'pointer',
510
+ color: T.secondary,
511
+ background: 'transparent',
512
+ },
513
+ onClick: () => store.set({ open: false, editing: false }),
514
+ title: '关闭',
515
+ },
516
+ '✕',
517
+ ),
518
+ ]),
519
+ ]),
520
+ // 内容
521
+ showConfig
522
+ ? h(ConfigCard)
523
+ : h('div', null, [
524
+ st?.error ? h('div', { key: 'err', style: { fontSize: 11, color: T.err, marginBottom: 8 } }, st.error.message) : null,
525
+ ...(st?.windows ?? []).map((w) => h(QuotaRow, { key: w.id, window: w })),
526
+ h('div', { key: 'tip', style: { fontSize: 10, color: T.secondary, textAlign: 'right', marginTop: 6 } }, `更新于 ${new Date(st?.fetchedAt || Date.now()).toLocaleTimeString()}`),
527
+ ]),
528
+ ],
529
+ )
530
+ }
531
+
532
+ // ---------- 注册 ----------
533
+ function apply(ctx) {
534
+ ctx.effect(() => {
535
+ const el = document.createElement('style')
536
+ el.id = 'dsh-opencode-status-styles'
537
+ el.textContent = CSS
538
+ document.head.appendChild(el)
539
+ return () => el.remove()
540
+ })
541
+ ctx.effect(() =>
542
+ ctx.slots.inject('sidebar.footer.action', () =>
543
+ ctx.slots.register({ name: 'sidebar.footer.action', id: 'opencode-status', order: 0 }, (props) => h(FooterEntry, props)),
544
+ ),
545
+ )
546
+ ctx.effect(() =>
547
+ ctx.slots.inject('shell.overlay', () =>
548
+ ctx.slots.register({ name: 'shell.overlay', id: 'opencode-status-panel', order: 5 }, () => h(OverlayPanel)),
549
+ ),
550
+ )
551
+ }
552
+
553
+ exports.apply = apply
554
+ exports.inject = ['slots']
555
+ return module.exports
556
+ },
557
+ })
package/src/index.js ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * dsh-opencode-status — Host half.
3
+ *
4
+ * 本机 HTTP 路由(loopback,Cache-Control: no-store):
5
+ * GET /api/opencode-status 摘要与配额窗口数据
6
+ * GET /api/opencode-status/config 脱敏配置
7
+ * PUT /api/opencode-status/config 创建/更新配置
8
+ * POST /api/opencode-status/sync 强制同步最新配额
9
+ *
10
+ * 数据源:https://opencode.ai/zen/go/v1/usage
11
+ */
12
+ import z from '@deepseek-ai/schemastery'
13
+
14
+ export const name = 'opencode-status'
15
+ export const inject = ['settings', 'credentials', 'webServer']
16
+
17
+ const NS = /** @type {any} */ ('opencode-status')
18
+ const DEFAULT_KEY_REF = /** @type {any} */ ('OPENCODE_GO_API_KEY')
19
+ const DEFAULT_BASE_URL = 'https://opencode.ai/zen/go'
20
+ const DEFAULT_CACHE_TTL_MS = 30_000
21
+ const REQUEST_TIMEOUT_MS = 10_000
22
+
23
+ const envBaseUrl = normalizeBase(process.env.OPENCODE_BASE_URL)
24
+
25
+ const schema = z.object({
26
+ // 环境变量只作为未持久化配置时的默认值;非法值不覆盖官方端点。
27
+ baseUrl: z.string().default(isAbsoluteHttpUrl(envBaseUrl) ? envBaseUrl : DEFAULT_BASE_URL),
28
+ keyRef: z.string().default(DEFAULT_KEY_REF),
29
+ })
30
+
31
+ function normalizeBase(input) {
32
+ return String(input ?? '').trim().replace(/\/+$/, '')
33
+ }
34
+
35
+ function isAbsoluteHttpUrl(input) {
36
+ try {
37
+ const u = new URL(input)
38
+ return u.protocol === 'http:' || u.protocol === 'https:'
39
+ } catch {
40
+ return false
41
+ }
42
+ }
43
+
44
+ async function fetchUsageFromGateway(baseUrl, apiKey) {
45
+ const ctrl = new AbortController()
46
+ const timer = setTimeout(() => ctrl.abort(), REQUEST_TIMEOUT_MS)
47
+ try {
48
+ const res = await fetch(`${normalizeBase(baseUrl)}/v1/usage`, {
49
+ headers: { Authorization: `Bearer ${apiKey}` },
50
+ signal: ctrl.signal,
51
+ })
52
+ if (!res.ok) {
53
+ const text = await res.text().catch(() => '')
54
+ throw new Error(`网关返回 HTTP ${res.status}: ${text.slice(0, 150)}`)
55
+ }
56
+ return await res.json()
57
+ } finally {
58
+ clearTimeout(timer)
59
+ }
60
+ }
61
+
62
+ export function apply(ctx) {
63
+ const scope = ctx.settings.register(NS, schema)
64
+
65
+ /** @type {{ at: number, data: any } | null} */
66
+ let usageCache = null
67
+
68
+ function invalidateCache() {
69
+ usageCache = null
70
+ }
71
+
72
+ async function getApiKey() {
73
+ const cfg = scope.get()
74
+ const keyRef = cfg.keyRef || DEFAULT_KEY_REF
75
+ const resolved = await ctx.credentials.resolve(keyRef).catch(() => undefined)
76
+ return resolved?.value || null
77
+ }
78
+
79
+ async function publicConfig() {
80
+ const cfg = scope.get()
81
+ const keyRef = cfg.keyRef || DEFAULT_KEY_REF
82
+ const info = await ctx.credentials.describe(keyRef)
83
+ let hint = null
84
+ if (info.configured) {
85
+ const resolved = await ctx.credentials.resolve(keyRef).catch(() => undefined)
86
+ hint = resolved?.value ? `••••${resolved.value.slice(-4)}` : '••••'
87
+ }
88
+ return {
89
+ baseUrl: cfg.baseUrl || DEFAULT_BASE_URL,
90
+ apiKey: {
91
+ configured: info.configured,
92
+ source: info.source ?? null,
93
+ writable: info.writable,
94
+ hint,
95
+ },
96
+ }
97
+ }
98
+
99
+ async function buildStatus(force = false) {
100
+ const cfg = scope.get()
101
+ const baseUrl = cfg.baseUrl || DEFAULT_BASE_URL
102
+ const key = await getApiKey()
103
+
104
+ if (!key) {
105
+ return {
106
+ ok: false,
107
+ mode: 'needs_config',
108
+ fetchedAt: Date.now(),
109
+ config: { baseUrl, hasKey: false },
110
+ windows: [],
111
+ error: { code: 'NOT_CONFIGURED', message: '需要配置 OpenCode API Key' },
112
+ }
113
+ }
114
+
115
+ const now = Date.now()
116
+ if (!force && usageCache && now - usageCache.at < DEFAULT_CACHE_TTL_MS) {
117
+ return usageCache.data
118
+ }
119
+
120
+ try {
121
+ const data = await fetchUsageFromGateway(baseUrl, key)
122
+ const u = data?.usage ?? {}
123
+
124
+ const windows = [
125
+ {
126
+ id: 'rolling',
127
+ label: '滚动窗口 (5h)',
128
+ shortLabel: '5h',
129
+ usedPct: typeof u.rolling?.percent === 'number' ? u.rolling.percent : null,
130
+ remainingPct: typeof u.rolling?.percent === 'number' ? Math.max(0, 100 - u.rolling.percent) : null,
131
+ status: u.rolling?.status ?? 'ok',
132
+ resetAt: u.rolling?.resetsAt ? Date.parse(u.rolling.resetsAt) : null,
133
+ },
134
+ {
135
+ id: 'weekly',
136
+ label: '周窗口',
137
+ shortLabel: 'Weekly',
138
+ usedPct: typeof u.weekly?.percent === 'number' ? u.weekly.percent : null,
139
+ remainingPct: typeof u.weekly?.percent === 'number' ? Math.max(0, 100 - u.weekly.percent) : null,
140
+ status: u.weekly?.status ?? 'ok',
141
+ resetAt: u.weekly?.resetsAt ? Date.parse(u.weekly.resetsAt) : null,
142
+ },
143
+ {
144
+ id: 'monthly',
145
+ label: '月窗口',
146
+ shortLabel: 'Monthly',
147
+ usedPct: typeof u.monthly?.percent === 'number' ? u.monthly.percent : null,
148
+ remainingPct: typeof u.monthly?.percent === 'number' ? Math.max(0, 100 - u.monthly.percent) : null,
149
+ status: u.monthly?.status ?? 'ok',
150
+ resetAt: u.monthly?.resetsAt ? Date.parse(u.monthly.resetsAt) : null,
151
+ },
152
+ ]
153
+
154
+ const result = {
155
+ ok: true,
156
+ mode: 'ready',
157
+ fetchedAt: now,
158
+ config: { baseUrl, hasKey: true },
159
+ monthlyUsedPct: typeof u.monthly?.percent === 'number' ? u.monthly.percent : null,
160
+ windows,
161
+ error: null,
162
+ }
163
+ usageCache = { at: now, data: result }
164
+ return result
165
+ } catch (error) {
166
+ return {
167
+ ok: false,
168
+ mode: 'ready',
169
+ fetchedAt: now,
170
+ config: { baseUrl, hasKey: true },
171
+ windows: [],
172
+ error: { code: 'GATEWAY_ERROR', message: String(error?.message ?? error) },
173
+ }
174
+ }
175
+ }
176
+
177
+ function sendJson(res, status, body) {
178
+ res.writeHead(status, {
179
+ 'content-type': 'application/json; charset=utf-8',
180
+ 'cache-control': 'no-store',
181
+ })
182
+ res.end(JSON.stringify(body))
183
+ }
184
+
185
+ async function readBody(req) {
186
+ const chunks = []
187
+ let totalBytes = 0
188
+ for await (const chunk of req) {
189
+ totalBytes += chunk.length
190
+ if (totalBytes > 64 * 1024) throw Object.assign(new Error('请求体过大'), { statusCode: 413 })
191
+ chunks.push(chunk)
192
+ }
193
+ const text = Buffer.concat(chunks).toString('utf8')
194
+ if (!text.trim()) return {}
195
+ const data = JSON.parse(text)
196
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
197
+ throw Object.assign(new Error('请求体必须是 JSON 对象'), { statusCode: 400 })
198
+ }
199
+ return data
200
+ }
201
+
202
+ function guard(handler) {
203
+ return async (req, res) => {
204
+ try {
205
+ await handler(req, res)
206
+ } catch (error) {
207
+ sendJson(res, error?.statusCode ?? 500, {
208
+ error: { code: 'INTERNAL', message: String(error?.message ?? error) },
209
+ })
210
+ }
211
+ }
212
+ }
213
+
214
+ // 路由 1:获取状态
215
+ ctx.effect(() =>
216
+ ctx.webServer.register({
217
+ kind: 'exact',
218
+ path: '/api/opencode-status',
219
+ handler: guard(async (req, res) => {
220
+ if (req.method !== 'GET') return sendJson(res, 405, { error: { code: 'METHOD', message: 'GET only' } })
221
+ const force = new URL(req.url ?? '/', 'http://localhost').searchParams.has('force')
222
+ sendJson(res, 200, await buildStatus(force))
223
+ }),
224
+ }),
225
+ )
226
+
227
+ // 路由 2:配置
228
+ ctx.effect(() =>
229
+ ctx.webServer.register({
230
+ kind: 'exact',
231
+ path: '/api/opencode-status/config',
232
+ handler: guard(async (req, res) => {
233
+ if (req.method === 'GET') {
234
+ return sendJson(res, 200, await publicConfig())
235
+ }
236
+ if (req.method !== 'PUT') {
237
+ return sendJson(res, 405, { error: { code: 'METHOD', message: 'GET/PUT only' } })
238
+ }
239
+ const body = await readBody(req)
240
+ const baseUrl = normalizeBase(body.baseUrl) || DEFAULT_BASE_URL
241
+ if (!isAbsoluteHttpUrl(baseUrl)) {
242
+ return sendJson(res, 400, { error: { code: 'INVALID', message: 'Base URL 必须是有效的 http(s) 地址' } })
243
+ }
244
+
245
+ const newKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : ''
246
+ const clearKey = body.clearApiKey === true
247
+ const keyRef = scope.get().keyRef || DEFAULT_KEY_REF
248
+
249
+ if (clearKey && newKey) {
250
+ return sendJson(res, 400, { error: { code: 'INVALID', message: '不能同时设置新密钥并清除密钥' } })
251
+ }
252
+
253
+ try {
254
+ if (clearKey) await ctx.credentials.unset(keyRef)
255
+ else if (newKey) await ctx.credentials.set(keyRef, newKey)
256
+ } catch (error) {
257
+ return sendJson(res, 409, { error: { code: 'KEY_NOT_WRITABLE', message: `密钥写入失败: ${error?.message ?? error}` } })
258
+ }
259
+
260
+ await scope.update({ baseUrl })
261
+ invalidateCache()
262
+
263
+ sendJson(res, 200, {
264
+ saved: true,
265
+ config: await publicConfig(),
266
+ status: await buildStatus(true),
267
+ })
268
+ }),
269
+ }),
270
+ )
271
+
272
+ // 路由 3:显式同步。保留 GET ?force=1 兼容旧客户端,新客户端使用该端点。
273
+ ctx.effect(() =>
274
+ ctx.webServer.register({
275
+ kind: 'exact',
276
+ path: '/api/opencode-status/sync',
277
+ handler: guard(async (req, res) => {
278
+ if (req.method !== 'POST') return sendJson(res, 405, { error: { code: 'METHOD', message: 'POST only' } })
279
+ sendJson(res, 200, await buildStatus(true))
280
+ }),
281
+ }),
282
+ )
283
+ }