@lingda-ai/dsh-plugin-skyport 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # 空港 · Skyport
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > 套件的驾驶舱:一屏回答"今天花得对吗、预算还剩多少、改坏了能不能退回"。
4
+
5
+ `@lingda-ai/dsh-plugin-skyport` 自己**不采集任何数据**。它只读另外三个插件暴露出来的只读服务:
6
+
7
+ | 岗位 | 服务名 | 它提供什么 |
8
+ | --- | --- | --- |
9
+ | 黑匣子 · Recorder | `replay` | `listSessions()`:会话、金额、节省、步骤 |
10
+ | 航油 · Fuel | `quota` | `snapshot()`:周期预算、已用、预测、到线动作 |
11
+ | 机库 · Hangar | `vault` | `list()`:备份列表与最近一份 |
12
+
13
+ 任何一个没装,总览照样打开,对应卡片显示「未安装」。理由很实际:多数人会先装一件,而不是三件一起装;一个"必须全家桶才能启动"的面板,在第一次使用就会被卸载。
14
+
15
+ ## 为什么总览不自己算钱
16
+
17
+ 这是本插件唯一的设计红线:**金额只信航油,会话只信黑匣子,备份只信机库**。
18
+
19
+ 如果总览自己再算一遍,就一定会出现"总览说 12.47、航油说 12.46"这种差一分钱的情况。用户无法判断哪个是对的,然后两个数都不再被信。跨模块汇总最容易犯的错,是把"聚合"做成了"第二次计算"。
20
+
21
+ 总览真正新增的价值只有两类:
22
+
23
+ 1. **判空**:某块数据没有时,明确说"未安装 / 未设置 / 未知",而不是显示 `0` 或 `¥0.0000`。
24
+ 2. **跨模块判断**:单个插件看不到的组合,比如"预算已越线,但机库里没有任何可退回的备份"。
25
+
26
+ 第二条才是它存在的理由。为此它维护一份提醒列表,每条都必须能指向一个用户立刻能做的动作——不能指向动作的提醒,就是噪音,一律不出。
27
+
28
+ ## 面板上有什么
29
+
30
+ - **一句结论**:`今天 3 个会话花了 ¥0.0126,本周期额度用了 62%(剩 ¥7.53),机库有 2 份备份。`
31
+ - **四张卡**:今天花费(含缓存已省)、本周期预算(含剩余与调用次数)、今日会话数、机库备份数。
32
+ - **预算进度条**:80% 变黄、100% 变红,与航油面板同一套阈值。
33
+ - **提醒列表**:高 / 中 / 信息三档,每条带动作标签(查看航油、备份一次、查看机库…)。
34
+ - **三个岗位入口**:显示各是否在线;明细请切到对应 tab。
35
+
36
+ ## 给 Agent 的工具
37
+
38
+ `skyport_summary`:Agent 可以问"今天怎么样",拿到同一份数据(`detail: true` 时附逐模块明细)。
39
+
40
+ 同一份数据、同一套口径,是因为"面板说的和 Agent 说的不一致"比"两边都看不到"更糟。
41
+
42
+ ## HTTP
43
+
44
+ ```
45
+ GET /dsh-skyport/api?summary=1
46
+ ```
47
+
48
+ 只读;`POST` 一律 405。返回 `{ ok, generatedAt, headline, modules:{recorder,fuel,hangar}, tips[] }`。
49
+
50
+ ## 权限与兼容
51
+
52
+ - 需要 Node ≥ 22.6,零运行时依赖,不发任何外部网络请求。
53
+ - 不读任何文件、不写任何文件:所有数据来自同进程内其它插件的服务对象。
54
+ - 对被消费的插件不做版本假设:字段缺失时显示"—",不抛错。
55
+ - 三个服务都是可选依赖:没有它们时插件仍能加载、面板仍能打开。
56
+
57
+ ## 安装
58
+
59
+ ```bash
60
+ dsh plugin --profile web add @lingda-ai/dsh-plugin-skyport
61
+ ```
62
+
63
+ 想看到完整数据,再装:
64
+
65
+ ```bash
66
+ dsh plugin --profile web add @lingda-ai/dsh-plugin-replay @lingda-ai/dsh-plugin-quota
67
+ npx dsh-vault create # 机库需要 CLI,装 @lingda-ai/dsh-plugin-vault
68
+ ```
69
+
70
+ ## 测试
71
+
72
+ ```bash
73
+ npm test # 13 项:聚合口径、缺失降级、提醒规则、HTTP 只读、客户端契约
74
+ npm run check # 收录前自检
75
+ npm run verify # 真机:在 acp profile 里确认工具注册与面板契约
76
+ ```
77
+
78
+ 其中三组断言对应三次真实故障的经验:
79
+
80
+ - **服务抛错不得 500**:三个服务全抛异常时,面板仍要能开,且结论读得懂。
81
+ - **损坏的备份不能当"最近一份"**:`latest` 必须指向一个真能用的退回点。
82
+ - **未知金额不摊进合计**:只计 `unknown` 计数,不让估算值污染总额。
83
+
84
+ ## 许可
85
+
86
+ Apache-2.0 © LingDaAi
@@ -0,0 +1,7 @@
1
+ # @lingda-ai/dsh-plugin-skyport —— 空港总览
2
+ #
3
+ # 一个 insert 行即可挂载。它只读消费 replay / quota / vault 三个服务,
4
+ # 缺哪个就显示未安装,不影响宿主启动。
5
+ - insert:
6
+ - id: lingda-skyport
7
+ name: '@lingda-ai/dsh-plugin-skyport'
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
2
+ <path d="M2.5 14.5h19" />
3
+ <path d="M4.5 14.5v4.2c0 .4.3.8.8.8h13.4c.5 0 .8-.4.8-.8v-4.2" />
4
+ <path d="M12 11.6V4.2" />
5
+ <path d="M8.6 7.4 12 4l3.4 3.4" />
6
+ <path d="M7 17.6h10" />
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 空港总览:三件套的驾驶舱。
3
+ *
4
+ * 它自己不采集任何数据——只消费另外三个插件 `provide` 出来的只读服务:
5
+ * replay.listSessions() → 会话与花费
6
+ * quota.snapshot() → 周期预算
7
+ * vault.list() → 备份
8
+ *
9
+ * 任何一个没装,总览照样能开,只是对应的卡片显示"未安装"。
10
+ * 这比"要求三件套都装"更符合真实使用:大多数人会先装一件。
11
+ */
12
+ import { collectSummary } from './lib/collect.js'
13
+ import { createApi, handleRequest, API_PREFIX } from './lib/route.js'
14
+ import { createSkyportTool } from './lib/tool.js'
15
+
16
+ export const name = '@lingda-ai/dsh-plugin-skyport'
17
+ export const inject = []
18
+
19
+ export function apply(ctx, config = {}) {
20
+ const services = { replay: null, quota: null, vault: null }
21
+ const now = config.now ?? (() => Date.now())
22
+
23
+ const bind = (serviceName, key) => {
24
+ const take = (inner) => {
25
+ try {
26
+ const value = inner[serviceName] ?? (typeof inner.get === 'function' ? inner.get(serviceName) : null)
27
+ if (value) services[key] = value
28
+ } catch {
29
+ /* 服务存在但取不到:按未安装处理,不让总览整体失败 */
30
+ }
31
+ }
32
+ if (typeof ctx.inject === 'function') {
33
+ try {
34
+ ctx.inject([serviceName], take)
35
+ } catch {
36
+ /* 服务不存在:保持未安装状态 */
37
+ }
38
+ return
39
+ }
40
+ try {
41
+ take(ctx)
42
+ } catch {
43
+ /* 老宿主:降级为未安装 */
44
+ }
45
+ }
46
+
47
+ bind('replay', 'replay')
48
+ bind('quota', 'quota')
49
+ bind('vault', 'vault')
50
+
51
+ const collect = (at) => collectSummary({ ...services, now: at })
52
+ const api = createApi({ collect, now })
53
+ const route = {
54
+ kind: 'prefix',
55
+ path: API_PREFIX,
56
+ handler: (req, res) => handleRequest(api, req, res),
57
+ }
58
+
59
+ if (typeof ctx.inject === 'function') {
60
+ ctx.inject(['webServer'], (inner) => {
61
+ const webServer = inner.webServer ?? (typeof inner.get === 'function' ? inner.get('webServer') : null)
62
+ if (!webServer || typeof webServer.register !== 'function') return
63
+ if (typeof inner.effect === 'function') inner.effect(() => webServer.register(route))
64
+ else webServer.register(route)
65
+ })
66
+ }
67
+
68
+ const tool = createSkyportTool({ collect })
69
+ if (typeof ctx.inject === 'function') {
70
+ ctx.inject(['tools'], (inner) => {
71
+ const registry = inner.tools ?? (typeof inner.get === 'function' ? inner.get('tools') : null)
72
+ if (registry && typeof registry.register === 'function') registry.register(tool)
73
+ })
74
+ }
75
+
76
+ return {
77
+ summary: () => collect(now()),
78
+ diagnostics: () => ({ installed: Object.entries(services).filter(([, value]) => value).map(([key]) => key) }),
79
+ }
80
+ }
package/lib/client.js ADDED
@@ -0,0 +1,374 @@
1
+ /**
2
+ * @lingda-ai/dsh-plugin-skyport —— Client 半(右侧栏「空港」tab)
3
+ *
4
+ * 这一屏的职责只有一个:五秒内回答"今天这个 Agent 花得对吗、要不要动手"。
5
+ * 所以它只放四张数字卡 + 一条结论 + 若干条带动作的提醒,不放下钻细节——
6
+ * 细节在各自岗位的 tab 里,那里才有权限与上下文。
7
+ */
8
+
9
+ window.__ModuleLoader__.load({
10
+ id: '@lingda-ai/dsh-plugin-skyport',
11
+ factory(require) {
12
+ const React = require('react')
13
+ const h = React.createElement
14
+ const { useState, useEffect, useRef, useCallback } = React
15
+
16
+ const ID = '@lingda-ai/dsh-plugin-skyport'
17
+ const KIND = 'skyport.overview'
18
+ const API = '/dsh-skyport/api'
19
+
20
+ const C = {
21
+ t1: '#1f2733', t2: '#5a6472', t3: '#64707f', t4: '#8a93a0',
22
+ hair: '#eef1f5', card: '#fafbfd', green: '#2f7d64', amber: '#c98a12', red: '#b4453c', blue: '#2f6feb',
23
+ }
24
+
25
+ const DICT = {
26
+ zh: {
27
+ title: '空港',
28
+ guideDesc: '一张图看懂:今天花了多少、预算还剩多少、改坏了能不能退回',
29
+ refresh: '刷新',
30
+ loading: '正在汇总…',
31
+ errTitle: '汇总失败',
32
+ todayCost: '今天花费',
33
+ budget: '本周期预算',
34
+ sessions: '今日会话',
35
+ backups: '机库备份',
36
+ notSet: '未设置',
37
+ notInstalled: '未安装',
38
+ savedToday: '缓存已省 {v}',
39
+ noLimit: '设一个额度后,到线才会提醒或降级',
40
+ remaining: '剩 {v}',
41
+ calls: '{n} 次调用',
42
+ latestBackup: '最近 {id}',
43
+ noBackup: '还没备过:装插件前拍一张',
44
+ tips: '需要你动手的',
45
+ allGood: '没有需要立刻处理的事',
46
+ entries: '三个岗位',
47
+ entryRecorder: '黑匣子 · 每一步花了多少',
48
+ entryFuel: '航油 · 这个周期还能花多少',
49
+ entryHangar: '机库 · 改坏了退回到哪一份',
50
+ entryHint: '在右侧栏切换对应 tab 查看明细',
51
+ unknownNote: '{n} 个会话金额未知(模型不在价表里)',
52
+ },
53
+ en: {
54
+ title: 'Skyport',
55
+ guideDesc: 'One screen: today’s spend, budget left, and whether you can roll back',
56
+ refresh: 'Refresh',
57
+ loading: 'Aggregating…',
58
+ errTitle: 'Aggregation failed',
59
+ todayCost: 'Today',
60
+ budget: 'Budget',
61
+ sessions: 'Sessions today',
62
+ backups: 'Snapshots',
63
+ notSet: 'not set',
64
+ notInstalled: 'not installed',
65
+ savedToday: 'saved {v}',
66
+ noLimit: 'Set a budget to get warnings or downgrades',
67
+ remaining: '{v} left',
68
+ calls: '{n} calls',
69
+ latestBackup: 'latest {id}',
70
+ noBackup: 'No snapshot yet — take one before installing plugins',
71
+ tips: 'Needs your attention',
72
+ allGood: 'Nothing urgent right now',
73
+ entries: 'Three stations',
74
+ entryRecorder: 'Recorder · what each step cost',
75
+ entryFuel: 'Fuel · what is left this period',
76
+ entryHangar: 'Hangar · which snapshot to return to',
77
+ entryHint: 'Switch tabs in the right sidebar for detail',
78
+ unknownNote: '{n} sessions with unknown cost (model not in price table)',
79
+ },
80
+ }
81
+
82
+ let T = DICT.zh
83
+
84
+ function getService(ctx, name) {
85
+ try {
86
+ if (ctx && typeof ctx.get === 'function') return ctx.get(name) ?? null
87
+ return (ctx && ctx[name]) ?? null
88
+ } catch {
89
+ return null
90
+ }
91
+ }
92
+
93
+ function detectLocale(ctx) {
94
+ const locale = getService(ctx, 'locale')
95
+ let id = ''
96
+ try {
97
+ const snapshot = typeof locale?.getLocale === 'function' ? locale.getLocale() : null
98
+ if (typeof snapshot === 'string') id = snapshot
99
+ else if (snapshot) id = String(snapshot.id || snapshot.locale || snapshot.language || '')
100
+ } catch {
101
+ id = ''
102
+ }
103
+ if (id.length === 0) {
104
+ try {
105
+ id = window.navigator.language || ''
106
+ } catch {
107
+ id = ''
108
+ }
109
+ }
110
+ return /^en/i.test(id) ? 'en' : 'zh'
111
+ }
112
+
113
+ function money(amount, currency) {
114
+ if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
115
+ const symbol = !currency || currency === 'CNY' || currency === 'RMB' ? '¥' : currency === 'USD' ? '$' : ''
116
+ if (Math.abs(amount) >= 100) return symbol + amount.toFixed(0)
117
+ if (Math.abs(amount) >= 1) return symbol + amount.toFixed(2)
118
+ return symbol + amount.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')
119
+ }
120
+
121
+ function pct(ratio) {
122
+ if (typeof ratio !== 'number' || !Number.isFinite(ratio)) return '—'
123
+ return (ratio * 100).toFixed(ratio < 0.1 ? 1 : 0) + '%'
124
+ }
125
+
126
+ function fillOf(ratio) {
127
+ if (typeof ratio !== 'number' || !Number.isFinite(ratio)) return C.t4
128
+ if (ratio >= 1) return C.red
129
+ if (ratio >= 0.8) return C.amber
130
+ return C.blue
131
+ }
132
+
133
+ async function getJson(signal) {
134
+ const response = await fetch(API + '?summary=1', { signal, headers: { accept: 'application/json' } })
135
+ if (!response.ok) throw new Error('HTTP ' + response.status)
136
+ const data = await response.json()
137
+ if (!data || data.ok !== true) throw new Error((data && data.error) || '汇总失败')
138
+ return data
139
+ }
140
+
141
+ function Card(props) {
142
+ return h('div', {
143
+ style: {
144
+ flex: '1 1 0', minWidth: 0, background: '#fff', border: '1px solid #e9edf3',
145
+ borderRadius: 10, padding: '9px 10px',
146
+ },
147
+ },
148
+ h('div', { style: { fontSize: 10.5, color: C.t3, marginBottom: 4, whiteSpace: 'nowrap' } }, props.label),
149
+ h('div', {
150
+ style: {
151
+ fontSize: 17, fontWeight: 600, color: props.tone || C.t1, lineHeight: 1.2,
152
+ fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
153
+ },
154
+ }, props.value),
155
+ props.hint
156
+ ? h('div', { style: { marginTop: 3, fontSize: 10, color: C.t4, lineHeight: 1.4 } }, props.hint)
157
+ : null)
158
+ }
159
+
160
+ function Panel() {
161
+ const [data, setData] = useState(null)
162
+ const [error, setError] = useState(null)
163
+ const [loading, setLoading] = useState(true)
164
+ const [tick, setTick] = useState(0)
165
+ const alive = useRef(true)
166
+
167
+ useEffect(() => () => { alive.current = false }, [])
168
+
169
+ useEffect(() => {
170
+ const controller = new AbortController()
171
+ setLoading(true)
172
+ getJson(controller.signal)
173
+ .then((payload) => {
174
+ if (!alive.current) return
175
+ setData(payload)
176
+ setError(null)
177
+ setLoading(false)
178
+ })
179
+ .catch((cause) => {
180
+ if (cause && cause.name === 'AbortError') return
181
+ if (!alive.current) return
182
+ setError(cause.message || '读取失败')
183
+ setLoading(false)
184
+ })
185
+ return () => controller.abort()
186
+ }, [tick])
187
+
188
+ const refresh = useCallback(() => setTick((n) => n + 1), [])
189
+
190
+ const head = h('div', {
191
+ style: { display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px 8px', borderBottom: '1px solid ' + C.hair },
192
+ },
193
+ h('span', { style: { fontSize: 13, fontWeight: 600, color: C.t1 } }, T.title),
194
+ h('button', {
195
+ type: 'button', onClick: refresh,
196
+ style: {
197
+ marginLeft: 'auto', border: '1px solid #d8dee7', background: '#fff',
198
+ borderRadius: 7, padding: '3px 9px', fontSize: 11.5, color: C.t2, cursor: 'pointer',
199
+ },
200
+ }, T.refresh))
201
+
202
+ if (loading && !data) {
203
+ return h('div', null, head, h('div', { style: { padding: '16px 14px', fontSize: 11.5, color: C.t3 } }, T.loading))
204
+ }
205
+ if (error) {
206
+ return h('div', null, head,
207
+ h('div', { style: { padding: '16px 14px' } },
208
+ h('div', { style: { fontSize: 13, fontWeight: 600, color: C.t1, marginBottom: 6 } }, T.errTitle),
209
+ h('div', { style: { fontSize: 11.5, color: C.t2, lineHeight: 1.7 } }, error)))
210
+ }
211
+
212
+ const { modules, tips, headline } = data
213
+ const recorder = modules.recorder
214
+ const fuel = modules.fuel
215
+ const hangar = modules.hangar
216
+
217
+ const fuelValue = fuel.ok
218
+ ? fuel.limit === null ? T.notSet : pct(fuel.ratio)
219
+ : T.notInstalled
220
+ const fuelHint = fuel.ok
221
+ ? fuel.limit === null
222
+ ? T.noLimit
223
+ : T.remaining.replace('{v}', money(fuel.remaining, fuel.currency)) + ' · ' + T.calls.replace('{n}', String(fuel.calls ?? 0))
224
+ : null
225
+
226
+ // 进度条:轨道要看得见,80% 处有一条刻度——那是"开始提醒"的线,比数字更好读
227
+ const bar = fuel.ok && typeof fuel.ratio === 'number'
228
+ ? h('div', {
229
+ style: {
230
+ position: 'relative', marginTop: 9, height: 6, background: '#e9edf4',
231
+ borderRadius: 999, overflow: 'hidden',
232
+ },
233
+ },
234
+ h('div', {
235
+ style: {
236
+ width: Math.min(100, Math.max(1.5, fuel.ratio * 100)) + '%', height: '100%',
237
+ background: fillOf(fuel.ratio), borderRadius: 999,
238
+ },
239
+ }),
240
+ h('div', {
241
+ style: {
242
+ position: 'absolute', left: '80%', top: 0, bottom: 0, width: 1,
243
+ background: '#c3cbd8',
244
+ },
245
+ }))
246
+ : null
247
+
248
+ return h('div', null,
249
+ head,
250
+
251
+ h('div', { style: { padding: '12px 14px 0' } },
252
+ h('div', { style: { fontSize: 12.5, lineHeight: 1.6, color: C.t1 } }, headline),
253
+ bar),
254
+
255
+ h('div', { style: { display: 'flex', gap: 8, padding: '10px 14px 0' } },
256
+ h(Card, {
257
+ label: T.todayCost,
258
+ value: recorder.ok ? money(recorder.todayAmount, recorder.todayCurrency) : '—',
259
+ hint: recorder.ok && recorder.todaySaved > 0 ? T.savedToday.replace('{v}', money(recorder.todaySaved, recorder.todayCurrency)) : null,
260
+ }),
261
+ h(Card, {
262
+ label: T.budget,
263
+ value: fuelValue,
264
+ tone: fuel.ok && typeof fuel.ratio === 'number' && fuel.ratio >= 0.8 ? fillOf(fuel.ratio) : null,
265
+ hint: fuelHint,
266
+ })),
267
+
268
+ h('div', { style: { display: 'flex', gap: 8, padding: '8px 14px 0' } },
269
+ h(Card, {
270
+ label: T.sessions,
271
+ value: recorder.ok ? String(recorder.todaySessions) : T.notInstalled,
272
+ hint: recorder.ok && recorder.unknownSessions > 0
273
+ ? T.unknownNote.replace('{n}', String(recorder.unknownSessions))
274
+ : null,
275
+ }),
276
+ h(Card, {
277
+ label: T.backups,
278
+ value: hangar.ok ? String(hangar.count) : T.notInstalled,
279
+ hint: hangar.ok
280
+ ? (hangar.latest ? T.latestBackup.replace('{id}', hangar.latest.id) : T.noBackup)
281
+ : null,
282
+ })),
283
+
284
+ h('div', { style: { padding: '12px 14px 0' } },
285
+ h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.tips),
286
+ tips.length === 0
287
+ ? h('div', { style: { padding: '6px 0', fontSize: 11, color: C.t3 } }, T.allGood)
288
+ : tips.map((tip, index) => h('div', {
289
+ key: index,
290
+ style: { display: 'flex', gap: 7, padding: '4px 0', alignItems: 'baseline' },
291
+ },
292
+ h('span', {
293
+ style: {
294
+ width: 5, height: 5, flex: 'none', borderRadius: 999, marginTop: 5,
295
+ background: tip.level === 'high' ? C.red : tip.level === 'mid' ? C.amber : C.t4,
296
+ },
297
+ }),
298
+ h('span', { style: { flex: 1, minWidth: 0, fontSize: 11, lineHeight: 1.6, color: C.t2 } }, tip.text),
299
+ h('span', { style: { fontSize: 10, color: C.blue, whiteSpace: 'nowrap' } }, tip.action)))),
300
+
301
+ h('div', { style: { padding: '12px 14px 14px' } },
302
+ h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.entries),
303
+ [
304
+ [T.entryRecorder, recorder.ok],
305
+ [T.entryFuel, fuel.ok],
306
+ [T.entryHangar, hangar.ok],
307
+ ].map(([label, installed], index) => h('div', {
308
+ key: index,
309
+ style: { display: 'flex', gap: 8, padding: '5px 0', alignItems: 'baseline', opacity: installed ? 1 : 0.55 },
310
+ },
311
+ h('span', { style: { flex: 1, minWidth: 0, fontSize: 11.5, color: C.t2 } }, label),
312
+ h('span', { style: { fontSize: 10, color: installed ? C.green : C.t4 } }, installed ? '●' : T.notInstalled))),
313
+ h('div', { style: { marginTop: 6, fontSize: 10.5, color: C.t4 } }, T.entryHint)))
314
+ }
315
+
316
+ function makeTitle() {
317
+ return function Title() {
318
+ return h('span', { style: { fontSize: 12, fontWeight: 600, color: C.t1 } }, T.title)
319
+ }
320
+ }
321
+
322
+ function apply(ctx) {
323
+ if (!ctx) return
324
+ T = DICT[detectLocale(ctx)] || DICT.zh
325
+
326
+ const tabs = getService(ctx, 'sidebarRightTabs')
327
+ const slots = getService(ctx, 'slots')
328
+ let disposers = []
329
+
330
+ if (tabs && typeof tabs.register === 'function') {
331
+ try {
332
+ disposers.push(tabs.register({
333
+ id: ID,
334
+ kind: KIND,
335
+ title: () => T.title,
336
+ priority: 'extension',
337
+ keepMounted: false,
338
+ guide: [{ id: 'skyport.open', order: 10, title: () => T.title, description: () => T.guideDesc }],
339
+ }))
340
+ } catch (error) {
341
+ console.warn('[skyport] 右栏 tab 登记失败:', error)
342
+ }
343
+ }
344
+
345
+ if (slots && typeof slots.inject === 'function' && typeof slots.register === 'function') {
346
+ try {
347
+ disposers.push(slots.inject('sidebar.right.pane.tab', () =>
348
+ slots.register({ name: 'sidebar.right.pane.tab', key: ID }, Panel)))
349
+ disposers.push(slots.inject('sidebar.right.pane.tab.title', () =>
350
+ slots.register({ name: 'sidebar.right.pane.tab.title', key: ID }, makeTitle())))
351
+ } catch (error) {
352
+ console.warn('[skyport] 面板挂载失败:', error)
353
+ }
354
+ }
355
+
356
+ const cleanup = () => {
357
+ for (const dispose of disposers) {
358
+ try {
359
+ dispose && dispose()
360
+ } catch {}
361
+ }
362
+ disposers = []
363
+ }
364
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
365
+ else if (typeof ctx.on === 'function') ctx.on('dispose', cleanup)
366
+ }
367
+
368
+ return {
369
+ inject: ['sidebarRightTabs'],
370
+ apply,
371
+ __test: { money, pct, fillOf, detectLocale, DICT, apply },
372
+ }
373
+ },
374
+ })
package/lib/collect.js ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * 空港总览的数据源:把三个岗位各自看到的一小块事实,拼成一张"今天怎么样"。
3
+ *
4
+ * 一条纪律:**这里不算钱、不查库存、不读文件**。
5
+ * 金额出自航油、会话出自黑匣子、备份出自机库——总览只做四件事:
6
+ * 取值、判空、跨模块对账(比如"花费超了但机库没有近期备份")、给一句人话结论。
7
+ *
8
+ * 这样做的理由:三个插件各自的口径已经过真机校验;总览再造一套口径,
9
+ * 就一定会出现"面板说 12 块、账本说 11 块"这种没人能解释的差。
10
+ */
11
+
12
+ const isNum = (value) => typeof value === 'number' && Number.isFinite(value)
13
+
14
+ function money(amount, currency = 'CNY') {
15
+ if (!isNum(amount)) return '—'
16
+ const symbol = currency === 'CNY' || currency === 'RMB' ? '¥' : currency === 'USD' ? '$' : ''
17
+ if (amount >= 100) return `${symbol}${amount.toFixed(0)}`
18
+ if (amount >= 1) return `${symbol}${amount.toFixed(2)}`
19
+ return `${symbol}${amount.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`
20
+ }
21
+
22
+ function pct(ratio) {
23
+ if (!isNum(ratio)) return '—'
24
+ return `${(ratio * 100).toFixed(ratio < 0.1 ? 1 : 0)}%`
25
+ }
26
+
27
+ /** 黑匣子:会话列表里最近几条 + 今日合计(按会话起点落在今天判断)。 */
28
+ function collectRecorder(replay, now) {
29
+ // 黑匣子 provide 出来的键叫 `list`(= store.listSessions);两个人名并存时都认,
30
+ // 但不要指望对面一定叫 listSessions —— 0.1.0 就是这样把"已安装"读成了"未安装"。
31
+ const list = replay && (typeof replay.listSessions === 'function' ? replay.listSessions : typeof replay.list === 'function' ? replay.list : null)
32
+ if (typeof list !== 'function') {
33
+ return { ok: false, reason: 'not-installed' }
34
+ }
35
+ let sessions = []
36
+ try {
37
+ sessions = list({ limit: 20 }) ?? []
38
+ } catch (error) {
39
+ return { ok: false, reason: 'error', message: String(error?.message ?? error) }
40
+ }
41
+ const dayStart = new Date(now)
42
+ dayStart.setHours(0, 0, 0, 0)
43
+ const dayStartMs = dayStart.getTime()
44
+
45
+ // 未收场的会话没有 sum 行,listSessions 给的 cost 是 null。
46
+ // 这时不自己算钱,而是问黑匣子自己的 summarize()——同一份口径,只是另一种读法。
47
+ const costOf = (session) => {
48
+ if (isNum(session.cost?.amount)) return { amount: session.cost.amount, currency: session.cost.currency ?? null }
49
+ if (session.closed === false && typeof replay.summarize === 'function') {
50
+ try {
51
+ const summary = replay.summarize(session.sid)
52
+ const amount = summary?.totals?.cost?.amount
53
+ if (isNum(amount)) return { amount, currency: summary.totals.cost.currency ?? null }
54
+ } catch {
55
+ /* 读不出来就保持未知 */
56
+ }
57
+ }
58
+ return null
59
+ }
60
+
61
+ let todayAmount = 0
62
+ let todaySaved = 0
63
+ let todayCurrency = 'CNY'
64
+ let todaySessions = 0
65
+ let todayKnown = 0
66
+ let unknownSessions = 0
67
+ for (const session of sessions) {
68
+ const at = session.startedAt ?? session.lastAt ?? 0
69
+ if (!isNum(at) || at < dayStartMs) continue
70
+ todaySessions += 1
71
+ const cost = costOf(session)
72
+ if (cost) {
73
+ todayAmount += cost.amount
74
+ todayKnown += 1
75
+ if (typeof cost.currency === 'string') todayCurrency = cost.currency
76
+ } else {
77
+ unknownSessions += 1
78
+ }
79
+ if (isNum(session.saved?.amount)) todaySaved += session.saved.amount
80
+ }
81
+
82
+ const latest = sessions[0] ?? null
83
+ return {
84
+ ok: true,
85
+ sessions: sessions.length,
86
+ todaySessions,
87
+ todayAmount,
88
+ todayKnown,
89
+ todaySaved,
90
+ todayCurrency,
91
+ unknownSessions,
92
+ latest: latest
93
+ ? {
94
+ sid: latest.sid,
95
+ title: latest.title ?? null,
96
+ cost: latest.cost?.amount ?? null,
97
+ saved: latest.saved?.amount ?? null,
98
+ steps: latest.steps ?? null,
99
+ closed: latest.closed === true,
100
+ lastAt: latest.lastAt ?? null,
101
+ }
102
+ : null,
103
+ totalAmount: sessions.reduce((sum, session) => sum + (isNum(session.cost?.amount) ? session.cost.amount : 0), 0),
104
+ }
105
+ }
106
+
107
+ /** 航油:周期预算与到线动作。 */
108
+ function collectFuel(quota) {
109
+ if (!quota || typeof quota.snapshot !== 'function') {
110
+ return { ok: false, reason: 'not-installed' }
111
+ }
112
+ try {
113
+ const state = quota.snapshot()
114
+ const policy = typeof quota.policy === 'function' ? quota.policy() : null
115
+ const diagnostics = typeof quota.diagnostics === 'function' ? quota.diagnostics() : null
116
+ return {
117
+ ok: true,
118
+ period: state.period,
119
+ amount: state.total?.amount ?? null,
120
+ calls: state.total?.calls ?? null,
121
+ saved: state.saved?.amount ?? null,
122
+ limit: state.limit ?? null,
123
+ ratio: state.ratio ?? null,
124
+ remaining: state.remaining ?? null,
125
+ forecast: state.forecast ?? null,
126
+ unknown: state.total?.unknown ?? 0,
127
+ currency: state.currency ?? 'CNY',
128
+ action: policy?.action ?? null,
129
+ warnings: Array.isArray(diagnostics?.warnings) ? diagnostics.warnings : [],
130
+ downgrades: diagnostics?.downgrades ?? 0,
131
+ }
132
+ } catch (error) {
133
+ return { ok: false, reason: 'error', message: String(error?.message ?? error) }
134
+ }
135
+ }
136
+
137
+ /** 机库:备份数量与最近一份。 */
138
+ function collectHangar(vault) {
139
+ if (!vault || typeof vault.list !== 'function') {
140
+ return { ok: false, reason: 'not-installed' }
141
+ }
142
+ try {
143
+ const backups = vault.list() ?? []
144
+ // 损坏的那份不能当"最近一份":面板要指向一个真能用的退回点
145
+ const latest = backups.find((item) => !item.broken) ?? null
146
+ const home = vault.diagnostics?.() ?? null
147
+ return {
148
+ ok: true,
149
+ count: backups.length,
150
+ latest: latest && !latest.broken ? { id: latest.id, at: latest.createdAt, files: latest.files ?? 0, note: latest.note ?? null } : null,
151
+ broken: backups.filter((item) => item.broken).length,
152
+ vaultDir: home?.vaultDir ?? null,
153
+ }
154
+ } catch (error) {
155
+ return { ok: false, reason: 'error', message: String(error?.message ?? error) }
156
+ }
157
+ }
158
+
159
+ /**
160
+ * 跨模块判断:哪些是"事实",哪些是"提醒"。
161
+ * 每条提醒都要能指向一个用户可以立刻做的动作,否则就是噪音。
162
+ */
163
+ function advise({ recorder, fuel, hangar }) {
164
+ const tips = []
165
+
166
+ if (fuel.ok && isNum(fuel.ratio)) {
167
+ if (fuel.ratio >= 1) {
168
+ tips.push({
169
+ level: 'high',
170
+ text: `本周期已用 ${pct(fuel.ratio)},${fuel.action?.atLimit === 'downgrade' ? '请求已按策略降级模型' : '策略未开启降级,可能继续超额'}`,
171
+ action: '查看航油',
172
+ })
173
+ } else if (fuel.ratio >= 0.8) {
174
+ tips.push({ level: 'mid', text: `本周期已用 ${pct(fuel.ratio)},接近阈值`, action: '查看航油' })
175
+ }
176
+ }
177
+ if (fuel.ok && fuel.limit === null) {
178
+ tips.push({ level: 'info', text: '还没设预算:现在不拦人,也不会有提醒', action: '设置预算' })
179
+ }
180
+ if (fuel.ok && fuel.warnings.length > 0) {
181
+ tips.push({ level: 'mid', text: `航油策略有 ${fuel.warnings.length} 条告警:${fuel.warnings[0]}`, action: '查看航油' })
182
+ }
183
+ if (hangar.ok && hangar.count === 0) {
184
+ tips.push({ level: 'mid', text: '机库还是空的:装插件前没有可退回的状态', action: '备份一次' })
185
+ }
186
+ if (hangar.ok && hangar.broken > 0) {
187
+ tips.push({ level: 'high', text: `有 ${hangar.broken} 份备份校验不通过`, action: '查看机库' })
188
+ }
189
+ if (recorder.ok && recorder.unknownSessions > 0) {
190
+ tips.push({ level: 'info', text: `今天有 ${recorder.unknownSessions} 个会话的金额无法计算(模型不在价表里)`, action: '查看黑匣子' })
191
+ }
192
+ if (!recorder.ok || !fuel.ok || !hangar.ok) {
193
+ const missing = [
194
+ !recorder.ok ? '黑匣子' : null,
195
+ !fuel.ok ? '航油' : null,
196
+ !hangar.ok ? '机库' : null,
197
+ ].filter(Boolean)
198
+ tips.push({ level: 'info', text: `未安装:${missing.join(' / ')}(其它模块照常工作)`, action: '查看安装' })
199
+ }
200
+
201
+ return tips
202
+ }
203
+
204
+ function headlineOf({ recorder, fuel, hangar }) {
205
+ if (!recorder.ok && !fuel.ok && !hangar.ok) return '三件套都没装:现在只能看到一个空港的壳'
206
+
207
+ const parts = []
208
+ if (recorder.ok) {
209
+ if (recorder.todaySessions === 0) parts.push('今天还没有会话记录')
210
+ else if (recorder.todayKnown === 0) parts.push(`今天 ${recorder.todaySessions} 个会话,金额暂时未知`)
211
+ else parts.push(`今天 ${recorder.todaySessions} 个会话花了 ${money(recorder.todayAmount, recorder.todayCurrency)}`)
212
+ }
213
+ if (fuel.ok && fuel.limit !== null) {
214
+ parts.push(`本周期额度用了 ${pct(fuel.ratio)}(剩 ${money(fuel.remaining, fuel.currency)})`)
215
+ } else if (fuel.ok) {
216
+ parts.push('预算未设置')
217
+ }
218
+ if (hangar.ok) {
219
+ parts.push(hangar.count > 0 ? `机库有 ${hangar.count} 份备份` : '机库为空')
220
+ }
221
+ return parts.join(',') + '。'
222
+ }
223
+
224
+ /**
225
+ * @param {{replay?: object, quota?: object, vault?: object, now?: number}} sources
226
+ */
227
+ export function collectSummary(sources = {}) {
228
+ const now = sources.now ?? Date.now()
229
+ const recorder = collectRecorder(sources.replay, now)
230
+ const fuel = collectFuel(sources.quota)
231
+ const hangar = collectHangar(sources.vault)
232
+ const modules = { recorder, fuel, hangar }
233
+ return {
234
+ generatedAt: now,
235
+ modules,
236
+ tips: advise(modules),
237
+ headline: headlineOf(modules),
238
+ }
239
+ }
240
+
241
+ export const __internal = { money, pct, collectRecorder, collectFuel, collectHangar, advise, headlineOf }
package/lib/route.js ADDED
@@ -0,0 +1,43 @@
1
+ export const API_PREFIX = '/dsh-skyport/api'
2
+
3
+ export function createApi({ collect, now = () => Date.now() }) {
4
+ return {
5
+ summary() {
6
+ const summary = collect(now())
7
+ return { ok: true, ...summary }
8
+ },
9
+ }
10
+ }
11
+
12
+ export function handleRequest(api, req, res) {
13
+ const send = (body, status = 200) => {
14
+ const text = JSON.stringify(body)
15
+ res.writeHead(status, {
16
+ 'content-type': 'application/json; charset=utf-8',
17
+ 'cache-control': 'no-store',
18
+ 'content-length': Buffer.byteLength(text),
19
+ })
20
+ res.end(text)
21
+ }
22
+
23
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
24
+ send({ ok: false, error: '空港总览只读' }, 405)
25
+ return
26
+ }
27
+ let url
28
+ try {
29
+ url = new URL(req.url ?? '/', 'http://localhost')
30
+ } catch {
31
+ send({ ok: false, error: '请求地址不合法' }, 400)
32
+ return
33
+ }
34
+ if (url.searchParams.has('summary') || url.search === '') {
35
+ try {
36
+ send(api.summary())
37
+ } catch (error) {
38
+ send({ ok: false, error: error instanceof Error ? error.message : String(error) }, 500)
39
+ }
40
+ return
41
+ }
42
+ send({ ok: false, error: '未知查询:用 ?summary=1' })
43
+ }
package/lib/tool.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * skyport_summary:给 Agent 一张"今天怎么样"。
3
+ * 与面板同一份数据,避免"面板说 A、Agent 说 B"。
4
+ */
5
+ export function createSkyportTool({ collect }) {
6
+ return {
7
+ name: 'skyport_summary',
8
+ description:
9
+ '查看空港总览:今天会话花了多少、本周期预算用了多少、机库有几份备份。'
10
+ + '数据来自黑匣子/航油/机库三个插件的只读服务,未安装的模块会明确标注。',
11
+ parameters: {
12
+ detail: { type: 'boolean', description: '是否带上逐模块明细(默认只给结论与提醒)' },
13
+ },
14
+ output: {
15
+ schema: { type: 'string' },
16
+ render(_args, value) {
17
+ return [{ type: 'text', text: String(value) }]
18
+ },
19
+ },
20
+ async execute(args) {
21
+ const summary = collect(Date.now())
22
+ const lines = [summary.headline]
23
+ if (summary.tips.length > 0) {
24
+ lines.push('')
25
+ for (const tip of summary.tips) lines.push(`· ${tip.text}(${tip.action})`)
26
+ }
27
+ if (args?.detail === true) {
28
+ const { recorder, fuel, hangar } = summary.modules
29
+ lines.push('')
30
+ lines.push(`黑匣子:${recorder.ok ? `${recorder.sessions} 个会话,今天 ${recorder.todaySessions} 个` : '未安装'}`)
31
+ lines.push(`航油:${fuel.ok ? (fuel.limit === null ? '预算未设置' : `已用 ${fuel.amount} / ${fuel.limit}`) : '未安装'}`)
32
+ lines.push(`机库:${hangar.ok ? `${hangar.count} 份备份` : '未安装'}`)
33
+ }
34
+ return lines.join('\n')
35
+ },
36
+ }
37
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Skyport",
4
+ "description": "Overview: today's spend, budget left this period, and whether you can roll back. A read-only roll-up of Recorder, Fuel and Hangar."
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,80 @@
1
1
  {
2
2
  "name": "@lingda-ai/dsh-plugin-skyport",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "空港总览:一张面板看懂今天花了多少、本周期预算还剩多少、机库能不能退回。消费黑匣子/航油/机库的只读服务,缺哪个就显示未安装,不假装有数据。",
5
+ "keywords": [
6
+ "dsh",
7
+ "dsh-plugin",
8
+ "deepseek-harness",
9
+ "dashboard",
10
+ "observability",
11
+ "cost",
12
+ "backup",
13
+ "overview"
14
+ ],
15
+ "license": "Apache-2.0",
16
+ "author": "LingDaAi",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/lingda-ai/dsh-plugin-skyport.git"
20
+ },
21
+ "homepage": "https://gitee.com/linzhengtong/dsh-plugin-skyport#readme",
22
+ "bugs": {
23
+ "url": "https://gitee.com/linzhengtong/dsh-plugin-skyport/issues"
24
+ },
25
+ "type": "module",
26
+ "main": "index.js",
27
+ "exports": {
28
+ ".": "./index.js",
29
+ "./client": "./lib/client.js",
30
+ "./collect": "./lib/collect.js",
31
+ "./locale/*.json": "./locale/*.json",
32
+ "./icon": "./icon.svg",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "index.js",
37
+ "lib",
38
+ "cordis.patch.yml",
39
+ "locale/*.json",
40
+ "icon.svg",
41
+ "README.md",
42
+ "docs/*.md"
43
+ ],
44
+ "engines": {
45
+ "node": ">=22.6"
46
+ },
47
+ "dsh": {
48
+ "bundle": {
49
+ "patch": "./cordis.patch.yml"
50
+ },
51
+ "client": {
52
+ "platform": "web",
53
+ "inject": [
54
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
55
+ ]
56
+ },
57
+ "catalog": {
58
+ "category": "other",
59
+ "summary": {
60
+ "en": "Skyport is the dashboard of the suite: today's spend, budget left this period, and whether your config can be rolled back — in one panel. It reads the read-only services of Recorder, Fuel and Hangar; anything not installed shows as such instead of faking numbers.",
61
+ "zh": "空港总览:今天花了多少、本周期预算还剩多少、配置能不能退回,一屏看完。只读消费黑匣子/航油/机库的服务,没装的模块明确显示「未安装」,不编数。"
62
+ },
63
+ "capabilities": [
64
+ "dashboard",
65
+ "observability",
66
+ "cost-summary",
67
+ "local-endpoint",
68
+ "dsh-client-ui-sidebar-right"
69
+ ]
70
+ }
71
+ },
72
+ "publishConfig": {
73
+ "access": "public"
74
+ },
75
+ "scripts": {
76
+ "test": "node --test test/*.test.mjs",
77
+ "check": "node scripts/check-listing.mjs",
78
+ "verify": "node scripts/verify-real-host.mjs"
79
+ }
80
+ }