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.
@@ -0,0 +1,304 @@
1
+ /**
2
+ * 请求体组装:把 DSH 的 `GenerateOptions`(provider-neutral 词汇)翻成
3
+ * zcode-plan 端点要求的 Anthropic Messages 形态。
4
+ *
5
+ * ## 三道准入闸门(缺一即 3012 / 3007,且 3012 有账号冷却惩罚)
6
+ *
7
+ * 1. **官方身份块**:`system` 必须以官方身份块结构**开头**(cliPrefix + stable 段),
8
+ * 否则 `3012 unusual activity`。实测矩阵:无 system → 3012;只有 cliPrefix → 3012;
9
+ * cliPrefix + stable → 200。判据是「身份块是否存在」,与 HTTP 头 / 运行时无关。
10
+ * 调用方(DSH)的 system 内容**追加在最后**,不得前置。
11
+ * 2. **首轮日期块**:第一条 user 消息的 content **数组**最前面插一个
12
+ * `<system-reminder>` 日期块(纯文本 content 会被转成块数组)。幂等:已以此开头则跳过。
13
+ * 3. **tools 缓存断点**:只在**最后一个** tool 上打 `cache_control` —— Anthropic 缓存是
14
+ * 前缀式的,一个断点即覆盖 system + 全部 tools;单请求最多 4 个断点。
15
+ */
16
+
17
+ /**
18
+ * 第一块:CLI 身份前缀(官方以此开头,42 字符)。
19
+ * ⚠ 不要"优化"这段文本:上游的准入检查看的是前缀结构。
20
+ */
21
+ export const OFFICIAL_CLI_PREFIX = 'You are ZCode, an interactive coding agent'
22
+
23
+ /**
24
+ * 第二块:stable 段(多段用 `\n\n` 连接)。
25
+ *
26
+ * ⚠ 只发**准入必需**的部分。官方完整身份块还含 ~5KB 的 dynamic 段
27
+ * (`# Communicating with the user` / `# Context management`),那是给壳内
28
+ * coding agent 的行为指令,与准入无关,且会被放在 system 开头**压过**调用方的
29
+ * prompt(表现为「啰嗦、慢」)—— 所以这里刻意不发。
30
+ */
31
+ export const OFFICIAL_STABLE_SECTIONS = Object.freeze([
32
+ '\nYou are an interactive ZCode agent that helps users with software engineering tasks.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n- Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n- Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don\'t retry verbatim.\n- The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.\n- Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n- Reference code as `file_path:line_number` — it\'s clickable.',
33
+ '# ZCode Desktop Context\n\n### Files & URLs\n- Return local web URLs as Markdown links (e.g., [label](http://127.0.0.1:8080)).\n- File should be an absolute path or include the workspace folder segment so it can be resolved relative to the workspace.\n- Unless otherwise specified, return local file references as Markdown links (e.g., [name.md](/absolute/path/to/name.md)).\n\n### Inline Code Comments\n- Use the ::code-comment{...} directive when you need to attach feedback directly to specific code lines.\n- Emit one directive per inline comment; emit none when there are no actionable inline comments.\n- Required attributes: title (short label), body (one-paragraph explanation), file (path to the file).\n- Optional attributes: start, end (1-based line numbers), priority (0-3).\n- file should be an absolute path or include the workspace folder segment so it can be resolved relative to the workspace.\n- Keep line ranges tight; end defaults to start.\n- Example: ::code-comment{title="[P2] Off-by-one" body="Loop iterates past the end when length is 0." file="/path/to/foo.ts" start=10 end=11 priority=2}',
34
+ '# Working style\n\nWhen you have enough information to act, act. Do not re-derive facts already established in the conversation, re-litigate a decision the user has already made, or narrate options you will not pursue. If you are weighing a choice, give a recommendation, not an exhaustive survey. Prefer reading the actual file or running the actual command over reasoning about what it probably contains. When a signal pattern-matches to a known failure, check that the evidence actually supports that specific diagnosis before acting on it.',
35
+ ])
36
+
37
+ /** `<system-reminder>` 日期块的固定文案(官方逐字)。 */
38
+ const CONTEXT_PREFIX_INTRO = "As you answer the user's questions, you can use the following context:"
39
+
40
+ /** 结尾段(⚠ 前有 **6 个空格**缩进,官方逐字如此)。 */
41
+ const CONTEXT_PREFIX_OUTRO =
42
+ ' IMPORTANT: this context may or may not be relevant to your tasks. ' +
43
+ 'You should not respond to this context unless it is highly relevant to your task.'
44
+
45
+ /** 本地时区的 ISO 日期(官方用本地日期,**不是** UTC)。 */
46
+ export function formatLocalIsoDate(date = new Date()) {
47
+ const pad = (value) => String(value).padStart(2, '0')
48
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
49
+ }
50
+
51
+ /** 构造 `<system-reminder>` 上下文块(整块是**一个** text 块)。 */
52
+ export function buildContextPrefixBlock(now = new Date()) {
53
+ const body = [
54
+ CONTEXT_PREFIX_INTRO,
55
+ `# currentDate\nToday's date is ${formatLocalIsoDate(now)}.`,
56
+ '',
57
+ CONTEXT_PREFIX_OUTRO,
58
+ ].join('\n')
59
+ return { type: 'text', text: `<system-reminder>${body}</system-reminder>` }
60
+ }
61
+
62
+ /** 判断一条消息的 content 是否已经以日期块开头(幂等判据)。 */
63
+ function startsWithSystemReminder(content) {
64
+ if (typeof content === 'string') return content.startsWith('<system-reminder>')
65
+ if (Array.isArray(content)) {
66
+ const first = content[0]
67
+ return typeof first?.text === 'string' && first.text.startsWith('<system-reminder>')
68
+ }
69
+ return false
70
+ }
71
+
72
+ /**
73
+ * 给**首轮 user 消息**的 content 数组最前面插入日期块。
74
+ *
75
+ * 规则(官方行为):只处理第一条消息且必须是 user;幂等;纯文本 content 转块数组。
76
+ */
77
+ export function withContextPrefix(messages, now = new Date()) {
78
+ const out = messages.map((message) => ({ ...message }))
79
+ const first = out[0]
80
+ if (first === undefined || first.role !== 'user') return out
81
+ if (startsWithSystemReminder(first.content)) return out
82
+
83
+ const prefix = buildContextPrefixBlock(now)
84
+ if (Array.isArray(first.content)) first.content = [prefix, ...first.content]
85
+ else if (typeof first.content === 'string') first.content = [prefix, { type: 'text', text: first.content }]
86
+ else first.content = [prefix]
87
+ return out
88
+ }
89
+
90
+ /** # Environment 段。 */
91
+ export function buildEnvironmentSection(options) {
92
+ const cwd = typeof options.cwd === 'string' && options.cwd.trim().length > 0 ? options.cwd : '.'
93
+ const provider = options.provider ?? 'zcode'
94
+ const model = options.model ?? 'glm-5.3-flash'
95
+ const platform = options.platform ?? process.platform
96
+ return [
97
+ '# Environment',
98
+ 'You have been invoked in the following environment:',
99
+ ` - Primary working directory: ${cwd}`,
100
+ ` - Platform: ${platform}`,
101
+ ` - Shell: ${platform === 'win32' ? 'powershell' : 'bash'}`,
102
+ ` - You are powered by the model named ${provider}/${model}.`,
103
+ ].join('\n')
104
+ }
105
+
106
+ /**
107
+ * 构造官方形态的 system 块数组。
108
+ *
109
+ * 结构(逐字复刻官方,**不要优化**):
110
+ * block[0] = cliPrefix ← 准入必需
111
+ * block[1] = stable ← 准入必需
112
+ * block[2] = # Environment
113
+ * block[3..] = 调用方 system(追加在最后)
114
+ *
115
+ * ⚠ 只在**最后一块**打 cache_control(前缀式缓存,一个断点覆盖面最大)。
116
+ */
117
+ export function buildZcodeSystemBlocks(callerSystem, options = {}) {
118
+ const stable = OFFICIAL_STABLE_SECTIONS.join('\n\n')
119
+ const blocks = [
120
+ { type: 'text', text: OFFICIAL_CLI_PREFIX },
121
+ { type: 'text', text: stable },
122
+ { type: 'text', text: buildEnvironmentSection(options) },
123
+ ]
124
+ if (typeof callerSystem === 'string' && callerSystem.trim().length > 0) {
125
+ blocks.push({ type: 'text', text: callerSystem })
126
+ }
127
+ const last = blocks[blocks.length - 1]
128
+ if (last !== undefined) last.cache_control = { type: 'ephemeral' }
129
+ return blocks
130
+ }
131
+
132
+ /** 把任意形态的 system 归一成块数组(Anthropic 允许字符串或块数组)。 */
133
+ export function normalizeSystem(system) {
134
+ if (typeof system === 'string') {
135
+ return system.trim().length > 0 ? [{ type: 'text', text: system }] : []
136
+ }
137
+ if (!Array.isArray(system)) return []
138
+ const blocks = []
139
+ for (const item of system) {
140
+ if (typeof item !== 'object' || item === null) continue
141
+ if (item.type !== 'text' || typeof item.text !== 'string') continue
142
+ const block = { type: 'text', text: item.text }
143
+ if (item.cache_control?.type === 'ephemeral') block.cache_control = { type: 'ephemeral' }
144
+ blocks.push(block)
145
+ }
146
+ return blocks
147
+ }
148
+
149
+ /** 给工具表的**最后一个**工具打缓存断点。 */
150
+ export function withToolCacheBreakpoint(tools) {
151
+ if (!Array.isArray(tools) || tools.length === 0) return []
152
+ return tools.map((tool, index) =>
153
+ index === tools.length - 1 ? { ...tool, cache_control: { type: 'ephemeral' } } : { ...tool },
154
+ )
155
+ }
156
+
157
+ /**
158
+ * DSH 工具定义 → Anthropic 工具声明。
159
+ *
160
+ * @param {readonly any[]} tools DSH 的 ToolDefinition 列表
161
+ * @returns {Array<any>}
162
+ */
163
+ export function convertTools(tools) {
164
+ if (!Array.isArray(tools) || tools.length === 0) return []
165
+ const out = []
166
+ for (const tool of tools) {
167
+ if (typeof tool?.name !== 'string' || typeof tool?.parameters !== 'object' || tool.parameters === null) continue
168
+ const schema = { ...tool.parameters }
169
+ /** Anthropic 要求顶层 type=object;DSH 的 schema 本来就满足,缺失时补上。 */
170
+ if (schema.type === undefined) schema.type = 'object'
171
+ /** Anthropic 不接受 `$schema` 之类的键。 */
172
+ delete schema['$schema']
173
+ delete schema['additionalProperties']
174
+ out.push({
175
+ name: tool.name,
176
+ ...(typeof tool.description === 'string' && tool.description.length > 0 ? { description: tool.description } : {}),
177
+ input_schema: schema,
178
+ })
179
+ }
180
+ return withToolCacheBreakpoint(out)
181
+ }
182
+
183
+ /** DSH 保存的是原始 JSON 字符串;Anthropic tool_use.input 要求对象。 */
184
+ function parseToolArguments(raw) {
185
+ if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) return raw
186
+ if (typeof raw !== 'string' || raw.length === 0) return {}
187
+ try {
188
+ const value = JSON.parse(raw)
189
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}
190
+ } catch {
191
+ return {}
192
+ }
193
+ }
194
+
195
+ /**
196
+ * DSH content blocks → Anthropic content blocks。
197
+ *
198
+ * 支持 text / image / tool-call / tool-result;
199
+ * 其余块(file 等)在 DSH 侧已被投影成文本或占位,这里保守丢弃并记一条提示。
200
+ *
201
+ * @param {readonly any[]} blocks
202
+ * @param {{ supportsImages?: boolean }} [options]
203
+ * @returns {Array<any>}
204
+ */
205
+ export function convertContent(blocks, options = {}) {
206
+ if (typeof blocks === 'string') return [{ type: 'text', text: blocks }]
207
+ if (!Array.isArray(blocks)) return []
208
+ const out = []
209
+ for (const block of blocks) {
210
+ if (block === null || typeof block !== 'object') continue
211
+ switch (block.type) {
212
+ case 'text':
213
+ if (typeof block.text === 'string' && block.text.length > 0) out.push({ type: 'text', text: block.text })
214
+ break
215
+ case 'image': {
216
+ if (options.supportsImages === false) {
217
+ out.push({ type: 'text', text: '[image omitted: this model does not accept image input]' })
218
+ break
219
+ }
220
+ const source = block.source
221
+ if (source?.type === 'base64' && typeof source.data === 'string') {
222
+ out.push({
223
+ type: 'image',
224
+ source: { type: 'base64', media_type: source.media_type ?? 'image/png', data: source.data },
225
+ })
226
+ } else if (source?.type === 'url' && typeof source.url === 'string') {
227
+ out.push({ type: 'image', source: { type: 'url', url: source.url } })
228
+ }
229
+ break
230
+ }
231
+ case 'tool-call':
232
+ out.push({
233
+ type: 'tool_use',
234
+ id: block.id ?? `toolu_${Math.random().toString(36).slice(2)}`,
235
+ name: block.name,
236
+ input: parseToolArguments(block.arguments ?? block.args),
237
+ })
238
+ break
239
+ case 'tool-result':
240
+ out.push({
241
+ type: 'tool_result',
242
+ tool_use_id: block.toolCallId ?? block.id,
243
+ content:
244
+ typeof block.output === 'string'
245
+ ? block.output
246
+ : JSON.stringify(block.output ?? block.content ?? ''),
247
+ ...(block.isError === true ? { is_error: true } : {}),
248
+ })
249
+ break
250
+ case 'thinking':
251
+ case 'reasoning':
252
+ /** 不向历史回放思考块:上游不接受无签名的 thinking。 */
253
+ break
254
+ default:
255
+ break
256
+ }
257
+ }
258
+ return out
259
+ }
260
+
261
+ /**
262
+ * 把 DSH 的 `GenerateOptions` 组装成上游请求体(**纯函数**)。
263
+ *
264
+ * @param {{
265
+ * options: any,
266
+ * cwd?: string,
267
+ * provider?: string,
268
+ * now?: Date,
269
+ * maxTokens?: number,
270
+ * supportsImages?: boolean,
271
+ * }} input
272
+ * @returns {Record<string, unknown>}
273
+ */
274
+ export function buildUpstreamBody(input) {
275
+ const options = input.options
276
+ const model = options.model
277
+ const callerBlocks = normalizeSystem(options.system)
278
+ const callerText = callerBlocks.map((block) => block.text).join('\n\n')
279
+
280
+ const messages = (Array.isArray(options.messages) ? options.messages : [])
281
+ .filter((message) => message?.role !== 'system')
282
+ .map((message) => ({
283
+ role: message.role === 'assistant' ? 'assistant' : 'user',
284
+ content: convertContent(message.content, { supportsImages: input.supportsImages }),
285
+ }))
286
+ .filter((message) => message.content.length > 0)
287
+
288
+ const body = {
289
+ model,
290
+ max_tokens: input.maxTokens ?? 32_768,
291
+ stream: true,
292
+ system: buildZcodeSystemBlocks(callerText.length > 0 ? callerText : undefined, {
293
+ cwd: input.cwd ?? '.',
294
+ provider: input.provider ?? 'zcode',
295
+ model,
296
+ }),
297
+ messages: withContextPrefix(messages, input.now ?? new Date()),
298
+ }
299
+
300
+ const tools = convertTools(options.tools)
301
+ if (tools.length > 0) body.tools = tools
302
+ if (typeof options.temperature === 'number') body.temperature = options.temperature
303
+ return body
304
+ }
@@ -0,0 +1,309 @@
1
+ /**
2
+ * 把 `apply` 里「异步就绪 + 注册 + 释放」这三件事收在一处。
3
+ *
4
+ * 拆出来的原因:`ctx.effect` 的回调必须是**同步**的(disposer 由 effect 持有),
5
+ * 而账号库打开(`node:sqlite` 动态 import)和本地端点监听都是异步的。
6
+ * 所以这里用「一次性的 `ctx.on('dispose')` + 惰性就绪」组合,而不是在
7
+ * 异步函数里调 `ctx.effect`(那样拿到的是未挂到 fiber 的注册,热重载后不会被撤销)。
8
+ */
9
+
10
+ import { SqliteStore, AccountPool, resolveDbFile, resolveDataDir } from './pool.js'
11
+ import { CaptchaMinter } from './captcha/minter.js'
12
+ import { ZcodePlanClient } from './plan-client.js'
13
+ import { NativeZcodeStartPlanAdapter } from './adapter.js'
14
+ import { startLocalEndpoint, resolveEndpointToken, resolvePort } from './local-endpoint.js'
15
+ import { fetchBalance, fetchCaptchaConfig, fetchModels } from './upstream-api.js'
16
+ import { ZCODE_FALLBACK_MODELS } from './upstream.js'
17
+ import { makeManageRoutes } from './manage-routes.js'
18
+
19
+ /**
20
+ * 装配并返回运行时句柄。
21
+ *
22
+ * @param {import('@deepseek-ai/cordis').Context} ctx
23
+ * @param {any} config 已解析的配置
24
+ * @param {{ log: (message: string) => void, warn: (message: string) => void }} logger
25
+ */
26
+ export function assemble(ctx, config, logger) {
27
+ const { log, warn } = logger
28
+ const dataDir = config.dataDir.trim().length > 0 ? config.dataDir.trim() : resolveDataDir(process.env)
29
+
30
+ /** 资源句柄(由 `dispose` 统一释放)。 */
31
+ const runtime = {
32
+ pool: undefined,
33
+ store: undefined,
34
+ minter: undefined,
35
+ client: undefined,
36
+ endpoint: undefined,
37
+ ready: false,
38
+ /** 适配器是否真的注册上了(状态工具据此报「为什么模型列表里没有」)。 */
39
+ adapterRegistered: false,
40
+ /** 最近一次致命错误(初始化 / 注册 / 加载)。 */
41
+ error: undefined,
42
+ }
43
+
44
+ /** 模型目录缓存(拉上游一次,失败回退到 config.models + 兜底表)。 */
45
+ let modelsCache = { at: 0, value: undefined }
46
+ const loadModels = async () => {
47
+ if (modelsCache.value !== undefined && Date.now() - modelsCache.at < config.modelCacheMs) {
48
+ return modelsCache.value
49
+ }
50
+ const fallback = config.models.map((id) => {
51
+ const known = ZCODE_FALLBACK_MODELS.find((model) => model.id === id)
52
+ return known ?? { id, name: id, contextWindow: 1_000_000, maxTokens: 32_768, supportsImage: true }
53
+ })
54
+ try {
55
+ const first = runtime.pool?.list({ withCredentials: true })[0]
56
+ if (first?.credential !== undefined) {
57
+ const remote = await fetchModels(first.credential)
58
+ if (remote !== undefined) {
59
+ const filtered = remote.filter((model) => config.models.includes(model.id))
60
+ const picked = filtered.length > 0 ? filtered : remote
61
+ modelsCache = { at: Date.now(), value: picked }
62
+ return picked
63
+ }
64
+ }
65
+ } catch (error) {
66
+ warn(`拉取模型目录失败(用本地兜底表):${error instanceof Error ? error.message : String(error)}`)
67
+ }
68
+ modelsCache = { at: Date.now(), value: fallback }
69
+ return fallback
70
+ }
71
+
72
+ const dispose = async () => {
73
+ try {
74
+ runtime.minter?.dispose()
75
+ } catch {
76
+ // 已释放。
77
+ }
78
+ try {
79
+ await runtime.endpoint?.close()
80
+ } catch {
81
+ // 已关闭。
82
+ }
83
+ try {
84
+ runtime.store?.close()
85
+ } catch {
86
+ // 已关闭。
87
+ }
88
+ }
89
+
90
+ /** 异步初始化(只做「建资源」,不注册任何 fiber 内对象)。 */
91
+ const init = async () => {
92
+ /**
93
+ * ⚠ 用 `dataDir` 解析库路径(而不是只读 `process.env`):`config.dataDir` 必须真的
94
+ * 决定落盘位置,否则测试/多实例会读写用户的**真实账号库**(本仓库的 apply 单测
95
+ * 就因此读到了真实登录的账号,导致断言随环境漂移)。
96
+ */
97
+ const dbFile = resolveDbFile(process.env, dataDir)
98
+ runtime.store = await new SqliteStore(dbFile)
99
+ if (runtime.store.inMemory === true) {
100
+ warn(
101
+ '账号库落盘失败(目录不可写 / 被占用),已降级为**内存库**:' +
102
+ '本次运行内可用,但重启后账号会消失。请用 config.dataDir 指到一个可写目录,' +
103
+ '或设环境变量 ZCODE_START_PLAN_DATA_DIR。原因:' +
104
+ `${runtime.store.mkdirError instanceof Error ? runtime.store.mkdirError.message : '未知'}`,
105
+ )
106
+ }
107
+ runtime.pool = new AccountPool({ store: runtime.store, log })
108
+ runtime.pool.sweepExpired()
109
+
110
+ runtime.minter = new CaptchaMinter({
111
+ debugPort: config.captcha.debugPort,
112
+ origin: config.captcha.origin,
113
+ log,
114
+ })
115
+ /** plan 客户端通过这个钩子拉服务端下发的 captcha 配置(60s TTL 在客户端里)。 */
116
+ runtime.minter.fetchConfig = (credential) => fetchCaptchaConfig(credential)
117
+
118
+ runtime.client = new ZcodePlanClient({
119
+ pool: runtime.pool,
120
+ minter: runtime.minter,
121
+ log,
122
+ })
123
+
124
+ if (config.endpoint.enabled === true) {
125
+ try {
126
+ const token = resolveEndpointToken(dataDir, process.env)
127
+ runtime.endpoint = await startLocalEndpoint({
128
+ port: resolvePort(config.endpoint.port),
129
+ token,
130
+ planClient: runtime.client,
131
+ models: loadModels,
132
+ log,
133
+ })
134
+ log(`本地端点就绪:${runtime.endpoint.baseUrl}(pi-ai 路线的 baseURL / apiKey)`)
135
+ } catch (error) {
136
+ warn(`本地端点启动失败(pi-ai 回落路线不可用):${error instanceof Error ? error.message : String(error)}`)
137
+ }
138
+ }
139
+ runtime.ready = true
140
+ log(`账号库:${dbFile}(${runtime.pool.list().length} 个账号)`)
141
+ return runtime
142
+ }
143
+
144
+ /**
145
+ * 注册 DSH 的扩展点(**同步**),返回可撤销的 cleanup。
146
+ *
147
+ * 官方标准:`apply` 内每个资源都用 `ctx.effect` / `ctx.on` 注册并交出 cleanup。
148
+ * 这里把「适配器 + 状态工具 + 定期清理」打成**一个** effect,返回的 disposer
149
+ * 会按反序释放它们 —— 这样插件被禁用/热重载时不会留下悬挂的 llm 路由。
150
+ *
151
+ * ⚠ 两条硬约束(都是「插件加载了但模型列表里没有」的直接成因):
152
+ * 1. `ctx.effect` 缺失时**直接注册**,不能整体放弃;
153
+ * 2. `ctx.llm` 此刻可能还没就绪 → 退到 `ctx.inject(['llm'])` 等它出现;
154
+ * 两者都不可用时把原因写进 `runtime.error`,让状态工具报出来。
155
+ */
156
+ const register = () => {
157
+ /** 已登记的撤销函数(反序执行)。 */
158
+ const undos = []
159
+ const addUndo = (undo) => {
160
+ if (typeof undo === 'function' && undo !== ctx) undos.push(undo)
161
+ }
162
+
163
+ const doRegister = () => {
164
+ /** ① llm 适配器路由。 */
165
+ const adapter = new NativeZcodeStartPlanAdapter({
166
+ client: runtime.client,
167
+ models: loadModels,
168
+ provider: config.provider,
169
+ displayName: config.displayName,
170
+ log,
171
+ })
172
+ try {
173
+ addUndo(ctx.llm.registerAdapter([config.provider], adapter))
174
+ runtime.adapterRegistered = true
175
+ log(`llm 路由已注册:${config.provider}(模型:${config.models.join(', ')})`)
176
+ } catch (error) {
177
+ runtime.error = `注册 llm 路由失败:${error instanceof Error ? error.message : String(error)}`
178
+ warn(`${runtime.error}(可能与其他适配器重名);本插件降级为仅提供状态工具。`)
179
+ }
180
+
181
+ /** ② 状态工具。 */
182
+ if (config.statusTool === true && ctx.tools !== undefined) {
183
+ addUndo(registerStatusTool(ctx, runtime, config, loadModels))
184
+ }
185
+
186
+ /** ③ 每小时清一次过期的「账号×模型」限流标记(免费额度按自然日结算)。 */
187
+ /**
188
+ * ⚠ 沙箱里**没有** `ctx.setInterval`(宿主禁掉了 Node 定时器),
189
+ * 必须用 `ctx.timer.interval` —— 且 `timer` 要先在 `inject` 里声明。
190
+ * 这是本插件「加载了却不工作」的根因之一。
191
+ */
192
+ if (ctx.timer !== undefined && typeof ctx.timer.interval === 'function') {
193
+ addUndo(ctx.timer.interval(() => runtime.pool?.sweepExpired(), 60 * 60_000))
194
+ } else {
195
+ warn('timer 服务不可用,跳过每小时限流清理(限流标记仍会在每次请求时自然过期)')
196
+ }
197
+
198
+ /** ④ 账号池管理路由(Web UI 用;webServer 未就绪时跳过,不影响其它功能)。 */
199
+ if (typeof ctx.webServer?.register === 'function' && runtime.pool !== undefined) {
200
+ try {
201
+ const routes = makeManageRoutes({
202
+ pool: runtime.pool,
203
+ fetchBalance: (credential) => fetchBalance(credential),
204
+ log,
205
+ })
206
+ for (const route of routes) addUndo(ctx.webServer.register(route))
207
+ log(`管理路由已注册:${routes.length} 条(/api/zcode-start-plan/*)`)
208
+ } catch (error) {
209
+ warn(`管理路由注册失败(Web UI 不可用,其它功能不受影响):${error instanceof Error ? error.message : String(error)}`)
210
+ }
211
+ }
212
+ }
213
+
214
+ /**
215
+ * `inject: ['llm', …]` 已保证 `ctx.llm` 就绪后才 apply,
216
+ * 所以这里直接注册即可;保留一个兜底分支应对宿主延迟挂载的情况。
217
+ * ⚠ 沙箱 façade 上没有 `ctx.inject`,不能用它做兜底。
218
+ */
219
+ if (ctx.llm !== undefined) {
220
+ doRegister()
221
+ } else {
222
+ runtime.error = 'llm 服务尚未就绪(inject 已声明,但 apply 时仍不可用)。'
223
+ warn(runtime.error)
224
+ }
225
+
226
+ /** 返回 cleanup:反序撤销。 */
227
+ return () => {
228
+ for (const undo of undos.splice(0).reverse()) {
229
+ try {
230
+ undo()
231
+ } catch (error) {
232
+ warn(`撤销注册失败:${error instanceof Error ? error.message : String(error)}`)
233
+ }
234
+ }
235
+ }
236
+ }
237
+
238
+ return { runtime, init, register, dispose, loadModels, dataDir }
239
+ }
240
+
241
+ /**
242
+ * 状态工具(模型可见):账号数 / 模型 / captcha 观测 / 本地端点。
243
+ *
244
+ * 刻意**不**返回凭据、token 或任何可用于登录的秘密 —— 只给可诊断的元数据。
245
+ */
246
+ export function registerStatusTool(ctx, runtime, config, loadModels) {
247
+ const tool = {
248
+ name: 'zcode_start_plan_status',
249
+ description:
250
+ 'Return the ZCode free-plan channel status for this DSH profile: registered provider route, models, ' +
251
+ 'account pool size (no credentials), per-account rate-limit markers, and captcha availability. ' +
252
+ 'Use when a model call on the zcode-start-plan provider fails with QUOTA / AUTH / RATE_LIMIT.',
253
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
254
+ output: {
255
+ schema: { type: 'object', additionalProperties: true },
256
+ /**
257
+ * ⚠ 输出必须是**无损 JSON**:宿主会校验 `JSON.parse(text)` 再与原值深比较,
258
+ * 带缩进的 `JSON.stringify(value, null, 2)` 会被判 `value is not lossless JSON`
259
+ * 而拒绝整个工具结果。故用紧凑序列化。
260
+ */
261
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
262
+ },
263
+ async execute() {
264
+ /**
265
+ * ⚠ 返回值里**不能有 `undefined`**:`JSON.stringify` 会直接丢掉这些键,
266
+ * 宿主拿 `JSON.parse(text)` 与原值深比较时会判定「不是无损 JSON」而拒绝整个结果。
267
+ * 故缺省值一律用 `null`。
268
+ */
269
+ const accounts = (runtime.pool?.list() ?? []).map((entry, index) => ({
270
+ index: index + 1,
271
+ id: entry.id,
272
+ nickname: entry.nickname,
273
+ enabled: entry.enabled,
274
+ userIdTail: typeof entry.user_id === 'string' ? entry.user_id.slice(-6) : null,
275
+ limitedModels: Object.keys(entry.model_rate_limits ?? {}),
276
+ lastError: entry.last_error ?? null,
277
+ }))
278
+ const captionProbe =
279
+ runtime.minter === undefined ? { ok: false, reason: 'captcha 产出器未初始化' } : await runtime.minter.probe()
280
+ return {
281
+ provider: config.provider,
282
+ displayName: config.displayName,
283
+ models: (await loadModels()).map((model) => model.id),
284
+ accountCount: accounts.length,
285
+ enabledAccountCount: accounts.filter((entry) => entry.enabled).length,
286
+ accounts,
287
+ captcha: {
288
+ mode: config.captcha.mode,
289
+ debugPort: config.captcha.debugPort,
290
+ reachable: captionProbe.ok,
291
+ reason: captionProbe.reason ?? null,
292
+ ...(runtime.client?.observability?.() ?? {}),
293
+ },
294
+ endpoint: runtime.endpoint === undefined ? null : { baseUrl: runtime.endpoint.baseUrl, port: runtime.endpoint.port },
295
+ /** 诊断字段:模型没出现在选择器里时,先看这两个。 */
296
+ adapterRegistered: runtime.adapterRegistered === true,
297
+ error: runtime.error ?? null,
298
+ }
299
+ },
300
+ }
301
+ /**
302
+ * 返回 disposer(官方标准:注册即交出 cleanup)。
303
+ * 有 `ctx.effect` 时由它托管;没有时把 `register()` 的撤销函数原样交出去。
304
+ */
305
+ if (typeof ctx.effect === 'function') {
306
+ return ctx.effect(() => ctx.tools.register(tool))
307
+ }
308
+ return ctx.tools.register(tool)
309
+ }