dsh-github-console 0.0.0-stage → 0.2.5

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/index.js ADDED
@@ -0,0 +1,3010 @@
1
+ /**
2
+ * DSH GitHub Console — Host half.
3
+ *
4
+ * GitHub App authentication (manifest flow) + installation tokens, a same-origin
5
+ * panel API, and agent tools for repositories, files, issues, pull requests,
6
+ * workflow runs, and plugin publishing.
7
+ *
8
+ * Secrets live only in the DSH credential service:
9
+ * github-console/app { appId, pem, slug, name, htmlUrl, owner, clientId, clientSecret }
10
+ * github-console/install { id, account, permissions } (which installation to use)
11
+ * github-console/bridge { token } (panel API bearer token)
12
+ * Installation access tokens are memory-only with a one hour life.
13
+ */
14
+
15
+ import crypto from 'node:crypto'
16
+ import fs from 'node:fs/promises'
17
+ import path from 'node:path'
18
+ import net from 'node:net'
19
+ import tls from 'node:tls'
20
+ import https from 'node:https'
21
+ import { fileURLToPath } from 'node:url'
22
+ import { promises as dnsPromises, Resolver } from 'node:dns'
23
+
24
+ const PLUGIN_VERSION = '0.2.5'
25
+ const APP_CRED = 'github-console/app'
26
+ const INSTALL_CRED = 'github-console/install'
27
+ const BRIDGE_CRED = 'github-console/bridge'
28
+ const INDEX_CRED = 'github-console/index'
29
+ const DEFAULT_API = 'https://api.github.com'
30
+ const PREFIX = '/github-console'
31
+ const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
32
+ const MANIFEST_TTL_MS = 60 * 60 * 1000
33
+ const INSTALL_TOKEN_MARGIN_MS = 5 * 60 * 1000
34
+
35
+ // A credential key outside "<scope>/<id>" poisons the whole credentials document
36
+ // and aborts the next startup, so refuse to run with a malformed key.
37
+ for (const key of [APP_CRED, INSTALL_CRED, BRIDGE_CRED, INDEX_CRED]) {
38
+ if (!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(key)) {
39
+ throw new Error(`Invalid credential key "${key}": expected "<scope>/<id>"`)
40
+ }
41
+ }
42
+
43
+ // Only machine-local or VCS internals are skipped: a bundle's runtime entry can
44
+ // legitimately live in lib/ or dist/, so those must be published.
45
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.cache', '.turbo'])
46
+ const SECRET_PATTERNS = [
47
+ ['GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,})\b/],
48
+ ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
49
+ ['OpenAI-style key', /\bsk-[A-Za-z0-9]{20,}\b/],
50
+ ['npm token', /\bnpm_[A-Za-z0-9]{20,}\b/],
51
+ ['AWS key', /\bAKIA[0-9A-Z]{16}\b/],
52
+ ]
53
+
54
+ // Directories that never contain a DSH plugin checkout worth listing, and that
55
+ // would make discovery slow in a large workspace.
56
+ const DISCOVER_SKIP = new Set([
57
+ 'node_modules', '.git', '.pnpm-store', '.cache', 'dist', 'build', '.next',
58
+ 'sessions', 'storages', 'profiles', 'attachments', 'cache', 'dsh-runtimes',
59
+ 'media-desk', 'memory', 'llm-deepseek', 'skills',
60
+ ])
61
+
62
+ async function looksLikePlugin(dir) {
63
+ const pkgPath = path.join(dir, 'package.json')
64
+ const stat = await fs.stat(pkgPath).catch(() => null)
65
+ if (!stat || !stat.isFile() || stat.size > 512 * 1024) return null
66
+ const raw = await fs.readFile(pkgPath, 'utf8').catch(() => '')
67
+ let pkg
68
+ try {
69
+ pkg = JSON.parse(raw)
70
+ } catch {
71
+ return null
72
+ }
73
+ const bundle = pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch ? String(pkg.dsh.bundle.patch) : ''
74
+ const client = pkg.dsh && pkg.dsh.client ? true : false
75
+ if (!bundle && !client) return null
76
+ const dirStat = await fs.stat(dir).catch(() => null)
77
+ const name = typeof pkg.name === 'string' ? pkg.name : ''
78
+ return {
79
+ dir,
80
+ name,
81
+ version: typeof pkg.version === 'string' ? pkg.version : '',
82
+ description: typeof pkg.description === 'string' ? pkg.description : '',
83
+ patch: bundle,
84
+ hasClient: client,
85
+ // A repository name GitHub accepts: drop the npm scope and any odd characters.
86
+ suggestedRepo: name.replace(/^@[^/]+\//, '').replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 90),
87
+ mtime: dirStat ? dirStat.mtime.toISOString() : null,
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Find publishable plugin checkouts without touching the network or GitHub, so
93
+ * the panel has something useful to show before anyone signs in.
94
+ */
95
+ async function discoverPlugins(roots, limit = 40) {
96
+ const candidates = []
97
+ const seen = new Set()
98
+ const scanned = []
99
+ let examined = 0
100
+ const budget = 600
101
+
102
+ for (const root of roots) {
103
+ const stat = await fs.stat(root).catch(() => null)
104
+ if (!stat || !stat.isDirectory()) {
105
+ scanned.push({ root, exists: false, found: 0 })
106
+ continue
107
+ }
108
+ let found = 0
109
+ const selfHit = await looksLikePlugin(root)
110
+ if (selfHit && !seen.has(selfHit.dir)) {
111
+ seen.add(selfHit.dir)
112
+ candidates.push(selfHit)
113
+ found += 1
114
+ }
115
+ let level1 = []
116
+ try {
117
+ level1 = await fs.readdir(root, { withFileTypes: true })
118
+ } catch {
119
+ level1 = []
120
+ }
121
+ for (const entry of level1) {
122
+ if (candidates.length >= limit || examined >= budget) break
123
+ if (!entry.isDirectory() || entry.name.startsWith('.') || DISCOVER_SKIP.has(entry.name)) continue
124
+ examined += 1
125
+ const dir = path.join(root, entry.name)
126
+ const hit = await looksLikePlugin(dir)
127
+ if (hit && !seen.has(hit.dir)) {
128
+ seen.add(hit.dir)
129
+ candidates.push(hit)
130
+ found += 1
131
+ continue
132
+ }
133
+ let level2 = []
134
+ try {
135
+ level2 = await fs.readdir(dir, { withFileTypes: true })
136
+ } catch {
137
+ level2 = []
138
+ }
139
+ for (const child of level2) {
140
+ if (candidates.length >= limit || examined >= budget) break
141
+ if (!child.isDirectory() || child.name.startsWith('.') || DISCOVER_SKIP.has(child.name)) continue
142
+ examined += 1
143
+ const hit2 = await looksLikePlugin(path.join(dir, child.name))
144
+ if (hit2 && !seen.has(hit2.dir)) {
145
+ seen.add(hit2.dir)
146
+ candidates.push(hit2)
147
+ found += 1
148
+ }
149
+ }
150
+ }
151
+ scanned.push({ root, exists: true, found })
152
+ }
153
+
154
+ candidates.sort((a, b) => String(b.mtime || '').localeCompare(String(a.mtime || '')))
155
+ return { roots: scanned, count: candidates.length, items: candidates, limited: candidates.length >= limit }
156
+ }
157
+
158
+ function normalizeConfig(raw) {
159
+ const config = raw && typeof raw === 'object' ? raw : {}
160
+ return {
161
+ baseUrl:
162
+ typeof config.baseUrl === 'string' && config.baseUrl
163
+ ? config.baseUrl.replace(/\/+$/, '')
164
+ : DEFAULT_API,
165
+ appName: typeof config.appName === 'string' ? config.appName.trim() : '',
166
+ publishBranch:
167
+ typeof config.publishBranch === 'string' && config.publishBranch ? config.publishBranch : 'main',
168
+ topic: typeof config.topic === 'string' && config.topic ? config.topic : 'dsh-plugin',
169
+ marketIndexUrls: Array.isArray(config.marketIndexUrls)
170
+ ? config.marketIndexUrls.filter((item) => typeof item === 'string' && /^https?:\/\//.test(item))
171
+ : [],
172
+ maxPushBytes:
173
+ Number.isFinite(config.maxPushBytes) && config.maxPushBytes > 0 ? config.maxPushBytes : 8 * 1024 * 1024,
174
+ // Network: a polluted hosts file (GitHub accelerators) or an intermittent
175
+ // local proxy must not decide whether the plugin works.
176
+ proxy: typeof config.proxy === 'string' ? config.proxy.trim() : '',
177
+ proxyPorts: Array.isArray(config.proxyPorts)
178
+ ? config.proxyPorts.filter((port) => Number.isInteger(port) && port > 0 && port < 65536)
179
+ : [7897, 7890, 1080, 10808, 10809, 2080, 8888],
180
+ dnsServers: Array.isArray(config.dnsServers)
181
+ ? config.dnsServers.filter((server) => typeof server === 'string' && server)
182
+ : ['223.5.5.5', '119.29.29.29', '114.114.114.114'],
183
+ bypassHosts: config.bypassHosts !== false,
184
+ caFile: typeof config.caFile === 'string' ? config.caFile.trim() : '',
185
+ requestTimeoutMs:
186
+ Number.isFinite(config.requestTimeoutMs) && config.requestTimeoutMs > 0 ? config.requestTimeoutMs : 20000,
187
+ // Publishing extras: the npm workflow lives in the repository, and the
188
+ // optional self-hosted market index is one JSON file next to the code.
189
+ npmWorkflow: typeof config.npmWorkflow === 'string' && config.npmWorkflow ? config.npmWorkflow : 'publish.yml',
190
+ npmPollSeconds:
191
+ Number.isFinite(config.npmPollSeconds) && config.npmPollSeconds > 0 ? config.npmPollSeconds : 90,
192
+ marketIndexPath:
193
+ typeof config.marketIndexPath === 'string' && config.marketIndexPath
194
+ ? config.marketIndexPath
195
+ : 'market/index.json',
196
+ npmUser: typeof config.npmUser === 'string' ? config.npmUser.trim() : '',
197
+ }
198
+ }
199
+
200
+ /* ------------------------------------------------------------------ */
201
+ /* Transport: direct, hosts-bypassing DNS, or a local proxy */
202
+ /* ------------------------------------------------------------------ */
203
+
204
+ function readUntil(socket, separator, timeoutMs) {
205
+ return new Promise((resolve, reject) => {
206
+ let buffer = ''
207
+ const timer = setTimeout(() => {
208
+ cleanup()
209
+ reject(new Error('READ_TIMEOUT'))
210
+ }, timeoutMs)
211
+ const onData = (chunk) => {
212
+ buffer += chunk.toString('latin1')
213
+ if (buffer.includes(separator)) {
214
+ cleanup()
215
+ resolve(buffer)
216
+ }
217
+ }
218
+ const onError = (error) => {
219
+ cleanup()
220
+ reject(error)
221
+ }
222
+ const cleanup = () => {
223
+ clearTimeout(timer)
224
+ socket.off('data', onData)
225
+ socket.off('error', onError)
226
+ }
227
+ socket.on('data', onData)
228
+ socket.on('error', onError)
229
+ })
230
+ }
231
+
232
+ /**
233
+ * Builds a lookup() that asks public resolvers over UDP, which ignores the
234
+ * system hosts file. GitHub accelerators rewrite hosts to 127.0.0.1 and answer
235
+ * with their own CA, which Node does not trust; skipping hosts sidesteps both.
236
+ */
237
+ function makeBypassLookup(servers) {
238
+ const resolver = new Resolver({ timeout: 4000, tries: 3 })
239
+ try {
240
+ resolver.setServers(servers)
241
+ } catch {
242
+ /* keep default servers */
243
+ }
244
+ // One publish writes ~10 blobs; resolving the host for every request both
245
+ // wastes time and multiplies the chance of a transient DNS timeout.
246
+ const cache = new Map()
247
+ const ttlMs = 5 * 60 * 1000
248
+ return (hostname, options, callback) => {
249
+ const wantAll = Boolean(options && options.all)
250
+ const settle = (list) => {
251
+ cache.set(hostname, { list, at: Date.now() })
252
+ if (wantAll) callback(null, list.map((address) => ({ address, family: net.isIP(address) })))
253
+ else callback(null, list[0], net.isIP(list[0]))
254
+ }
255
+ const cached = cache.get(hostname)
256
+ if (cached && cached.list.length && Date.now() - cached.at < ttlMs) {
257
+ if (wantAll) callback(null, cached.list.map((address) => ({ address, family: net.isIP(address) })))
258
+ else callback(null, cached.list[0], net.isIP(cached.list[0]))
259
+ return
260
+ }
261
+ resolver.resolve4(hostname, (error4, list4) => {
262
+ if (!error4 && list4 && list4.length) return settle(list4)
263
+ resolver.resolve6(hostname, (error6, list6) => {
264
+ if (!error6 && list6 && list6.length) return settle(list6)
265
+ callback(error4 || error6 || new Error('DNS_LOOKUP_FAILED'))
266
+ })
267
+ })
268
+ }
269
+ }
270
+
271
+ function createTransport(cfg) {
272
+ const state = {
273
+ preferred: '',
274
+ lastRoute: '',
275
+ lastError: '',
276
+ proxy: '',
277
+ attempts: [],
278
+ checkedAt: 0,
279
+ }
280
+ let caPem
281
+ let caLoaded = false
282
+ const bypassLookup = makeBypassLookup(cfg.dnsServers)
283
+
284
+ async function loadCa() {
285
+ if (caLoaded) return caPem
286
+ caLoaded = true
287
+ if (!cfg.caFile) return undefined
288
+ caPem = await fs.readFile(cfg.caFile, 'utf8').catch(() => undefined)
289
+ return caPem
290
+ }
291
+
292
+ function probePort(port, timeoutMs = 400) {
293
+ return new Promise((resolve) => {
294
+ const socket = net.connect({ host: '127.0.0.1', port })
295
+ const done = (value) => {
296
+ socket.destroy()
297
+ resolve(value)
298
+ }
299
+ socket.setTimeout(timeoutMs, () => done(false))
300
+ socket.once('connect', () => done(true))
301
+ socket.once('error', () => done(false))
302
+ })
303
+ }
304
+
305
+ // A local proxy may be up, down, or started later; re-probe at most every 30s.
306
+ async function detectProxy(force) {
307
+ if (cfg.proxy) {
308
+ state.proxy = cfg.proxy
309
+ return cfg.proxy
310
+ }
311
+ if (!force && Date.now() - state.checkedAt < 30000) return state.proxy
312
+ state.checkedAt = Date.now()
313
+ const envProxy =
314
+ process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || ''
315
+ if (envProxy) {
316
+ state.proxy = envProxy
317
+ return envProxy
318
+ }
319
+ for (const port of cfg.proxyPorts) {
320
+ if (await probePort(port)) {
321
+ state.proxy = `http://127.0.0.1:${port}`
322
+ return state.proxy
323
+ }
324
+ }
325
+ state.proxy = ''
326
+ return ''
327
+ }
328
+
329
+ function routesFor(proxy) {
330
+ const routes = []
331
+ if (proxy) routes.push({ id: `proxy:${proxy}`, kind: 'proxy', proxy })
332
+ if (cfg.bypassHosts) routes.push({ id: 'direct:public-dns', kind: 'direct', lookup: bypassLookup })
333
+ routes.push({ id: 'direct:system-dns', kind: 'direct' })
334
+ if (state.preferred) {
335
+ const index = routes.findIndex((route) => route.id === state.preferred)
336
+ if (index > 0) routes.unshift(routes.splice(index, 1)[0])
337
+ }
338
+ return routes
339
+ }
340
+
341
+ function rawRequest(options, body, timeoutMs) {
342
+ return new Promise((resolve, reject) => {
343
+ const request = https.request(options, (response) => {
344
+ const chunks = []
345
+ response.on('data', (chunk) => chunks.push(chunk))
346
+ response.on('end', () =>
347
+ resolve({
348
+ status: response.statusCode || 0,
349
+ headers: response.headers,
350
+ text: Buffer.concat(chunks).toString('utf8'),
351
+ }),
352
+ )
353
+ response.on('error', reject)
354
+ })
355
+ request.setTimeout(timeoutMs, () => request.destroy(new Error('ETIMEDOUT')))
356
+ request.on('error', reject)
357
+ if (body) request.write(body)
358
+ request.end()
359
+ })
360
+ }
361
+
362
+ async function openTunnel(proxyUrl, host, port) {
363
+ const url = new URL(proxyUrl)
364
+ const secure = url.protocol === 'https:'
365
+ const proxyPort = Number(url.port || (secure ? 443 : 80))
366
+ const socket = await new Promise((resolve, reject) => {
367
+ const created = secure
368
+ ? tls.connect({ host: url.hostname, port: proxyPort, servername: url.hostname }, () => resolve(created))
369
+ : net.connect({ host: url.hostname, port: proxyPort }, () => resolve(created))
370
+ created.setTimeout(8000, () => created.destroy(new Error('PROXY_TIMEOUT')))
371
+ created.once('error', reject)
372
+ })
373
+ const auth =
374
+ url.username || url.password
375
+ ? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString('base64')}\r\n`
376
+ : ''
377
+ socket.write(`CONNECT ${host}:${port} HTTP/1.1\r\nHost: ${host}:${port}\r\n${auth}\r\n`)
378
+ const head = await readUntil(socket, '\r\n\r\n', 8000)
379
+ if (!/^HTTP\/1\.[01] 200/.test(head)) {
380
+ socket.destroy()
381
+ throw new Error(`PROXY_CONNECT_FAILED ${head.split('\r\n')[0]}`)
382
+ }
383
+ const ca = await loadCa()
384
+ return new Promise((resolve, reject) => {
385
+ const secured = tls.connect({ socket, servername: host, ca }, () => resolve(secured))
386
+ secured.once('error', reject)
387
+ })
388
+ }
389
+
390
+ async function requestViaRoute(route, url, options) {
391
+ const target = new URL(url)
392
+ const host = target.hostname
393
+ const port = Number(target.port || 443)
394
+ const path = `${target.pathname}${target.search}`
395
+ const headers = {
396
+ Host: host,
397
+ Connection: 'close',
398
+ // GitHub rejects requests without a User-Agent (HTTP 403 "Request
399
+ // forbidden by administrative rules"), and fetch used to add one for us.
400
+ 'User-Agent': `dsh-github-console/${PLUGIN_VERSION}`,
401
+ ...options.headers,
402
+ }
403
+ if (options.body) headers['Content-Length'] = Buffer.byteLength(options.body)
404
+
405
+ if (route.kind === 'proxy') {
406
+ const tunnel = await openTunnel(route.proxy, host, port)
407
+ // https.Agent.createConnection is expected to hand back a secured socket.
408
+ const agent = new https.Agent({
409
+ keepAlive: false,
410
+ maxSockets: 1,
411
+ createConnection: () => tunnel,
412
+ })
413
+ try {
414
+ return await rawRequest(
415
+ { method: options.method, host, port, path, headers, agent, servername: host },
416
+ options.body,
417
+ cfg.requestTimeoutMs,
418
+ )
419
+ } finally {
420
+ tunnel.destroy()
421
+ agent.destroy()
422
+ }
423
+ }
424
+
425
+ const ca = await loadCa()
426
+ return rawRequest(
427
+ {
428
+ method: options.method,
429
+ host,
430
+ port,
431
+ path,
432
+ headers,
433
+ servername: host,
434
+ ca,
435
+ lookup: route.lookup,
436
+ },
437
+ options.body,
438
+ cfg.requestTimeoutMs,
439
+ )
440
+ }
441
+
442
+ async function request(url, options = {}) {
443
+ const failures = []
444
+ // One transient timeout must not fail a publish: retry the whole route set
445
+ // a couple of times, re-probing the proxy so one that just came up is seen.
446
+ const backoff = [0, 800, 2500]
447
+ for (let round = 0; round < backoff.length; round++) {
448
+ if (backoff[round]) await new Promise((resolve) => setTimeout(resolve, backoff[round]))
449
+ const proxy = await detectProxy(round > 0)
450
+ const routes = routesFor(proxy)
451
+ for (const route of routes) {
452
+ try {
453
+ const response = await requestViaRoute(route, url, options)
454
+ state.preferred = route.id
455
+ state.lastRoute = route.id
456
+ state.lastError = ''
457
+ state.attempts = [{ route: route.id, ok: true, round }]
458
+ return response
459
+ } catch (failure) {
460
+ const described = describeFetchFailure(failure)
461
+ const detail = described.codes.join('/') || errorMessage(failure)
462
+ if (!failures.some((item) => item.route === route.id)) failures.push({ route: route.id, error: detail })
463
+ state.lastError = `${route.id}: ${detail}`
464
+ }
465
+ }
466
+ // Forget the remembered route so the retry re-evaluates the order.
467
+ state.preferred = ''
468
+ }
469
+ state.attempts = failures.map((item) => ({ route: item.route, ok: false, error: item.error }))
470
+ const hint = await proxyHint(failures)
471
+ throw new GhError(
472
+ 0,
473
+ 'NETWORK',
474
+ `所有线路都失败(${failures.map((item) => `${item.route}=${item.error}`).join(';')})${hint}`,
475
+ { failures },
476
+ )
477
+ }
478
+
479
+ async function proxyHint(failures) {
480
+ if (failures.some((item) => String(item.error).includes('UNABLE_TO_VERIFY_LEAF_SIGNATURE'))) {
481
+ return ':证书不被 Node 信任(常见于 GitHub 加速工具的本地中间人)。可在配置里写 caFile 指向其根证书,或让 hosts 不要劫持 api.github.com。'
482
+ }
483
+ if (failures.every((item) => String(item.error).includes('ENOTFOUND') || String(item.error).includes('EAI_AGAIN'))) {
484
+ return ':域名解析失败,检查 DNS 或代理。'
485
+ }
486
+ if (failures.every((item) => String(item.error).includes('ECONNREFUSED'))) {
487
+ return ':连接被拒,可能是 hosts 指向 127.0.0.1 而代理没开。'
488
+ }
489
+ return ''
490
+ }
491
+
492
+ return {
493
+ request,
494
+ state,
495
+ detectProxy,
496
+ refresh: () => {
497
+ state.checkedAt = 0
498
+ state.preferred = ''
499
+ },
500
+ }
501
+ }
502
+
503
+ class GhError extends Error {
504
+ constructor(status, code, message, detail) {
505
+ super(message)
506
+ this.name = 'GhError'
507
+ this.status = status
508
+ this.code = code
509
+ this.detail = detail
510
+ }
511
+ }
512
+
513
+ function jsonSafe(value) {
514
+ if (value === null) return null
515
+ if (typeof value === 'string' || typeof value === 'boolean') return value
516
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
517
+ if (typeof value === 'bigint') return value.toString()
518
+ if (Array.isArray(value)) return value.map((item) => jsonSafe(item) ?? null)
519
+ if (typeof value === 'object') {
520
+ const result = {}
521
+ for (const [key, item] of Object.entries(value)) {
522
+ if (item === undefined) continue
523
+ const safe = jsonSafe(item)
524
+ if (safe !== undefined) result[key] = safe
525
+ }
526
+ return result
527
+ }
528
+ return undefined
529
+ }
530
+
531
+ function errorMessage(error) {
532
+ if (error instanceof GhError) return error.message
533
+ return error instanceof Error ? error.message : String(error)
534
+ }
535
+
536
+ /**
537
+ * A bare "fetch failed" hides everything worth knowing, so surface the cause
538
+ * code and, for the common local-proxy/hosts cases, what to do about it.
539
+ */
540
+ function describeFetchFailure(error) {
541
+ const codes = []
542
+ let cause = error && error.cause
543
+ let depth = 0
544
+ while (cause && depth < 5) {
545
+ if (cause.code) codes.push(String(cause.code))
546
+ else if (cause.message) codes.push(String(cause.message))
547
+ cause = cause.cause
548
+ depth += 1
549
+ }
550
+ const text = codes.join(' / ')
551
+ const hint =
552
+ text.includes('UNABLE_TO_VERIFY_LEAF_SIGNATURE') ||
553
+ text.includes('SELF_SIGNED_CERT_IN_CHAIN') ||
554
+ text.includes('DEPTH_ZERO_SELF_SIGNED_CERT')
555
+ ? 'GitHub 域名的证书不被 Node 信任:通常是 GitHub 加速工具写入 hosts 后,由本地中间人证书应答。关掉加速工具并清理 hosts 中的 GitHub 条目,或改用系统代理。'
556
+ : text.includes('ENOTFOUND') || text.includes('EAI_AGAIN')
557
+ ? '域名解析失败:检查 DNS / hosts / 代理是否在运行。'
558
+ : text.includes('ECONNREFUSED')
559
+ ? '连接被拒绝:本机 hosts 可能把域名指向了 127.0.0.1,而该端口的代理没有运行。'
560
+ : text.includes('ETIMEDOUT') || text.includes('UND_ERR_CONNECT_TIMEOUT')
561
+ ? '连接超时:网络或代理不通。'
562
+ : ''
563
+ return { message: `网络请求失败(${text || 'unknown'})`, codes, hint }
564
+ }
565
+
566
+ /**
567
+ * DNS is resolved by the same process that makes the request, so a hosts entry
568
+ * that points GitHub at localhost is visible here without any network call.
569
+ */
570
+ async function describeDns(host) {
571
+ try {
572
+ const addresses = await dnsPromises.lookup(host, { all: true })
573
+ const list = addresses.map((item) => `${item.address}/${item.family}`)
574
+ const local = addresses.some(
575
+ (item) =>
576
+ item.address === '127.0.0.1' ||
577
+ item.address === '::1' ||
578
+ item.address.startsWith('127.') ||
579
+ item.address === '0.0.0.0',
580
+ )
581
+ return {
582
+ host,
583
+ addresses: list,
584
+ localRedirect: local,
585
+ hint: local
586
+ ? `${host} 被解析到本机地址(${list.join(', ')}):通常是 GitHub 加速工具写入的 hosts 重定向,或本地代理未运行。浏览器可能仍能打开 GitHub,但本插件的网络请求会失败。`
587
+ : '',
588
+ }
589
+ } catch (error) {
590
+ return { host, addresses: [], localRedirect: false, hint: `解析 ${host} 失败:${errorMessage(error)}` }
591
+ }
592
+ }
593
+
594
+ function escapeHtml(text) {
595
+ return String(text).replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch])
596
+ }
597
+
598
+ function sendHtml(response, status, title, detail, extraHtml = '') {
599
+ response.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
600
+ response.end(
601
+ `<!doctype html><meta charset="utf-8"><title>${escapeHtml(title)}</title>` +
602
+ `<body style="font-family:system-ui,-apple-system,'Segoe UI',sans-serif;background:#f6f7f9;margin:0;padding:48px 16px;color:#1f2328">` +
603
+ `<div style="max-width:600px;margin:0 auto;background:#fff;border:1px solid #e3e6ea;border-radius:12px;padding:26px 30px">` +
604
+ `<h2 style="margin:0 0 10px;font-size:19px;font-weight:600">${escapeHtml(title)}</h2>` +
605
+ `<p style="color:#57606a;line-height:1.75;font-size:13px;margin:0 0 6px">${escapeHtml(detail)}</p>${extraHtml}</div></body>`,
606
+ )
607
+ }
608
+
609
+ function sendJson(response, status, value) {
610
+ const body = JSON.stringify(value)
611
+ response.writeHead(status, {
612
+ 'Content-Type': 'application/json; charset=utf-8',
613
+ 'Cache-Control': 'no-store',
614
+ })
615
+ response.end(body)
616
+ }
617
+
618
+ function readBody(request, limit = 512 * 1024) {
619
+ return new Promise((resolve, reject) => {
620
+ let data = ''
621
+ request.setEncoding('utf8')
622
+ request.on('data', (chunk) => {
623
+ data += chunk
624
+ if (data.length > limit) {
625
+ reject(new Error('请求体过大'))
626
+ request.destroy()
627
+ }
628
+ })
629
+ request.on('end', () => resolve(data))
630
+ request.on('error', reject)
631
+ })
632
+ }
633
+
634
+ function requestOrigin(request) {
635
+ const host = request.headers.host
636
+ if (host && /^[A-Za-z0-9.:\-[\]]+$/.test(host)) {
637
+ const proto = String(request.headers['x-forwarded-proto'] || 'http').split(',')[0].trim()
638
+ return `${proto === 'https' ? 'https' : 'http'}://${host}`
639
+ }
640
+ return 'http://127.0.0.1'
641
+ }
642
+
643
+ function bearerToken(request) {
644
+ const header = String(request.headers.authorization || '')
645
+ const match = /^Bearer\s+(.+)$/i.exec(header)
646
+ return match ? match[1].trim() : ''
647
+ }
648
+
649
+ function base64url(input) {
650
+ return Buffer.from(input).toString('base64url')
651
+ }
652
+
653
+ function semverCore(text) {
654
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(text || '').trim())
655
+ return match ? `${match[1]}.${match[2]}.${match[3]}` : ''
656
+ }
657
+
658
+ function fmtBytes(bytes) {
659
+ const n = Number(bytes) || 0
660
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`
661
+ if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`
662
+ return `${n} B`
663
+ }
664
+
665
+ function textOf(value) {
666
+ return [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
667
+ }
668
+
669
+ /* ------------------------------------------------------------------ */
670
+ /* GitHub App authentication */
671
+ /* ------------------------------------------------------------------ */
672
+
673
+ function createGithub(ctx, cfg, transport) {
674
+ let installationTokenCache = null // { token, expiresAt }
675
+ const pendingManifests = new Map() // state -> startedAt
676
+
677
+ function store() {
678
+ return ctx.get('credentials')
679
+ }
680
+
681
+ async function readRecord(key) {
682
+ const credentials = store()
683
+ if (!credentials) return undefined
684
+ const record = await credentials.readRecord(key).catch(() => undefined)
685
+ return record && record.payload && typeof record.payload === 'object' ? record.payload : undefined
686
+ }
687
+
688
+ async function writeRecord(key, payload) {
689
+ const credentials = store()
690
+ if (!credentials) throw new Error('凭据服务不可用,无法保存 GitHub 凭据')
691
+ await credentials.modifyRecord(key, async () => ({ kind: 'grant', payload: jsonSafe(payload) }))
692
+ }
693
+
694
+ async function deleteRecord(key) {
695
+ const credentials = store()
696
+ if (credentials) await credentials.deleteRecord(key).catch(() => {})
697
+ }
698
+
699
+ async function readApp() {
700
+ const app = await readRecord(APP_CRED)
701
+ if (!app || !app.appId || !app.pem) return undefined
702
+ return app
703
+ }
704
+
705
+ async function waitForCredentials() {
706
+ let credentials = store()
707
+ // The credentials service can activate after this plugin; without a short
708
+ // bounded wait, the bridge token would be regenerated on every reload.
709
+ for (let attempt = 0; attempt < 30 && !credentials; attempt++) {
710
+ await new Promise((resolve) => setTimeout(resolve, 100))
711
+ credentials = store()
712
+ }
713
+ return credentials
714
+ }
715
+
716
+ function appJwt(app) {
717
+ const now = Math.floor(Date.now() / 1000)
718
+ const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))
719
+ const payload = base64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: String(app.appId) }))
720
+ const signingInput = `${header}.${payload}`
721
+ const signature = crypto.createSign('RSA-SHA256').update(signingInput).sign(app.pem).toString('base64url')
722
+ return `${signingInput}.${signature}`
723
+ }
724
+
725
+ async function call(pathname, options = {}) {
726
+ const { method = 'GET', body, auth = 'installation', headers = {} } = options
727
+ const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
728
+ if (auth === 'app') {
729
+ const app = await readApp()
730
+ if (!app) throw new GhError(401, 'AUTH_MISSING', '尚未注册 GitHub App:在侧栏「GitHub 控制台」点「注册 GitHub App」')
731
+ init.headers.Authorization = `Bearer ${appJwt(app)}`
732
+ } else if (auth === 'installation') {
733
+ init.headers.Authorization = `Bearer ${await installationToken()}`
734
+ } else {
735
+ init.headers.Authorization = `Bearer ${auth}`
736
+ }
737
+ if (body !== undefined) {
738
+ init.headers['Content-Type'] = 'application/json'
739
+ init.body = JSON.stringify(body)
740
+ }
741
+ let response
742
+ try {
743
+ response = await transport.request(`${cfg.baseUrl}${pathname}`, { method, headers: init.headers, body: init.body })
744
+ } catch (failure) {
745
+ if (failure instanceof GhError) throw failure
746
+ const described = describeFetchFailure(failure)
747
+ throw new GhError(0, 'NETWORK', described.hint ? `${described.message}:${described.hint}` : described.message, {
748
+ codes: described.codes,
749
+ })
750
+ }
751
+ const raw = response.text
752
+ let data = null
753
+ if (raw) {
754
+ try {
755
+ data = JSON.parse(raw)
756
+ } catch {
757
+ data = { raw: raw.slice(0, 400) }
758
+ }
759
+ }
760
+ if (response.status < 200 || response.status >= 300) {
761
+ // GitHub sometimes answers with an empty or non-JSON body, which used to
762
+ // surface as a bare "HTTP 403"; keep a short body peek in the message.
763
+ const bodyPeek =
764
+ data && data.message
765
+ ? ''
766
+ : data && data.raw
767
+ ? `:${String(data.raw).slice(0, 200)}`
768
+ : raw
769
+ ? `:${String(raw).slice(0, 200)}`
770
+ : '(空响应体)'
771
+ const message = data && data.message ? String(data.message) : `HTTP ${response.status}${bodyPeek}`
772
+ const remaining = response.headers['x-ratelimit-remaining']
773
+ const reset = response.headers['x-ratelimit-reset']
774
+ let code = `HTTP_${response.status}`
775
+ const limited =
776
+ response.status === 403 &&
777
+ (remaining === '0' || /rate limit/i.test(String(message || '')))
778
+ if (response.status === 401) code = 'AUTH_EXPIRED'
779
+ if (limited) code = 'RATE_LIMITED'
780
+ if (response.status === 403 && !limited) code = 'SCOPE_DENIED'
781
+ if (response.status === 404) code = 'NOT_FOUND'
782
+ if (response.status === 409) code = 'REF_CONFLICT'
783
+ if (response.status === 422) code = 'INVALID'
784
+ const suffix =
785
+ code === 'RATE_LIMITED' && reset
786
+ ? `(限流重置于 ${new Date(Number(reset) * 1000).toLocaleString()})`
787
+ : ''
788
+ throw new GhError(response.status, code, `${message}${suffix}`, data)
789
+ }
790
+ return data
791
+ }
792
+
793
+ async function installations() {
794
+ const list = await call('/app/installations?per_page=100', { auth: 'app' })
795
+ return (Array.isArray(list) ? list : []).map((item) => ({
796
+ id: item.id,
797
+ account: item.account ? item.account.login : '',
798
+ accountType: item.account ? item.account.type : '',
799
+ avatarUrl: item.account ? item.account.avatar_url : '',
800
+ target: item.target_type || '',
801
+ permissions: item.permissions || {},
802
+ repositorySelection: item.repository_selection || '',
803
+ }))
804
+ }
805
+
806
+ async function selectedInstallation() {
807
+ const saved = await readRecord(INSTALL_CRED)
808
+ if (saved && saved.id) return saved
809
+ const list = await installations()
810
+ if (list.length === 1) {
811
+ const only = list[0]
812
+ await writeRecord(INSTALL_CRED, only)
813
+ return only
814
+ }
815
+ return undefined
816
+ }
817
+
818
+ async function installationToken(force = false) {
819
+ if (!force && installationTokenCache && Date.now() < installationTokenCache.expiresAt - INSTALL_TOKEN_MARGIN_MS) {
820
+ return installationTokenCache.token
821
+ }
822
+ const installation = await selectedInstallation()
823
+ if (!installation) {
824
+ throw new GhError(
825
+ 401,
826
+ 'AUTH_MISSING',
827
+ 'GitHub App 还没有安装到任何账号:在 App 设置页点 Install,或在侧栏里选择 installation',
828
+ )
829
+ }
830
+ const created = await call(`/app/installations/${installation.id}/access_tokens`, {
831
+ method: 'POST',
832
+ auth: 'app',
833
+ })
834
+ const expiresAt = created.expires_at ? Date.parse(created.expires_at) : Date.now() + 3600 * 1000
835
+ installationTokenCache = { token: created.token, expiresAt }
836
+ return created.token
837
+ }
838
+
839
+ /* ---------------- manifest flow ---------------- */
840
+
841
+ function beginManifest() {
842
+ const state = crypto.randomBytes(16).toString('hex')
843
+ pendingManifests.set(state, Date.now())
844
+ for (const [key, startedAt] of pendingManifests) {
845
+ if (Date.now() - startedAt > MANIFEST_TTL_MS) pendingManifests.delete(key)
846
+ }
847
+ return state
848
+ }
849
+
850
+ function claimManifest(state) {
851
+ if (!state) return false
852
+ const startedAt = pendingManifests.get(state)
853
+ if (!startedAt) return false
854
+ return Date.now() - startedAt <= MANIFEST_TTL_MS
855
+ }
856
+
857
+ async function completeManifest(code, state) {
858
+ if (!claimManifest(state)) {
859
+ throw new Error('manifest state 不匹配或已过期(超过 1 小时),请重新注册')
860
+ }
861
+ const response = await transport
862
+ .request(`${cfg.baseUrl}/app-manifests/${encodeURIComponent(code)}/conversions`, {
863
+ method: 'POST',
864
+ headers: { Accept: 'application/vnd.github+json' },
865
+ })
866
+ .catch((failure) => {
867
+ const described = describeFetchFailure(failure)
868
+ throw new Error(errorMessage(failure).startsWith('所有线路')
869
+ ? errorMessage(failure)
870
+ : described.hint
871
+ ? `${described.message}:${described.hint}`
872
+ : described.message)
873
+ })
874
+ const data = (() => {
875
+ try {
876
+ return JSON.parse(response.text || '{}')
877
+ } catch {
878
+ return {}
879
+ }
880
+ })()
881
+ if (response.status < 200 || response.status >= 300 || !data.id || !data.pem) {
882
+ throw new Error(`换取 App 凭据失败(HTTP ${response.status}):${data.message || '未返回 id/pem'}`)
883
+ }
884
+ // Retire the state only after the exchange succeeded: a retried callback or
885
+ // a flaky network must not force the user to register a second App.
886
+ pendingManifests.delete(state)
887
+ // webhook_secret is not needed by this plugin: no inbound events.
888
+ await writeRecord(APP_CRED, {
889
+ appId: String(data.id),
890
+ pem: data.pem,
891
+ slug: data.slug || '',
892
+ name: data.name || '',
893
+ htmlUrl: data.html_url || '',
894
+ clientId: data.client_id || '',
895
+ clientSecret: data.client_secret || '',
896
+ owner: data.owner ? data.owner.login : '',
897
+ registeredAt: new Date().toISOString(),
898
+ })
899
+ await deleteRecord(INSTALL_CRED)
900
+ installationTokenCache = null
901
+ return { appId: String(data.id), slug: data.slug || '', htmlUrl: data.html_url || '' }
902
+ }
903
+
904
+ async function resetApp() {
905
+ await deleteRecord(APP_CRED)
906
+ await deleteRecord(INSTALL_CRED)
907
+ installationTokenCache = null
908
+ return { ok: true }
909
+ }
910
+
911
+ async function status() {
912
+ const app = await readApp()
913
+ const installError = []
914
+ let networkFailure = null
915
+ const installationsList = app
916
+ ? await installations().catch((error) => {
917
+ installError.push(errorMessage(error))
918
+ if (error && error.code === 'NETWORK') networkFailure = error
919
+ return []
920
+ })
921
+ : []
922
+ const installation = app
923
+ ? await selectedInstallation().catch((error) => {
924
+ installError.push(errorMessage(error))
925
+ if (error && error.code === 'NETWORK') networkFailure = error
926
+ return undefined
927
+ })
928
+ : undefined
929
+ // One transport failure produced two identical lines before; report each
930
+ // distinct message once.
931
+ const errors = Array.from(new Set(installError))
932
+ const host = (() => {
933
+ try {
934
+ return new URL(cfg.baseUrl).hostname
935
+ } catch {
936
+ return 'api.github.com'
937
+ }
938
+ })()
939
+ const network = app || networkFailure ? await describeDns(host) : { host, addresses: [], localRedirect: false, hint: '' }
940
+ network.route = transport.state.lastRoute || ''
941
+ network.preferred = transport.state.preferred || ''
942
+ network.proxy = transport.state.proxy || ''
943
+ network.attempts = transport.state.attempts || []
944
+ // The hosts hijack only matters when we could NOT route around it.
945
+ if (network.localRedirect) {
946
+ network.hint =
947
+ network.route === 'direct:public-dns'
948
+ ? `${host} 在 hosts 里被指向本机地址,已自动改用公共 DNS 直连(当前线路 ${network.route})。若想彻底干净,可以关掉加速工具或清理 hosts 中的 GitHub 条目。`
949
+ : network.hint
950
+ } else {
951
+ network.hint = ''
952
+ }
953
+ const tokenReady = Boolean(installationTokenCache)
954
+ const base = {
955
+ version: PLUGIN_VERSION,
956
+ apiBase: cfg.baseUrl,
957
+ configured: Boolean(app),
958
+ app: app
959
+ ? {
960
+ appId: app.appId,
961
+ name: app.name || '',
962
+ slug: app.slug || '',
963
+ htmlUrl: app.htmlUrl || '',
964
+ owner: app.owner || '',
965
+ registeredAt: app.registeredAt || null,
966
+ hasPrivateKey: Boolean(app.pem),
967
+ }
968
+ : null,
969
+ installations: installationsList.map((item) => ({
970
+ id: item.id,
971
+ account: item.account,
972
+ accountType: item.accountType,
973
+ repositorySelection: item.repositorySelection,
974
+ })),
975
+ installationCount: installationsList.length,
976
+ installation: installation
977
+ ? { id: installation.id, account: installation.account, permissions: installation.permissions || {} }
978
+ : null,
979
+ installationToken: tokenReady && installationTokenCache
980
+ ? { expiresAt: new Date(installationTokenCache.expiresAt).toISOString() }
981
+ : null,
982
+ publish: { branch: cfg.publishBranch, topic: cfg.topic, marketIndexUrls: cfg.marketIndexUrls },
983
+ errors,
984
+ network,
985
+ }
986
+ if (!app || !installation) return base
987
+ try {
988
+ const viewer = await call('/installation/repositories?per_page=1')
989
+ return {
990
+ ...base,
991
+ // The call above is what mints the installation token, so read the cache
992
+ // again instead of reporting the pre-call state.
993
+ installationToken: installationTokenCache
994
+ ? { expiresAt: new Date(installationTokenCache.expiresAt).toISOString() }
995
+ : null,
996
+ repositoryCount: typeof viewer.total_count === 'number' ? viewer.total_count : null,
997
+ }
998
+ } catch (error) {
999
+ return { ...base, error: errorMessage(error) }
1000
+ }
1001
+ }
1002
+
1003
+ async function listRepositories(query) {
1004
+ const json = await call('/installation/repositories?per_page=100')
1005
+ const items = (json.repositories || []).map((repo) => ({
1006
+ id: repo.id,
1007
+ fullName: repo.full_name,
1008
+ owner: repo.owner ? repo.owner.login : '',
1009
+ name: repo.name,
1010
+ private: Boolean(repo.private),
1011
+ description: repo.description || '',
1012
+ defaultBranch: repo.default_branch || 'main',
1013
+ updatedAt: repo.updated_at || null,
1014
+ topics: Array.isArray(repo.topics) ? repo.topics : [],
1015
+ }))
1016
+ const needle = String(query || '').toLowerCase()
1017
+ const filtered = needle ? items.filter((repo) => repo.fullName.toLowerCase().includes(needle)) : items
1018
+ return { total: json.total_count || items.length, returned: filtered.length, items: filtered }
1019
+ }
1020
+
1021
+ function repoPath(owner, name) {
1022
+ if (!owner || !name) throw new Error('需要 owner 与 name')
1023
+ return `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1024
+ }
1025
+
1026
+ async function readTree(owner, name, ref) {
1027
+ const repo = repoPath(owner, name)
1028
+ const meta = await call(repo)
1029
+ const branch = ref || meta.default_branch || 'main'
1030
+ const tree = await call(`${repo}/git/trees/${encodeURIComponent(branch)}`)
1031
+ const entries = (tree.tree || [])
1032
+ .slice(0, 1000)
1033
+ .map((entry) => ({ path: entry.path, type: entry.type, size: entry.size ?? null, sha: entry.sha }))
1034
+ return { owner, name, ref: branch, truncated: Boolean(tree.truncated), returned: entries.length, entries }
1035
+ }
1036
+
1037
+ async function readFile(owner, name, filePath, ref) {
1038
+ const repo = repoPath(owner, name)
1039
+ const query = ref ? `?ref=${encodeURIComponent(ref)}` : ''
1040
+ const json = await call(`${repo}/contents/${filePath.split('/').map(encodeURIComponent).join('/')}${query}`)
1041
+ if (Array.isArray(json)) throw new Error(`${filePath} 是目录,请用 gh_tree`)
1042
+ const text =
1043
+ json.encoding === 'base64' && json.content ? Buffer.from(json.content, 'base64').toString('utf8') : ''
1044
+ return { path: json.path, sha: json.sha, size: json.size, truncated: false, text }
1045
+ }
1046
+
1047
+ async function writeFile(owner, name, filePath, text, message, sha, branch) {
1048
+ const repo = repoPath(owner, name)
1049
+ const body = {
1050
+ message: message || `chore: update ${filePath}`,
1051
+ content: Buffer.from(text, 'utf8').toString('base64'),
1052
+ }
1053
+ if (sha) body.sha = sha
1054
+ if (branch) body.branch = branch
1055
+ const json = await call(`${repo}/contents/${filePath.split('/').map(encodeURIComponent).join('/')}`, {
1056
+ method: 'PUT',
1057
+ body,
1058
+ })
1059
+ return {
1060
+ path: json.content ? json.content.path : filePath,
1061
+ sha: json.content ? json.content.sha : null,
1062
+ commit: json.commit ? json.commit.sha : null,
1063
+ }
1064
+ }
1065
+
1066
+ async function listIssues(owner, name, state) {
1067
+ const repo = repoPath(owner, name)
1068
+ const json = await call(`${repo}/issues?state=${state || 'open'}&per_page=30`)
1069
+ const items = (Array.isArray(json) ? json : []).map((item) => ({
1070
+ number: item.number,
1071
+ title: item.title,
1072
+ state: item.state,
1073
+ user: item.user ? item.user.login : '',
1074
+ labels: (item.labels || []).map((label) => (typeof label === 'string' ? label : label.name)),
1075
+ isPullRequest: Boolean(item.pull_request),
1076
+ comments: item.comments,
1077
+ updatedAt: item.updated_at,
1078
+ htmlUrl: item.html_url,
1079
+ }))
1080
+ return { returned: items.length, items }
1081
+ }
1082
+
1083
+ async function createIssue(owner, name, title, body) {
1084
+ const repo = repoPath(owner, name)
1085
+ const json = await call(`${repo}/issues`, { method: 'POST', body: { title, body: body || '' } })
1086
+ return { number: json.number, title: json.title, htmlUrl: json.html_url }
1087
+ }
1088
+
1089
+ async function commentIssue(owner, name, number, body) {
1090
+ const repo = repoPath(owner, name)
1091
+ const json = await call(`${repo}/issues/${number}/comments`, { method: 'POST', body: { body } })
1092
+ return { id: json.id, htmlUrl: json.html_url }
1093
+ }
1094
+
1095
+ async function listPulls(owner, name, state) {
1096
+ const repo = repoPath(owner, name)
1097
+ const json = await call(`${repo}/pulls?state=${state || 'open'}&per_page=30`)
1098
+ const items = (Array.isArray(json) ? json : []).map((item) => ({
1099
+ number: item.number,
1100
+ title: item.title,
1101
+ state: item.state,
1102
+ draft: Boolean(item.draft),
1103
+ user: item.user ? item.user.login : '',
1104
+ head: item.head ? item.head.ref : '',
1105
+ base: item.base ? item.base.ref : '',
1106
+ mergeableState: item.mergeable_state || '',
1107
+ updatedAt: item.updated_at,
1108
+ htmlUrl: item.html_url,
1109
+ }))
1110
+ return { returned: items.length, items }
1111
+ }
1112
+
1113
+ async function createPull(owner, name, head, base, title, body) {
1114
+ const repo = repoPath(owner, name)
1115
+ const json = await call(`${repo}/pulls`, { method: 'POST', body: { head, base, title, body: body || '' } })
1116
+ return { number: json.number, htmlUrl: json.html_url, state: json.state }
1117
+ }
1118
+
1119
+ async function mergePull(owner, name, number, method) {
1120
+ const repo = repoPath(owner, name)
1121
+ const json = await call(`${repo}/pulls/${number}/merge`, {
1122
+ method: 'PUT',
1123
+ body: { merge_method: method || 'squash' },
1124
+ })
1125
+ return { merged: Boolean(json.merged), message: json.message || '', sha: json.sha || null }
1126
+ }
1127
+
1128
+ async function listRuns(owner, name) {
1129
+ const repo = repoPath(owner, name)
1130
+ const json = await call(`${repo}/actions/runs?per_page=15`)
1131
+ const runs = json.workflow_runs || []
1132
+ return {
1133
+ total: json.total_count || runs.length,
1134
+ items: runs.map((run) => ({
1135
+ id: run.id,
1136
+ name: run.name,
1137
+ status: run.status,
1138
+ conclusion: run.conclusion,
1139
+ branch: run.head_branch,
1140
+ event: run.event,
1141
+ createdAt: run.created_at,
1142
+ htmlUrl: run.html_url,
1143
+ })),
1144
+ }
1145
+ }
1146
+
1147
+ async function rerunWorkflow(owner, name, runId) {
1148
+ const repo = repoPath(owner, name)
1149
+ await call(`${repo}/actions/runs/${runId}/rerun`, { method: 'POST' })
1150
+ return { ok: true, runId }
1151
+ }
1152
+
1153
+ return {
1154
+ call,
1155
+ installToken: installationToken,
1156
+ status,
1157
+ installations,
1158
+ selectedInstallation,
1159
+ selectInstallation: async (id) => {
1160
+ const list = await installations()
1161
+ const match = list.find((item) => String(item.id) === String(id))
1162
+ if (!match) throw new Error(`找不到 installation ${id}`)
1163
+ await writeRecord(INSTALL_CRED, match)
1164
+ installationTokenCache = null
1165
+ return match
1166
+ },
1167
+ beginManifest,
1168
+ completeManifest,
1169
+ resetApp,
1170
+ appConfigured: async () => Boolean(await readApp()),
1171
+ waitForCredentials,
1172
+ readRecord,
1173
+ writeRecord,
1174
+ listRepositories,
1175
+ readTree,
1176
+ readFile,
1177
+ writeFile,
1178
+ listIssues,
1179
+ createIssue,
1180
+ commentIssue,
1181
+ listPulls,
1182
+ createPull,
1183
+ mergePull,
1184
+ listRuns,
1185
+ rerunWorkflow,
1186
+ }
1187
+ }
1188
+
1189
+ /* ------------------------------------------------------------------ */
1190
+ /* Plugin preflight and publishing */
1191
+ /* ------------------------------------------------------------------ */
1192
+
1193
+ async function exists(target) {
1194
+ try {
1195
+ await fs.access(target)
1196
+ return true
1197
+ } catch {
1198
+ return false
1199
+ }
1200
+ }
1201
+
1202
+ async function collectFiles(root, budget) {
1203
+ const files = []
1204
+ let total = 0
1205
+ let skipped = 0
1206
+ async function walk(dir) {
1207
+ let entries = []
1208
+ try {
1209
+ entries = await fs.readdir(dir, { withFileTypes: true })
1210
+ } catch {
1211
+ return
1212
+ }
1213
+ for (const entry of entries) {
1214
+ if (files.length >= 300) return
1215
+ const full = path.join(dir, entry.name)
1216
+ if (entry.isDirectory()) {
1217
+ if (SKIP_DIRS.has(entry.name)) continue
1218
+ await walk(full)
1219
+ continue
1220
+ }
1221
+ if (!entry.isFile()) continue
1222
+ const stat = await fs.stat(full).catch(() => null)
1223
+ if (!stat) continue
1224
+ if (stat.size > 1024 * 1024) {
1225
+ skipped += 1
1226
+ continue
1227
+ }
1228
+ if (total + stat.size > budget) {
1229
+ skipped += 1
1230
+ continue
1231
+ }
1232
+ const content = await fs.readFile(full)
1233
+ total += content.length
1234
+ files.push({ path: path.relative(root, full).split(path.sep).join('/'), content })
1235
+ }
1236
+ }
1237
+ await walk(root)
1238
+ return { files, total, skipped }
1239
+ }
1240
+
1241
+ function findSecrets(files) {
1242
+ const hits = []
1243
+ for (const file of files) {
1244
+ if (!/\.(js|mjs|cjs|ts|tsx|jsx|json|ya?ml|md|txt|env|sh|ps1|ini|toml)$/i.test(file.path) && !file.path.includes('.env')) {
1245
+ continue
1246
+ }
1247
+ const text = file.content.toString('utf8')
1248
+ for (const [name, pattern] of SECRET_PATTERNS) {
1249
+ const match = pattern.exec(text)
1250
+ if (!match) continue
1251
+ const line = text.slice(0, match.index).split('\n').length
1252
+ hits.push({ file: file.path, line, kind: name })
1253
+ }
1254
+ }
1255
+ return hits
1256
+ }
1257
+
1258
+ async function preflight(dir, gh, cfg) {
1259
+ const checks = []
1260
+ const add = (id, level, title, detail) => checks.push({ id, level, title, detail: detail || '' })
1261
+ const root = path.resolve(dir)
1262
+ const packagePath = path.join(root, 'package.json')
1263
+
1264
+ if (!(await exists(root))) {
1265
+ add('dir', 'block', '插件目录不存在', root)
1266
+ return { dir: root, checks, ready: false }
1267
+ }
1268
+ if (!(await exists(packagePath))) {
1269
+ add('package.json', 'block', '根目录缺 package.json', '')
1270
+ return { dir: root, checks, ready: false }
1271
+ }
1272
+
1273
+ let pkg = null
1274
+ try {
1275
+ pkg = JSON.parse(await fs.readFile(packagePath, 'utf8'))
1276
+ add('package.json', 'pass', 'package.json 可解析', `${pkg.name || '未命名'}@${pkg.version || '?'}`)
1277
+ } catch (error) {
1278
+ add('package.json', 'block', 'package.json 不是合法 JSON', errorMessage(error))
1279
+ return { dir: root, checks, ready: false }
1280
+ }
1281
+
1282
+ if (!pkg.name) add('name', 'block', '缺少 name 字段', '')
1283
+ else add('name', 'pass', '包名', String(pkg.name))
1284
+ if (!semverCore(pkg.version)) add('version', 'block', 'version 不是 semver', String(pkg.version || ''))
1285
+ else add('version', 'pass', '版本号', String(pkg.version))
1286
+
1287
+ const patchPath = pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch ? pkg.dsh.bundle.patch : ''
1288
+ if (!patchPath) add('bundle.patch', 'block', '未声明 dsh.bundle.patch', '这不是一个 DSH bundle')
1289
+ else if (!(await exists(path.join(root, patchPath)))) add('bundle.patch', 'block', 'patch 文件不存在', patchPath)
1290
+ else add('bundle.patch', 'pass', 'bundle patch', patchPath)
1291
+
1292
+ // Bundles may declare the Host entry through exports instead of main.
1293
+ const dotExport = pkg.exports && typeof pkg.exports === 'object' ? pkg.exports['.'] : pkg.exports
1294
+ const mainEntry =
1295
+ typeof pkg.main === 'string' && pkg.main
1296
+ ? pkg.main
1297
+ : typeof dotExport === 'string'
1298
+ ? dotExport
1299
+ : dotExport && typeof dotExport === 'object' && typeof dotExport.default === 'string'
1300
+ ? dotExport.default
1301
+ : ''
1302
+ if (mainEntry) {
1303
+ if (await exists(path.join(root, mainEntry))) add('entry', 'pass', '入口文件存在', mainEntry)
1304
+ else add('entry', 'block', '入口文件不存在', mainEntry)
1305
+ } else {
1306
+ add('entry', 'warn', '未声明 main 或 exports["."] 入口', '发布前确认 exports 指向真实文件')
1307
+ }
1308
+
1309
+ if (pkg.dsh && pkg.dsh.client) {
1310
+ const clientFile = typeof pkg.exports === 'object' && pkg.exports['./client'] ? pkg.exports['./client'] : './client.js'
1311
+ const resolved = typeof clientFile === 'string' ? clientFile : clientFile.default || ''
1312
+ if (resolved && (await exists(path.join(root, resolved)))) add('client', 'pass', '客户端入口存在', resolved)
1313
+ else add('client', 'block', 'dsh.client 声明的客户端入口不存在', resolved || '')
1314
+ }
1315
+
1316
+ for (const [file, level, title] of [
1317
+ ['README.md', 'warn', '缺 README.md'],
1318
+ ['LICENSE', 'warn', '缺 LICENSE'],
1319
+ ['.gitignore', 'warn', '缺 .gitignore'],
1320
+ ]) {
1321
+ if (!(await exists(path.join(root, file)))) add(file, level, title, '')
1322
+ }
1323
+
1324
+ const collected = await collectFiles(root, cfg.maxPushBytes)
1325
+ const secrets = findSecrets(collected.files)
1326
+ if (secrets.length) {
1327
+ add(
1328
+ 'secrets',
1329
+ 'block',
1330
+ `检出 ${secrets.length} 处疑似密钥`,
1331
+ secrets.slice(0, 5).map((hit) => `${hit.file}:${hit.line} ${hit.kind}`).join('; '),
1332
+ )
1333
+ } else {
1334
+ add('secrets', 'pass', '未检出疑似密钥', `扫描 ${collected.files.length} 个文件`)
1335
+ }
1336
+
1337
+ const hardPaths = []
1338
+ for (const file of collected.files) {
1339
+ if (!/\.(js|mjs|ts|json|md)$/.test(file.path)) continue
1340
+ const text = file.content.toString('utf8')
1341
+ const match = /[A-Za-z]:\\\\Users\\\\|[A-Za-z]:\\Users\\|\/Users\/[A-Za-z0-9._-]+\//.exec(text)
1342
+ if (match) hardPaths.push(file.path)
1343
+ }
1344
+ if (hardPaths.length) add('local-paths', 'warn', '代码里出现本机绝对路径', hardPaths.slice(0, 5).join(', '))
1345
+
1346
+ add('files', 'info', `待推送 ${collected.files.length} 个文件`, fmtBytes(collected.total) + (collected.skipped ? `(跳过 ${collected.skipped} 个大文件)` : ''))
1347
+
1348
+ if (gh) {
1349
+ try {
1350
+ const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}`)
1351
+ if (response.status === 200) {
1352
+ const data = await response.json()
1353
+ const latest = data['dist-tags'] ? data['dist-tags'].latest : ''
1354
+ if (latest === pkg.version) {
1355
+ add('npm', 'block', 'npm 上已存在同名同版本', `${pkg.name}@${latest}`)
1356
+ } else {
1357
+ add('npm', 'info', 'npm 上已存在该包', `latest ${latest}`)
1358
+ }
1359
+ } else if (response.status === 404) {
1360
+ add('npm', 'pass', 'npm 上没有同名包', pkg.name)
1361
+ } else {
1362
+ add('npm', 'info', 'npm 查询未确认', `HTTP ${response.status}`)
1363
+ }
1364
+ } catch (error) {
1365
+ add('npm', 'info', 'npm 查询失败', errorMessage(error))
1366
+ }
1367
+ }
1368
+
1369
+ const ready = !checks.some((check) => check.level === 'block')
1370
+ return { dir: root, package: { name: pkg.name, version: pkg.version }, files: collected.files.length, checks, ready }
1371
+ }
1372
+
1373
+ async function ensureRepo(gh, owner, name) {
1374
+ try {
1375
+ const repo = await gh.call(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`)
1376
+ return repo
1377
+ } catch (error) {
1378
+ if (error.status === 404) {
1379
+ throw new GhError(
1380
+ 404,
1381
+ 'REPO_MISSING',
1382
+ `仓库 ${owner}/${name} 不存在或未授权给当前安装:先到 GitHub 建仓并把该仓库加入 App 的授权范围(https://github.com/new?name=${encodeURIComponent(name)})`,
1383
+ )
1384
+ }
1385
+ throw error
1386
+ }
1387
+ }
1388
+
1389
+ async function pushFiles(gh, owner, name, branch, files, message) {
1390
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1391
+ const repo = repoPath
1392
+ const encodePath = (filePath) => String(filePath).split('/').map(encodeURIComponent).join('/')
1393
+ let baseCommitSha = null
1394
+ let baseTreeSha = null
1395
+ let bootstrapped = false
1396
+ let stage = 'read-ref'
1397
+ try {
1398
+ stage = 'read-ref'
1399
+ let ref = null
1400
+ try {
1401
+ ref = await gh.call(`${repo}/git/ref/heads/${encodeURIComponent(branch)}`)
1402
+ } catch (error) {
1403
+ // A missing branch answers 404; a repository with no commit at all answers
1404
+ // 409 "Git Repository is empty.". Both mean "no base to build on".
1405
+ const empty = error.status === 409 || /repository is empty/i.test(String(error.message || ''))
1406
+ if (error.status !== 404 && !empty) throw error
1407
+ if (empty) bootstrapped = true
1408
+ ref = null
1409
+ }
1410
+ baseCommitSha = ref && ref.object ? ref.object.sha : null
1411
+
1412
+ // The Git Data API refuses to create blobs in a repository without commits,
1413
+ // so seed one file through the contents API first and then build on it.
1414
+ if (!baseCommitSha && bootstrapped) {
1415
+ stage = 'bootstrap-empty-repo'
1416
+ const seed =
1417
+ files.find((file) => /^readme\.md$/i.test(file.path)) ||
1418
+ files.find((file) => /^\.gitignore$/i.test(file.path)) ||
1419
+ files[0] || { path: '.gitkeep', content: Buffer.from('') }
1420
+ await gh.call(`${repo}/contents/${encodePath(seed.path)}`, {
1421
+ method: 'PUT',
1422
+ body: { message: message || 'chore: initial commit', content: seed.content.toString('base64') },
1423
+ })
1424
+ stage = 'resync-after-bootstrap'
1425
+ const meta = await gh.call(repo)
1426
+ const defaultBranch = meta.default_branch || branch
1427
+ const seedRef = await gh.call(`${repo}/git/ref/heads/${encodeURIComponent(defaultBranch)}`)
1428
+ const seedSha = seedRef.object ? seedRef.object.sha : null
1429
+ if (!seedSha) throw new Error(`初始化后仍读不到 ${defaultBranch} 分支`)
1430
+ if (defaultBranch !== branch) {
1431
+ await gh.call(`${repo}/git/refs`, { method: 'POST', body: { ref: `refs/heads/${branch}`, sha: seedSha } })
1432
+ }
1433
+ baseCommitSha = seedSha
1434
+ const seedCommit = await gh.call(`${repo}/git/commits/${seedSha}`)
1435
+ baseTreeSha = seedCommit.tree ? seedCommit.tree.sha : null
1436
+ }
1437
+
1438
+ if (baseCommitSha && !baseTreeSha) {
1439
+ stage = 'read-base-commit'
1440
+ const base = await gh.call(`${repo}/git/commits/${baseCommitSha}`)
1441
+ baseTreeSha = base.tree ? base.tree.sha : null
1442
+ }
1443
+
1444
+ stage = 'create-blobs'
1445
+ const blobs = []
1446
+ for (const file of files) {
1447
+ const blob = await gh.call(`${repo}/git/blobs`, {
1448
+ method: 'POST',
1449
+ body: { content: file.content.toString('base64'), encoding: 'base64' },
1450
+ })
1451
+ blobs.push(blob.sha)
1452
+ }
1453
+
1454
+ stage = 'create-tree'
1455
+ const treeBody = {
1456
+ tree: files.map((file, index) => ({ path: file.path, mode: '100644', type: 'blob', sha: blobs[index] })),
1457
+ }
1458
+ if (baseTreeSha) treeBody.base_tree = baseTreeSha
1459
+ const tree = await gh.call(`${repo}/git/trees`, { method: 'POST', body: treeBody })
1460
+
1461
+ stage = 'create-commit'
1462
+ const commitBody = { message, tree: tree.sha }
1463
+ if (baseCommitSha) commitBody.parents = [baseCommitSha]
1464
+ const commit = await gh.call(`${repo}/git/commits`, { method: 'POST', body: commitBody })
1465
+
1466
+ stage = 'update-ref'
1467
+ if (baseCommitSha) {
1468
+ await gh.call(`${repo}/git/refs/heads/${encodeURIComponent(branch)}`, {
1469
+ method: 'PATCH',
1470
+ body: { sha: commit.sha, force: false },
1471
+ })
1472
+ } else {
1473
+ await gh.call(`${repo}/git/refs`, {
1474
+ method: 'POST',
1475
+ body: { ref: `refs/heads/${branch}`, sha: commit.sha },
1476
+ })
1477
+ }
1478
+ return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped }
1479
+ } catch (error) {
1480
+ // Naming the failed stage turns "Git Repository is empty." into something
1481
+ // actionable instead of a single opaque message.
1482
+ throw new Error(`推送在「${stage}」阶段失败:${errorMessage(error)}`)
1483
+ }
1484
+ }
1485
+
1486
+ async function mergeTopics(gh, owner, name, topics) {
1487
+ const repo = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1488
+ const current = await gh.call(`${repo}/topics`, { headers: { Accept: 'application/vnd.github+json' } })
1489
+ const existing = Array.isArray(current.names) ? current.names : []
1490
+ const merged = Array.from(new Set([...existing, ...topics].map((item) => String(item).toLowerCase())))
1491
+ // The topics endpoint replaces the whole set, so always send the union.
1492
+ const updated = await gh.call(`${repo}/topics`, {
1493
+ method: 'PUT',
1494
+ headers: { Accept: 'application/vnd.github+json' },
1495
+ body: { names: merged },
1496
+ })
1497
+ return { before: existing, after: Array.isArray(updated.names) ? updated.names : merged }
1498
+ }
1499
+
1500
+ async function createRelease(gh, owner, name, version, branch, notes) {
1501
+ const repo = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1502
+ const tag = `v${version}`
1503
+ try {
1504
+ const release = await gh.call(`${repo}/releases/tags/${encodeURIComponent(tag)}`)
1505
+ return { skipped: true, tag, htmlUrl: release.html_url, reason: '该 tag 的 Release 已存在' }
1506
+ } catch (error) {
1507
+ if (error.status !== 404) throw error
1508
+ }
1509
+ const release = await gh.call(`${repo}/releases`, {
1510
+ method: 'POST',
1511
+ body: {
1512
+ tag_name: tag,
1513
+ target_commitish: branch,
1514
+ name: tag,
1515
+ body: notes || `Release ${tag}`,
1516
+ draft: false,
1517
+ prerelease: false,
1518
+ },
1519
+ })
1520
+ return { skipped: false, tag, htmlUrl: release.html_url }
1521
+ }
1522
+
1523
+ const WORKFLOW_DIR = '.github/workflows'
1524
+
1525
+ function publishWorkflowYaml() {
1526
+ // npm cannot attach a trusted publisher to a package that does not exist yet,
1527
+ // so this workflow also accepts an optional NPM_TOKEN secret for the very
1528
+ // first publish; after that, OIDC needs no secret at all.
1529
+ return `name: publish
1530
+ on:
1531
+ workflow_dispatch:
1532
+ inputs:
1533
+ dry_run:
1534
+ description: 'Run npm publish --dry-run'
1535
+ type: boolean
1536
+ default: false
1537
+ permissions:
1538
+ contents: read
1539
+ id-token: write
1540
+ concurrency:
1541
+ group: npm-publish
1542
+ cancel-in-progress: false
1543
+ jobs:
1544
+ publish:
1545
+ runs-on: ubuntu-latest
1546
+ steps:
1547
+ - uses: actions/checkout@v4
1548
+ - uses: actions/setup-node@v4
1549
+ with:
1550
+ node-version: '22'
1551
+ registry-url: 'https://registry.npmjs.org'
1552
+ - name: Ensure npm supports trusted publishing (needs >= 11.5.1)
1553
+ run: npm install -g npm@11 && npm --version
1554
+ - name: Show target
1555
+ run: node -e "const p=require('./package.json');console.log(p.name+'@'+p.version)"
1556
+ - name: Publish
1557
+ run: npm publish --provenance --access public \${{ inputs.dry_run && '--dry-run' || '' }}
1558
+ env:
1559
+ NODE_AUTH_TOKEN: \${{ secrets.NPM_TOKEN }}
1560
+ `
1561
+ }
1562
+
1563
+ async function repoFile(gh, owner, repo, filePath, ref) {
1564
+ try {
1565
+ return await gh.readFile(owner, repo, filePath, ref)
1566
+ } catch (error) {
1567
+ if (error.status === 404) return null
1568
+ throw error
1569
+ }
1570
+ }
1571
+
1572
+ async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
1573
+ const filePath = `${WORKFLOW_DIR}/${workflowFile}`
1574
+ const desired = publishWorkflowYaml()
1575
+ const existing = await repoFile(gh, owner, repo, filePath, branch)
1576
+ if (existing && String(existing.text).trim() === desired.trim()) {
1577
+ return { path: filePath, changed: false }
1578
+ }
1579
+ await gh.writeFile(
1580
+ owner,
1581
+ repo,
1582
+ filePath,
1583
+ desired,
1584
+ existing ? 'ci: update npm publish workflow' : 'ci: add npm publish workflow',
1585
+ existing ? existing.sha : undefined,
1586
+ branch,
1587
+ )
1588
+ return { path: filePath, changed: true }
1589
+ }
1590
+
1591
+ async function dispatchWorkflow(gh, owner, repo, workflowFile, ref, inputs) {
1592
+ const body = inputs && Object.keys(inputs).length ? { ref, inputs } : { ref }
1593
+ await gh.call(
1594
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/workflows/${encodeURIComponent(workflowFile)}/dispatches`,
1595
+ { method: 'POST', body },
1596
+ )
1597
+ }
1598
+
1599
+ async function waitForWorkflowRun(gh, owner, repo, workflowFile, sinceMs, timeoutMs) {
1600
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
1601
+ const deadline = Date.now() + timeoutMs
1602
+ let last = null
1603
+ while (Date.now() < deadline) {
1604
+ const data = await gh
1605
+ .call(`${repoPath}/actions/workflows/${encodeURIComponent(workflowFile)}/runs?event=workflow_dispatch&per_page=5`)
1606
+ .catch(() => null)
1607
+ const run = data && Array.isArray(data.workflow_runs) ? data.workflow_runs[0] : null
1608
+ if (run && Date.parse(run.created_at) >= sinceMs - 15000) {
1609
+ last = {
1610
+ id: run.id,
1611
+ status: run.status,
1612
+ conclusion: run.conclusion || null,
1613
+ url: run.html_url,
1614
+ createdAt: run.created_at,
1615
+ }
1616
+ if (run.status === 'completed') return last
1617
+ }
1618
+ await new Promise((resolve) => setTimeout(resolve, 3000))
1619
+ }
1620
+ return last ? { ...last, status: 'timeout' } : { status: 'unknown', url: null }
1621
+ }
1622
+
1623
+ function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription }) {
1624
+ const repositoryUrl = `https://github.com/${owner}/${repo}`
1625
+ const engines =
1626
+ pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
1627
+ ? { dsh: pkg.engines.dsh.trim() }
1628
+ : {}
1629
+ const plugin = {
1630
+ name: pkg.name,
1631
+ title: entryTitle || pkg.name,
1632
+ description: entryDescription || pkg.description || pkg.name,
1633
+ // Resolved against the index URL, so the icon ships with the repository.
1634
+ icon: '../icon.svg',
1635
+ author: owner,
1636
+ repository: { url: repositoryUrl },
1637
+ metadata: {
1638
+ keywords: Array.isArray(pkg.keywords) ? pkg.keywords.filter((item) => typeof item === 'string').slice(0, 20) : [],
1639
+ },
1640
+ versions: [
1641
+ {
1642
+ version: pkg.version,
1643
+ publishTimestamp: Math.floor(Date.now() / 1000),
1644
+ source: { type: 'git', url: repositoryUrl, commit },
1645
+ engines,
1646
+ },
1647
+ ],
1648
+ }
1649
+ if (pkg.homepage && /^https?:\/\//.test(pkg.homepage)) plugin.homepage = pkg.homepage
1650
+ return {
1651
+ format: 1,
1652
+ title: `${owner} DSH plugin index`,
1653
+ description: 'Self-hosted DSH plugin index generated by the GitHub console.',
1654
+ metadata: {},
1655
+ plugins: [plugin],
1656
+ }
1657
+ }
1658
+
1659
+ async function readLocalPackage(dir) {
1660
+ const raw = await fs.readFile(path.join(dir, 'package.json'), 'utf8')
1661
+ const pkg = JSON.parse(raw)
1662
+ if (!pkg.name || !pkg.version) throw new Error('package.json 缺少 name 或 version')
1663
+ return pkg
1664
+ }
1665
+
1666
+ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
1667
+ // The registry answers whether a first publish is still needed; the workflow
1668
+ // file tells whether the automation is already in the repository.
1669
+ let pkg = null
1670
+ try {
1671
+ pkg = await readLocalPackage(dir)
1672
+ } catch {
1673
+ pkg = null
1674
+ }
1675
+ const name = pkg ? pkg.name : ''
1676
+ let exists = null
1677
+ if (name) {
1678
+ try {
1679
+ const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`, {
1680
+ headers: { 'User-Agent': `dsh-github-console/${PLUGIN_VERSION}` },
1681
+ })
1682
+ exists = response.status === 200
1683
+ } catch {
1684
+ exists = null
1685
+ }
1686
+ }
1687
+ const workflowPath = `${WORKFLOW_DIR}/${cfg.npmWorkflow}`
1688
+ const workflow = owner && repo ? await repoFile(gh, owner, repo, workflowPath, cfg.publishBranch).catch(() => null) : null
1689
+ const workflowPresent = Boolean(workflow)
1690
+ const phase = !name ? 'unknown' : exists === true ? (workflowPresent ? 'ready' : 'needs-workflow') : 'needs-first-publish'
1691
+ return {
1692
+ name,
1693
+ version: pkg ? pkg.version : '',
1694
+ registryHasPackage: exists,
1695
+ workflowPath,
1696
+ workflowPresent,
1697
+ phase,
1698
+ urls: {
1699
+ package: name ? `https://www.npmjs.com/package/${name}` : '',
1700
+ trustedPublisher: name ? `https://www.npmjs.com/package/${name}/access` : '',
1701
+ secrets: owner && repo ? `https://github.com/${owner}/${repo}/settings/secrets/actions/new` : '',
1702
+ // /settings/~tokens is a 404; the token list lives under the npm user name.
1703
+ tokens: cfg.npmUser ? `https://www.npmjs.com/settings/${cfg.npmUser}/tokens` : 'https://www.npmjs.com/settings/',
1704
+ workflow: owner && repo ? `https://github.com/${owner}/${repo}/blob/${cfg.publishBranch}/${workflowPath}` : '',
1705
+ },
1706
+ trustedPublisherValues: {
1707
+ provider: 'GitHub Actions',
1708
+ userOrOrg: owner || '',
1709
+ repository: repo || '',
1710
+ workflowFile: cfg.npmWorkflow,
1711
+ allowedAction: 'npm publish',
1712
+ },
1713
+ steps:
1714
+ phase === 'needs-first-publish'
1715
+ ? [
1716
+ '打开下面的 npm 链接,Token name 填 dsh-github-console-ci(唯一的必填项)。',
1717
+ '勾上 Bypass two-factor authentication (2FA)——这是第二处需要你点的。',
1718
+ '其余保持默认(下表),点 Generate token 后立刻复制。',
1719
+ '打开 GitHub 的 Secrets 页面,Name 用 NPM_TOKEN,值粘贴 token,Add secret。',
1720
+ '回到这里点「生成 workflow 并触发发布」。',
1721
+ ]
1722
+ : phase === 'ready'
1723
+ ? [
1724
+ '包已经在 npm 上:打开该包的 Settings → Trusted Publisher,按下面五个值填一次(Provider 选 GitHub Actions)。',
1725
+ '注意 48 小时窗口:配好信任后要在 48 小时内跑一次发布,否则要重新配置。',
1726
+ '回到这里点「生成 workflow 并触发发布」。运行里会先把 npm 升到 11(可信发布要求 ≥ 11.5.1),再以 OIDC 身份发布,不再需要任何 token。',
1727
+ ]
1728
+ : ['先在 npm 上发一次这个包(本机没有 npm),或添加 NPM_TOKEN 后再触发。'],
1729
+ // Mirrors the real form field by field, so the user compares instead of guessing.
1730
+ fields: [
1731
+ { label: 'Token name', value: 'dsh-github-console-ci', note: '必填,只有这里需要你输入' },
1732
+ { label: 'Description', value: '(可留空)', note: '' },
1733
+ { label: 'Bypass two-factor authentication (2FA)', value: '勾上', note: '第二处需要你点的:CI 里没人能输 OTP' },
1734
+ { label: 'Allowed IP ranges', value: '留空', note: 'Actions 出口 IP 不固定' },
1735
+ { label: 'Permissions', value: 'Read and write (publish and stage)', note: '不要选 stage only' },
1736
+ { label: 'Select packages', value: 'All packages', note: '新包还不存在,只有它能覆盖未来创建的包' },
1737
+ { label: 'Organizations → Permissions', value: 'No access', note: '' },
1738
+ { label: 'Expiration Date', value: '7 days(默认)', note: '最长 90 天;发完就撤销' },
1739
+ ],
1740
+ }
1741
+ }
1742
+
1743
+ async function probeMarket(input, gh, cfg) {
1744
+ const checkedAt = new Date().toISOString()
1745
+ const results = []
1746
+ const push = (id, state, detail, extra = {}) => results.push({ id, state, detail, checkedAt, ...extra })
1747
+
1748
+ // 1. npm package presence
1749
+ try {
1750
+ const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(input.name)}/latest`)
1751
+ if (response.status === 200) {
1752
+ const data = await response.json()
1753
+ push('npm', 'listed', `${input.name}@${data.version}`, { version: data.version })
1754
+ } else if (response.status === 404) {
1755
+ push('npm', 'absent', 'npm 上没有这个包名')
1756
+ } else {
1757
+ push('npm', 'unknown', `npm 返回 HTTP ${response.status}`)
1758
+ }
1759
+ } catch (error) {
1760
+ push('npm', 'unknown', `npm 探测失败:${errorMessage(error)}`)
1761
+ }
1762
+
1763
+ // 2. GitHub side: release tag and the topic crawlers look for
1764
+ if (gh && input.owner && input.repo) {
1765
+ try {
1766
+ const repo = `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}`
1767
+ const meta = await gh.call(`${repo}`)
1768
+ const topics = Array.isArray(meta.topics) ? meta.topics : []
1769
+ push(
1770
+ 'github-topic',
1771
+ topics.includes(cfg.topic) ? 'listed' : 'absent',
1772
+ topics.includes(cfg.topic) ? `已带 ${cfg.topic} topic` : `缺少 ${cfg.topic} topic`,
1773
+ { topics },
1774
+ )
1775
+ } catch (error) {
1776
+ push('github-topic', 'unknown', `仓库信息读取失败:${errorMessage(error)}`)
1777
+ }
1778
+ if (input.version) {
1779
+ try {
1780
+ const repo = `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}`
1781
+ const release = await gh.call(`${repo}/releases/tags/${encodeURIComponent(`v${input.version}`)}`)
1782
+ push('github-release', 'listed', `v${input.version}`, { htmlUrl: release.html_url })
1783
+ } catch (error) {
1784
+ push(
1785
+ 'github-release',
1786
+ error.status === 404 ? 'absent' : 'unknown',
1787
+ error.status === 404 ? `没有 v${input.version} 的 Release` : errorMessage(error),
1788
+ )
1789
+ }
1790
+ } else {
1791
+ push('github-release', 'unknown', '未提供版本号,已跳过 Release 探测')
1792
+ }
1793
+ } else {
1794
+ push('github-topic', 'unknown', '未提供 owner/repo,已跳过 GitHub 侧探测')
1795
+ push('github-release', 'unknown', '未提供 owner/repo,已跳过 GitHub 侧探测')
1796
+ }
1797
+
1798
+ // 3. Configured market indexes (format 1 JSON with an items/plugins array)
1799
+ for (const url of cfg.marketIndexUrls) {
1800
+ try {
1801
+ const response = await fetch(url)
1802
+ if (!response.ok) {
1803
+ push(`index:${url}`, 'unknown', `HTTP ${response.status}`)
1804
+ continue
1805
+ }
1806
+ const text = await response.text()
1807
+ const found = text.includes(`"${input.name}"`) || text.includes(`"${input.name}@`)
1808
+ push(`index:${url}`, found ? 'listed' : 'absent', found ? '索引里出现该包名' : '索引里没有该包名')
1809
+ } catch (error) {
1810
+ push(`index:${url}`, 'unknown', `索引探测失败:${errorMessage(error)}`)
1811
+ }
1812
+ }
1813
+
1814
+ return {
1815
+ input,
1816
+ results,
1817
+ // A failed probe is never reported as "absent": crawlers lag 1-2 days.
1818
+ summary: results.some((item) => item.state === 'listed')
1819
+ ? 'listed'
1820
+ : results.some((item) => item.state === 'unknown')
1821
+ ? 'unknown'
1822
+ : 'absent',
1823
+ }
1824
+ }
1825
+
1826
+ /* ------------------------------------------------------------------ */
1827
+ /* Jobs (publish state machine with resumable steps) */
1828
+ /* ------------------------------------------------------------------ */
1829
+
1830
+ function createJobStore() {
1831
+ const jobs = new Map()
1832
+ const order = []
1833
+ function create(meta) {
1834
+ const id = crypto.randomBytes(6).toString('hex')
1835
+ const job = {
1836
+ id,
1837
+ createdAt: new Date().toISOString(),
1838
+ finishedAt: null,
1839
+ ok: null,
1840
+ target: meta,
1841
+ steps: [
1842
+ { id: 'preflight', title: '体检', state: 'pending', detail: '' },
1843
+ { id: 'repo', title: '确认仓库', state: 'pending', detail: '' },
1844
+ { id: 'push', title: '推送文件', state: 'pending', detail: '' },
1845
+ { id: 'topics', title: '设置 topic', state: 'pending', detail: '' },
1846
+ { id: 'release', title: '创建 Release', state: 'pending', detail: '' },
1847
+ { id: 'market', title: '市场探测', state: 'pending', detail: '' },
1848
+ ],
1849
+ }
1850
+ jobs.set(id, job)
1851
+ order.push(id)
1852
+ while (order.length > 20) {
1853
+ const oldest = order.shift()
1854
+ if (oldest && jobs.get(oldest) && jobs.get(oldest).finishedAt) jobs.delete(oldest)
1855
+ }
1856
+ return job
1857
+ }
1858
+ return {
1859
+ create,
1860
+ get: (id) => jobs.get(id),
1861
+ list: () => order.filter((id) => jobs.has(id)).map((id) => jobs.get(id)),
1862
+ }
1863
+ }
1864
+
1865
+ function step(job, id) {
1866
+ return job.steps.find((item) => item.id === id)
1867
+ }
1868
+
1869
+ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts }) {
1870
+ const finish = (ok) => {
1871
+ job.ok = ok
1872
+ job.finishedAt = new Date().toISOString()
1873
+ return job
1874
+ }
1875
+
1876
+ const report = await preflight(dir, gh, cfg)
1877
+ step(job, 'preflight').state = report.ready ? 'done' : 'failed'
1878
+ step(job, 'preflight').detail = report.ready
1879
+ ? `${report.files} 个文件通过`
1880
+ : report.checks.filter((check) => check.level === 'block').map((check) => check.title).join(';')
1881
+ job.preflight = report
1882
+ if (!report.ready) return finish(false)
1883
+
1884
+ const pkgName = report.package ? report.package.name : ''
1885
+ const semver = version || (report.package ? report.package.version : '')
1886
+ if (!owner || !repo) {
1887
+ step(job, 'repo').state = 'failed'
1888
+ step(job, 'repo').detail = '缺少 owner/repo'
1889
+ return finish(false)
1890
+ }
1891
+
1892
+ try {
1893
+ const meta = await ensureRepo(gh, owner, repo)
1894
+ step(job, 'repo').state = 'done'
1895
+ step(job, 'repo').detail = `${owner}/${repo}(默认分支 ${meta.default_branch || 'main'})`
1896
+ } catch (error) {
1897
+ step(job, 'repo').state = 'failed'
1898
+ step(job, 'repo').detail = errorMessage(error)
1899
+ return finish(false)
1900
+ }
1901
+
1902
+ const branch = opts.branch || cfg.publishBranch
1903
+ try {
1904
+ const collected = await collectFiles(path.resolve(dir), cfg.maxPushBytes)
1905
+ const pushed = await pushFiles(gh, owner, repo, branch, collected.files, opts.message || `chore(release): v${semver}`)
1906
+ step(job, 'push').state = 'done'
1907
+ step(job, 'push').detail = `${pushed.files} 个文件 → ${branch} @ ${pushed.commit.slice(0, 7)}${pushed.firstCommit ? '(仓库原本为空,这是首个提交)' : ''}`
1908
+ job.commit = pushed.commit
1909
+ } catch (error) {
1910
+ step(job, 'push').state = 'failed'
1911
+ step(job, 'push').detail = errorMessage(error)
1912
+ return finish(false)
1913
+ }
1914
+
1915
+ try {
1916
+ const topics = await mergeTopics(gh, owner, repo, [cfg.topic])
1917
+ step(job, 'topics').state = 'done'
1918
+ step(job, 'topics').detail = topics.after.join(', ')
1919
+ } catch (error) {
1920
+ step(job, 'topics').state = 'failed'
1921
+ step(job, 'topics').detail = `${errorMessage(error)}(需 Administration: write)`
1922
+ }
1923
+
1924
+ try {
1925
+ const release = await createRelease(gh, owner, repo, semver, branch, notes)
1926
+ step(job, 'release').state = 'done'
1927
+ step(job, 'release').detail = release.skipped ? `${release.tag} 已存在,跳过` : `${release.tag} 已创建`
1928
+ job.releaseUrl = release.htmlUrl || null
1929
+ } catch (error) {
1930
+ step(job, 'release').state = 'failed'
1931
+ step(job, 'release').detail = errorMessage(error)
1932
+ }
1933
+
1934
+ try {
1935
+ const probe = await probeMarket({ name: pkgName, owner, repo, version: semver }, gh, cfg)
1936
+ step(job, 'market').state = 'done'
1937
+ step(job, 'market').detail = probe.results.map((item) => `${item.id}:${item.state}`).join(' · ')
1938
+ job.market = probe
1939
+ } catch (error) {
1940
+ step(job, 'market').state = 'failed'
1941
+ step(job, 'market').detail = errorMessage(error)
1942
+ }
1943
+
1944
+ const failed = job.steps.some((item) => item.state === 'failed')
1945
+ return finish(!failed)
1946
+ }
1947
+
1948
+ /* ------------------------------------------------------------------ */
1949
+ /* Plugin */
1950
+ /* ------------------------------------------------------------------ */
1951
+
1952
+ export const inject = ['tools']
1953
+
1954
+ export function apply(ctx, rawConfig) {
1955
+ const cfg = normalizeConfig(rawConfig)
1956
+ const transport = createTransport(cfg)
1957
+ const gh = createGithub(ctx, cfg, transport)
1958
+ const jobs = createJobStore()
1959
+ let bridgeToken = ''
1960
+ let webAttached = false
1961
+
1962
+ // Relative plugin directories resolve against the calling session's working
1963
+ // directory, then the deployment default; the profile directory is not a
1964
+ // useful base for a user's plugin checkout.
1965
+ const sessionBase = (exec) => {
1966
+ const workingDirectory = ctx.get('workingDirectory')
1967
+ if (workingDirectory) {
1968
+ const session = exec && exec.agent ? exec.agent.session : undefined
1969
+ if (session) {
1970
+ try {
1971
+ const directory = workingDirectory.get(session)
1972
+ if (typeof directory === 'string' && directory) return directory
1973
+ } catch {
1974
+ /* fall through */
1975
+ }
1976
+ }
1977
+ if (typeof workingDirectory.defaultDirectory === 'string' && workingDirectory.defaultDirectory) {
1978
+ return workingDirectory.defaultDirectory
1979
+ }
1980
+ }
1981
+ return process.cwd()
1982
+ }
1983
+
1984
+ const resolveDir = (dir, exec) => {
1985
+ if (!dir) throw new Error('需要插件目录 dir')
1986
+ return path.isAbsolute(dir) ? path.normalize(dir) : path.resolve(sessionBase(exec), dir)
1987
+ }
1988
+
1989
+ // Discovery must run before any sign-in: the panel shows local candidates and
1990
+ // an offline report first, and asks for GitHub only when the user publishes.
1991
+ // Project directories the user actually works in are the useful roots here;
1992
+ // the profile directory only holds installed links.
1993
+ const discoveryRoots = (extra) => {
1994
+ const roots = []
1995
+ const add = (value) => {
1996
+ if (typeof value !== 'string' || !value) return
1997
+ const normalized = path.normalize(value)
1998
+ if (!roots.includes(normalized)) roots.push(normalized)
1999
+ }
2000
+ add(extra)
2001
+ const registry = ctx.get('workspaceRegistry')
2002
+ if (registry && typeof registry.list === 'function') {
2003
+ try {
2004
+ for (const workspace of registry.list()) {
2005
+ if (!workspace) continue
2006
+ const directory =
2007
+ typeof workspace.directory === 'string'
2008
+ ? workspace.directory
2009
+ : typeof workspace.getDirectory === 'function'
2010
+ ? workspace.getDirectory()
2011
+ : typeof workspace.path === 'string'
2012
+ ? workspace.path
2013
+ : ''
2014
+ add(directory)
2015
+ }
2016
+ } catch {
2017
+ /* a registry that cannot list is not fatal for discovery */
2018
+ }
2019
+ }
2020
+ const workingDirectory = ctx.get('workingDirectory')
2021
+ if (workingDirectory && typeof workingDirectory.defaultDirectory === 'string') {
2022
+ add(workingDirectory.defaultDirectory)
2023
+ }
2024
+ add(process.cwd())
2025
+ return roots
2026
+ }
2027
+
2028
+ const discover = (extra) => discoverPlugins(discoveryRoots(extra))
2029
+
2030
+ async function withToken() {
2031
+ if (!bridgeToken) {
2032
+ const credentials = await gh.waitForCredentials()
2033
+ if (!credentials) return crypto.randomBytes(32).toString('hex')
2034
+ const record = await credentials.readRecord(BRIDGE_CRED).catch(() => undefined)
2035
+ const saved = record && record.payload && typeof record.payload.token === 'string' ? record.payload.token : ''
2036
+ if (saved.length >= 32) return saved
2037
+ const token = crypto.randomBytes(32).toString('hex')
2038
+ await credentials.modifyRecord(BRIDGE_CRED, async () => ({ kind: 'grant', payload: { token } }))
2039
+ return token
2040
+ }
2041
+ return bridgeToken
2042
+ }
2043
+
2044
+ const tokenPromise = withToken()
2045
+ .then((token) => {
2046
+ bridgeToken = token
2047
+ return token
2048
+ })
2049
+ .catch(() => '')
2050
+
2051
+ const bridgeInfo = () => ({ base: '', token: bridgeToken, setup: `${PREFIX}/setup` })
2052
+ const bridgeStatus = () => ({
2053
+ webAttached,
2054
+ tokenPersisted: bridgeToken.length >= 32,
2055
+ routes: [`${PREFIX}/setup`, `${PREFIX}/callback`, `${PREFIX}/api/*`],
2056
+ })
2057
+
2058
+ /* ---------------- HTTP surface ---------------- */
2059
+
2060
+ async function handleSetup(request, response) {
2061
+ const state = gh.beginManifest()
2062
+ const origin = requestOrigin(request)
2063
+ const manifest = buildManifestFor(origin)
2064
+ const action = `https://github.com/settings/apps/new?state=${encodeURIComponent(state)}`
2065
+ const html = `<!doctype html><meta charset="utf-8"><title>注册 GitHub App</title>
2066
+ <body style="font-family:system-ui,-apple-system,'Segoe UI',sans-serif;background:#f6f7f9;margin:0;padding:48px 16px">
2067
+ <div style="max-width:560px;margin:0 auto;background:#fff;border:1px solid #e3e6ea;border-radius:12px;padding:26px 30px">
2068
+ <h2 style="margin:0 0 10px;font-size:19px">正在跳转到 GitHub 创建 App</h2>
2069
+ <p style="color:#57606a;font-size:13px;line-height:1.7">GitHub 页面上只需点一次 <b>Create GitHub App</b>,回调地址已预填为 <code>${escapeHtml(origin + PREFIX + '/callback')}</code>。若页面没有自动跳转,点下面的按钮。</p>
2070
+ <form id="dgh-form" method="post" action="${escapeHtml(action)}">
2071
+ <input type="hidden" name="manifest" value="${escapeHtml(JSON.stringify(manifest))}">
2072
+ <button type="submit" style="margin-top:16px;padding:9px 18px;border:0;border-radius:8px;background:#3E6FD8;color:#fff;font-size:14px;cursor:pointer">打开 GitHub 创建页</button>
2073
+ </form>
2074
+ <script>document.getElementById('dgh-form').submit()</script>
2075
+ </div></body>`
2076
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
2077
+ response.end(html)
2078
+ }
2079
+
2080
+ function buildManifestFor(origin) {
2081
+ const suffix = crypto.randomBytes(3).toString('hex')
2082
+ return {
2083
+ name: cfg.appName || `DSH GitHub Console ${suffix}`,
2084
+ url: 'https://github.com/deepseek-ai/deepseek-harness',
2085
+ description: 'DeepSeek Harness GitHub console: repository tools and plugin publishing.',
2086
+ redirect_url: `${origin}${PREFIX}/callback`,
2087
+ public: false,
2088
+ request_oauth_on_install: false,
2089
+ default_permissions: {
2090
+ metadata: 'read',
2091
+ contents: 'write',
2092
+ administration: 'write',
2093
+ pull_requests: 'write',
2094
+ issues: 'write',
2095
+ actions: 'write',
2096
+ workflows: 'write',
2097
+ },
2098
+ default_events: [],
2099
+ }
2100
+ }
2101
+
2102
+ async function handleCallback(request, response, url) {
2103
+ const code = url.searchParams.get('code')
2104
+ const state = url.searchParams.get('state')
2105
+ const error = url.searchParams.get('error')
2106
+ if (error || !code) {
2107
+ sendHtml(response, 400, '注册中断', error || '没有收到 code,请回到侧栏重新发起注册。')
2108
+ return
2109
+ }
2110
+ try {
2111
+ const result = await gh.completeManifest(code, state)
2112
+ const installUrl = result.slug ? `https://github.com/apps/${result.slug}/installations/new` : 'https://github.com/apps'
2113
+ sendHtml(
2114
+ response,
2115
+ 200,
2116
+ 'GitHub App 已创建',
2117
+ '私钥已写入 DSH 凭据服务。下一步把 App 安装到你的账号或组织,安装完成后回到 DSH 侧栏。',
2118
+ `<p style="margin:14px 0 0"><a href="${escapeHtml(installUrl)}" style="display:inline-block;padding:8px 16px;border-radius:8px;background:#3E6FD8;color:#fff;text-decoration:none;font-size:13px">安装 App</a></p>` +
2119
+ `<p style="color:#8c959f;font-size:12px;margin-top:12px">App ID ${escapeHtml(result.appId)}</p>`,
2120
+ )
2121
+ } catch (failure) {
2122
+ sendHtml(response, 400, '换取 App 凭据失败', errorMessage(failure))
2123
+ }
2124
+ }
2125
+
2126
+ // One click instead of "Settings → Plugins → market sources → paste": the
2127
+ // plugin-market service owns that list, and it is reachable from the Host.
2128
+ function webOrigin() {
2129
+ const webServer = ctx.get('webServer')
2130
+ if (webServer && typeof webServer.getOrigin === 'function') {
2131
+ try {
2132
+ return String(webServer.getOrigin()).replace(/\/+$/, '')
2133
+ } catch {
2134
+ /* not bound yet */
2135
+ }
2136
+ }
2137
+ return String(process.env.DSH_WEB_URL || '').replace(/\/+$/, '')
2138
+ }
2139
+
2140
+ async function attachIndexToMarket(input = {}) {
2141
+ const record = await gh.readRecord(INDEX_CRED).catch(() => undefined)
2142
+ if (!record || typeof record.body !== 'string') {
2143
+ return { attached: false, reason: '还没有生成市场索引:先在「市场」页点「生成 / 更新市场索引」' }
2144
+ }
2145
+ const origin = webOrigin()
2146
+ const url = input.url || (origin ? `${origin}${PREFIX}/market/index.json` : '')
2147
+ if (!url) {
2148
+ return { attached: false, reason: '拿不到本机 web 地址:请在参数里明确传 url' }
2149
+ }
2150
+ const service = ctx.get('pluginMarket')
2151
+ if (!service || typeof service.setIndexes !== 'function') {
2152
+ return {
2153
+ attached: false,
2154
+ url,
2155
+ reason: '当前 profile 没有挂载 plugin-market 服务(官方市场 bundle 未启用),无法自动写入市场源',
2156
+ manual: '设置 → 插件 → 发现 / 市场源 → 粘贴上面这个地址',
2157
+ }
2158
+ }
2159
+ try {
2160
+ const before = typeof service.listIndexes === 'function' ? await service.listIndexes() : []
2161
+ const urls = before
2162
+ .map((item) => (typeof item === 'string' ? item : item && item.url))
2163
+ .filter((item) => typeof item === 'string' && item)
2164
+ if (!urls.includes(url)) urls.push(url)
2165
+ await service.setIndexes(urls)
2166
+ const after = typeof service.listIndexes === 'function' ? await service.listIndexes() : urls
2167
+ // Read it back through the market service itself: this is what Discover
2168
+ // does, so a successful search proves the index is readable end to end.
2169
+ let verification = null
2170
+ if (typeof service.search === 'function') {
2171
+ try {
2172
+ const page = await service.search(url, { sort: { kind: 'index' }, offset: 0, limit: 5 })
2173
+ const entries = page && Array.isArray(page.entries) ? page.entries : []
2174
+ verification = {
2175
+ ok: true,
2176
+ total: page && typeof page.total === 'number' ? page.total : entries.length,
2177
+ indexTitle: page ? page.title : null,
2178
+ entries: entries.map((item) => ({
2179
+ name: item.name,
2180
+ defaultVersion: item.defaultVersion || null,
2181
+ status: item.installation ? item.installation.status : null,
2182
+ })),
2183
+ }
2184
+ } catch (failure) {
2185
+ verification = { ok: false, reason: errorMessage(failure) }
2186
+ }
2187
+ }
2188
+ return { attached: true, url, added: !before.some((item) => (item && item.url) === url), indexes: after, verification }
2189
+ } catch (failure) {
2190
+ return { attached: false, url, reason: errorMessage(failure), manual: '设置 → 插件 → 发现 / 市场源 → 粘贴上面这个地址' }
2191
+ }
2192
+ }
2193
+
2194
+ async function dispatchApi(request, response, url, body) {
2195
+ const route = `${request.method} ${url.pathname}`
2196
+ const args = body && typeof body === 'object' ? body : {}
2197
+
2198
+ if (route === 'POST /github-console/api/status') {
2199
+ return sendJson(response, 200, { ...(await gh.status()), bridge: bridgeStatus() })
2200
+ }
2201
+ if (route === 'POST /github-console/api/auth/register') {
2202
+ // Re-registering throws away the current App (and its private key) and
2203
+ // drops the chosen installation, so require an explicit reset flag. The
2204
+ // panel otherwise offers the install page instead of a second App.
2205
+ const existing = await gh.appConfigured()
2206
+ if (existing && args.reset !== true) {
2207
+ return sendJson(response, 409, {
2208
+ error: '已经注册过 GitHub App:要沿用就打开安装页,确实要重来请用状态页的「重新注册」',
2209
+ code: 'APP_EXISTS',
2210
+ })
2211
+ }
2212
+ const origin = requestOrigin(request)
2213
+ const state = gh.beginManifest()
2214
+ return sendJson(response, 200, {
2215
+ setupUrl: `${origin}${PREFIX}/setup`,
2216
+ state,
2217
+ note: '打开 setupUrl 完成 GitHub 侧注册;回调成功后回到这里刷新',
2218
+ })
2219
+ }
2220
+ if (route === 'POST /github-console/api/auth/reset') {
2221
+ return sendJson(response, 200, await gh.resetApp())
2222
+ }
2223
+ if (route === 'POST /github-console/api/installations') {
2224
+ return sendJson(response, 200, { items: await gh.installations() })
2225
+ }
2226
+ if (route === 'POST /github-console/api/installations/select') {
2227
+ return sendJson(response, 200, await gh.selectInstallation(args.id))
2228
+ }
2229
+ if (route === 'POST /github-console/api/repos') {
2230
+ return sendJson(response, 200, await gh.listRepositories(args.q))
2231
+ }
2232
+ if (route === 'POST /github-console/api/tree') {
2233
+ return sendJson(response, 200, await gh.readTree(args.owner, args.name, args.ref))
2234
+ }
2235
+ if (route === 'POST /github-console/api/file/read') {
2236
+ return sendJson(response, 200, await gh.readFile(args.owner, args.name, args.path, args.ref))
2237
+ }
2238
+ if (route === 'POST /github-console/api/file/write') {
2239
+ return sendJson(
2240
+ response,
2241
+ 200,
2242
+ await gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref),
2243
+ )
2244
+ }
2245
+ if (route === 'POST /github-console/api/issues') {
2246
+ return sendJson(response, 200, await gh.listIssues(args.owner, args.name, args.state))
2247
+ }
2248
+ if (route === 'POST /github-console/api/pulls') {
2249
+ return sendJson(response, 200, await gh.listPulls(args.owner, args.name, args.state))
2250
+ }
2251
+ if (route === 'POST /github-console/api/actions') {
2252
+ return sendJson(response, 200, await gh.listRuns(args.owner, args.name))
2253
+ }
2254
+ if (route === 'POST /github-console/api/npm/status') {
2255
+ return sendJson(
2256
+ response,
2257
+ 200,
2258
+ await npmPublishState(gh, cfg, {
2259
+ owner: args.owner,
2260
+ repo: args.repo,
2261
+ dir: resolveDir(args.dir),
2262
+ }),
2263
+ )
2264
+ }
2265
+ if (route === 'POST /github-console/api/market/attach') {
2266
+ return sendJson(
2267
+ response,
2268
+ 200,
2269
+ await attachIndexToMarket({ url: args.url || `${requestOrigin(request)}${PREFIX}/market/index.json` }),
2270
+ )
2271
+ }
2272
+ if (route === 'POST /github-console/api/npm/prepare') {
2273
+ const pkg = await readLocalPackage(resolveDir(args.dir))
2274
+ const branch = args.branch || cfg.publishBranch
2275
+ const prepared = await ensurePublishWorkflow(gh, args.owner, args.repo, branch, cfg.npmWorkflow)
2276
+ return sendJson(response, 200, {
2277
+ ...prepared,
2278
+ branch,
2279
+ package: `${pkg.name}@${pkg.version}`,
2280
+ hint:
2281
+ '首次发布前:到 npmjs.com 手动发一次该版本(或给仓库加 NPM_TOKEN secret);随后在包设置里把 Trusted Publisher 指向本仓库与本 workflow。',
2282
+ })
2283
+ }
2284
+ if (route === 'POST /github-console/api/npm/dispatch') {
2285
+ const since = Date.now()
2286
+ await dispatchWorkflow(gh, args.owner, args.repo, cfg.npmWorkflow, args.branch || cfg.publishBranch, args.dryRun ? { dry_run: 'true' } : undefined)
2287
+ const run = await waitForWorkflowRun(gh, args.owner, args.repo, cfg.npmWorkflow, since, cfg.npmPollSeconds * 1000)
2288
+ return sendJson(response, 200, { run })
2289
+ }
2290
+ if (route === 'POST /github-console/api/market/index') {
2291
+ const dir = resolveDir(args.dir)
2292
+ const pkg = await readLocalPackage(dir)
2293
+ const branch = args.branch || cfg.publishBranch
2294
+ const repoPath = `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}`
2295
+ const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
2296
+ const commit = ref.object ? ref.object.sha : ''
2297
+ if (!commit) return sendJson(response, 400, { error: `读不到 ${branch} 的最新提交,请先发布一次` })
2298
+ const doc = marketIndexDocument({
2299
+ pkg,
2300
+ owner: args.owner,
2301
+ repo: args.repo,
2302
+ commit,
2303
+ entryTitle: args.title,
2304
+ entryDescription: args.description,
2305
+ })
2306
+ const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
2307
+ await gh.writeFile(
2308
+ args.owner,
2309
+ args.repo,
2310
+ cfg.marketIndexPath,
2311
+ JSON.stringify(doc, null, 2) + '\n',
2312
+ `chore: update market index for v${pkg.version}`,
2313
+ existing ? existing.sha : undefined,
2314
+ branch,
2315
+ )
2316
+ // Keep a copy locally so this machine can serve the index even when its
2317
+ // network cannot reach raw.githubusercontent.com.
2318
+ await gh
2319
+ .writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
2320
+ .catch(() => {})
2321
+ return sendJson(response, 200, {
2322
+ url: `https://raw.githubusercontent.com/${args.owner}/${args.repo}/${branch}/${cfg.marketIndexPath}`,
2323
+ localUrl: `${PREFIX}/market/index.json`,
2324
+ commit,
2325
+ installSpec: `git+https://github.com/${args.owner}/${args.repo}.git#${commit}`,
2326
+ index: doc,
2327
+ })
2328
+ }
2329
+ if (route === 'POST /github-console/api/publish/preflight') {
2330
+ return sendJson(response, 200, await preflight(resolveDir(args.dir), gh, cfg))
2331
+ }
2332
+ if (route === 'POST /github-console/api/discover') {
2333
+ return sendJson(response, 200, await discover(args.root))
2334
+ }
2335
+ if (route === 'POST /github-console/api/publish/run') {
2336
+ const dir = resolveDir(args.dir)
2337
+ const job = jobs.create({ dir, owner: args.owner, repo: args.repo })
2338
+ void runPublish({ job, gh, cfg, dir, owner: args.owner, repo: args.repo, version: args.version, notes: args.notes, opts: args })
2339
+ return sendJson(response, 200, { jobId: job.id })
2340
+ }
2341
+ if (route === 'POST /github-console/api/publish/job') {
2342
+ const job = jobs.get(args.jobId)
2343
+ if (!job) return sendJson(response, 404, { error: '没有这个任务' })
2344
+ return sendJson(response, 200, job)
2345
+ }
2346
+ if (route === 'POST /github-console/api/publish/jobs') {
2347
+ return sendJson(response, 200, { items: jobs.list() })
2348
+ }
2349
+ if (route === 'POST /github-console/api/market/probe') {
2350
+ return sendJson(
2351
+ response,
2352
+ 200,
2353
+ await probeMarket(
2354
+ { name: args.name, owner: args.owner, repo: args.repo, version: args.version },
2355
+ gh,
2356
+ cfg,
2357
+ ),
2358
+ )
2359
+ }
2360
+ return sendJson(response, 404, { error: `no route for ${route}` })
2361
+ }
2362
+
2363
+ async function handlePanelHttp(request, response, url) {
2364
+ try {
2365
+ if (url.pathname === `${PREFIX}/setup`) {
2366
+ await handleSetup(request, response)
2367
+ return
2368
+ }
2369
+ if (url.pathname === `${PREFIX}/callback`) {
2370
+ await handleCallback(request, response, url)
2371
+ return
2372
+ }
2373
+ if (url.pathname === `${PREFIX}/icon.svg`) {
2374
+ // The index references ../icon.svg relative to /github-console/market/index.json.
2375
+ const svg = await fs.readFile(path.join(PLUGIN_DIR, 'icon.svg')).catch(() => null)
2376
+ if (!svg) {
2377
+ sendJson(response, 404, { error: 'icon.svg 不存在' })
2378
+ return
2379
+ }
2380
+ response.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store' })
2381
+ response.end(svg)
2382
+ return
2383
+ }
2384
+ if (url.pathname === `${PREFIX}/market/index.json`) {
2385
+ // Anonymous by design: a market reader fetches its index without
2386
+ // credentials. Only the generated index document is served here.
2387
+ const record = await gh.readRecord(INDEX_CRED).catch(() => undefined)
2388
+ if (!record || typeof record.body !== 'string') {
2389
+ sendJson(response, 404, { error: '还没有生成市场索引:在面板「市场」页点「生成 / 更新市场索引」' })
2390
+ return
2391
+ }
2392
+ response.writeHead(200, {
2393
+ 'Content-Type': 'application/json; charset=utf-8',
2394
+ 'Cache-Control': 'no-store',
2395
+ })
2396
+ response.end(record.body)
2397
+ return
2398
+ }
2399
+ if (url.pathname.startsWith(`${PREFIX}/api/`)) {
2400
+ const expected = await tokenPromise
2401
+ if (!expected || bearerToken(request) !== expected) {
2402
+ sendJson(response, 401, { error: 'unauthorized' })
2403
+ return
2404
+ }
2405
+ const raw = request.method === 'POST' ? await readBody(request) : ''
2406
+ let body = {}
2407
+ if (raw) {
2408
+ try {
2409
+ body = JSON.parse(raw)
2410
+ } catch {
2411
+ sendJson(response, 400, { error: '请求体不是合法 JSON' })
2412
+ return
2413
+ }
2414
+ }
2415
+ await dispatchApi(request, response, url, body)
2416
+ return
2417
+ }
2418
+ sendJson(response, 404, { error: 'not found' })
2419
+ } catch (error) {
2420
+ // Keep the structured code: the panel maps it to a recovery action, and a
2421
+ // bare 500 would make 401/403/429/409 indistinguishable.
2422
+ const status = Number(error.status) >= 400 && Number(error.status) <= 599 ? Number(error.status) : 500
2423
+ sendJson(response, status, { error: errorMessage(error), code: error.code || 'INTERNAL' })
2424
+ }
2425
+ }
2426
+
2427
+ const attachWeb = (webServer) => {
2428
+ if (!webServer || webAttached) return
2429
+ webAttached = true
2430
+ if (typeof webServer.register === 'function') {
2431
+ ctx.effect(() =>
2432
+ webServer.register({
2433
+ kind: 'prefix',
2434
+ path: PREFIX,
2435
+ handler: (request, response) => handlePanelHttp(request, response, new URL(request.url || '/', 'http://127.0.0.1')),
2436
+ }),
2437
+ )
2438
+ }
2439
+ if (typeof webServer.tapIndex === 'function') {
2440
+ ctx.effect(() =>
2441
+ webServer.tapIndex((html) => {
2442
+ const payload = JSON.stringify(bridgeInfo()).replace(/</g, '\\u003c')
2443
+ const script = `<script>window.__DGH_BRIDGE__=${payload}</script>`
2444
+ return html.includes('</head>') ? html.replace('</head>', `${script}</head>`) : `${html}${script}`
2445
+ }),
2446
+ )
2447
+ }
2448
+ }
2449
+
2450
+ const existingWeb = ctx.get('webServer')
2451
+ if (existingWeb) attachWeb(existingWeb)
2452
+ else if (typeof ctx.inject === 'function') {
2453
+ ctx.effect(() =>
2454
+ ctx.inject(['webServer'], (scoped) => {
2455
+ attachWeb(scoped.webServer)
2456
+ }),
2457
+ )
2458
+ }
2459
+
2460
+ // The index-inject event is the documented way to publish a window global for
2461
+ // the client half; keep it as well because tapIndex is not always available.
2462
+ ctx.effect(() =>
2463
+ ctx.on('webserver/index-inject', (table) => {
2464
+ const info = bridgeInfo()
2465
+ if (info.token) table.push({ kind: 'global', name: '__DGH_BRIDGE__', value: info })
2466
+ }),
2467
+ )
2468
+
2469
+ /* ---------------- tools ---------------- */
2470
+
2471
+ const register = (definition) => ctx.effect(() => ctx.tools.register(definition))
2472
+
2473
+ register({
2474
+ name: 'gh_status',
2475
+ description:
2476
+ 'Show GitHub console state: whether a GitHub App is registered, the selected installation, token expiry, repository count, and publish defaults. Read-only, never returns secrets.',
2477
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
2478
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2479
+ async execute() {
2480
+ return { ...(await gh.status()), bridge: bridgeStatus() }
2481
+ },
2482
+ })
2483
+
2484
+ register({
2485
+ name: 'gh_auth',
2486
+ description:
2487
+ 'GitHub App sign-in steps. action=start returns the local setup URL that registers a GitHub App in the user\'s own account (the browser posts the manifest to GitHub); action=installations lists installations; action=select picks an installation id.',
2488
+ parameters: {
2489
+ type: 'object',
2490
+ properties: {
2491
+ action: { type: 'string', enum: ['start', 'installations', 'select'] },
2492
+ installationId: { type: 'string', description: 'Installation id, for action=select' },
2493
+ },
2494
+ required: ['action'],
2495
+ additionalProperties: false,
2496
+ },
2497
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2498
+ async execute(args) {
2499
+ if (args.action === 'start') {
2500
+ const base = String(process.env.DSH_WEB_URL || '').replace(/\/+$/, '')
2501
+ return {
2502
+ setupUrl: base ? `${base}${PREFIX}/setup` : `${PREFIX}/setup`,
2503
+ next: base
2504
+ ? '在浏览器打开 setupUrl,GitHub 页面点一次 Create GitHub App,再点 Install;完成后回到 gh_status'
2505
+ : '侧栏「GitHub 控制台 → 状态 → 注册 GitHub App」是可靠入口(本进程没有 DSH_WEB_URL)',
2506
+ }
2507
+ }
2508
+ if (args.action === 'installations') return { items: await gh.installations() }
2509
+ if (args.action === 'select') return gh.selectInstallation(args.installationId)
2510
+ throw new Error(`未知 action:${args.action}`)
2511
+ },
2512
+ })
2513
+
2514
+ register({
2515
+ name: 'gh_repos',
2516
+ description:
2517
+ 'List repositories the GitHub App installation can access. Optional q filters by full name. Requires a registered App and a selected installation.',
2518
+ parameters: {
2519
+ type: 'object',
2520
+ properties: { q: { type: 'string', description: 'Case-insensitive substring filter on owner/name' } },
2521
+ additionalProperties: false,
2522
+ },
2523
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2524
+ async execute(args) {
2525
+ return gh.listRepositories(args.q)
2526
+ },
2527
+ })
2528
+
2529
+ register({
2530
+ name: 'gh_tree',
2531
+ description: 'List the file tree of a repository branch (flat paths). Use owner/name from gh_repos.',
2532
+ parameters: {
2533
+ type: 'object',
2534
+ properties: {
2535
+ owner: { type: 'string' },
2536
+ name: { type: 'string' },
2537
+ ref: { type: 'string', description: 'Branch or ref, default the repository default branch' },
2538
+ },
2539
+ required: ['owner', 'name'],
2540
+ additionalProperties: false,
2541
+ },
2542
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2543
+ async execute(args) {
2544
+ return gh.readTree(args.owner, args.name, args.ref)
2545
+ },
2546
+ })
2547
+
2548
+ register({
2549
+ name: 'gh_file_read',
2550
+ description: 'Read one text file from a repository. Returns the file sha, which a later write must carry.',
2551
+ parameters: {
2552
+ type: 'object',
2553
+ properties: {
2554
+ owner: { type: 'string' },
2555
+ name: { type: 'string' },
2556
+ path: { type: 'string', description: 'Path inside the repository, for example src/index.js' },
2557
+ ref: { type: 'string' },
2558
+ },
2559
+ required: ['owner', 'name', 'path'],
2560
+ additionalProperties: false,
2561
+ },
2562
+ output: {
2563
+ schema: { type: 'object' },
2564
+ render: (args, value) => [
2565
+ {
2566
+ type: 'text',
2567
+ text: `${value.path} · sha ${value.sha} · ${value.size} B\n\n${String(value.text || '')}`,
2568
+ },
2569
+ ],
2570
+ },
2571
+ async execute(args) {
2572
+ return gh.readFile(args.owner, args.name, args.path, args.ref)
2573
+ },
2574
+ })
2575
+
2576
+ register({
2577
+ name: 'gh_file_write',
2578
+ description:
2579
+ 'Create or update one file in a repository through the contents API. Pass the sha from gh_file_read to update; a stale sha fails with REF_CONFLICT instead of overwriting.',
2580
+ parameters: {
2581
+ type: 'object',
2582
+ properties: {
2583
+ owner: { type: 'string' },
2584
+ name: { type: 'string' },
2585
+ path: { type: 'string' },
2586
+ text: { type: 'string', description: 'Full new file content' },
2587
+ message: { type: 'string', description: 'Commit message' },
2588
+ sha: { type: 'string', description: 'Current blob sha for an update' },
2589
+ ref: { type: 'string', description: 'Branch, default the repository default branch' },
2590
+ },
2591
+ required: ['owner', 'name', 'path', 'text'],
2592
+ additionalProperties: false,
2593
+ },
2594
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2595
+ async execute(args) {
2596
+ return gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref)
2597
+ },
2598
+ })
2599
+
2600
+ register({
2601
+ name: 'gh_issues',
2602
+ description: 'List repository issues (pull requests are flagged, not filtered out).',
2603
+ parameters: {
2604
+ type: 'object',
2605
+ properties: {
2606
+ owner: { type: 'string' },
2607
+ name: { type: 'string' },
2608
+ state: { type: 'string', enum: ['open', 'closed', 'all'] },
2609
+ },
2610
+ required: ['owner', 'name'],
2611
+ additionalProperties: false,
2612
+ },
2613
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2614
+ async execute(args) {
2615
+ return gh.listIssues(args.owner, args.name, args.state)
2616
+ },
2617
+ })
2618
+
2619
+ register({
2620
+ name: 'gh_issue_create',
2621
+ description: 'Create an issue in a repository.',
2622
+ parameters: {
2623
+ type: 'object',
2624
+ properties: {
2625
+ owner: { type: 'string' },
2626
+ name: { type: 'string' },
2627
+ title: { type: 'string' },
2628
+ body: { type: 'string' },
2629
+ },
2630
+ required: ['owner', 'name', 'title'],
2631
+ additionalProperties: false,
2632
+ },
2633
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2634
+ async execute(args) {
2635
+ return gh.createIssue(args.owner, args.name, args.title, args.body)
2636
+ },
2637
+ })
2638
+
2639
+ register({
2640
+ name: 'gh_issue_comment',
2641
+ description: 'Comment on an issue or pull request.',
2642
+ parameters: {
2643
+ type: 'object',
2644
+ properties: {
2645
+ owner: { type: 'string' },
2646
+ name: { type: 'string' },
2647
+ number: { type: 'integer', minimum: 1 },
2648
+ body: { type: 'string' },
2649
+ },
2650
+ required: ['owner', 'name', 'number', 'body'],
2651
+ additionalProperties: false,
2652
+ },
2653
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2654
+ async execute(args) {
2655
+ return gh.commentIssue(args.owner, args.name, args.number, args.body)
2656
+ },
2657
+ })
2658
+
2659
+ register({
2660
+ name: 'gh_pulls',
2661
+ description: 'List pull requests of a repository with head/base branches and mergeable state.',
2662
+ parameters: {
2663
+ type: 'object',
2664
+ properties: {
2665
+ owner: { type: 'string' },
2666
+ name: { type: 'string' },
2667
+ state: { type: 'string', enum: ['open', 'closed', 'all'] },
2668
+ },
2669
+ required: ['owner', 'name'],
2670
+ additionalProperties: false,
2671
+ },
2672
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2673
+ async execute(args) {
2674
+ return gh.listPulls(args.owner, args.name, args.state)
2675
+ },
2676
+ })
2677
+
2678
+ register({
2679
+ name: 'gh_pull_create',
2680
+ description: 'Open a pull request from an existing head branch into a base branch.',
2681
+ parameters: {
2682
+ type: 'object',
2683
+ properties: {
2684
+ owner: { type: 'string' },
2685
+ name: { type: 'string' },
2686
+ head: { type: 'string', description: 'Source branch, for example feature/x' },
2687
+ base: { type: 'string', description: 'Target branch, for example main' },
2688
+ title: { type: 'string' },
2689
+ body: { type: 'string' },
2690
+ },
2691
+ required: ['owner', 'name', 'head', 'base', 'title'],
2692
+ additionalProperties: false,
2693
+ },
2694
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2695
+ async execute(args) {
2696
+ return gh.createPull(args.owner, args.name, args.head, args.base, args.title, args.body)
2697
+ },
2698
+ })
2699
+
2700
+ register({
2701
+ name: 'gh_pull_merge',
2702
+ description:
2703
+ 'Merge a pull request. Irreversible on the remote: confirm with the user first and pass confirm: true. Method defaults to squash.',
2704
+ parameters: {
2705
+ type: 'object',
2706
+ properties: {
2707
+ owner: { type: 'string' },
2708
+ name: { type: 'string' },
2709
+ number: { type: 'integer', minimum: 1 },
2710
+ method: { type: 'string', enum: ['merge', 'squash', 'rebase'] },
2711
+ confirm: { type: 'boolean', description: 'Must be true' },
2712
+ },
2713
+ required: ['owner', 'name', 'number', 'confirm'],
2714
+ additionalProperties: false,
2715
+ },
2716
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2717
+ async execute(args) {
2718
+ if (args.confirm !== true) throw new Error('合并 PR 必须显式确认:传 confirm: true')
2719
+ return gh.mergePull(args.owner, args.name, args.number, args.method)
2720
+ },
2721
+ })
2722
+
2723
+ register({
2724
+ name: 'gh_actions',
2725
+ description: 'List recent GitHub Actions workflow runs of a repository.',
2726
+ parameters: {
2727
+ type: 'object',
2728
+ properties: { owner: { type: 'string' }, name: { type: 'string' } },
2729
+ required: ['owner', 'name'],
2730
+ additionalProperties: false,
2731
+ },
2732
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2733
+ async execute(args) {
2734
+ return gh.listRuns(args.owner, args.name)
2735
+ },
2736
+ })
2737
+
2738
+ register({
2739
+ name: 'gh_actions_rerun',
2740
+ description: 'Re-run a workflow run by id. Confirm with the user first; pass confirm: true.',
2741
+ parameters: {
2742
+ type: 'object',
2743
+ properties: {
2744
+ owner: { type: 'string' },
2745
+ name: { type: 'string' },
2746
+ runId: { type: 'integer', minimum: 1 },
2747
+ confirm: { type: 'boolean' },
2748
+ },
2749
+ required: ['owner', 'name', 'runId', 'confirm'],
2750
+ additionalProperties: false,
2751
+ },
2752
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2753
+ async execute(args) {
2754
+ if (args.confirm !== true) throw new Error('重跑 CI 必须显式确认:传 confirm: true')
2755
+ return gh.rerunWorkflow(args.owner, args.name, args.runId)
2756
+ },
2757
+ })
2758
+
2759
+ register({
2760
+ name: 'plugin_discover',
2761
+ description:
2762
+ 'Find publishable DSH plugin directories on this machine without any GitHub sign-in: scans the session workspace and the current process directory for package.json files declaring dsh.bundle.patch or dsh.client. Returns each directory with name, version, and a suggested repository name. Use it before plugin_preflight or plugin_publish when the user has not named the directory.',
2763
+ parameters: {
2764
+ type: 'object',
2765
+ properties: {
2766
+ root: { type: 'string', description: 'Optional extra absolute directory to scan first' },
2767
+ },
2768
+ additionalProperties: false,
2769
+ },
2770
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2771
+ async execute(args) {
2772
+ return discover(args.root)
2773
+ },
2774
+ })
2775
+
2776
+ register({
2777
+ name: 'plugin_preflight',
2778
+ description:
2779
+ 'Static checks on a local DSH plugin directory before publishing: manifest and bundle patch, entry files, README/LICENSE/.gitignore, hardcoded secrets, local absolute paths, and npm name collisions. Never executes package scripts.',
2780
+ parameters: {
2781
+ type: 'object',
2782
+ properties: { dir: { type: 'string', description: 'Plugin directory; relative paths resolve against the workspace' } },
2783
+ required: ['dir'],
2784
+ additionalProperties: false,
2785
+ },
2786
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2787
+ async execute(args, exec) {
2788
+ return preflight(resolveDir(args.dir, exec), gh, cfg)
2789
+ },
2790
+ })
2791
+
2792
+ register({
2793
+ name: 'plugin_publish',
2794
+ description:
2795
+ 'Publish a local DSH plugin to an existing GitHub repository: preflight, commit every bundled file through the Git Data API, merge the dsh-plugin topic, create the v<version> Release, then probe npm and market indexes. The repository must already exist and be authorized for the App. Returns a job id; poll with plugin_publish_status.',
2796
+ parameters: {
2797
+ type: 'object',
2798
+ properties: {
2799
+ dir: { type: 'string', description: 'Local plugin directory' },
2800
+ owner: { type: 'string', description: 'Repository owner (user or org)' },
2801
+ repo: { type: 'string', description: 'Repository name; create it on GitHub first if missing' },
2802
+ version: { type: 'string', description: 'Version for the tag; defaults to package.json version' },
2803
+ branch: { type: 'string', description: 'Target branch, default from plugin config (main)' },
2804
+ message: { type: 'string', description: 'Commit message' },
2805
+ notes: { type: 'string', description: 'Release notes body' },
2806
+ },
2807
+ required: ['dir', 'owner', 'repo'],
2808
+ additionalProperties: false,
2809
+ },
2810
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2811
+ async execute(args, exec) {
2812
+ const dir = resolveDir(args.dir, exec)
2813
+ const job = jobs.create({ dir, owner: args.owner, repo: args.repo })
2814
+ await runPublish({
2815
+ job,
2816
+ gh,
2817
+ cfg,
2818
+ dir,
2819
+ owner: args.owner,
2820
+ repo: args.repo,
2821
+ version: args.version,
2822
+ notes: args.notes,
2823
+ opts: args,
2824
+ })
2825
+ return {
2826
+ jobId: job.id,
2827
+ ok: job.ok,
2828
+ steps: job.steps.map((item) => ({ id: item.id, title: item.title, state: item.state, detail: item.detail })),
2829
+ releaseUrl: job.releaseUrl || null,
2830
+ market: job.market ? job.market.summary : null,
2831
+ }
2832
+ },
2833
+ })
2834
+
2835
+ register({
2836
+ name: 'plugin_npm_publish',
2837
+ description:
2838
+ 'Publish the plugin to npm through GitHub Actions. Writes (or updates) .github/workflows/publish.yml, dispatches it on the publish branch, and waits for the run to finish. Needs confirm: true. npm cannot attach a trusted publisher to a package that does not exist yet, so the very first version must be published once by hand (or with an NPM_TOKEN repository secret); every version after that runs tokenless over OIDC.',
2839
+ parameters: {
2840
+ type: 'object',
2841
+ properties: {
2842
+ dir: { type: 'string', description: 'Local plugin directory' },
2843
+ owner: { type: 'string' },
2844
+ repo: { type: 'string' },
2845
+ branch: { type: 'string', description: 'Branch that dispatches the workflow; default the publish branch' },
2846
+ dryRun: { type: 'boolean', description: 'Ask the workflow to run npm publish --dry-run' },
2847
+ confirm: { type: 'boolean', description: 'Must be true' },
2848
+ },
2849
+ required: ['dir', 'owner', 'repo', 'confirm'],
2850
+ additionalProperties: false,
2851
+ },
2852
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2853
+ async execute(args, exec) {
2854
+ if (args.confirm !== true) throw new Error('触发 npm 发布需要确认:传 confirm: true')
2855
+ const dir = resolveDir(args.dir, exec)
2856
+ const pkg = await readLocalPackage(dir)
2857
+ const branch = args.branch || cfg.publishBranch
2858
+ const prepared = await ensurePublishWorkflow(gh, args.owner, args.repo, branch, cfg.npmWorkflow)
2859
+ const since = Date.now()
2860
+ await dispatchWorkflow(
2861
+ gh,
2862
+ args.owner,
2863
+ args.repo,
2864
+ cfg.npmWorkflow,
2865
+ branch,
2866
+ args.dryRun ? { dry_run: 'true' } : undefined,
2867
+ )
2868
+ const run = await waitForWorkflowRun(gh, args.owner, args.repo, cfg.npmWorkflow, since, cfg.npmPollSeconds * 1000)
2869
+ const state = await npmPublishState(gh, cfg, { owner: args.owner, repo: args.repo, dir }).catch(() => null)
2870
+ return {
2871
+ package: `${pkg.name}@${pkg.version}`,
2872
+ workflow: prepared.path,
2873
+ workflowChanged: prepared.changed,
2874
+ branch,
2875
+ dryRun: args.dryRun === true,
2876
+ run,
2877
+ npmState: state,
2878
+ next:
2879
+ args.dryRun === true
2880
+ ? run.conclusion === 'success'
2881
+ ? 'dry-run 通过:真实发布前仍需跨过「首次发布」这一步(面板里按 npmState.steps 做)。'
2882
+ : 'dry-run 未通过,看 run 日志。'
2883
+ : run.conclusion === 'success'
2884
+ ? 'npm 已发布,可到 npmjs.com 查看 provenance。'
2885
+ : run.status === 'timeout'
2886
+ ? `运行仍在进行,打开 run 页面查看:${run.url || ''}`
2887
+ : '运行失败时看 run 日志:首次发布需要先手动发一次该版本,或在仓库 Secrets 里加 NPM_TOKEN。',
2888
+ }
2889
+ },
2890
+ })
2891
+
2892
+ register({
2893
+ name: 'plugin_market_index',
2894
+ description:
2895
+ 'Generate or refresh a self-hosted format-1 plugin market index for this repository and commit it (default market/index.json). Returns the raw URL to add to DSH plugin market sources, plus the commit-pinned install spec. The index pins the current branch head commit, so publish first and then refresh the index.',
2896
+ parameters: {
2897
+ type: 'object',
2898
+ properties: {
2899
+ dir: { type: 'string', description: 'Local plugin directory' },
2900
+ owner: { type: 'string' },
2901
+ repo: { type: 'string' },
2902
+ branch: { type: 'string', description: 'Branch to pin; default the publish branch' },
2903
+ title: { type: 'string', description: 'Display title for the entry; defaults to the package name' },
2904
+ description: { type: 'string', description: 'Display description; defaults to package.json description' },
2905
+ },
2906
+ required: ['dir', 'owner', 'repo'],
2907
+ additionalProperties: false,
2908
+ },
2909
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2910
+ async execute(args, exec) {
2911
+ const dir = resolveDir(args.dir, exec)
2912
+ const pkg = await readLocalPackage(dir)
2913
+ const branch = args.branch || cfg.publishBranch
2914
+ const repoPath = `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}`
2915
+ const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
2916
+ const commit = ref.object ? ref.object.sha : ''
2917
+ if (!commit) throw new Error(`读不到 ${branch} 的最新提交:请先发布一次`)
2918
+ const doc = marketIndexDocument({
2919
+ pkg,
2920
+ owner: args.owner,
2921
+ repo: args.repo,
2922
+ commit,
2923
+ entryTitle: args.title,
2924
+ entryDescription: args.description,
2925
+ })
2926
+ const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
2927
+ await gh.writeFile(
2928
+ args.owner,
2929
+ args.repo,
2930
+ cfg.marketIndexPath,
2931
+ JSON.stringify(doc, null, 2) + '\n',
2932
+ `chore: update market index for v${pkg.version}`,
2933
+ existing ? existing.sha : undefined,
2934
+ branch,
2935
+ )
2936
+ await gh
2937
+ .writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
2938
+ .catch(() => {})
2939
+ return {
2940
+ url: `https://raw.githubusercontent.com/${args.owner}/${args.repo}/${branch}/${cfg.marketIndexPath}`,
2941
+ localUrl: `${PREFIX}/market/index.json`,
2942
+ localUrlNote: '本机直接可读的地址(前面要加 DSH 的 web 地址);适用于 raw.githubusercontent.com 或 CDN 在本机不可达的情况',
2943
+ path: cfg.marketIndexPath,
2944
+ commit,
2945
+ version: pkg.version,
2946
+ installSpec: `git+https://github.com/${args.owner}/${args.repo}.git#${commit}`,
2947
+ next: '把 url 加进 DSH 的插件市场源(设置 → 插件 → 发现/市场源),即可在 Discover 里看到它',
2948
+ index: doc,
2949
+ }
2950
+ },
2951
+ })
2952
+
2953
+ register({
2954
+ name: 'plugin_market_attach',
2955
+ description:
2956
+ 'Add this plugin\'s own market index to the DSH plugin market sources with one call, by writing the plugin-market index list. Falls back to instructions when the profile has no plugin-market service mounted. Generate the index first with plugin_market_index.',
2957
+ parameters: {
2958
+ type: 'object',
2959
+ properties: {
2960
+ url: {
2961
+ type: 'string',
2962
+ description: 'Index URL to attach; defaults to the local route of this DSH instance',
2963
+ },
2964
+ },
2965
+ additionalProperties: false,
2966
+ },
2967
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2968
+ async execute(args) {
2969
+ return attachIndexToMarket({ url: args.url })
2970
+ },
2971
+ })
2972
+
2973
+ register({
2974
+ name: 'plugin_publish_status',
2975
+ description: 'Read a publish job by id, including each step state and detail.',
2976
+ parameters: {
2977
+ type: 'object',
2978
+ properties: { jobId: { type: 'string' } },
2979
+ required: ['jobId'],
2980
+ additionalProperties: false,
2981
+ },
2982
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
2983
+ async execute(args) {
2984
+ const job = jobs.get(args.jobId)
2985
+ if (!job) throw new Error(`没有任务 ${args.jobId}`)
2986
+ return job
2987
+ },
2988
+ })
2989
+
2990
+ register({
2991
+ name: 'plugin_market_probe',
2992
+ description:
2993
+ 'Check whether a plugin is published and indexed: npm package, the GitHub dsh-plugin topic, the release tag, and any configured market index URLs. A failed probe reports unknown, never absent.',
2994
+ parameters: {
2995
+ type: 'object',
2996
+ properties: {
2997
+ name: { type: 'string', description: 'npm package name' },
2998
+ owner: { type: 'string' },
2999
+ repo: { type: 'string' },
3000
+ version: { type: 'string' },
3001
+ },
3002
+ required: ['name'],
3003
+ additionalProperties: false,
3004
+ },
3005
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
3006
+ async execute(args) {
3007
+ return probeMarket(args, gh, cfg)
3008
+ },
3009
+ })
3010
+ }