@xiangyixie/dsh-superagent 0.14.1 → 0.14.3

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/lib/wizard.js ADDED
@@ -0,0 +1,1498 @@
1
+ /**
2
+ * First-use wizard for the conversation console.
3
+ *
4
+ * Everything here is written for a user who has never opened a terminal:
5
+ * environment checks explain themselves, the API key is verified against the
6
+ * real endpoint before anything is written, and the profile patch is edited
7
+ * with a backup that can be restored from the page. The module never returns,
8
+ * logs, or puts an API key into a file under the repository; it is handed to
9
+ * the host's credential store and the configuration only names the reference.
10
+ *
11
+ * The patch editor intentionally understands just the two entries the wizard
12
+ * owns (`llm-pi-ai` and `agent-default-model`). It edits those in place and
13
+ * leaves every other line, comment, and entry untouched.
14
+ *
15
+ * @module dsh-superagent/wizard
16
+ */
17
+ import { randomBytes, randomUUID } from 'node:crypto'
18
+ import { constants as fsConstants } from 'node:fs'
19
+ import fsp from 'node:fs/promises'
20
+ import os from 'node:os'
21
+ import path from 'node:path'
22
+ import { computeCost, formatMoney } from './cost.js'
23
+ import { WorkbenchError } from './workbench.js'
24
+
25
+ export const WIZARD_DEFAULTS = Object.freeze({
26
+ provider: 'haoduo',
27
+ baseURL: 'https://byte.haoduotoken.com/v1',
28
+ model: 'gpt-6.1-sol',
29
+ })
30
+
31
+ const META_FILE = 'wizard.json'
32
+ const BACKUP_DIR = path.join('wizard', 'backups')
33
+ const BACKUP_LIMIT = 10
34
+ const PROBE_TIMEOUT_MS = 8_000
35
+ const TRIAL_TIMEOUT_MS = 120_000
36
+ const TRIAL_FILE = 'wizard-trial.txt'
37
+ const TRIAL_PROMPT = [
38
+ '这是一次安装自检。请只在这个临时目录里操作,不要访问其他目录:',
39
+ `1. 创建文件 ${TRIAL_FILE},内容写 ok;`,
40
+ '2. 读回这个文件,确认内容。',
41
+ '做完后用一句话说明结果。',
42
+ ].join('\n')
43
+
44
+ /** @param {unknown} value @returns {string} */
45
+ function messageOf(value) {
46
+ return value instanceof Error ? value.message : String(value)
47
+ }
48
+
49
+ function contentText(content) {
50
+ if (typeof content === 'string') return content
51
+ if (!Array.isArray(content)) return ''
52
+ return content
53
+ .filter(part => part && part.type === 'text' && typeof part.text === 'string')
54
+ .map(part => part.text)
55
+ .join('')
56
+ }
57
+
58
+ function summarizeArgs(value) {
59
+ if (value === undefined || value === null) return ''
60
+ let text
61
+ if (typeof value === 'string') text = value
62
+ else {
63
+ try {
64
+ text = JSON.stringify(value)
65
+ } catch {
66
+ text = String(value)
67
+ }
68
+ }
69
+ return text.replace(/\s+/g, ' ').trim().slice(0, 180)
70
+ }
71
+
72
+ /** A reference name is a POSIX shell identifier, matching the host seam. */
73
+ export function credentialRefFor(provider) {
74
+ const name = String(provider ?? '')
75
+ .trim()
76
+ .toUpperCase()
77
+ .replace(/[^A-Z0-9]+/g, '_')
78
+ .replace(/^_+|_+$/g, '')
79
+ return `${name || 'PROVIDER'}_API_KEY`
80
+ }
81
+
82
+ /** Only ever show a short mask; the stored value is never read back. */
83
+ export function maskKey(value) {
84
+ const text = String(value ?? '')
85
+ if (!text) return null
86
+ if (text.length <= 8) return '••••'
87
+ return `${text.slice(0, 3)}…${text.slice(-4)}`
88
+ }
89
+
90
+ function normalizeProvider(value) {
91
+ const raw = String(value ?? '').trim().toLowerCase()
92
+ if (!raw) return WIZARD_DEFAULTS.provider
93
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(raw)) {
94
+ throw new WorkbenchError(400, '提供商名只能包含小写字母、数字和短横线,并以字母开头。', {
95
+ id: 'bad-provider',
96
+ hint: '例如 haoduo、openai、my-gateway。',
97
+ })
98
+ }
99
+ return raw
100
+ }
101
+
102
+ function normalizeBaseURL(value) {
103
+ const raw = String(value ?? '').trim()
104
+ if (!raw) {
105
+ throw new WorkbenchError(400, 'baseURL 不能为空。', {
106
+ id: 'bad-base-url',
107
+ hint: 'OpenAI 兼容端点通常形如 https://example.com/v1。',
108
+ })
109
+ }
110
+ let parsed
111
+ try {
112
+ parsed = new URL(raw)
113
+ } catch {
114
+ throw new WorkbenchError(400, 'baseURL 不是合法的网址。', {
115
+ id: 'bad-base-url',
116
+ hint: '需要以 http:// 或 https:// 开头,例如 https://byte.haoduotoken.com/v1。',
117
+ })
118
+ }
119
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
120
+ throw new WorkbenchError(400, 'baseURL 只支持 http 或 https。', { id: 'bad-base-url' })
121
+ }
122
+ if (parsed.username || parsed.password) {
123
+ throw new WorkbenchError(400, 'baseURL 里不能带用户名或密码。', {
124
+ id: 'bad-base-url',
125
+ hint: 'API key 请填在 key 输入框里,它会被存到宿主凭据库。',
126
+ })
127
+ }
128
+ return raw.replace(/\/+$/, '')
129
+ }
130
+
131
+ function normalizeInput(input = {}) {
132
+ const model = String(input.model ?? '').trim()
133
+ if (!model) {
134
+ throw new WorkbenchError(400, '模型名不能为空。', {
135
+ id: 'bad-model',
136
+ hint: '填提供商控制台里显示的模型 id,例如 gpt-6.1-sol。',
137
+ })
138
+ }
139
+ if (model.length > 200) {
140
+ throw new WorkbenchError(400, '模型名太长了。', { id: 'bad-model' })
141
+ }
142
+ const provider = normalizeProvider(input.provider)
143
+ return {
144
+ provider,
145
+ baseURL: normalizeBaseURL(input.baseURL),
146
+ model,
147
+ apiKey: typeof input.apiKey === 'string' ? input.apiKey.trim() : '',
148
+ }
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // Small line-based YAML editor for the two profile entries the wizard owns.
153
+ // ---------------------------------------------------------------------------
154
+
155
+ function indentOf(line) {
156
+ return line.length - line.trimStart().length
157
+ }
158
+
159
+ function unquote(value) {
160
+ const text = String(value ?? '').trim()
161
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) {
162
+ try {
163
+ return JSON.parse(text)
164
+ } catch {
165
+ return text.slice(1, -1)
166
+ }
167
+ }
168
+ if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) {
169
+ return text.slice(1, -1).replace(/''/g, "'")
170
+ }
171
+ return text
172
+ }
173
+
174
+ function yamlScalar(value) {
175
+ const text = String(value)
176
+ return /^[A-Za-z0-9._/@+-]+$/.test(text) ? text : JSON.stringify(text)
177
+ }
178
+
179
+ function entryBlocks(lines) {
180
+ const starts = []
181
+ for (let index = 0; index < lines.length; index++) {
182
+ if (/^-\s/.test(lines[index])) starts.push(index)
183
+ }
184
+ return starts.map((start, position) => ({ start, end: starts[position + 1] ?? lines.length }))
185
+ }
186
+
187
+ function findEntry(lines, id) {
188
+ for (const block of entryBlocks(lines)) {
189
+ const match = /^-\s+id:\s*(.+?)\s*$/.exec(lines[block.start])
190
+ if (match && unquote(match[1]) === id) return block
191
+ }
192
+ return null
193
+ }
194
+
195
+ function sectionEnd(lines, headerIndex, limit, indent) {
196
+ for (let index = headerIndex + 1; index < limit; index++) {
197
+ if (!lines[index].trim()) continue
198
+ if (indentOf(lines[index]) <= indent) return index
199
+ }
200
+ return limit
201
+ }
202
+
203
+ function findChild(lines, start, end, indent, key) {
204
+ const pattern = new RegExp(`^ {${indent}}${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:\\s*(.*)$`)
205
+ for (let index = start; index < end; index++) {
206
+ const match = pattern.exec(lines[index])
207
+ if (match) return { index, value: unquote(match[1]) }
208
+ }
209
+ return null
210
+ }
211
+
212
+ function trimInsertion(lines, start, end) {
213
+ let at = end
214
+ while (at > start + 1 && !lines[at - 1].trim()) at -= 1
215
+ return at
216
+ }
217
+
218
+ function replaceScalar(line, key, value) {
219
+ const pattern = new RegExp(`^(\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:\\s*)(.*?)(\\s+#.*)?$`)
220
+ const match = pattern.exec(line)
221
+ if (!match) return `${' '.repeat(indentOf(line))}${key}: ${yamlScalar(value)}`
222
+ return `${match[1]}${yamlScalar(value)}${match[3] ?? ''}`
223
+ }
224
+
225
+ function setChild(lines, start, end, indent, key, value, { keepExisting = false, beforeKey = null } = {}) {
226
+ const found = findChild(lines, start, end, indent, key)
227
+ if (found) {
228
+ if (!keepExisting && found.value !== String(value)) {
229
+ lines[found.index] = replaceScalar(lines[found.index], key, value)
230
+ }
231
+ return false
232
+ }
233
+ const before = beforeKey ? findChild(lines, start, end, indent, beforeKey) : null
234
+ const at = before ? before.index : trimInsertion(lines, start, end)
235
+ lines.splice(at, 0, `${' '.repeat(indent)}${key}: ${yamlScalar(value)}`)
236
+ return true
237
+ }
238
+
239
+ function findProviderBlock(lines, entry, provider) {
240
+ const providers = findChild(lines, entry.start, entry.end, 4, 'providers')
241
+ if (!providers) return null
242
+ const providersEnd = sectionEnd(lines, providers.index, entry.end, 4)
243
+ for (let index = providers.index + 1; index < providersEnd; index++) {
244
+ if (!lines[index].trim()) continue
245
+ if (indentOf(lines[index]) !== 6) continue
246
+ const match = /^ {6}([A-Za-z0-9._-]+):\s*(?:#.*)?$/.exec(lines[index])
247
+ if (!match || unquote(match[1]) !== provider) continue
248
+ let end = providersEnd
249
+ for (let next = index + 1; next < providersEnd; next++) {
250
+ if (lines[next].trim() && indentOf(lines[next]) <= 6) {
251
+ end = next
252
+ break
253
+ }
254
+ }
255
+ return { start: index, end }
256
+ }
257
+ return null
258
+ }
259
+
260
+ function providerBlockLines(provider, { ref, baseURL, model }) {
261
+ return [
262
+ ` ${provider}:`,
263
+ ` apiKeyEnv: ${yamlScalar(ref)}`,
264
+ ` displayName: ${yamlScalar(provider)}`,
265
+ ' api: openai-completions',
266
+ ` baseURL: ${yamlScalar(baseURL)}`,
267
+ ' models:',
268
+ ` - id: ${yamlScalar(model)}`,
269
+ ]
270
+ }
271
+
272
+ function ensureEntry(lines, id) {
273
+ const found = findEntry(lines, id)
274
+ if (found) return { entry: found, created: false }
275
+ if (lines.length > 0 && lines[lines.length - 1].trim()) lines.push('')
276
+ const start = lines.length
277
+ lines.push(`- id: ${id}`)
278
+ return { entry: { start, end: lines.length }, created: true }
279
+ }
280
+
281
+ function ensureConfig(lines, id) {
282
+ let entry = findEntry(lines, id)
283
+ const existing = findChild(lines, entry.start, entry.end, 2, 'config')
284
+ if (existing) return { entry, config: existing }
285
+ lines.splice(entry.start + 1, 0, ' config:')
286
+ entry = findEntry(lines, id)
287
+ return { entry, config: findChild(lines, entry.start, entry.end, 2, 'config') }
288
+ }
289
+
290
+ function ensureProviders(lines, id) {
291
+ const ensured = ensureConfig(lines, id)
292
+ const configEnd = sectionEnd(lines, ensured.config.index, ensured.entry.end, 2)
293
+ const existing = findChild(lines, ensured.config.index, configEnd, 4, 'providers')
294
+ if (existing) return { entry: ensured.entry, providers: existing }
295
+ const at = trimInsertion(lines, ensured.config.index, configEnd)
296
+ lines.splice(at, 0, ' providers:')
297
+ const entry = findEntry(lines, id)
298
+ return { entry, providers: findChild(lines, entry.start, entry.end, 4, 'providers') }
299
+ }
300
+
301
+ /**
302
+ * Merge the wizard's provider and default-model settings into one patch text.
303
+ *
304
+ * @param {string} text - current `cordis.patch.yml`, or an empty string.
305
+ * @param {object} input - normalized `{ provider, baseURL, model }`.
306
+ * @returns {{ text: string, changes: object, summary: string[], previous: object | null }}
307
+ */
308
+ export function mergeWizardPatch(text, input) {
309
+ const lines = String(text ?? '').replace(/\r\n/g, '\n').split('\n')
310
+ const ref = credentialRefFor(input.provider)
311
+ const changes = {
312
+ createdEntries: [],
313
+ createdProvider: false,
314
+ addedModel: false,
315
+ previousDefault: null,
316
+ defaultChanged: false,
317
+ }
318
+
319
+ const llmEntry = findEntry(lines, 'llm-pi-ai')
320
+ const previous = readDefaultModelFromLines(lines)
321
+ changes.previousDefault = previous
322
+
323
+ const createdLlm = llmEntry === null
324
+ const created = ensureEntry(lines, 'llm-pi-ai')
325
+ if (createdLlm) changes.createdEntries.push('llm-pi-ai')
326
+ if (createdLlm) {
327
+ const ensured = ensureProviders(lines, 'llm-pi-ai')
328
+ const providersEnd = sectionEnd(lines, ensured.providers.index, ensured.entry.end, 4)
329
+ const at = trimInsertion(lines, ensured.providers.index, providersEnd)
330
+ lines.splice(at, 0, ...providerBlockLines(input.provider, { ref, baseURL: input.baseURL, model: input.model }))
331
+ changes.createdProvider = true
332
+ changes.addedModel = true
333
+ } else {
334
+ const entry = created.entry
335
+ const existing = findProviderBlock(lines, entry, input.provider)
336
+ if (!existing) {
337
+ const ensured = ensureProviders(lines, 'llm-pi-ai')
338
+ const providersEnd = sectionEnd(lines, ensured.providers.index, ensured.entry.end, 4)
339
+ const at = trimInsertion(lines, ensured.providers.index, providersEnd)
340
+ lines.splice(at, 0, ...providerBlockLines(input.provider, { ref, baseURL: input.baseURL, model: input.model }))
341
+ changes.createdProvider = true
342
+ changes.addedModel = true
343
+ } else {
344
+ // Re-find after every insertion: the line array shifts under us.
345
+ for (const [key, value, options] of [
346
+ ['apiKeyEnv', ref, {}],
347
+ ['displayName', input.provider, { keepExisting: true }],
348
+ ['api', 'openai-completions', { keepExisting: true }],
349
+ ['baseURL', input.baseURL, {}],
350
+ ]) {
351
+ const block = findProviderBlock(lines, findEntry(lines, 'llm-pi-ai'), input.provider)
352
+ setChild(lines, block.start, block.end, 8, key, value, { beforeKey: 'models', ...options })
353
+ }
354
+ let block = findProviderBlock(lines, findEntry(lines, 'llm-pi-ai'), input.provider)
355
+ let models = findChild(lines, block.start, block.end, 8, 'models')
356
+ if (!models) {
357
+ const at = trimInsertion(lines, block.start, block.end)
358
+ lines.splice(at, 0, ' models:')
359
+ block = findProviderBlock(lines, findEntry(lines, 'llm-pi-ai'), input.provider)
360
+ models = findChild(lines, block.start, block.end, 8, 'models')
361
+ }
362
+ const modelsEnd = sectionEnd(lines, models.index, block.end, 8)
363
+ const hasModel = lines
364
+ .slice(models.index + 1, modelsEnd)
365
+ .some(line => /^\s+-\s+id:\s*/.test(line) && unquote(line.replace(/^\s+-\s+id:\s*/, '')) === input.model)
366
+ if (!hasModel) {
367
+ const at = trimInsertion(lines, models.index, modelsEnd)
368
+ lines.splice(at, 0, ` - id: ${yamlScalar(input.model)}`)
369
+ changes.addedModel = true
370
+ }
371
+ }
372
+ }
373
+
374
+ const defaultEntry = findEntry(lines, 'agent-default-model')
375
+ if (!defaultEntry) {
376
+ changes.createdEntries.push('agent-default-model')
377
+ if (lines.length > 0 && lines[lines.length - 1].trim()) lines.push('')
378
+ lines.push('- id: agent-default-model', ' config:', ` provider: ${yamlScalar(input.provider)}`, ` model: ${yamlScalar(input.model)}`)
379
+ } else {
380
+ const ensured = ensureConfig(lines, 'agent-default-model')
381
+ const configEnd = sectionEnd(lines, ensured.config.index, ensured.entry.end, 2)
382
+ setChild(lines, ensured.config.index, configEnd, 4, 'provider', input.provider)
383
+ const afterProvider = ensureConfig(lines, 'agent-default-model')
384
+ setChild(
385
+ lines,
386
+ afterProvider.config.index,
387
+ sectionEnd(lines, afterProvider.config.index, afterProvider.entry.end, 2),
388
+ 4,
389
+ 'model',
390
+ input.model,
391
+ )
392
+ }
393
+
394
+ changes.defaultChanged = !previous
395
+ || previous.provider !== input.provider
396
+ || previous.model !== input.model
397
+
398
+ const summary = summarizeMerge(input, changes, ref)
399
+ const merged = lines.join('\n')
400
+ return {
401
+ text: merged.endsWith('\n') ? merged : `${merged}\n`,
402
+ changes,
403
+ summary,
404
+ previous,
405
+ }
406
+ }
407
+
408
+ function readDefaultModelFromLines(lines) {
409
+ const entry = findEntry(lines, 'agent-default-model')
410
+ if (!entry) return null
411
+ const config = findChild(lines, entry.start, entry.end, 2, 'config')
412
+ if (!config) return null
413
+ const configEnd = sectionEnd(lines, config.index, entry.end, 2)
414
+ const provider = findChild(lines, config.index, configEnd, 4, 'provider')
415
+ const model = findChild(lines, config.index, configEnd, 4, 'model')
416
+ if (!provider?.value || !model?.value) return null
417
+ return { provider: provider.value, model: model.value }
418
+ }
419
+
420
+ /** Read the profile's current default model without exposing anything else. */
421
+ export function readDefaultModel(text) {
422
+ const lines = String(text ?? '').replace(/\r\n/g, '\n').split('\n')
423
+ return readDefaultModelFromLines(lines)
424
+ }
425
+
426
+ /** Read one provider route (`baseURL` and model ids) from a patch text. */
427
+ export function readProviderRoute(text, provider) {
428
+ const lines = String(text ?? '').replace(/\r\n/g, '\n').split('\n')
429
+ const entry = findEntry(lines, 'llm-pi-ai')
430
+ if (!entry) return null
431
+ const block = findProviderBlock(lines, entry, provider)
432
+ if (!block) return null
433
+ const baseURL = findChild(lines, block.start, block.end, 8, 'baseURL')?.value ?? null
434
+ const models = findChild(lines, block.start, block.end, 8, 'models')
435
+ const ids = []
436
+ if (models) {
437
+ const end = sectionEnd(lines, models.index, block.end, 8)
438
+ for (const line of lines.slice(models.index + 1, end)) {
439
+ const match = /^\s+-\s+id:\s*(.+?)\s*$/.exec(line)
440
+ if (match) ids.push(unquote(match[1]))
441
+ }
442
+ }
443
+ return { baseURL, models: ids }
444
+ }
445
+
446
+ function summarizeMerge(input, changes, ref) {
447
+ const summary = []
448
+ if (changes.createdEntries.includes('llm-pi-ai')) {
449
+ summary.push('新增 llm-pi-ai 配置段(OpenAI 兼容提供方)。')
450
+ }
451
+ if (changes.createdProvider) {
452
+ summary.push(`新增提供方 ${input.provider},地址 ${input.baseURL},模型 ${input.model}。`)
453
+ } else {
454
+ summary.push(`更新提供方 ${input.provider} 的地址与密钥引用${changes.addedModel ? `,并新增模型 ${input.model}` : ''}。`)
455
+ }
456
+ if (changes.previousDefault) {
457
+ const same = changes.previousDefault.provider === input.provider
458
+ && changes.previousDefault.model === input.model
459
+ summary.push(same
460
+ ? `默认模型保持 ${input.provider}/${input.model}。`
461
+ : `默认模型从 ${changes.previousDefault.provider}/${changes.previousDefault.model} 改为 ${input.provider}/${input.model}。`)
462
+ } else {
463
+ summary.push(`把默认模型设为 ${input.provider}/${input.model}。`)
464
+ }
465
+ summary.push(`密钥写入宿主凭据库,配置里只出现引用名 ${ref}。`)
466
+ summary.push('保留文件里其余条目和注释;写入前自动备份。')
467
+ return summary
468
+ }
469
+
470
+ // ---------------------------------------------------------------------------
471
+ // Wizard implementation
472
+ // ---------------------------------------------------------------------------
473
+
474
+ /**
475
+ * Create the first-use wizard.
476
+ *
477
+ * @param {object} options - dependencies.
478
+ * @param {string} options.stateRoot - plugin state directory (holds meta + backups).
479
+ * @param {string} options.version - plugin version.
480
+ * @param {() => object | null} [options.getProfile] - host `profileContext`.
481
+ * @param {() => object | undefined} [options.getCredentials] - host credential seam.
482
+ * @param {() => object | null} [options.getDefaultModel] - current host model selection.
483
+ * @param {() => object | null} [options.getSessionController] - host session service.
484
+ * @param {(sessionId: string) => Promise<object[] | null>} [options.listTools] - session tools.
485
+ * @param {object} [options.pricing] - plugin price table.
486
+ * @param {typeof fetch} [options.fetchImpl] - injectable fetch for tests.
487
+ * @param {(message: string) => void} [options.log] - diagnostics sink.
488
+ */
489
+ export function createWizard({
490
+ stateRoot,
491
+ version,
492
+ getProfile = () => null,
493
+ getCredentials = () => undefined,
494
+ getDefaultModel = () => null,
495
+ getSessionController = () => null,
496
+ listTools = async () => null,
497
+ pricing = {},
498
+ fetchImpl = fetch,
499
+ log = () => {},
500
+ } = {}) {
501
+ if (!stateRoot) throw new Error('createWizard needs a stateRoot')
502
+ const metaPath = path.join(stateRoot, META_FILE)
503
+ const backupRoot = path.join(stateRoot, BACKUP_DIR)
504
+ let writeQueue = Promise.resolve()
505
+ let trialInFlight = null
506
+
507
+ function serialize(task) {
508
+ const run = writeQueue.then(task, task)
509
+ writeQueue = run.then(() => {}, () => {})
510
+ return run
511
+ }
512
+
513
+ async function readMeta() {
514
+ try {
515
+ const parsed = JSON.parse(await fsp.readFile(metaPath, 'utf8'))
516
+ if (parsed && typeof parsed === 'object' && parsed.version === 1) return parsed
517
+ } catch {
518
+ // A missing or damaged sidecar is not an error: the wizard can rebuild it.
519
+ }
520
+ return { version: 1, backups: [] }
521
+ }
522
+
523
+ async function writeMeta(meta) {
524
+ await fsp.mkdir(stateRoot, { recursive: true })
525
+ const tmp = `${metaPath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
526
+ await fsp.writeFile(tmp, `${JSON.stringify(meta, null, 2)}\n`, { mode: 0o600 })
527
+ await fsp.rename(tmp, metaPath)
528
+ try {
529
+ await fsp.chmod(metaPath, 0o600)
530
+ } catch {
531
+ // Windows ignores most mode bits; the file's ACL still applies.
532
+ }
533
+ }
534
+
535
+ function profileInfo() {
536
+ let profile = null
537
+ try {
538
+ profile = getProfile?.() ?? null
539
+ } catch (error) {
540
+ return {
541
+ ok: false,
542
+ reason: `读取 profile 位置失败:${messageOf(error)}`,
543
+ name: null,
544
+ dir: null,
545
+ patchPath: null,
546
+ }
547
+ }
548
+ const dir = typeof profile?.dir === 'string' && profile.dir ? profile.dir : null
549
+ if (!dir) {
550
+ return {
551
+ ok: false,
552
+ reason: '宿主没有提供 profileContext,向导不知道要把配置写到哪里。',
553
+ name: null,
554
+ dir: null,
555
+ patchPath: null,
556
+ }
557
+ }
558
+ return {
559
+ ok: true,
560
+ reason: null,
561
+ name: typeof profile.name === 'string' ? profile.name : path.basename(dir),
562
+ dir,
563
+ patchPath: typeof profile.patchPath === 'string' && profile.patchPath
564
+ ? profile.patchPath
565
+ : path.join(dir, 'cordis.patch.yml'),
566
+ }
567
+ }
568
+
569
+ async function readPatch(info) {
570
+ try {
571
+ return await fsp.readFile(info.patchPath, 'utf8')
572
+ } catch (error) {
573
+ if (error?.code === 'ENOENT') return ''
574
+ throw error
575
+ }
576
+ }
577
+
578
+ async function patchWritable(info) {
579
+ try {
580
+ await fsp.access(info.patchPath, fsConstants.W_OK)
581
+ return { ok: true, reason: null }
582
+ } catch (error) {
583
+ if (error?.code !== 'ENOENT') {
584
+ return { ok: false, reason: `${info.patchPath} 不可写:${messageOf(error)}` }
585
+ }
586
+ try {
587
+ await fsp.access(info.dir, fsConstants.W_OK)
588
+ return { ok: true, reason: null }
589
+ } catch (inner) {
590
+ return { ok: false, reason: `${info.dir} 不可写:${messageOf(inner)}` }
591
+ }
592
+ }
593
+ }
594
+
595
+ async function writeAtomic(file, text) {
596
+ await fsp.mkdir(path.dirname(file), { recursive: true })
597
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`)
598
+ let handle
599
+ try {
600
+ handle = await fsp.open(tmp, 'w', 0o600)
601
+ await handle.writeFile(text, 'utf8')
602
+ await handle.sync?.()
603
+ } finally {
604
+ await handle?.close()
605
+ }
606
+ try {
607
+ await fsp.rename(tmp, file)
608
+ } catch (error) {
609
+ await fsp.unlink(tmp).catch(() => {})
610
+ throw error
611
+ }
612
+ }
613
+
614
+ async function ensureBackupDir() {
615
+ await fsp.mkdir(backupRoot, { recursive: true })
616
+ }
617
+
618
+ function backupId(now) {
619
+ const stamp = now.toISOString().replace(/[-:T]/g, '').slice(0, 14)
620
+ return `${stamp}-${randomBytes(3).toString('hex')}`
621
+ }
622
+
623
+ async function saveBackup(info, text, summary, now) {
624
+ await ensureBackupDir()
625
+ const id = backupId(now)
626
+ const file = path.join(backupRoot, `${id}.yml`)
627
+ await fsp.writeFile(file, text, 'utf8')
628
+ try {
629
+ await fsp.chmod(file, 0o600)
630
+ } catch {
631
+ // See writeMeta.
632
+ }
633
+ return {
634
+ id,
635
+ file,
636
+ createdAt: now.toISOString(),
637
+ patchPath: info.patchPath,
638
+ summary: summary.slice(0, 6),
639
+ }
640
+ }
641
+
642
+ async function pruneBackups(meta) {
643
+ const keep = meta.backups.slice(0, BACKUP_LIMIT)
644
+ const drop = meta.backups.slice(BACKUP_LIMIT)
645
+ meta.backups = keep
646
+ for (const entry of drop) {
647
+ if (entry?.file) await fsp.unlink(entry.file).catch(() => {})
648
+ }
649
+ }
650
+
651
+ function credentialService() {
652
+ let service
653
+ try {
654
+ service = getCredentials?.()
655
+ } catch {
656
+ service = undefined
657
+ }
658
+ return service && typeof service.set === 'function' ? service : null
659
+ }
660
+
661
+ async function describeRef(ref) {
662
+ const service = credentialService()
663
+ if (!service) return { configured: false, writable: false, source: null, available: false }
664
+ try {
665
+ const info = await service.describe(ref)
666
+ return {
667
+ configured: info?.configured === true,
668
+ writable: info?.writable === true,
669
+ source: info?.source ?? null,
670
+ available: true,
671
+ }
672
+ } catch (error) {
673
+ return { configured: false, writable: false, source: null, available: false, reason: messageOf(error) }
674
+ }
675
+ }
676
+
677
+ async function resolveRef(ref) {
678
+ const service = credentialService()
679
+ if (!service || typeof service.resolve !== 'function') return null
680
+ try {
681
+ return (await service.resolve(ref))?.value ?? null
682
+ } catch {
683
+ return null
684
+ }
685
+ }
686
+
687
+ function networkError(error, baseURL) {
688
+ const code = error?.cause?.code ?? error?.code ?? ''
689
+ const host = (() => {
690
+ try {
691
+ return new URL(baseURL).host
692
+ } catch {
693
+ return baseURL
694
+ }
695
+ })()
696
+ if (error?.name === 'AbortError') {
697
+ return new WorkbenchError(422, `连接 ${host} 超过 ${PROBE_TIMEOUT_MS / 1000} 秒没有响应。`, {
698
+ id: 'base-timeout',
699
+ hint: '确认这个地址能从本机访问;公司网络或代理环境下,可能需要先配置代理。',
700
+ })
701
+ }
702
+ if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') {
703
+ return new WorkbenchError(422, `找不到 ${host}(域名解析失败)。`, {
704
+ id: 'base-unreachable',
705
+ hint: '检查 baseURL 的域名是否拼错,以及本机是否能正常上网。',
706
+ })
707
+ }
708
+ if (code === 'ECONNREFUSED') {
709
+ return new WorkbenchError(422, `连接 ${host} 被拒绝。`, {
710
+ id: 'base-unreachable',
711
+ hint: '检查 baseURL 的端口和协议(http/https),以及服务是否已经启动。',
712
+ })
713
+ }
714
+ if (String(code).startsWith('CERT_') || code === 'DEPTH_ZERO_SELF_SIGNED_CERT' || code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE') {
715
+ return new WorkbenchError(422, `连接 ${host} 时 TLS 证书校验失败。`, {
716
+ id: 'base-tls',
717
+ hint: '确认 baseURL 使用受信任的 https 证书;如果是内网自签名证书,需要先在系统里信任它。',
718
+ })
719
+ }
720
+ return new WorkbenchError(422, `连不上 ${host}(网络不通,或者地址写错了)。`, {
721
+ id: 'base-unreachable',
722
+ hint: '检查地址拼写、网络和代理设置。OpenAI 兼容端点通常以 /v1 结尾。',
723
+ })
724
+ }
725
+
726
+ function keyRejected(status) {
727
+ return new WorkbenchError(422, `API key 被端点拒绝(HTTP ${status})。`, {
728
+ id: 'key-rejected',
729
+ hint: '检查 key 是否复制完整、是否属于这个提供商;确认后重新粘贴。',
730
+ })
731
+ }
732
+
733
+ function modelMissing(model, ids) {
734
+ const examples = Array.isArray(ids) && ids.length > 0 ? ids.slice(0, 5).join('、') : ''
735
+ return new WorkbenchError(422, `端点里没有模型「${model}」。`, {
736
+ id: 'model-missing',
737
+ hint: examples
738
+ ? `可用的模型示例:${examples}。也可以去提供商控制台确认模型 id。`
739
+ : '检查模型名是否拼写正确,或先在提供商控制台确认这个模型已经开通。',
740
+ })
741
+ }
742
+
743
+ function httpFailure(status, detail) {
744
+ const suffix = detail ? ` 端点返回:${detail}` : ''
745
+ let hint = '查看提供商状态页,或确认 baseURL 指向一个 OpenAI 兼容接口。'
746
+ if (status === 429) hint = '请求太频繁,等几十秒再试。'
747
+ if (status >= 500) hint = '端点自己出错了,稍后重试;如果一直这样,换一个 baseURL 或联系提供商。'
748
+ return new WorkbenchError(422, `端点返回 HTTP ${status}。${suffix}`, { id: 'endpoint-http', hint })
749
+ }
750
+
751
+ async function fetchWithTimeout(url, options) {
752
+ const controller = new AbortController()
753
+ const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS)
754
+ timer.unref?.()
755
+ try {
756
+ return await fetchImpl(url, { ...options, signal: controller.signal })
757
+ } finally {
758
+ clearTimeout(timer)
759
+ }
760
+ }
761
+
762
+ async function snippet(response) {
763
+ try {
764
+ const text = (await response.text()).replace(/\s+/g, ' ').trim()
765
+ return text.slice(0, 200)
766
+ } catch {
767
+ return ''
768
+ }
769
+ }
770
+
771
+ /**
772
+ * Verify one route and its key without writing anything.
773
+ *
774
+ * `GET /models` answers all three failure modes cheaply. An endpoint that
775
+ * does not implement it falls back to a one-token chat completion, which is
776
+ * the only way left to distinguish "wrong path" from "unknown model".
777
+ */
778
+ async function probeRoute({ provider, baseURL, model, apiKey }) {
779
+ let modelsResponse
780
+ try {
781
+ modelsResponse = await fetchWithTimeout(`${baseURL}/models`, {
782
+ headers: { authorization: `Bearer ${apiKey}`, accept: 'application/json' },
783
+ })
784
+ } catch (error) {
785
+ throw networkError(error, baseURL)
786
+ }
787
+ if (modelsResponse.status === 401 || modelsResponse.status === 403) {
788
+ throw keyRejected(modelsResponse.status)
789
+ }
790
+ if (modelsResponse.ok) {
791
+ let document = null
792
+ try {
793
+ document = await modelsResponse.json()
794
+ } catch {
795
+ document = null
796
+ }
797
+ if (document) {
798
+ const ids = Array.isArray(document.data)
799
+ ? document.data.map(entry => entry?.id).filter(id => typeof id === 'string' && id)
800
+ : []
801
+ if (ids.length > 0) {
802
+ if (!ids.includes(model)) throw modelMissing(model, ids)
803
+ return { checked: 'models', models: ids.slice(0, 8), provider }
804
+ }
805
+ }
806
+ } else if (modelsResponse.status !== 404 && modelsResponse.status !== 405) {
807
+ throw httpFailure(modelsResponse.status, await snippet(modelsResponse))
808
+ }
809
+
810
+ let chatResponse
811
+ try {
812
+ chatResponse = await fetchWithTimeout(`${baseURL}/chat/completions`, {
813
+ method: 'POST',
814
+ headers: {
815
+ authorization: `Bearer ${apiKey}`,
816
+ 'content-type': 'application/json',
817
+ accept: 'application/json',
818
+ },
819
+ body: JSON.stringify({
820
+ model,
821
+ messages: [{ role: 'user', content: 'ping' }],
822
+ max_tokens: 4,
823
+ stream: false,
824
+ }),
825
+ })
826
+ } catch (error) {
827
+ throw networkError(error, baseURL)
828
+ }
829
+ if (chatResponse.ok) return { checked: 'chat', models: [], provider }
830
+ const detail = await snippet(chatResponse)
831
+ if (chatResponse.status === 401 || chatResponse.status === 403) throw keyRejected(chatResponse.status)
832
+ if (chatResponse.status === 404) {
833
+ throw new WorkbenchError(422, '在 baseURL 后面找不到 chat/completions 接口。', {
834
+ id: 'endpoint-invalid',
835
+ hint: 'OpenAI 兼容端点通常以 /v1 结尾,例如 https://example.com/v1;检查地址是否少了一段。',
836
+ })
837
+ }
838
+ if (chatResponse.status === 400 && /model/i.test(detail)) throw modelMissing(model, [])
839
+ throw httpFailure(chatResponse.status, detail)
840
+ }
841
+
842
+ function credentialRef(input, meta) {
843
+ if (meta?.provider === input.provider && typeof meta?.ref === 'string' && meta.ref) return meta.ref
844
+ return credentialRefFor(input.provider)
845
+ }
846
+
847
+ async function resolveApiKey(input, meta) {
848
+ if (input.apiKey) return { key: input.apiKey, source: 'input', ref: credentialRef(input, meta) }
849
+ const ref = credentialRef(input, meta)
850
+ const value = await resolveRef(ref)
851
+ if (!value) {
852
+ await describeRef(ref)
853
+ throw new WorkbenchError(422, '还没有可用的 API key。', {
854
+ id: 'missing-key',
855
+ hint: '在向导里填一次 key,再点“检查并预览”。它只会写进宿主凭据库。',
856
+ })
857
+ }
858
+ return { key: value, source: 'stored', ref }
859
+ }
860
+
861
+ /** Build the full plan, including the text that would be written. */
862
+ async function prepare(body) {
863
+ const input = normalizeInput(body)
864
+ const profile = profileInfo()
865
+ if (!profile.ok) {
866
+ throw new WorkbenchError(503, profile.reason, {
867
+ id: 'profile-unavailable',
868
+ hint: '确认宿主提供了 profileContext;这个向导不会猜配置文件的位置。',
869
+ })
870
+ }
871
+ const writable = await patchWritable(profile)
872
+ if (!writable.ok) {
873
+ throw new WorkbenchError(503, writable.reason, {
874
+ id: 'patch-readonly',
875
+ hint: '检查这个文件的权限,或把宿主换到当前用户可写的 profile。',
876
+ })
877
+ }
878
+ const meta = await readMeta()
879
+ const { key, source, ref } = await resolveApiKey(input, meta)
880
+ const probe = await probeRoute({ provider: input.provider, baseURL: input.baseURL, model: input.model, apiKey: key })
881
+ const before = await readPatch(profile)
882
+ const merged = mergeWizardPatch(before, input)
883
+ return {
884
+ input,
885
+ profile,
886
+ meta,
887
+ ref,
888
+ keySource: source,
889
+ keyMask: maskKey(key),
890
+ probe,
891
+ before,
892
+ merged,
893
+ }
894
+ }
895
+
896
+ function publicPlan(plan) {
897
+ return {
898
+ provider: plan.input.provider,
899
+ baseURL: plan.input.baseURL,
900
+ model: plan.input.model,
901
+ key: {
902
+ ref: plan.ref,
903
+ source: plan.keySource,
904
+ configured: true,
905
+ writable: credentialService() !== null,
906
+ mask: plan.keyMask ?? null,
907
+ verified: true,
908
+ checked: plan.probe.checked,
909
+ },
910
+ summary: plan.merged.summary,
911
+ changes: plan.merged.changes,
912
+ previous: plan.merged.previous,
913
+ target: {
914
+ profile: plan.profile.name,
915
+ patchPath: plan.profile.patchPath,
916
+ exists: plan.before.length > 0,
917
+ },
918
+ note: '密钥只写入宿主凭据库;页面不会显示完整值,日志里也不会出现。',
919
+ }
920
+ }
921
+
922
+ async function preview(body) {
923
+ const plan = await prepare(body)
924
+ return publicPlan(plan)
925
+ }
926
+
927
+ async function save(body) {
928
+ return serialize(async () => {
929
+ const plan = await prepare(body)
930
+ const service = credentialService()
931
+ if (!service) {
932
+ throw new WorkbenchError(503, '宿主没有提供凭据库,向导不会把 key 写进配置文件。', {
933
+ id: 'credentials-unavailable',
934
+ hint: '这个 profile 缺少 dsh-credentials;先启用它,或使用宿主的环境变量方式配置 key。',
935
+ })
936
+ }
937
+ const meta = plan.meta
938
+ const beforeHadKey = await describeRef(plan.ref)
939
+ let keyPersisted = null
940
+ try {
941
+ if (plan.input.apiKey) await service.set(plan.ref, plan.input.apiKey)
942
+ } catch (error) {
943
+ throw new WorkbenchError(503, `key 没能写入宿主凭据库:${messageOf(error)}`, {
944
+ id: 'credential-write-failed',
945
+ hint: '检查 $DSH_HOME 下的凭据存储是否可写,然后重试。',
946
+ })
947
+ }
948
+ if (plan.input.apiKey) {
949
+ const after = await describeRef(plan.ref)
950
+ // The managed store reports itself as `file`; environment layers use
951
+ // their own names (`env`, `project-env`, `user-env`).
952
+ keyPersisted = after.source === 'file'
953
+ }
954
+
955
+ const now = new Date()
956
+ let backup = null
957
+ let written = false
958
+ try {
959
+ backup = await saveBackup(plan.profile, plan.before, plan.merged.summary, now)
960
+ await writeAtomic(plan.profile.patchPath, plan.merged.text)
961
+ written = true
962
+ } catch (error) {
963
+ if (!written && backup) {
964
+ await writeAtomic(plan.profile.patchPath, plan.before).catch(() => {})
965
+ }
966
+ if (plan.input.apiKey && !beforeHadKey.configured) {
967
+ try {
968
+ await service.unset?.(plan.ref)
969
+ } catch {
970
+ // The old value is already gone; the failed write is what matters.
971
+ }
972
+ }
973
+ throw new WorkbenchError(500, `配置没有写成功:${messageOf(error)}`, {
974
+ id: 'patch-write-failed',
975
+ hint: '文件已按备份恢复(如果存在备份);稍后可以重试。',
976
+ })
977
+ }
978
+
979
+ meta.version = 1
980
+ meta.provider = plan.input.provider
981
+ meta.baseURL = plan.input.baseURL
982
+ meta.model = plan.input.model
983
+ meta.ref = plan.ref
984
+ if (plan.input.apiKey) meta.mask = maskKey(plan.input.apiKey)
985
+ meta.verifiedAt = now.toISOString()
986
+ meta.verification = {
987
+ provider: plan.input.provider,
988
+ baseURL: plan.input.baseURL,
989
+ model: plan.input.model,
990
+ ok: true,
991
+ checked: plan.probe.checked,
992
+ at: now.toISOString(),
993
+ }
994
+ meta.backups = Array.isArray(meta.backups) ? meta.backups : []
995
+ if (backup) meta.backups.unshift(backup)
996
+ await pruneBackups(meta)
997
+ await writeMeta(meta)
998
+
999
+ const view = publicPlan(plan)
1000
+ const modelLive = await waitForConfiguredModel()
1001
+ return {
1002
+ ...view,
1003
+ key: { ...view.key, persisted: keyPersisted },
1004
+ saved: true,
1005
+ backup: backup
1006
+ ? { id: backup.id, createdAt: backup.createdAt }
1007
+ : null,
1008
+ restartHint: modelLive
1009
+ ? null
1010
+ : '宿主还没切换到新模型。如果试跑时模型没变,重启宿主后再试一次。',
1011
+ }
1012
+ })
1013
+ }
1014
+
1015
+ async function rollback(id) {
1016
+ return serialize(async () => {
1017
+ const meta = await readMeta()
1018
+ const key = String(id ?? '').trim()
1019
+ if (!/^[0-9a-z-]+$/i.test(key)) {
1020
+ throw new WorkbenchError(400, '备份编号不合法。', { id: 'bad-backup-id' })
1021
+ }
1022
+ const entry = (meta.backups ?? []).find(item => item?.id === key)
1023
+ if (!entry) {
1024
+ throw new WorkbenchError(404, `找不到备份 ${key}。`, {
1025
+ id: 'unknown-backup',
1026
+ hint: '刷新页面看当前可用的备份;备份最多保留 10 份。',
1027
+ })
1028
+ }
1029
+ const profile = profileInfo()
1030
+ if (!profile.ok) throw new WorkbenchError(503, profile.reason, { id: 'profile-unavailable' })
1031
+ let text
1032
+ try {
1033
+ text = await fsp.readFile(entry.file, 'utf8')
1034
+ } catch (error) {
1035
+ throw new WorkbenchError(404, `备份文件读不到:${messageOf(error)}`, { id: 'backup-missing' })
1036
+ }
1037
+ try {
1038
+ await writeAtomic(profile.patchPath, text)
1039
+ } catch (error) {
1040
+ throw new WorkbenchError(500, `回滚没有写成功:${messageOf(error)}`, { id: 'rollback-failed' })
1041
+ }
1042
+ meta.lastRollbackAt = new Date().toISOString()
1043
+ meta.verification = null
1044
+ await writeMeta(meta)
1045
+ return {
1046
+ restored: true,
1047
+ id: key,
1048
+ patchPath: profile.patchPath,
1049
+ summary: '已恢复到写入前的配置。API key 仍留在宿主凭据库中;如需删除,请在凭据设置里移除。',
1050
+ }
1051
+ })
1052
+ }
1053
+
1054
+ async function trialStatusInfo(status, sessionId) {
1055
+ if (!sessionId) return { ok: false, value: '还没有会话', hint: '先在页面上完成初始化(或点“重新检查”)。' }
1056
+ if (typeof listTools !== 'function') return { ok: false, value: '宿主不能枚举工具', hint: null }
1057
+ try {
1058
+ const tools = await listTools(sessionId)
1059
+ if (!Array.isArray(tools)) return { ok: false, value: '读不到工具清单', hint: '宿主没有返回这个会话的工具。' }
1060
+ const names = tools.map(tool => tool?.name).filter(name => typeof name === 'string')
1061
+ const core = names.filter(name => /^(bash|pwsh|read|write|edit|glob|grep)$/.test(name))
1062
+ return {
1063
+ ok: names.length > 0,
1064
+ value: `${names.length} 个`,
1065
+ hint: core.length > 0 ? `含 ${core.slice(0, 4).join('、')}` : null,
1066
+ }
1067
+ } catch (error) {
1068
+ return { ok: false, value: '读取工具清单失败', hint: messageOf(error) }
1069
+ }
1070
+ }
1071
+
1072
+ async function status({ sessionId = null, probe = false } = {}) {
1073
+ const profile = profileInfo()
1074
+ const writable = profile.ok ? await patchWritable(profile) : { ok: false, reason: profile.reason }
1075
+ const meta = await readMeta()
1076
+ let patchText = ''
1077
+ if (profile.ok) {
1078
+ try {
1079
+ patchText = await readPatch(profile)
1080
+ } catch {
1081
+ patchText = ''
1082
+ }
1083
+ }
1084
+ const patchDefault = readDefaultModel(patchText)
1085
+ let hostModel = null
1086
+ try {
1087
+ const selection = getDefaultModel?.()
1088
+ if (selection && typeof selection === 'object') {
1089
+ hostModel = {
1090
+ provider: typeof selection.provider === 'string' ? selection.provider : null,
1091
+ model: typeof selection.model === 'string' ? selection.model : null,
1092
+ }
1093
+ }
1094
+ } catch {
1095
+ hostModel = null
1096
+ }
1097
+ // The form only reflects what the wizard layer controls: an explicit default
1098
+ // model in the patch, then the last thing the wizard saved, then the
1099
+ // documented defaults. A host-level default belongs in the status row, not
1100
+ // in a form that would then pair it with the wrong baseURL.
1101
+ const form = {
1102
+ provider: patchDefault?.provider ?? meta.provider ?? WIZARD_DEFAULTS.provider,
1103
+ model: patchDefault?.model ?? meta.model ?? WIZARD_DEFAULTS.model,
1104
+ baseURL: (patchDefault?.provider ? readProviderRoute(patchText, patchDefault.provider)?.baseURL : null)
1105
+ ?? meta.baseURL
1106
+ ?? WIZARD_DEFAULTS.baseURL,
1107
+ }
1108
+ const ref = credentialRefFor(form.provider)
1109
+ const keyInfo = await describeRef(ref)
1110
+ let keyMask = meta.ref === ref ? meta.mask ?? null : null
1111
+ if (!keyMask && keyInfo.configured) {
1112
+ const value = await resolveRef(ref)
1113
+ if (value) keyMask = maskKey(value)
1114
+ }
1115
+ const verification = meta.verification
1116
+ && meta.verification.provider === form.provider
1117
+ && meta.verification.model === form.model
1118
+ ? meta.verification
1119
+ : null
1120
+
1121
+ let liveVerification = null
1122
+ if (probe && keyInfo.configured) {
1123
+ const apiKey = await resolveRef(ref)
1124
+ if (apiKey) {
1125
+ try {
1126
+ const result = await probeRoute({ provider: form.provider, baseURL: form.baseURL, model: form.model, apiKey })
1127
+ liveVerification = { ok: true, at: new Date().toISOString(), checked: result.checked }
1128
+ } catch (error) {
1129
+ liveVerification = {
1130
+ ok: false,
1131
+ at: new Date().toISOString(),
1132
+ code: error?.id ?? 'probe-failed',
1133
+ message: messageOf(error),
1134
+ hint: error?.hint ?? null,
1135
+ }
1136
+ }
1137
+ if (liveVerification.ok) {
1138
+ meta.verification = { provider: form.provider, baseURL: form.baseURL, model: form.model, ...liveVerification }
1139
+ } else {
1140
+ meta.verification = { provider: form.provider, baseURL: form.baseURL, model: form.model, ...liveVerification }
1141
+ }
1142
+ meta.ref = ref
1143
+ if (!meta.provider) {
1144
+ meta.provider = form.provider
1145
+ meta.baseURL = form.baseURL
1146
+ meta.model = form.model
1147
+ }
1148
+ await writeMeta(meta).catch(() => {})
1149
+ } else {
1150
+ liveVerification = { ok: false, message: '凭据库里有记录,但读不出值。', hint: '重新填一次 key。' }
1151
+ }
1152
+ }
1153
+ const effectiveVerification = liveVerification ?? verification
1154
+ const toolInfo = await trialStatusInfo(status, sessionId)
1155
+ const modelOk = Boolean(form.provider && form.model)
1156
+ const modelWritten = Boolean(patchDefault?.provider && patchDefault?.model)
1157
+
1158
+ const environment = [
1159
+ {
1160
+ id: 'host',
1161
+ label: '宿主会话服务',
1162
+ ok: typeof getSessionController?.() === 'object' && getSessionController?.() !== null,
1163
+ value: getSessionController?.() ? '已就绪' : '不可用',
1164
+ hint: getSessionController?.() ? null : '这个宿主没有挂载 sessionController;需要一个带会话能力的 Web profile。',
1165
+ action: { kind: 'retry', label: '点这里处理' },
1166
+ },
1167
+ {
1168
+ id: 'plugin',
1169
+ label: '插件版本',
1170
+ ok: typeof version === 'string' && version.length > 0,
1171
+ value: version || '未知',
1172
+ hint: null,
1173
+ action: null,
1174
+ },
1175
+ {
1176
+ id: 'tools',
1177
+ label: '工具注册',
1178
+ ok: toolInfo.ok,
1179
+ value: toolInfo.value,
1180
+ hint: toolInfo.hint,
1181
+ action: toolInfo.ok ? null : { kind: 'retry', label: '点这里处理' },
1182
+ },
1183
+ {
1184
+ id: 'model',
1185
+ label: '当前模型',
1186
+ ok: modelOk,
1187
+ value: hostModel?.provider && hostModel?.model
1188
+ ? `${hostModel.provider} / ${hostModel.model}`
1189
+ : (modelOk ? `${form.provider} / ${form.model}` : '未配置'),
1190
+ hint: modelOk ? null : '还没有读到默认模型;下一步填写即可。',
1191
+ action: modelOk ? null : { kind: 'step', step: 2, label: '点这里处理' },
1192
+ },
1193
+ {
1194
+ id: 'config',
1195
+ label: '配置文件',
1196
+ ok: profile.ok && writable.ok,
1197
+ value: profile.ok ? profile.patchPath : '未知位置',
1198
+ hint: profile.ok ? (writable.ok ? null : writable.reason) : profile.reason,
1199
+ action: profile.ok && writable.ok ? null : { kind: 'retry', label: '点这里处理' },
1200
+ },
1201
+ {
1202
+ id: 'key',
1203
+ label: 'API key',
1204
+ ok: keyInfo.configured && (effectiveVerification?.ok !== false),
1205
+ value: keyInfo.configured
1206
+ ? `${keyMask ?? '已保存(内容不可回读)'} · ${effectiveVerification?.ok === true ? '已验证' : effectiveVerification?.ok === false ? '未通过' : '未验证'}`
1207
+ : '未配置',
1208
+ hint: keyInfo.configured
1209
+ ? (effectiveVerification?.ok === false ? effectiveVerification.message : null)
1210
+ : '在这一步填一次 key;它只会写进宿主凭据库。',
1211
+ action: keyInfo.configured && effectiveVerification?.ok !== false
1212
+ ? null
1213
+ : { kind: 'step', step: 2, label: '点这里处理' },
1214
+ },
1215
+ ]
1216
+
1217
+ return {
1218
+ environment,
1219
+ needsSetup: !keyInfo.configured || !modelOk || !modelWritten || !profile.ok || !writable.ok,
1220
+ provider: form.provider,
1221
+ baseURL: form.baseURL,
1222
+ model: form.model,
1223
+ defaults: { ...WIZARD_DEFAULTS },
1224
+ key: {
1225
+ ref,
1226
+ configured: keyInfo.configured,
1227
+ writable: keyInfo.writable,
1228
+ available: keyInfo.available,
1229
+ source: keyInfo.source,
1230
+ mask: keyMask,
1231
+ verified: effectiveVerification?.ok === true,
1232
+ verification: effectiveVerification,
1233
+ },
1234
+ profile: profile.ok
1235
+ ? { name: profile.name, dir: profile.dir, patchPath: profile.patchPath, writable: writable.ok }
1236
+ : { name: null, dir: null, patchPath: null, writable: false, reason: profile.reason },
1237
+ backups: (meta.backups ?? []).map(entry => ({
1238
+ id: entry.id,
1239
+ createdAt: entry.createdAt,
1240
+ summary: Array.isArray(entry.summary) ? entry.summary : [],
1241
+ })),
1242
+ lastTrial: meta.lastTrial ?? null,
1243
+ version,
1244
+ }
1245
+ }
1246
+
1247
+ function addUsage(usage, recorded, source) {
1248
+ if (!recorded || typeof recorded !== 'object') return
1249
+ const inputTokens = Number(recorded.inputTokens) || 0
1250
+ const outputTokens = Number(recorded.outputTokens) || 0
1251
+ if (inputTokens === 0 && outputTokens === 0) return
1252
+ usage.inputTokens += inputTokens
1253
+ usage.outputTokens += outputTokens
1254
+ usage.cacheReadTokens += Number(recorded.cacheReadTokens) || 0
1255
+ usage.totalTokens += Number(recorded.totalTokens) || inputTokens + outputTokens
1256
+ usage.modelCalls += 1
1257
+ if (source?.kind === 'model') {
1258
+ const key = `${source.provider ?? '?'}/${source.model ?? '?'}`
1259
+ const entry = usage.models[key] ?? (usage.models[key] = {
1260
+ inputTokens: 0,
1261
+ outputTokens: 0,
1262
+ cacheReadTokens: 0,
1263
+ calls: 0,
1264
+ })
1265
+ entry.inputTokens += inputTokens
1266
+ entry.outputTokens += outputTokens
1267
+ entry.cacheReadTokens += Number(recorded.cacheReadTokens) || 0
1268
+ entry.calls += 1
1269
+ }
1270
+ }
1271
+
1272
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
1273
+
1274
+ function currentSelection() {
1275
+ try {
1276
+ const selection = getDefaultModel?.()
1277
+ if (!selection || typeof selection !== 'object') return null
1278
+ return {
1279
+ provider: typeof selection.provider === 'string' ? selection.provider : null,
1280
+ model: typeof selection.model === 'string' ? selection.model : null,
1281
+ }
1282
+ } catch {
1283
+ return null
1284
+ }
1285
+ }
1286
+
1287
+ // The patch layer hot-reloads, but a session created in the same tick can
1288
+ // still see the old provider. Wait until the host reports the model we just
1289
+ // wrote so the trial is not a race.
1290
+ async function waitForConfiguredModel(timeoutMs = 4000) {
1291
+ const meta = await readMeta().catch(() => ({}))
1292
+ if (!meta.provider || !meta.model) return true
1293
+ const matches = selection =>
1294
+ selection?.provider === meta.provider && selection?.model === meta.model
1295
+ if (matches(currentSelection())) return true
1296
+ const deadline = Date.now() + timeoutMs
1297
+ while (Date.now() < deadline) {
1298
+ await sleep(150)
1299
+ if (matches(currentSelection())) return true
1300
+ }
1301
+ return false
1302
+ }
1303
+
1304
+ async function runTrial() {
1305
+ const session = getSessionController?.()
1306
+ if (!session || typeof session.create !== 'function' || typeof session.prompt !== 'function' || typeof session.follow !== 'function') {
1307
+ throw new WorkbenchError(503, '宿主没有可用的会话服务,没法试跑。', {
1308
+ id: 'trial-unavailable',
1309
+ hint: '先让宿主的 sessionController 正常工作,再打开向导。',
1310
+ })
1311
+ }
1312
+ let dir
1313
+ let sessionId = null
1314
+ let created
1315
+ await waitForConfiguredModel()
1316
+ try {
1317
+ dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'dsh-superagent-wizard-'))
1318
+ created = await session.create({ cwd: dir })
1319
+ sessionId = created?.sessionId ?? null
1320
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('sessionController.create returned no sessionId')
1321
+ } catch (error) {
1322
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {})
1323
+ throw new WorkbenchError(502, `试跑没能建立临时会话:${messageOf(error)}`, {
1324
+ id: 'trial-session-failed',
1325
+ hint: '先在对话页发一句话确认会话能启动,再回来试跑。',
1326
+ })
1327
+ }
1328
+
1329
+ const startedAt = Date.now()
1330
+ const controller = new AbortController()
1331
+ const events = []
1332
+ let readError = null
1333
+ let timedOut = false
1334
+ let turnEnded = false
1335
+ const loop = (async () => {
1336
+ try {
1337
+ for await (const frame of session.follow({
1338
+ address: { kind: 'session', sessionId },
1339
+ assistantStream: false,
1340
+ }, controller.signal)) {
1341
+ if (frame?.type !== 'event' || !frame.event) continue
1342
+ events.push(frame.event)
1343
+ if (frame.event.type === 'turn/end') {
1344
+ turnEnded = true
1345
+ break
1346
+ }
1347
+ }
1348
+ } catch (error) {
1349
+ if (error?.name !== 'AbortError') readError = error
1350
+ }
1351
+ })()
1352
+ const timer = setTimeout(() => {
1353
+ timedOut = true
1354
+ controller.abort()
1355
+ }, TRIAL_TIMEOUT_MS)
1356
+ timer.unref?.()
1357
+ let promptError = null
1358
+ try {
1359
+ await session.prompt({
1360
+ requestId: randomUUID(),
1361
+ sessionId,
1362
+ mode: 'queue',
1363
+ content: [{ type: 'text', text: TRIAL_PROMPT }],
1364
+ }, controller.signal)
1365
+ await Promise.race([
1366
+ loop,
1367
+ new Promise(resolve => {
1368
+ const wait = setTimeout(resolve, TRIAL_TIMEOUT_MS + 1_000)
1369
+ wait.unref?.()
1370
+ }),
1371
+ ])
1372
+ } catch (error) {
1373
+ promptError = error
1374
+ } finally {
1375
+ clearTimeout(timer)
1376
+ controller.abort()
1377
+ }
1378
+ await loop.catch(() => {})
1379
+
1380
+ const usage = {
1381
+ inputTokens: 0,
1382
+ outputTokens: 0,
1383
+ cacheReadTokens: 0,
1384
+ totalTokens: 0,
1385
+ modelCalls: 0,
1386
+ models: {},
1387
+ }
1388
+ const subtasks = []
1389
+ const byCallId = new Map()
1390
+ let assistantText = ''
1391
+ let reason = null
1392
+ for (const event of events) {
1393
+ const data = event?.data && typeof event.data === 'object' ? event.data : {}
1394
+ if (event.type === 'tool/call') {
1395
+ const step = {
1396
+ index: subtasks.length + 1,
1397
+ title: typeof data.name === 'string' ? data.name : 'tool',
1398
+ detail: summarizeArgs(data.arguments),
1399
+ status: 'running',
1400
+ }
1401
+ subtasks.push(step)
1402
+ if (typeof data.callId === 'string') byCallId.set(data.callId, step)
1403
+ } else if (event.type === 'tool/result') {
1404
+ const callId = data.callId ?? data.message?.toolCallId ?? data.message?.source?.callId
1405
+ const step = byCallId.get(callId)
1406
+ if (step) {
1407
+ step.status = data.message?.isError === true ? 'failed' : 'completed'
1408
+ const text = contentText(data.message?.content).slice(0, 500)
1409
+ if (text) step.detail = text
1410
+ }
1411
+ } else if (event.type === 'assistant/message') {
1412
+ assistantText += contentText(data.message?.content)
1413
+ addUsage(usage, data.usage, data.message?.source)
1414
+ } else if (event.type === 'turn/end') {
1415
+ reason = data.reason?.kind ?? 'ended'
1416
+ }
1417
+ }
1418
+
1419
+ let file = { name: TRIAL_FILE, exists: false, bytes: 0, preview: null, verified: false }
1420
+ try {
1421
+ const content = await fsp.readFile(path.join(dir, TRIAL_FILE), 'utf8')
1422
+ file = {
1423
+ name: TRIAL_FILE,
1424
+ exists: true,
1425
+ bytes: Buffer.byteLength(content),
1426
+ preview: content.slice(0, 200),
1427
+ verified: content.trim().toLowerCase().includes('ok'),
1428
+ }
1429
+ } catch {
1430
+ // Missing file is reported, never invented.
1431
+ }
1432
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {})
1433
+
1434
+ const cost = computeCost(usage, pricing)
1435
+ const costView = cost
1436
+ ? {
1437
+ text: formatMoney(cost),
1438
+ complete: cost.complete === true,
1439
+ unpriced: Array.isArray(cost.unpriced) ? cost.unpriced : [],
1440
+ }
1441
+ : null
1442
+ const failed = Boolean(readError || promptError) || reason === 'error'
1443
+ const ok = file.verified && !failed && !timedOut
1444
+ let hint = null
1445
+ if (!ok) {
1446
+ if (timedOut) {
1447
+ hint = '试跑超过 120 秒没有结束。可能是模型端点在排队或网络很慢;可以重试,或先在对话页发一句话确认模型能响应。'
1448
+ } else if (promptError || readError) {
1449
+ hint = `模型调用失败:${messageOf(promptError ?? readError)}。回到第 2 步检查 key、地址和模型名。`
1450
+ } else if (!file.exists) {
1451
+ hint = '模型回复了,但没有在临时目录创建约定文件。可以让它重试,或到对话页看看工具是否可用。'
1452
+ } else if (!file.verified) {
1453
+ hint = `文件创建了,但内容不是约定的 ok(读到:${file.preview ?? '空'})。`
1454
+ } else if (failed) {
1455
+ hint = `这一轮以 ${reason ?? '异常'} 结束,文件虽然存在,但状态不算成功。`
1456
+ }
1457
+ }
1458
+ const result = {
1459
+ ok,
1460
+ at: new Date().toISOString(),
1461
+ elapsedMs: Date.now() - startedAt,
1462
+ sessionId,
1463
+ reason,
1464
+ timedOut,
1465
+ message: assistantText.trim().slice(0, 800),
1466
+ subtasks,
1467
+ file,
1468
+ usage,
1469
+ cost: costView,
1470
+ hint,
1471
+ }
1472
+ const meta = await readMeta()
1473
+ meta.lastTrial = {
1474
+ at: result.at,
1475
+ ok: result.ok,
1476
+ tokens: usage.totalTokens,
1477
+ cost: costView?.text ?? null,
1478
+ subtasks: subtasks.length,
1479
+ elapsedMs: result.elapsedMs,
1480
+ }
1481
+ await writeMeta(meta).catch(error => log(`wizard: cannot record the trial result: ${messageOf(error)}`))
1482
+ return result
1483
+ }
1484
+
1485
+ async function trial() {
1486
+ if (trialInFlight) {
1487
+ throw new WorkbenchError(409, '试跑已经在进行,等它结束再看结果。', { id: 'trial-busy' })
1488
+ }
1489
+ trialInFlight = runTrial()
1490
+ try {
1491
+ return await trialInFlight
1492
+ } finally {
1493
+ trialInFlight = null
1494
+ }
1495
+ }
1496
+
1497
+ return { status, preview, save, rollback, trial }
1498
+ }