dsh-zcode-startplan 0.0.0-stage → 0.2.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/CHANGELOG.md +108 -0
- package/LICENSE +674 -0
- package/README.md +345 -2
- package/bin/cli.mjs +450 -0
- package/client.js +659 -0
- package/cordis.patch.yml +30 -0
- package/icon.svg +18 -0
- package/index.js +313 -0
- package/lib/adapter.js +286 -0
- package/lib/anthropic-body.js +304 -0
- package/lib/assemble.js +309 -0
- package/lib/captcha/minter.js +654 -0
- package/lib/captcha/sdk-page.js +20 -0
- package/lib/errors.js +125 -0
- package/lib/local-endpoint.js +338 -0
- package/lib/manage-routes.js +414 -0
- package/lib/plan-client.js +427 -0
- package/lib/pool.js +467 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +279 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +544 -0
- package/lib/upstream.js +123 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -6
- package/scripts/bench-toks.mjs +138 -0
- package/scripts/check-data-dir.mjs +31 -0
- package/scripts/restart-dsh.ps1 +76 -0
- package/scripts/run-tests.mjs +68 -0
- package/scripts/smoke-install.mjs +204 -0
- package/scripts/verify_compat.mjs +64 -0
package/icon.svg
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="ZCode Start Plan">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#3B82F6"/>
|
|
5
|
+
<stop offset="1" stop-color="#8B5CF6"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<!-- 底座:代表"通道" -->
|
|
9
|
+
<rect x="4" y="4" width="56" height="56" rx="14" fill="url(#g)"/>
|
|
10
|
+
<!-- Z 字形折线:ZCode 的首字母 -->
|
|
11
|
+
<path d="M19 19 H45 L19 45 H45" fill="none" stroke="#FFFFFF" stroke-width="6"
|
|
12
|
+
stroke-linecap="round" stroke-linejoin="round"/>
|
|
13
|
+
<!-- 右上角的"起点"圆点:Start -->
|
|
14
|
+
<circle cx="47" cy="17" r="5" fill="#FFFFFF" opacity="0.9"/>
|
|
15
|
+
<!-- 左下角的勾:免费额度已领取的状态暗示 -->
|
|
16
|
+
<path d="M15 50 L19 54 L26 47" fill="none" stroke="#FFFFFF" stroke-width="3.5"
|
|
17
|
+
stroke-linecap="round" stroke-linejoin="round" opacity="0.75"/>
|
|
18
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件入口:把「ZCode 赠送免费 plan」接进 DSH 的 `llm` 服务。
|
|
3
|
+
*
|
|
4
|
+
* ## 装配(顺序不可乱)
|
|
5
|
+
*
|
|
6
|
+
* ```
|
|
7
|
+
* 解析配置 → 异步建资源(账号库 / 账号池 / captcha 产出器 / plan 客户端 / 可选本地端点)
|
|
8
|
+
* → 同步注册 llm 适配器(路由名 = config.provider,默认 zcode-start-plan)
|
|
9
|
+
* → 同步注册状态工具
|
|
10
|
+
* → 就绪后向 ctx 发出 `llm/adapters-updated`,让模型选择器立刻刷新
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* ## 为什么「注册」必须同步
|
|
14
|
+
*
|
|
15
|
+
* `ctx.effect(fn)` 要求 `fn` 同步返回 disposer;在异步函数里调用 `ctx.effect` 会拿到
|
|
16
|
+
* 一条**未挂到 fiber** 的注册 —— 热重载或禁用插件后路由不会被撤销,表现为
|
|
17
|
+
* 「插件已禁用,模型却还在选择器里且每次调用都失败」。故异步部分只负责**建资源**,
|
|
18
|
+
* 注册统一放在同步入口里做。
|
|
19
|
+
*
|
|
20
|
+
* ## 与其他 llm 插件的关系
|
|
21
|
+
*
|
|
22
|
+
* 只要 `config.provider` 不与 `llm-pi-ai` / `llm-deepseek` 的路由重名就不会冲突。
|
|
23
|
+
* 重名时 `registerAdapter` 抛 `DUPLICATE_ADAPTER`:这里捕获并降级为「只提供状态工具」,
|
|
24
|
+
* 不让整个 fiber 崩掉(其余模型仍可正常服务)。
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { assemble } from './lib/assemble.js'
|
|
28
|
+
import { LOGIN_CHANNELS } from './lib/upstream-api.js'
|
|
29
|
+
|
|
30
|
+
/** 默认模型列表(同时作为 Config 的默认值来源)。 */
|
|
31
|
+
const DEFAULT_MODELS = Object.freeze(['GLM-5.3-Flash', 'GLM-5.3'])
|
|
32
|
+
|
|
33
|
+
/** 插件名(Cordis 用它标识 fiber)。 */
|
|
34
|
+
export const name = 'zcode-start-plan'
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 依赖的服务。
|
|
38
|
+
*
|
|
39
|
+
* ⚠ 宿主 ctx 是沙箱 façade:**只有这里列出的服务才会挂到 ctx 上**,
|
|
40
|
+
* 少写一个,`apply` 里一碰就抛 `cannot get property "X" without inject`,
|
|
41
|
+
* 整个插件静默失效(宿主只往 stderr 打一条 warning,打包态下看不到)。
|
|
42
|
+
*
|
|
43
|
+
* - `llm` 注册 provider 适配器(本插件的主用途)
|
|
44
|
+
* - `tools` 注册 `zcode_start_plan_status` 状态工具
|
|
45
|
+
* - `timer` 每小时清理过期的「账号×模型」限流标记
|
|
46
|
+
* - `webServer` 注册账号池管理路由(Web UI 面板的数据通道;可选增强)
|
|
47
|
+
*/
|
|
48
|
+
export const inject = ['llm', 'tools', 'timer', 'webServer']
|
|
49
|
+
|
|
50
|
+
const PROVIDER = 'zcode-start-plan'
|
|
51
|
+
|
|
52
|
+
/** 默认配置(每个字段都能由 profile 的 cordis.patch.yml 覆盖)。 */
|
|
53
|
+
const DEFAULT_CONFIG = Object.freeze({
|
|
54
|
+
/** DSH 里的路由名;模型选择器里显示为 `<displayName>`。 */
|
|
55
|
+
provider: PROVIDER,
|
|
56
|
+
displayName: 'ZCode Start Plan(赠送免费 plan)',
|
|
57
|
+
/** 暴露给 DSH 的模型 id 列表(与上游模型目录求交集;拉不到时直接用这份)。 */
|
|
58
|
+
models: DEFAULT_MODELS,
|
|
59
|
+
/** 上游模型目录缓存时长(毫秒)。 */
|
|
60
|
+
modelCacheMs: 10 * 60_000,
|
|
61
|
+
/** 数据目录(空 = ~/.dsh/zcode-start-plan)。 */
|
|
62
|
+
dataDir: '',
|
|
63
|
+
/**
|
|
64
|
+
* 登录渠道:`cn`(智谱国内站 bigmodel.cn)或 `intl`(Z.AI 国际站 z.ai)。
|
|
65
|
+
*
|
|
66
|
+
* 两条渠道**协议完全一致**,只是 `provider` 与授权站点不同:
|
|
67
|
+
* 国内账号用 `cn`,国际账号用 `intl`。账号池可以同时容纳两边登录进来的账号
|
|
68
|
+
* (每条凭据都记着自己的 `login_channel`,推理走同一个 zcode-plan 端点)。
|
|
69
|
+
*
|
|
70
|
+
* 这个配置只影响「在 DSH 里发起登录」的场景;用 CLI 登录时以 `--channel` 为准。
|
|
71
|
+
*/
|
|
72
|
+
channel: 'cn',
|
|
73
|
+
captcha: Object.freeze({
|
|
74
|
+
/** 'cdp' = 用宿主 Electron 产出(默认);'manual' = 由人工粘贴 param(见 CLI)。 */
|
|
75
|
+
mode: 'cdp',
|
|
76
|
+
/** 宿主调试端口(DSH 桌面端需以 --remote-debugging-port 启动)。 */
|
|
77
|
+
debugPort: 9229,
|
|
78
|
+
/** captcha 页面 origin(必须是真实 https origin,否则二次 mint 必失败)。 */
|
|
79
|
+
origin: 'https://zcode.z.ai/',
|
|
80
|
+
}),
|
|
81
|
+
endpoint: Object.freeze({
|
|
82
|
+
/** 是否启动本地 Anthropic 兼容端点(仅 `llm-pi-ai` 回落路线需要)。 */
|
|
83
|
+
enabled: false,
|
|
84
|
+
port: 17_899,
|
|
85
|
+
}),
|
|
86
|
+
/** 是否注册 `zcode_start_plan_status` 工具。 */
|
|
87
|
+
statusTool: true,
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 深合并默认值(只做一层嵌套:够用且不易写错)。
|
|
92
|
+
*
|
|
93
|
+
* ⚠ `models` 只在**未写**(undefined/null)时补默认值;写了但类型不对
|
|
94
|
+
* (例如 `models: "GLM"`)必须原样保留,让 `validateConfig` 报错 ——
|
|
95
|
+
* 若在这里悄悄替换成默认值,非法配置就会被静默接受。
|
|
96
|
+
*/
|
|
97
|
+
export function resolveConfig(raw) {
|
|
98
|
+
const src = raw !== null && typeof raw === 'object' ? raw : {}
|
|
99
|
+
const out = { ...DEFAULT_CONFIG, ...src }
|
|
100
|
+
out.captcha = { ...DEFAULT_CONFIG.captcha, ...(src.captcha ?? {}) }
|
|
101
|
+
out.endpoint = { ...DEFAULT_CONFIG.endpoint, ...(src.endpoint ?? {}) }
|
|
102
|
+
if (src.models === undefined || src.models === null) out.models = [...DEFAULT_CONFIG.models]
|
|
103
|
+
else if (Array.isArray(src.models)) out.models = src.models.length > 0 ? src.models.slice() : [...DEFAULT_CONFIG.models]
|
|
104
|
+
return out
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Config 契约:**零依赖的 schemastery 兼容 schema**。
|
|
109
|
+
*
|
|
110
|
+
* ## 为什么必须"长得像 schemastery"
|
|
111
|
+
*
|
|
112
|
+
* DSH 用 `isNativeConfigSchema(config)` 判定一行能否进配置目录:
|
|
113
|
+
* `Symbol.for('schemastery') === true` + string `type` + object `meta`。
|
|
114
|
+
* 不属于 native 就得到 `status: 'unsupported'`,于是设置页不可编辑、
|
|
115
|
+
* **provider 也进不了模型选择器**(选择器按配置目录解析 provider)。
|
|
116
|
+
*
|
|
117
|
+
* ## 为什么不直接 `import '@deepseek-ai/schemastery'`
|
|
118
|
+
*
|
|
119
|
+
* `plugin_manager` 用**软链**安装 bundle(`link:`),插件的 `index.js` 实际运行在
|
|
120
|
+
* 源码目录,那里解析不到 profile 的 `node_modules` —— 一旦顶层静态 import 就
|
|
121
|
+
* `ERR_MODULE_NOT_FOUND`,模块加载失败,`apply` 永不执行:表现为
|
|
122
|
+
* "行状态 schema、插件列表可见,但工具与模型全都没有"(本仓库真实踩过)。
|
|
123
|
+
*
|
|
124
|
+
* 官方标准也明确:Host-only bundle 不需要运行时依赖。
|
|
125
|
+
* 故这里手写一个**最小兼容对象**:属性名与判据完全一致,求值语义与 schemastery
|
|
126
|
+
* 的 `Schema(...)` 调用一致(返回补全默认值后的配置,非法值抛错)。
|
|
127
|
+
*/
|
|
128
|
+
const SCHEMASTERNY_SYMBOL = Symbol.for('schemastery')
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 构造一个 schemastery 兼容的 object schema。
|
|
132
|
+
*
|
|
133
|
+
* @param {(value: any) => any} validate 校验并补全默认值;非法值应抛错
|
|
134
|
+
* @param {Record<string, any>} fields 字段名 → 该字段的默认值(供文档/投影使用)
|
|
135
|
+
*/
|
|
136
|
+
function makeConfigSchema(validate, fields) {
|
|
137
|
+
const schema = (value) => validate(value ?? {})
|
|
138
|
+
Object.defineProperty(schema, SCHEMASTERNY_SYMBOL, { value: true, enumerable: false })
|
|
139
|
+
Object.defineProperty(schema, 'type', { value: 'object', enumerable: true })
|
|
140
|
+
Object.defineProperty(schema, 'meta', { value: { default: {}, ...fields }, enumerable: true })
|
|
141
|
+
/** Standard Schema 兼容层:让不认识 schemastery 的消费者也能校验。 */
|
|
142
|
+
Object.defineProperty(schema, '~standard', {
|
|
143
|
+
value: {
|
|
144
|
+
version: 1,
|
|
145
|
+
vendor: 'dsh-zcode-startplan',
|
|
146
|
+
validate: (value) => {
|
|
147
|
+
try {
|
|
148
|
+
return { value: validate(value ?? {}) }
|
|
149
|
+
} catch (error) {
|
|
150
|
+
return { issues: [{ message: error instanceof Error ? error.message : String(error) }] }
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
enumerable: false,
|
|
155
|
+
})
|
|
156
|
+
return schema
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 单个 `channel` 值是否合法(与运行时归一化共用同一张表)。 */
|
|
160
|
+
const isChannelValue = (value) => {
|
|
161
|
+
const raw = String(value ?? '').trim().toLowerCase()
|
|
162
|
+
return raw.length > 0 && Object.values(LOGIN_CHANNELS).some(
|
|
163
|
+
(entry) => entry.provider === raw || entry.aliases.some((alias) => alias.toLowerCase() === raw),
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 校验并补全配置。非法值**抛错**(激活期即失败,不静默降级)。
|
|
169
|
+
*
|
|
170
|
+
* @param {any} value
|
|
171
|
+
*/
|
|
172
|
+
export function validateConfig(value) {
|
|
173
|
+
const src = value === undefined || value === null ? {} : value
|
|
174
|
+
if (typeof src !== 'object' || Array.isArray(src)) throw new Error('config 必须是对象')
|
|
175
|
+
|
|
176
|
+
const out = resolveConfig(src)
|
|
177
|
+
|
|
178
|
+
if (typeof out.provider !== 'string' || out.provider.trim().length === 0) {
|
|
179
|
+
throw new Error('config.provider 必须是非空字符串')
|
|
180
|
+
}
|
|
181
|
+
if (!Array.isArray(out.models) || !out.models.every((id) => typeof id === 'string')) {
|
|
182
|
+
throw new Error('config.models 必须是字符串数组')
|
|
183
|
+
}
|
|
184
|
+
if (!Number.isInteger(out.modelCacheMs) || out.modelCacheMs < 0) {
|
|
185
|
+
throw new Error('config.modelCacheMs 必须是非负整数')
|
|
186
|
+
}
|
|
187
|
+
if (!isChannelValue(out.channel)) {
|
|
188
|
+
throw new Error('config.channel 只能是 "cn"(国内智谱)或 "intl"(国际 Z.AI)')
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const { captcha, endpoint } = out
|
|
192
|
+
if (typeof captcha !== 'object' || captcha === null) throw new Error('config.captcha 必须是对象')
|
|
193
|
+
if (captcha.mode !== 'cdp' && captcha.mode !== 'manual') {
|
|
194
|
+
throw new Error('config.captcha.mode 只能是 "cdp" 或 "manual"')
|
|
195
|
+
}
|
|
196
|
+
if (!Number.isInteger(captcha.debugPort) || captcha.debugPort < 1 || captcha.debugPort > 65_535) {
|
|
197
|
+
throw new Error('config.captcha.debugPort 必须是 1-65535 的整数')
|
|
198
|
+
}
|
|
199
|
+
if (typeof captcha.origin !== 'string' || !captcha.origin.startsWith('http')) {
|
|
200
|
+
throw new Error('config.captcha.origin 必须是 http(s) URL')
|
|
201
|
+
}
|
|
202
|
+
if (typeof endpoint !== 'object' || endpoint === null) throw new Error('config.endpoint 必须是对象')
|
|
203
|
+
if (!Number.isInteger(endpoint.port) || endpoint.port < 0 || endpoint.port > 65_535) {
|
|
204
|
+
throw new Error('config.endpoint.port 必须是 0-65535 的整数')
|
|
205
|
+
}
|
|
206
|
+
if (typeof endpoint.enabled !== 'boolean') throw new Error('config.endpoint.enabled 必须是布尔值')
|
|
207
|
+
if (typeof out.statusTool !== 'boolean') throw new Error('config.statusTool 必须是布尔值')
|
|
208
|
+
|
|
209
|
+
return out
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export const Config = makeConfigSchema(validateConfig, {
|
|
213
|
+
provider: PROVIDER,
|
|
214
|
+
displayName: 'ZCode Start Plan(赠送免费 plan)',
|
|
215
|
+
models: [...DEFAULT_MODELS],
|
|
216
|
+
modelCacheMs: 10 * 60_000,
|
|
217
|
+
dataDir: '',
|
|
218
|
+
channel: 'cn',
|
|
219
|
+
captcha: { mode: 'cdp', debugPort: 9229, origin: 'https://zcode.z.ai/' },
|
|
220
|
+
endpoint: { enabled: false, port: 17_899 },
|
|
221
|
+
statusTool: true,
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Cordis 插件入口。
|
|
226
|
+
*
|
|
227
|
+
* ## ⚠ 宿主的 `ctx` 是**沙箱 façade**,这是本插件最大的坑
|
|
228
|
+
*
|
|
229
|
+
* 宿主只把 `inject` 声明过的服务挂到 ctx 上。实测(一次性诊断插件):
|
|
230
|
+
* `Object.keys(ctx)` 只有 `['fiber']`,未声明的服务访问即抛
|
|
231
|
+
* `cannot get property "tools" without inject`,整个 `apply` 失败 ——
|
|
232
|
+
* 而宿主只把它当一条 warning 打到 stderr(打包态被丢弃),
|
|
233
|
+
* 表现为「插件在列表里、Config 是 schema,但工具和模型全都没有」。
|
|
234
|
+
*
|
|
235
|
+
* 因此:**用到哪个服务就必须在 `inject` 里声明**。本插件用到
|
|
236
|
+
* `llm`(注册适配器)、`tools`(状态工具)、`timer`(定期清理)、
|
|
237
|
+
* `webServer`(账号池管理路由,供插件 Web UI 面板调用)。
|
|
238
|
+
*
|
|
239
|
+
* 另外 `ctx.effect` 在沙箱里可用(它不是服务,是 ctx 动词),
|
|
240
|
+
* 而 `ctx.emit` / `ctx.on` / `ctx.setInterval` **不可用** ——
|
|
241
|
+
* 分别改用 `ctx.llm.emitAdaptersUpdated?.()` 与 `ctx.timer.interval`。
|
|
242
|
+
*
|
|
243
|
+
* `webServer`(账号池管理路由)也在 `inject` 里声明了,但注册处做了
|
|
244
|
+
* 容错(`ctx.webServer?.register` 探测 + try/catch 降级):单测假 ctx、
|
|
245
|
+
* 或未来宿主版本缺该服务时,只跳过面板路由,其余功能不受影响。
|
|
246
|
+
*
|
|
247
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
248
|
+
* @param {ReturnType<typeof resolveConfig>} rawConfig
|
|
249
|
+
*/
|
|
250
|
+
export function apply(ctx, rawConfig) {
|
|
251
|
+
const config = resolveConfig(rawConfig)
|
|
252
|
+
const log = (message) => {
|
|
253
|
+
try {
|
|
254
|
+
ctx.logger?.info?.(`[zcode-start-plan] ${message}`)
|
|
255
|
+
} catch {
|
|
256
|
+
// logger 不可用时静默(不要让日志把插件弄崩)。
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const warn = (message) => {
|
|
260
|
+
try {
|
|
261
|
+
ctx.logger?.warn?.(`[zcode-start-plan] ${message}`)
|
|
262
|
+
} catch {
|
|
263
|
+
// 同上。
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const assembled = assemble(ctx, config, { log, warn })
|
|
268
|
+
let adapterRegistered = false
|
|
269
|
+
let disposed = false
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* 异步建资源;就绪后才注册适配器。
|
|
273
|
+
*
|
|
274
|
+
* 官方标准:每个资源都用 `ctx.effect` 注册并交出 cleanup。
|
|
275
|
+
* ① 适配器 / 工具 / 定时器 —— 就绪后在 `ctx.effect` 里注册;
|
|
276
|
+
* ② 账号库 / 端点 / DB 句柄 —— 异步资源,由 `apply` 返回的 cleanup 释放。
|
|
277
|
+
*/
|
|
278
|
+
void assembled
|
|
279
|
+
.init()
|
|
280
|
+
.then(() => {
|
|
281
|
+
if (adapterRegistered || disposed) return
|
|
282
|
+
adapterRegistered = true
|
|
283
|
+
ctx.effect(() => {
|
|
284
|
+
const undo = assembled.register()
|
|
285
|
+
return () => {
|
|
286
|
+
if (typeof undo === 'function') undo()
|
|
287
|
+
}
|
|
288
|
+
})
|
|
289
|
+
/**
|
|
290
|
+
* 拓扑变了:让模型选择器重读注册表。
|
|
291
|
+
* ⚠ 沙箱里没有 `ctx.emit`,改用 `ctx.llm.emitAdaptersUpdated?.()`
|
|
292
|
+
* (`dsh-llm` 自己的发布入口,`workbuddy` 插件也是这么用的)。
|
|
293
|
+
*/
|
|
294
|
+
try {
|
|
295
|
+
ctx.llm.emitAdaptersUpdated?.()
|
|
296
|
+
} catch {
|
|
297
|
+
// 老版本没有这个方法;选择器下次刷新自然会看到。
|
|
298
|
+
}
|
|
299
|
+
})
|
|
300
|
+
.catch((error) => {
|
|
301
|
+
warn(
|
|
302
|
+
`初始化失败(本插件不提供服务,其它模型不受影响):${error instanceof Error ? error.message : String(error)}`,
|
|
303
|
+
)
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 插件级 cleanup(官方标准:`apply` 返回它)。
|
|
308
|
+
*/
|
|
309
|
+
return async () => {
|
|
310
|
+
disposed = true
|
|
311
|
+
await assembled.dispose()
|
|
312
|
+
}
|
|
313
|
+
}
|
package/lib/adapter.js
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 两个 llm 适配器:**原生适配器**(默认)与 **pi-ai 适配器**(可选回落)。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么是「适配器」而不是代理
|
|
5
|
+
*
|
|
6
|
+
* DSH 里每个请求都由 `ctx.llm` 分派给某个 adapter;adapter 负责把上游 wire 翻成 DSH 的
|
|
7
|
+
* `StreamChunk` 词汇。参考实现(ZCode 插件)是一层本地 HTTP 代理,由 ZCode 自带的
|
|
8
|
+
* Anthropic SDK 解析字节流——DSH 侧没有那条通道,所以这里直接实现 adapter:
|
|
9
|
+
*
|
|
10
|
+
* ```
|
|
11
|
+
* NativeZcodeStartPlanAdapter ← 推荐:账号池 / captcha / 切号 / 重试 全在本插件内
|
|
12
|
+
* PiAiZcodeStartPlanAdapter ← 可选:沿用 DSH 的 dsh-llm-pi-ai,本插件只做参数注入
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* pi-ai 适配器之所以能工作,是因为它只按「provider 名」路由:`llm-pi-ai` 的
|
|
16
|
+
* `providers` 配置里可以声明任意自定义 provider(`api: anthropic-messages` +
|
|
17
|
+
* `baseURL`),而本插件把自己暴露成 `127.0.0.1:<port>` 上的 Anthropic 兼容端点
|
|
18
|
+
* (`lib/local-endpoint.js`)。两条路共用同一套账号池与 captcha 产出器。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { AnthropicStreamTranslator } from './stream-translator.js'
|
|
22
|
+
import { ZCODE_FALLBACK_MODELS } from './upstream.js'
|
|
23
|
+
|
|
24
|
+
/** 从上游模型目录构造 DSH 的 `LlmModelInfo`。 */
|
|
25
|
+
export function toModelInfo(provider, model) {
|
|
26
|
+
const info = {
|
|
27
|
+
provider,
|
|
28
|
+
id: model.id,
|
|
29
|
+
name: model.name ?? model.id,
|
|
30
|
+
inputModalities: model.supportsImage === false ? ['text'] : ['text', 'image'],
|
|
31
|
+
context: { contextWindow: model.contextWindow ?? 1_000_000 },
|
|
32
|
+
defaultMaxTokens: model.maxTokens ?? 32_768,
|
|
33
|
+
}
|
|
34
|
+
if (Array.isArray(model.reasoningLevels) && model.reasoningLevels.length > 0) {
|
|
35
|
+
/**
|
|
36
|
+
* 思考档位。
|
|
37
|
+
*
|
|
38
|
+
* ⚠ 每个 effort **必须同时有非空 `id` 和非空 `name`**,且 `id` 不得重复 ——
|
|
39
|
+
* `dsh-llm` 的 `normalizeModelInfo` 会逐项校验,缺一个字段就抛
|
|
40
|
+
* `INVALID_MODEL_REASONING`("invalid or duplicate reasoning effort metadata"),
|
|
41
|
+
* 整个模型在宿主里不可用。
|
|
42
|
+
*
|
|
43
|
+
* `name` 用档位 id 的展示名(如 `low` → `Low`);`id` 原样透传,
|
|
44
|
+
* 因为 `plan-client` 发请求时按上游档位键取值。
|
|
45
|
+
*/
|
|
46
|
+
const efforts = []
|
|
47
|
+
const seen = new Set()
|
|
48
|
+
for (const level of model.reasoningLevels) {
|
|
49
|
+
const id = typeof level === 'string' ? level.trim() : ''
|
|
50
|
+
if (id.length === 0 || seen.has(id)) continue
|
|
51
|
+
seen.add(id)
|
|
52
|
+
efforts.push({ id, name: id.charAt(0).toUpperCase() + id.slice(1) })
|
|
53
|
+
}
|
|
54
|
+
if (efforts.length > 0) {
|
|
55
|
+
info.reasoning = {
|
|
56
|
+
efforts,
|
|
57
|
+
...(typeof model.defaultReasoningLevel === 'string' && model.defaultReasoningLevel.length > 0
|
|
58
|
+
? { defaultEffort: model.defaultReasoningLevel }
|
|
59
|
+
: {}),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return info
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const findModel = (models, id) => models.find((model) => model.id === id)
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 原生适配器:一次 `stream()` 就是一次 plan-client 调用 + 流翻译。
|
|
70
|
+
*
|
|
71
|
+
* 只实现 DSH `LlmAdapter` 契约里必需的方法(`providerInfo` / `listModels` /
|
|
72
|
+
* `resolveModel` / `stream`);不 `extends` 具体类,避免与宿主版本耦合。
|
|
73
|
+
*/
|
|
74
|
+
export class NativeZcodeStartPlanAdapter {
|
|
75
|
+
#client
|
|
76
|
+
#models
|
|
77
|
+
#provider
|
|
78
|
+
#displayName
|
|
79
|
+
#log
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {{
|
|
83
|
+
* client: import('./plan-client.js').ZcodePlanClient,
|
|
84
|
+
* models: () => Promise<Array<any>>,
|
|
85
|
+
* provider?: string,
|
|
86
|
+
* displayName?: string,
|
|
87
|
+
* log?: (message: string) => void,
|
|
88
|
+
* }} options
|
|
89
|
+
*/
|
|
90
|
+
constructor(options) {
|
|
91
|
+
this.#client = options.client
|
|
92
|
+
this.#models = options.models
|
|
93
|
+
this.#provider = options.provider ?? 'zcode-start-plan'
|
|
94
|
+
this.#displayName = options.displayName ?? 'ZCode Start Plan(赠送免费 plan)'
|
|
95
|
+
this.#log = options.log ?? (() => {})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
providerInfo(provider) {
|
|
99
|
+
return { id: provider, name: this.#displayName }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 重试策略。
|
|
104
|
+
*
|
|
105
|
+
* ⚠ **必须实现**:`ctx.llm.registerAdapter()` 在 `prepareRoutes` 里会**直接调用**
|
|
106
|
+
* `adapter.providerRetryPolicy(provider)`(没有可选调用保护),漏掉它在宿主里报
|
|
107
|
+
* `adapter.providerRetryPolicy is not a function`,整条路由注册失败 ——
|
|
108
|
+
* 表现为「工具注册成功、模型列表里却没有」。
|
|
109
|
+
*
|
|
110
|
+
* 返回 `undefined` 表示用宿主默认策略:本插件的重试已由
|
|
111
|
+
* `plan-client` 按上游错误表(3009 退避 / 3007 换 captcha / 3012 不重试)编排,
|
|
112
|
+
* 不需要宿主再包一层。
|
|
113
|
+
*
|
|
114
|
+
* @param {string} _provider
|
|
115
|
+
* @returns {undefined}
|
|
116
|
+
*/
|
|
117
|
+
providerRetryPolicy(_provider) {
|
|
118
|
+
return undefined
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async listModels(provider) {
|
|
122
|
+
return (await this.#models()).map((model) => toModelInfo(provider, model))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async resolveModel(provider, model) {
|
|
126
|
+
const found = findModel(await this.#models(), model)
|
|
127
|
+
if (found === undefined) return { provider, id: model, name: model }
|
|
128
|
+
return toModelInfo(provider, found)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 绑定「精确模型元数据」与「最终派发」。
|
|
133
|
+
*
|
|
134
|
+
* ⚠ **必须实现**:宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`。
|
|
135
|
+
* 基类 `LlmAdapter` 提供了默认实现,但本适配器**没有 extends 基类**(避免与宿主版本耦合),
|
|
136
|
+
* 所以必须自己补 —— 漏掉它表现为
|
|
137
|
+
* `registration.adapter.prepareCall is not a function`:**选模型即报错**。
|
|
138
|
+
*
|
|
139
|
+
* 语义(与宿主基类一致):返回的 `model` 是该模型的精确元数据,
|
|
140
|
+
* `stream` 是**同一次准备代际**的流入口。
|
|
141
|
+
*
|
|
142
|
+
* @param {string} provider
|
|
143
|
+
* @param {string} model
|
|
144
|
+
* @param {AbortSignal} [signal]
|
|
145
|
+
*/
|
|
146
|
+
async prepareCall(provider, model, signal) {
|
|
147
|
+
return {
|
|
148
|
+
model: await this.resolveModel(provider, model, signal),
|
|
149
|
+
stream: (options) => this.stream(options),
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 流式调用。
|
|
155
|
+
*
|
|
156
|
+
* ⚠ 失败以 **terminal `finish` 错误 chunk** 收尾(DSH 契约:每次流恰好一个终止 chunk),
|
|
157
|
+
* 而不是抛异常 —— 抛异常会让 agent-loop 把整步标成插件崩溃。
|
|
158
|
+
*
|
|
159
|
+
* @param {any} options DSH GenerateOptions
|
|
160
|
+
*/
|
|
161
|
+
stream(options) {
|
|
162
|
+
const adapter = this
|
|
163
|
+
return (async function* () {
|
|
164
|
+
const provider = options.provider ?? adapter.#provider
|
|
165
|
+
const translator = new AnthropicStreamTranslator()
|
|
166
|
+
let failure
|
|
167
|
+
try {
|
|
168
|
+
const resolved = findModel(await adapter.#models(), options.model)
|
|
169
|
+
const result = await adapter.#client.call({
|
|
170
|
+
options: { ...options, provider },
|
|
171
|
+
model: resolved,
|
|
172
|
+
maxTokens: options.maxTokens,
|
|
173
|
+
signal: options.signal,
|
|
174
|
+
onRetry: (info) => adapter.#log(`[zcode] 重试(${info.reason},第 ${info.attempt + 1} 次):${info.message}`),
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
/** ① 先消费判定阶段缓冲的事件(含首个内容帧),② 再接续剩余流。 */
|
|
178
|
+
for (const event of result.head) {
|
|
179
|
+
for (const chunk of translator.push(event)) yield chunk
|
|
180
|
+
}
|
|
181
|
+
if (result.decoder !== undefined) {
|
|
182
|
+
for (;;) {
|
|
183
|
+
const next = await result.decoder.read()
|
|
184
|
+
if (next.done === true) break
|
|
185
|
+
for (const chunk of translator.push(next.value)) yield chunk
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} catch (error) {
|
|
189
|
+
failure = {
|
|
190
|
+
code: error?.code ?? 'PROVIDER_ERROR',
|
|
191
|
+
message: error instanceof Error ? error.message : String(error),
|
|
192
|
+
}
|
|
193
|
+
adapter.#log(`[zcode] 调用失败(${failure.code}):${failure.message}`)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (failure !== undefined) {
|
|
197
|
+
yield { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }
|
|
198
|
+
yield { type: 'finish', kind: 'error', failure }
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
if (translator.error !== undefined) {
|
|
202
|
+
for (const chunk of translator.finish()) yield chunk
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
for (const chunk of translator.finish()) yield chunk
|
|
206
|
+
})()
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* pi-ai 回落适配器:只提供 provider 元数据,真正的 wire 由 `dsh-llm-pi-ai` 负责。
|
|
212
|
+
*
|
|
213
|
+
* 使用条件:profile 里同时启用 `llm-pi-ai`,并给它声明本插件暴露的 provider:
|
|
214
|
+
*
|
|
215
|
+
* ```yaml
|
|
216
|
+
* - id: llm-pi-ai
|
|
217
|
+
* name: '@deepseek-ai/dsh-llm-pi-ai'
|
|
218
|
+
* config:
|
|
219
|
+
* providers:
|
|
220
|
+
* zcode-start-plan:
|
|
221
|
+
* displayName: ZCode Start Plan
|
|
222
|
+
* api: anthropic-messages
|
|
223
|
+
* baseURL: http://127.0.0.1:17899
|
|
224
|
+
* apiKeyEnv: ZCODE_START_PLAN_LOCAL_TOKEN
|
|
225
|
+
* models: [{ id: GLM-5.3-Flash, name: GLM-5.3-Flash }]
|
|
226
|
+
* ```
|
|
227
|
+
*
|
|
228
|
+
* ⚠ 选它就意味着**放弃**本插件的切号/自动 captcha(那些在原生适配器里),
|
|
229
|
+
* 只保留「本地端点 + captcha 产出」;默认配置里它是关的。
|
|
230
|
+
*/
|
|
231
|
+
export class PiAiZcodeStartPlanAdapter {
|
|
232
|
+
#models
|
|
233
|
+
#displayName
|
|
234
|
+
|
|
235
|
+
constructor(options) {
|
|
236
|
+
this.#models = options.models
|
|
237
|
+
this.#displayName = options.displayName ?? 'ZCode Start Plan(pi-ai 路由)'
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
providerInfo(provider) {
|
|
241
|
+
return { id: provider, name: this.#displayName }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 重试策略。
|
|
246
|
+
*
|
|
247
|
+
* ⚠ **必须实现**:`ctx.llm.registerAdapter()` 在 `prepareRoutes` 里会**直接调用**
|
|
248
|
+
* `adapter.providerRetryPolicy(provider)`(没有可选调用保护),漏掉它在宿主里报
|
|
249
|
+
* `adapter.providerRetryPolicy is not a function`,整条路由注册失败 ——
|
|
250
|
+
* 表现为「工具注册成功、模型列表里却没有」。
|
|
251
|
+
*
|
|
252
|
+
* 返回 `undefined` 表示用宿主默认策略:本插件的重试已由
|
|
253
|
+
* `plan-client` 按上游错误表(3009 退避 / 3007 换 captcha / 3012 不重试)编排,
|
|
254
|
+
* 不需要宿主再包一层。
|
|
255
|
+
*
|
|
256
|
+
* @param {string} _provider
|
|
257
|
+
* @returns {undefined}
|
|
258
|
+
*/
|
|
259
|
+
providerRetryPolicy(_provider) {
|
|
260
|
+
return undefined
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async listModels(provider) {
|
|
264
|
+
return (await this.#models()).map((model) => toModelInfo(provider, model))
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* 绑定「精确模型元数据」与「最终派发」。
|
|
269
|
+
*
|
|
270
|
+
* ⚠ 必须实现:宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`;
|
|
271
|
+
* 漏掉它表现为 `registration.adapter.prepareCall is not a function`(选模型即报错)。
|
|
272
|
+
* 本回落适配器不自己发流(由 `dsh-llm-pi-ai` 负责),故 `stream` 交回宿主默认路径。
|
|
273
|
+
*
|
|
274
|
+
* @param {string} provider
|
|
275
|
+
* @param {string} model
|
|
276
|
+
* @param {AbortSignal} [signal]
|
|
277
|
+
*/
|
|
278
|
+
async prepareCall(provider, model, signal) {
|
|
279
|
+
const found = findModel(await this.#models(), model)
|
|
280
|
+
const resolved = found === undefined ? { provider, id: model, name: model } : toModelInfo(provider, found)
|
|
281
|
+
return { model: resolved, stream: undefined }
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 兜底模型表。 */
|
|
286
|
+
export { ZCODE_FALLBACK_MODELS }
|