dsh-sub2api 0.0.0-stage → 0.1.4

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/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # dsh-sub2api
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
+ 把 [sub2api](https://github.com/Wei-Shaw/sub2api) 中转站接进 DeepSeek Harness(DSH)的插件。
4
+
5
+ 用户装完插件后,在 **设置 → Sub2API** 里填一次邮箱和密码就能用:插件自动判断该登录还是注册,注册后自动创建名为 `dsh` 的 API 密钥、写入本机凭据库,并把上游模型同步进模型选择器。余额、订阅进度、兑换码和充值入口都在同一个面板里。
6
+
7
+ ## 它解决什么
8
+
9
+ 手动把中转站接进 DSH 需要四步:拿账号 → 去后台建 Key → 把 Key 填进设置 → 记住模型名。任何一步出错,用户就卡住了。
10
+
11
+ 这个插件把这四步压成一次输入:
12
+
13
+ | 手动接入 | 本插件 |
14
+ |---|---|
15
+ | 注册账号(可能要跳浏览器) | 面板里填邮箱密码 |
16
+ | 去后台创建 API Key 并复制 | 自动创建名为 `dsh` 的密钥 |
17
+ | 把 Key 粘贴到设置页 | 自动写入凭据库 |
18
+ | 手动填 baseUrl 和模型列表 | 自动同步 `/v1/models` |
19
+
20
+ ## 功能
21
+
22
+ - **单表单登录/注册**:先试登录,只有"凭据错误"才自动注册;密码错不会被误报成"账号不存在",也不会重复建号。
23
+ - **自动开通**:建 Key → 写凭据 → 同步模型,五步各自报告结果,某一步失败不会拖垮整体。
24
+ - **模型自动同步**:目录来自上游 `/v1/models`,10 分钟 TTL、磁盘缓存、可手动刷新。
25
+ - **流式对话**:协议层复用 `@dsh-ai-providers/openai-compatible`,工具调用、推理增量、图片输入、重试都由它负责。
26
+ - **余额与用量**:登录态下读 `/user/profile`、订阅进度与用量统计。
27
+ - **充值**:面板内选金额,按 `1 元 = 2 美元` 显示预计到账,点「去支付」在新标签页打开支付页;订单状态可轮询到「已到账」。
28
+ - **兑换码**:面板内直接兑换。
29
+ - **Agent 工具**:`sub2api_status`、`sub2api_models`,让模型能回答"我还有多少额度"。
30
+
31
+ ## 安装
32
+
33
+ ### 普通 DSH(命令行 / Web)
34
+
35
+ ```sh
36
+ dsh plugin --profile web add dsh-sub2api
37
+ ```
38
+
39
+ 重启后打开 **设置 → Sub2API**。
40
+
41
+ > 每个 profile 的插件列表独立:终端界面还需单独装一次。
42
+
43
+ ### DSH Desktop
44
+
45
+ Desktop 用的就是官方 Harness 插件体系,本插件只依赖官方契约(`llm` / `webServer` / `tools` / `slots`),所以在桌面端原样可用。
46
+
47
+ 在托盘菜单打开的终端里,裸命令默认作用于**当前激活的 profile**:
48
+
49
+ ```sh
50
+ dsh plugin add dsh-sub2api
51
+ ```
52
+
53
+ 或者显式指定(Desktop 的默认 profile 叫 `desktop`):
54
+
55
+ ```sh
56
+ dsh plugin --profile desktop add dsh-sub2api
57
+ ```
58
+
59
+ 装完**需要重启 DSH Desktop**,新的 bundle 才会进入 Loader 组合。桌面端不会把插件从一个 profile 复制到另一个,所以命令必须打在你实际在用的那个 profile 上。
60
+
61
+ **通道兼容性**(`upstream.json` 实测):
62
+
63
+ | Desktop 通道 | 内置 DSH | 本插件 |
64
+ |---|---|---|
65
+ | stable | 0.2.1-rc.3 | ✅ |
66
+ | beta | 0.2.2-rc.3 | ✅ |
67
+ | next | 0.2.2-rc.3 | ✅ |
68
+
69
+ 插件声明 `>=0.2.1-rc.2 <0.2.3`,并固定 `@dsh-ai-providers/openai-compatible@0.7.0`——这个版本同时接受 0.2.1 与 0.2.2 两个通道(0.7.3 只接受 0.2.2)。
70
+
71
+ **从插件市场一键安装的前提**:Desktop 的市场只对满足四个条件的条目提供自动安装——单一 npm 包名、官方 registry 的 `latest` 返回同名稳定版本、包内声明 `dsh.bundle.patch`。本包满足后三项,**还差发布到 npm**。在发布之前,用上面的终端命令安装;GitHub 地址在市场里只会显示为「可浏览」,不会标成可自动安装。
72
+
73
+ ## 配置
74
+
75
+ 插件行写在 `$DSH_HOME/profiles/<profile>/cordis.patch.yml`:
76
+
77
+ ```yaml
78
+ - id: llm-sub2api
79
+ name: "dsh-sub2api"
80
+ config:
81
+ apiBase: "https://sub.pscly.cc"
82
+ payBase: "https://pay.pscly.cc"
83
+ apiKeyEnv: SUB2API_API_KEY
84
+ ```
85
+
86
+ | 字段 | 默认值 | 说明 |
87
+ |---|---|---|
88
+ | `apiBase` | `https://sub.pscly.cc` | 中转站地址,`/v1` 后缀会被自动去掉 |
89
+ | `payBase` | `https://pay.pscly.cc` | 充值中转站地址 |
90
+ | `apiKeyEnv` | `SUB2API_API_KEY` | 存 API Key 的凭据引用名 |
91
+ | `keyName` | `dsh` | 自动创建的密钥名 |
92
+ | `groupId` | 自动选择 | 强制指定密钥所属分组(自动选择见下) |
93
+ | `requestTimeoutMs` | 300000 | 普通请求超时 |
94
+ | `streamIdleTimeoutMs` | 300000 | 流式请求空闲超时 |
95
+ | `modelsCachePath` | `$DSH_HOME/sub2api-models.json` | 模型目录缓存 |
96
+ | `visibleModels` | 全部 | 只显示这些模型 id |
97
+ | `contextWindow` | 跟随上游 | 强制覆盖上下文窗口 |
98
+ | `showSidebarQuota` | false | 侧边栏余额卡片 |
99
+ | `autoProvision` | true | 登录后自动建 Key |
100
+ | `announceToAgent` | true | 向 agent 注入插件说明 |
101
+
102
+ ## 数据与凭据
103
+
104
+ | 数据 | 位置 | 权限 |
105
+ |---|---|---|
106
+ | 登录会话(token) | DSH 凭据库 record `llm-sub2api/session` | 0600 |
107
+ | API Key | 凭据引用 `SUB2API_API_KEY` | 0600 |
108
+ | 模型目录缓存 | `$DSH_HOME/sub2api-models.json` | 0600 |
109
+ | 密码 | **不保存** | — |
110
+
111
+ 面板永远只显示密钥掩码;「复制」会向本机路由临时取一次明文。
112
+
113
+ ## 安全边界
114
+
115
+ - 所有 `/api/sub2api/*` 路由只接受本机回环请求,非本机一律 403。
116
+ - 日志与错误信息不包含 token、密钥或密码。
117
+ - 支付链接里的 `token` 是 sub2api 的访问令牌,只在用户点「去支付」时生成,不写日志、不落盘。
118
+
119
+ ## 密钥建在哪个分组
120
+
121
+ 网关会拒绝**没有分组的密钥**(`API key is not assigned to a group`),所以自动选择必须有确定结果:
122
+
123
+ 1. 配置里的 `groupId`
124
+ 2. 账号的 `allowed_groups` 里能匹配到的组
125
+ 3. 只有一个组时,就用它
126
+ 4. 多个组时,优先 `platform` 为 `openai` 的组(中间层走的是 `chat/completions`,别的平台的组服务不了)
127
+ 5. 否则取第一个非独占组
128
+
129
+ ## 余额为 0 时为什么没有模型
130
+
131
+ Sub2API 的网关对 `/v1/models` 有余额门槛:**账户余额为 0 时直接返回 `403 INSUFFICIENT_BALANCE`**,模型列表拿不到。这不是插件的解析问题,实测确认:
132
+
133
+ ```
134
+ [200] POST /api/v1/keys → 正常返回明文 key
135
+ [403] GET /v1/models → {"code":"INSUFFICIENT_BALANCE"}
136
+ [200] GET /v1/sub2api/billing → 正常(Key 绑定分组后)
137
+ [404] GET /api/v1/models → 控制面没有模型接口
138
+ ```
139
+
140
+ 所以插件把零余额当作**"待充值"状态**而不是错误:设置页里显示「余额不足,暂时拿不到模型列表」和一个「去充值」按钮,充值到账后自动同步,不需要重新登录。
141
+
142
+ > 对运营者的建议:如果希望新用户注册后就能看到模型,在后台给注册赠送一点初始余额;否则新用户的第一屏必然是空的。
143
+
144
+ ## 关于充值
145
+
146
+ 支付是独立服务 `pay.pscly.cc`。它的嵌入式充值页要求带上 `user_id` 和 `token` 并回源校验 Sub2API 身份,所以**裸链接一定 403**——这也是为什么不能只在设置里放一个跳转按钮。
147
+
148
+ 插件提供两条路径:
149
+
150
+ 1. **链接模式**:生成带身份的 URL,新标签页打开,金额在支付页选。
151
+ 2. **直达模式**:面板里选金额,Host 完成 CSRF 握手后直接拿到 `/checkout/{orderNo}`,并可轮询到账状态。失败时自动退回模式 1。
152
+
153
+ ## 开发
154
+
155
+ ```sh
156
+ npm install # 安装 @dsh-ai-providers/*
157
+ npm test # 冒烟 + 边界测试(本地假服务,不联网)
158
+ ```
159
+
160
+ 测试用假 sub2api、假支付站和内存凭据服务跑真实插件入口,覆盖注册开通、重复登录复用密钥、错误密码、流式对话、充值下单与轮询、兑换码、登出清理,以及无头环境、缺凭据服务、空目录、传输层缺失等边界。
161
+
162
+ ## 许可证
163
+
164
+ GPL-3.0-only。协议层复用了 `@dsh-ai-providers/openai-compatible`(GPL-3.0-only)。
@@ -0,0 +1,16 @@
1
+ # dsh-sub2api bundle layer.
2
+ #
3
+ # One plugin row: registers the `sub2api` provider route, its Models-page card,
4
+ # and the /api/sub2api/* routes the browser panel talks to.
5
+ #
6
+ # `name` must be the FULL package specifier as installed in the profile's
7
+ # node_modules, quoted (a YAML scalar starting with `@` would parse as a
8
+ # directive). This package is unscoped, so the bare name is correct — but the
9
+ # rule still applies if it is ever published under a scope.
10
+ - insert:
11
+ - id: llm-sub2api
12
+ name: "dsh-sub2api"
13
+ config:
14
+ apiBase: "https://sub.pscly.cc"
15
+ payBase: "https://pay.pscly.cc"
16
+ apiKeyEnv: SUB2API_API_KEY
package/lib/adapter.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The provider adapter.
3
+ *
4
+ * Protocol work is delegated: `@dsh-ai-providers/openai-compatible` already
5
+ * speaks `chat/completions`, including streaming, tool calls, reasoning
6
+ * deltas, image parts and retries. What is left here is the seam between the
7
+ * host's request shape and that service's `LlmCall`: build the route from the
8
+ * live catalog, merge the sampling controls, and dispatch.
9
+ *
10
+ * The transport is imported lazily so a missing or broken dependency leaves the
11
+ * settings panel fully usable and only disables chat, with an error that says
12
+ * exactly that.
13
+ * @module dsh-sub2api/adapter
14
+ */
15
+
16
+ import { LlmAdapter, attributionHeaders } from "@deepseek-ai/dsh-llm";
17
+ import { PROVIDER } from "./constants.js";
18
+ import { Sub2ApiError } from "./util.js";
19
+
20
+ /** @type {Promise<any> | undefined} */
21
+ let transportModule;
22
+
23
+ /**
24
+ * Load the reused transport once. A rejection is remembered: retrying a broken
25
+ * dependency on every request would turn one clear error into a stream of them.
26
+ * @returns {Promise<any>}
27
+ */
28
+ export function loadTransport() {
29
+ if (transportModule === undefined) {
30
+ transportModule = import("@dsh-ai-providers/openai-compatible").catch((error) => {
31
+ const detail = error instanceof Error ? error.message : String(error);
32
+ throw new Sub2ApiError(
33
+ `缺少 @dsh-ai-providers/openai-compatible(${detail})。安装插件时请一并安装依赖。`,
34
+ { code: "transport_missing", cause: error },
35
+ );
36
+ });
37
+ }
38
+ return transportModule;
39
+ }
40
+
41
+ /**
42
+ * A `Volatile<T>` backed by a getter.
43
+ *
44
+ * The transport reads its configuration through `Volatile.get()` on every call,
45
+ * which is what lets a refreshed catalog apply without rebuilding the service.
46
+ * A snapshot from `createVolatile` would freeze the first catalog forever.
47
+ * @template T
48
+ * @param {() => T} get
49
+ * @returns {{get: () => T}}
50
+ */
51
+ export function liveRef(get) {
52
+ return { get };
53
+ }
54
+
55
+ export class Sub2ApiAdapter extends LlmAdapter {
56
+ /**
57
+ * @param {object} deps
58
+ * @param {() => any} deps.ctx host context, for the credential and attachment services
59
+ * @param {import("./sub2api/catalog.js").ModelCatalog} deps.catalog
60
+ * @param {() => string} deps.apiBase
61
+ * @param {() => string} deps.apiKeyEnv credential reference holding the key
62
+ * @param {() => number} deps.timeoutMs
63
+ * @param {() => number} deps.idleTimeoutMs
64
+ * @param {{warn: Function}} [deps.logger]
65
+ */
66
+ constructor(deps) {
67
+ super();
68
+ this.deps = deps;
69
+ /** @type {any} */
70
+ this.service = undefined;
71
+ }
72
+
73
+ /** Build the transport on first use, once the catalog has something to offer. */
74
+ async #service() {
75
+ if (this.service !== undefined) return this.service;
76
+
77
+ const module = await loadTransport();
78
+ const { OpenAiLlmService } = module;
79
+ if (typeof OpenAiLlmService !== "function") {
80
+ throw new Sub2ApiError("@dsh-ai-providers/openai-compatible 未导出 OpenAiLlmService", {
81
+ code: "transport_broken",
82
+ });
83
+ }
84
+
85
+ const deps = this.deps;
86
+ const config = {
87
+ connections: liveRef(() => [
88
+ {
89
+ id: PROVIDER,
90
+ name: "Sub2API",
91
+ baseUrl: `${deps.apiBase()}/v1`,
92
+ apiKeyRef: deps.apiKeyEnv(),
93
+ },
94
+ ]),
95
+ llmRoutes: liveRef(() => [
96
+ {
97
+ id: PROVIDER,
98
+ name: "Sub2API",
99
+ connection: PROVIDER,
100
+ models: deps.catalog.llmModels(),
101
+ maxCompletionTokens: false,
102
+ },
103
+ ]),
104
+ llmIdleTimeoutMs: liveRef(() => deps.idleTimeoutMs()),
105
+ timeoutMs: liveRef(() => deps.timeoutMs()),
106
+ batchSize: liveRef(() => 16),
107
+ };
108
+
109
+ this.service = new OpenAiLlmService({
110
+ config,
111
+ provider: PROVIDER,
112
+ credentials: () => optionalService(deps.ctx, "credentials"),
113
+ images: () => optionalService(deps.ctx, "attachments"),
114
+ });
115
+ return this.service;
116
+ }
117
+
118
+ providerInfo(provider) {
119
+ return { id: provider, name: "Sub2API" };
120
+ }
121
+
122
+ async listModels(provider) {
123
+ await this.deps.catalog.load();
124
+ return this.deps.catalog.listModels(provider);
125
+ }
126
+
127
+ /**
128
+ * Per-model facts the host uses for context metering and auto-compaction.
129
+ * The base class would answer with the id as the name and no capacity at all.
130
+ */
131
+ async resolveModel(provider, model) {
132
+ await this.deps.catalog.load();
133
+ const known = this.deps.catalog.visible().find((entry) => entry.id === model);
134
+ /** @type {Record<string, unknown>} */
135
+ const resolved = { provider, id: model, name: known?.name ?? model };
136
+ if (known?.contextWindow !== undefined) resolved.context = { contextWindow: known.contextWindow };
137
+ if (known?.maxTokens !== undefined) resolved.defaultMaxTokens = known.maxTokens;
138
+ if (known?.vision === true) resolved.inputModalities = ["text", "image"];
139
+ return resolved;
140
+ }
141
+
142
+ async *stream(options) {
143
+ const service = await this.#service();
144
+ const route = service.routes()[0];
145
+ // An empty `models` array still yields a route object; without this check
146
+ // the transport would build a request with no model and fail at the wire.
147
+ if (route === undefined || route.models.length === 0) {
148
+ throw new Sub2ApiError("尚未同步到可用模型,请先在 Sub2API 面板登录或刷新模型", {
149
+ code: "no_models",
150
+ });
151
+ }
152
+
153
+ const model = route.models.find((entry) => entry.id === options.model);
154
+ /** @type {any} */
155
+ const call = {
156
+ options,
157
+ route,
158
+ model,
159
+ sampling: mergeSampling(route.sampling, model?.sampling, options),
160
+ headers: safeAttributionHeaders(),
161
+ };
162
+
163
+ yield* service.stream(call);
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Merge the sampling controls the request sets over the route's and the
169
+ * model's defaults. Explicit `undefined` must not erase a configured default.
170
+ * @param {any} routeSampling
171
+ * @param {any} modelSampling
172
+ * @param {any} options
173
+ */
174
+ export function mergeSampling(routeSampling, modelSampling, options) {
175
+ /** @type {Record<string, unknown>} */
176
+ const merged = { ...(modelSampling ?? {}), ...(routeSampling ?? {}) };
177
+ const overlay = {
178
+ temperature: options?.temperature,
179
+ topP: options?.topP,
180
+ maxTokens: options?.maxTokens,
181
+ stop: options?.stop,
182
+ };
183
+ for (const [key, value] of Object.entries(overlay)) {
184
+ if (value !== undefined) merged[key] = value;
185
+ }
186
+ return merged;
187
+ }
188
+
189
+ /** Read an optional host service without letting an absent one abort the call. */
190
+ function optionalService(ctx, name) {
191
+ try {
192
+ return ctx?.get?.(name);
193
+ } catch {
194
+ return undefined;
195
+ }
196
+ }
197
+
198
+ /** Harness attribution headers, when the host exports them. */
199
+ function safeAttributionHeaders() {
200
+ try {
201
+ return typeof attributionHeaders === "function" ? attributionHeaders() : {};
202
+ } catch {
203
+ return {};
204
+ }
205
+ }