dsh-github-console 0.2.5 → 0.4.1

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 CHANGED
@@ -15,17 +15,26 @@
15
15
  import crypto from 'node:crypto'
16
16
  import fs from 'node:fs/promises'
17
17
  import path from 'node:path'
18
+ import os from 'node:os'
18
19
  import net from 'node:net'
19
20
  import tls from 'node:tls'
20
21
  import https from 'node:https'
22
+ import zlib from 'node:zlib'
21
23
  import { fileURLToPath } from 'node:url'
22
24
  import { promises as dnsPromises, Resolver } from 'node:dns'
23
25
 
24
- const PLUGIN_VERSION = '0.2.5'
26
+ const PLUGIN_VERSION = '0.4.1'
25
27
  const APP_CRED = 'github-console/app'
26
28
  const INSTALL_CRED = 'github-console/install'
27
29
  const BRIDGE_CRED = 'github-console/bridge'
28
30
  const INDEX_CRED = 'github-console/index'
31
+ // Connection choices: GitHub App installation (default), a user PAT, or a token
32
+ // taken from an environment variable. The active one is remembered separately so
33
+ // switching does not throw away another connection's credentials.
34
+ const PAT_CRED = 'github-console/pat'
35
+ const AUTH_CRED = 'github-console/active'
36
+ // App user authorization (user-to-server): short-lived token plus a refresh token.
37
+ const OAUTH_CRED = 'github-console/oauth'
29
38
  const DEFAULT_API = 'https://api.github.com'
30
39
  const PREFIX = '/github-console'
31
40
  const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
@@ -34,7 +43,7 @@ const INSTALL_TOKEN_MARGIN_MS = 5 * 60 * 1000
34
43
 
35
44
  // A credential key outside "<scope>/<id>" poisons the whole credentials document
36
45
  // 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]) {
46
+ for (const key of [APP_CRED, INSTALL_CRED, BRIDGE_CRED, INDEX_CRED, PAT_CRED, AUTH_CRED, OAUTH_CRED]) {
38
47
  if (!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(key)) {
39
48
  throw new Error(`Invalid credential key "${key}": expected "<scope>/<id>"`)
40
49
  }
@@ -194,6 +203,42 @@ function normalizeConfig(raw) {
194
203
  ? config.marketIndexPath
195
204
  : 'market/index.json',
196
205
  npmUser: typeof config.npmUser === 'string' ? config.npmUser.trim() : '',
206
+ // Connection selection: 'auto' prefers App, then PAT, then the environment.
207
+ authMode: ['auto', 'app', 'pat', 'env'].includes(config.authMode) ? config.authMode : 'auto',
208
+ patEnvName: typeof config.patEnvName === 'string' && config.patEnvName ? config.patEnvName : 'GITHUB_TOKEN',
209
+ readOnly: config.readOnly === true,
210
+ }
211
+ }
212
+
213
+ /** Append-only record of write actions taken through this plugin. */
214
+ function auditPath() {
215
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
216
+ return path.join(home, 'storages', 'dsh-github-console', 'audit.ndjson')
217
+ }
218
+
219
+ async function appendAudit(entry) {
220
+ try {
221
+ const target = auditPath()
222
+ await fs.mkdir(path.dirname(target), { recursive: true })
223
+ await fs.appendFile(target, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8')
224
+ } catch {
225
+ /* auditing never breaks an action */
226
+ }
227
+ }
228
+
229
+ async function readAudit(limit = 50) {
230
+ try {
231
+ const text = await fs.readFile(auditPath(), 'utf8')
232
+ const lines = text.trim().split('\n').filter(Boolean)
233
+ return lines.slice(-Math.max(1, Math.min(500, limit))).map((line) => {
234
+ try {
235
+ return JSON.parse(line)
236
+ } catch {
237
+ return { raw: line }
238
+ }
239
+ })
240
+ } catch {
241
+ return []
197
242
  }
198
243
  }
199
244
 
@@ -338,18 +383,20 @@ function createTransport(cfg) {
338
383
  return routes
339
384
  }
340
385
 
341
- function rawRequest(options, body, timeoutMs) {
386
+ function rawRequest(options, body, timeoutMs, binary = false) {
342
387
  return new Promise((resolve, reject) => {
343
388
  const request = https.request(options, (response) => {
344
389
  const chunks = []
345
390
  response.on('data', (chunk) => chunks.push(chunk))
346
- response.on('end', () =>
391
+ response.on('end', () => {
392
+ const joined = Buffer.concat(chunks)
347
393
  resolve({
348
394
  status: response.statusCode || 0,
349
395
  headers: response.headers,
350
- text: Buffer.concat(chunks).toString('utf8'),
351
- }),
352
- )
396
+ text: binary ? '' : joined.toString('utf8'),
397
+ buffer: binary ? joined : null,
398
+ })
399
+ })
353
400
  response.on('error', reject)
354
401
  })
355
402
  request.setTimeout(timeoutMs, () => request.destroy(new Error('ETIMEDOUT')))
@@ -415,6 +462,7 @@ function createTransport(cfg) {
415
462
  { method: options.method, host, port, path, headers, agent, servername: host },
416
463
  options.body,
417
464
  cfg.requestTimeoutMs,
465
+ options.binary === true,
418
466
  )
419
467
  } finally {
420
468
  tunnel.destroy()
@@ -436,6 +484,7 @@ function createTransport(cfg) {
436
484
  },
437
485
  options.body,
438
486
  cfg.requestTimeoutMs,
487
+ options.binary === true,
439
488
  )
440
489
  }
441
490
 
@@ -723,7 +772,7 @@ function createGithub(ctx, cfg, transport) {
723
772
  }
724
773
 
725
774
  async function call(pathname, options = {}) {
726
- const { method = 'GET', body, auth = 'installation', headers = {} } = options
775
+ const { method = 'GET', body, auth = 'auto', headers = {}, rawBody = false } = options
727
776
  const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
728
777
  if (auth === 'app') {
729
778
  const app = await readApp()
@@ -731,16 +780,36 @@ function createGithub(ctx, cfg, transport) {
731
780
  init.headers.Authorization = `Bearer ${appJwt(app)}`
732
781
  } else if (auth === 'installation') {
733
782
  init.headers.Authorization = `Bearer ${await installationToken()}`
734
- } else {
783
+ } else if (auth !== 'auto') {
735
784
  init.headers.Authorization = `Bearer ${auth}`
785
+ } else {
786
+ const current = await resolveAuth()
787
+ if (current.kind === 'app') {
788
+ init.headers.Authorization = `Bearer ${await installationToken()}`
789
+ } else if (current.kind === 'pat' || current.kind === 'env' || current.kind === 'oauth') {
790
+ init.headers.Authorization = `Bearer ${current.token}`
791
+ } else {
792
+ throw new GhError(
793
+ 401,
794
+ 'AUTH_MISSING',
795
+ '还没有可用的 GitHub 连接:在面板「状态」里选一种(GitHub App / 个人访问令牌 / 环境变量)',
796
+ )
797
+ }
736
798
  }
737
799
  if (body !== undefined) {
738
- init.headers['Content-Type'] = 'application/json'
739
- init.body = JSON.stringify(body)
800
+ if (rawBody) {
801
+ // Binary uploads (release assets) pass the bytes through unchanged.
802
+ init.body = body
803
+ } else {
804
+ init.headers['Content-Type'] = 'application/json'
805
+ init.body = JSON.stringify(body)
806
+ }
740
807
  }
808
+ // Absolute URLs reach another host (uploads.github.com for release assets).
809
+ const target = /^https?:\/\//i.test(pathname) ? pathname : `${cfg.baseUrl}${pathname}`
741
810
  let response
742
811
  try {
743
- response = await transport.request(`${cfg.baseUrl}${pathname}`, { method, headers: init.headers, body: init.body })
812
+ response = await transport.request(target, { method, headers: init.headers, body: init.body })
744
813
  } catch (failure) {
745
814
  if (failure instanceof GhError) throw failure
746
815
  const described = describeFetchFailure(failure)
@@ -908,6 +977,369 @@ function createGithub(ctx, cfg, transport) {
908
977
  return { ok: true }
909
978
  }
910
979
 
980
+ async function readPat() {
981
+ const record = await readRecord(PAT_CRED)
982
+ return record && typeof record.token === 'string' ? record.token : ''
983
+ }
984
+
985
+ function fingerprint(token) {
986
+ const text = String(token || '')
987
+ return text.length <= 4 ? '****' : `****${text.slice(-4)}`
988
+ }
989
+
990
+ /** Ask GitHub who a token belongs to; used before storing a PAT. */
991
+ async function whoAmI(token) {
992
+ const response = await transport.request(`${cfg.baseUrl}/user`, {
993
+ headers: {
994
+ Accept: 'application/vnd.github+json',
995
+ 'X-GitHub-Api-Version': '2022-11-28',
996
+ Authorization: `Bearer ${token}`,
997
+ },
998
+ })
999
+ if (response.status !== 200) {
1000
+ throw new GhError(response.status, response.status === 401 ? 'AUTH_EXPIRED' : 'HTTP_' + response.status, `令牌无效(HTTP ${response.status})`)
1001
+ }
1002
+ const data = JSON.parse(response.text || '{}')
1003
+ const scopes = String(response.headers['x-oauth-scopes'] || '')
1004
+ return { login: data.login || '', id: data.id, name: data.name || '', scopes: scopes ? scopes.split(',').map((item) => item.trim()) : [] }
1005
+ }
1006
+
1007
+ let authCache = null
1008
+
1009
+ /** The App's own OAuth callback must be registered before the authorize step. */
1010
+ async function ensureOAuthCallback(origin) {
1011
+ const app = await readApp()
1012
+ if (!app) throw new Error('还没有注册 GitHub App')
1013
+ if (!app.clientId) throw new Error('这个 App 没有 client_id:请重新注册一次 GitHub App')
1014
+ const callbackUrl = `${origin}${PREFIX}/oauth/callback`
1015
+ let current = null
1016
+ try {
1017
+ current = await call('/app', { auth: 'app' })
1018
+ } catch {
1019
+ current = null
1020
+ }
1021
+ const existing = current && Array.isArray(current.callback_urls) ? current.callback_urls : []
1022
+ let registered = existing.includes(callbackUrl)
1023
+ if (!registered) {
1024
+ // `PATCH /app` is not available for every app type; when it fails the user
1025
+ // registers the callback once in the App settings instead.
1026
+ try {
1027
+ await call('/app', { method: 'PATCH', auth: 'app', body: { callback_urls: [...existing, callbackUrl] } })
1028
+ registered = true
1029
+ } catch {
1030
+ registered = false
1031
+ }
1032
+ }
1033
+ return { callbackUrl, clientId: app.clientId, clientSecret: app.clientSecret, registered }
1034
+ }
1035
+
1036
+ function beginOAuth(origin) {
1037
+ return ensureOAuthCallback(origin).then(({ callbackUrl, clientId, registered }) => {
1038
+ const state = crypto.randomBytes(16).toString('hex')
1039
+ pendingManifests.set(`oauth:${state}`, Date.now())
1040
+ const url = new URL('https://github.com/login/oauth/authorize')
1041
+ url.searchParams.set('client_id', clientId)
1042
+ url.searchParams.set('redirect_uri', callbackUrl)
1043
+ url.searchParams.set('state', state)
1044
+ return {
1045
+ url: url.toString(),
1046
+ state,
1047
+ callbackUrl,
1048
+ callbackRegistered: registered,
1049
+ note: registered
1050
+ ? '打开 url 授权即可'
1051
+ : `先把 ${callbackUrl} 加到 App 设置页(User authorization callback URL)再打开 url,否则 GitHub 会报 redirect_uri 不匹配`,
1052
+ }
1053
+ })
1054
+ }
1055
+
1056
+ async function completeOAuth(code, state, origin) {
1057
+ const key = `oauth:${state}`
1058
+ const startedAt = pendingManifests.get(key)
1059
+ if (!startedAt) throw new Error('OAuth state 不匹配或已过期,请重新发起授权')
1060
+ if (Date.now() - startedAt > 30 * 60 * 1000) {
1061
+ pendingManifests.delete(key)
1062
+ throw new Error('OAuth 授权超时(30 分钟),请重新发起')
1063
+ }
1064
+ const app = await readApp()
1065
+ if (!app || !app.clientId || !app.clientSecret) throw new Error('缺少 App 的 client_id / client_secret')
1066
+ const callbackUrl = `${origin}${PREFIX}/oauth/callback`
1067
+ const response = await transport.request('https://github.com/login/oauth/access_token', {
1068
+ method: 'POST',
1069
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1070
+ body: JSON.stringify({
1071
+ client_id: app.clientId,
1072
+ client_secret: app.clientSecret,
1073
+ code,
1074
+ redirect_uri: callbackUrl,
1075
+ }),
1076
+ })
1077
+ const data = (() => {
1078
+ try {
1079
+ return JSON.parse(response.text || '{}')
1080
+ } catch {
1081
+ return {}
1082
+ }
1083
+ })()
1084
+ if (!data.access_token) {
1085
+ throw new Error(`换取用户令牌失败:${data.error_description || data.error || `HTTP ${response.status}`}`)
1086
+ }
1087
+ pendingManifests.delete(key)
1088
+ const now = Date.now()
1089
+ await writeRecord(OAUTH_CRED, {
1090
+ accessToken: data.access_token,
1091
+ refreshToken: data.refresh_token || '',
1092
+ expiresAt: now + Number(data.expires_in || 28800) * 1000,
1093
+ refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : null,
1094
+ scope: data.scope || '',
1095
+ addedAt: new Date().toISOString(),
1096
+ })
1097
+ authCache = null
1098
+ return { ok: true }
1099
+ }
1100
+
1101
+ async function refreshOAuth() {
1102
+ const record = await readRecord(OAUTH_CRED)
1103
+ if (!record || !record.refreshToken) throw new Error('用户授权已失效且没有 refresh token,请重新授权')
1104
+ const app = await readApp()
1105
+ const response = await transport.request('https://github.com/login/oauth/access_token', {
1106
+ method: 'POST',
1107
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1108
+ body: JSON.stringify({
1109
+ client_id: app.clientId,
1110
+ client_secret: app.clientSecret,
1111
+ grant_type: 'refresh_token',
1112
+ refresh_token: record.refreshToken,
1113
+ }),
1114
+ })
1115
+ const data = (() => {
1116
+ try {
1117
+ return JSON.parse(response.text || '{}')
1118
+ } catch {
1119
+ return {}
1120
+ }
1121
+ })()
1122
+ if (!data.access_token) throw new Error(`刷新用户令牌失败:${data.error_description || data.error || response.status}`)
1123
+ const now = Date.now()
1124
+ await writeRecord(OAUTH_CRED, {
1125
+ ...record,
1126
+ accessToken: data.access_token,
1127
+ refreshToken: data.refresh_token || record.refreshToken,
1128
+ expiresAt: now + Number(data.expires_in || 28800) * 1000,
1129
+ refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : record.refreshExpiresAt,
1130
+ })
1131
+ return readRecord(OAUTH_CRED)
1132
+ }
1133
+
1134
+ async function oauthToken() {
1135
+ const record = await readRecord(OAUTH_CRED)
1136
+ if (!record || !record.accessToken) return ''
1137
+ if (record.expiresAt && Date.now() > record.expiresAt - 120000) {
1138
+ const fresh = await refreshOAuth().catch(() => null)
1139
+ if (fresh && fresh.accessToken) return fresh.accessToken
1140
+ }
1141
+ return record.accessToken
1142
+ }
1143
+
1144
+ const pendingDevices = new Map()
1145
+
1146
+ /**
1147
+ * Device flow: no redirect URI, so no port to pin and nothing to register in
1148
+ * the App settings beyond enabling "Device Flow" once.
1149
+ */
1150
+ async function deviceStart() {
1151
+ const app = await readApp()
1152
+ if (!app || !app.clientId) throw new Error('需要先注册 GitHub App(缺少 client_id)')
1153
+ const response = await transport.request('https://github.com/login/device/code', {
1154
+ method: 'POST',
1155
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1156
+ body: JSON.stringify({ client_id: app.clientId }),
1157
+ })
1158
+ const data = (() => {
1159
+ try {
1160
+ return JSON.parse(response.text || '{}')
1161
+ } catch {
1162
+ return {}
1163
+ }
1164
+ })()
1165
+ if (!data.device_code) {
1166
+ const reason = /device flow/i.test(`${data.error || ''} ${data.error_description || ''}`)
1167
+ ? 'App 没有启用 Device Flow:到 App 设置页勾选「Enable Device Flow」保存后再试'
1168
+ : `申请设备码失败:${data.error_description || data.error || `HTTP ${response.status}`}`
1169
+ throw new Error(reason)
1170
+ }
1171
+ pendingDevices.set(data.device_code, {
1172
+ interval: Number(data.interval) || 5,
1173
+ startedAt: Date.now(),
1174
+ expiresIn: Number(data.expires_in) || 900,
1175
+ })
1176
+ return {
1177
+ deviceCode: data.device_code,
1178
+ userCode: data.user_code,
1179
+ verificationUri: data.verification_uri,
1180
+ expiresIn: Number(data.expires_in) || 900,
1181
+ interval: Number(data.interval) || 5,
1182
+ }
1183
+ }
1184
+
1185
+ async function devicePoll(deviceCode) {
1186
+ const app = await readApp()
1187
+ const entry = pendingDevices.get(deviceCode)
1188
+ if (!entry) throw new Error('这个设备码不在本进程里(插件可能重载过),请重新发起设备码授权')
1189
+ const response = await transport.request('https://github.com/login/oauth/access_token', {
1190
+ method: 'POST',
1191
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1192
+ body: JSON.stringify({
1193
+ client_id: app.clientId,
1194
+ device_code: deviceCode,
1195
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
1196
+ }),
1197
+ })
1198
+ const data = (() => {
1199
+ try {
1200
+ return JSON.parse(response.text || '{}')
1201
+ } catch {
1202
+ return {}
1203
+ }
1204
+ })()
1205
+ if (data.access_token) {
1206
+ const now = Date.now()
1207
+ await writeRecord(OAUTH_CRED, {
1208
+ accessToken: data.access_token,
1209
+ refreshToken: data.refresh_token || '',
1210
+ expiresAt: now + Number(data.expires_in || 28800) * 1000,
1211
+ refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : null,
1212
+ scope: data.scope || '',
1213
+ via: 'device',
1214
+ addedAt: new Date().toISOString(),
1215
+ })
1216
+ pendingDevices.delete(deviceCode)
1217
+ await writeRecord(AUTH_CRED, { kind: 'oauth' })
1218
+ authCache = null
1219
+ return { status: 'ok' }
1220
+ }
1221
+ const state = data.error || 'unknown'
1222
+ if (state === 'authorization_pending') return { status: 'pending' }
1223
+ if (state === 'slow_down') {
1224
+ pendingDevices.set(deviceCode, { ...entry, interval: entry.interval + 2 })
1225
+ return { status: 'pending', slowDown: true }
1226
+ }
1227
+ if (state === 'expired_token') {
1228
+ pendingDevices.delete(deviceCode)
1229
+ return { status: 'expired' }
1230
+ }
1231
+ if (state === 'access_denied') {
1232
+ pendingDevices.delete(deviceCode)
1233
+ return { status: 'denied' }
1234
+ }
1235
+ throw new Error(`设备码轮询失败:${data.error_description || state}`)
1236
+ }
1237
+
1238
+ /**
1239
+ * Pick the connection to use. Order is App → PAT → environment unless the
1240
+ * profile pins one; the active choice is remembered in credentials.
1241
+ */
1242
+ async function resolveAuth() {
1243
+ if (authCache && Date.now() - authCache.at < 30000) return authCache.value
1244
+ const stored = await readRecord(AUTH_CRED).catch(() => undefined)
1245
+ const storedKind = stored && typeof stored.kind === 'string' ? stored.kind : ''
1246
+ const preferred = cfg.authMode !== 'auto' ? cfg.authMode : storedKind || 'auto'
1247
+ const order =
1248
+ preferred === 'app'
1249
+ ? ['app']
1250
+ : preferred === 'oauth'
1251
+ ? ['oauth']
1252
+ : preferred === 'pat'
1253
+ ? ['pat']
1254
+ : preferred === 'env'
1255
+ ? ['env']
1256
+ : ['app', 'oauth', 'pat', 'env']
1257
+ let value = { kind: 'none' }
1258
+ for (const kind of order) {
1259
+ if (kind === 'app') {
1260
+ const app = await readApp()
1261
+ if (!app) continue
1262
+ const installation = await selectedInstallation().catch(() => undefined)
1263
+ if (!installation) continue
1264
+ value = {
1265
+ kind: 'app',
1266
+ account: installation.account,
1267
+ installationId: installation.id,
1268
+ permissions: installation.permissions || {},
1269
+ }
1270
+ break
1271
+ }
1272
+ if (kind === 'oauth') {
1273
+ const token = await oauthToken().catch(() => '')
1274
+ if (!token) continue
1275
+ value = { kind: 'oauth', token, fingerprint: fingerprint(token) }
1276
+ break
1277
+ }
1278
+ if (kind === 'pat') {
1279
+ const token = await readPat()
1280
+ if (!token) continue
1281
+ value = { kind: 'pat', token, fingerprint: fingerprint(token) }
1282
+ break
1283
+ }
1284
+ if (kind === 'env') {
1285
+ const token = process.env[cfg.patEnvName] || ''
1286
+ if (!token) continue
1287
+ value = { kind: 'env', token, fingerprint: fingerprint(token), envName: cfg.patEnvName }
1288
+ break
1289
+ }
1290
+ }
1291
+ authCache = { at: Date.now(), value }
1292
+ return value
1293
+ }
1294
+
1295
+ /**
1296
+ * What the active connection can do. An installation token is scoped by the
1297
+ * App's permissions and cannot read notifications or search code; a user token
1298
+ * can do both.
1299
+ */
1300
+ function capabilitiesOf(auth) {
1301
+ const none = {
1302
+ repoRead: false,
1303
+ repoWrite: false,
1304
+ pullWrite: false,
1305
+ issueWrite: false,
1306
+ actionsWrite: false,
1307
+ workflowsWrite: false,
1308
+ adminWrite: false,
1309
+ notifications: false,
1310
+ codeSearch: false,
1311
+ userLevel: false,
1312
+ }
1313
+ if (auth.kind === 'app') {
1314
+ const p = auth.permissions || {}
1315
+ return {
1316
+ ...none,
1317
+ repoRead: true,
1318
+ repoWrite: p.contents === 'write',
1319
+ pullWrite: p.pull_requests === 'write',
1320
+ issueWrite: p.issues === 'write',
1321
+ actionsWrite: p.actions === 'write',
1322
+ workflowsWrite: p.workflows === 'write',
1323
+ adminWrite: p.administration === 'write',
1324
+ }
1325
+ }
1326
+ if (auth.kind === 'pat' || auth.kind === 'env' || auth.kind === 'oauth') {
1327
+ return {
1328
+ repoRead: true,
1329
+ repoWrite: true,
1330
+ pullWrite: true,
1331
+ issueWrite: true,
1332
+ actionsWrite: true,
1333
+ workflowsWrite: true,
1334
+ adminWrite: true,
1335
+ notifications: true,
1336
+ codeSearch: true,
1337
+ userLevel: true,
1338
+ }
1339
+ }
1340
+ return none
1341
+ }
1342
+
911
1343
  async function status() {
912
1344
  const app = await readApp()
913
1345
  const installError = []
@@ -951,6 +1383,23 @@ function createGithub(ctx, cfg, transport) {
951
1383
  network.hint = ''
952
1384
  }
953
1385
  const tokenReady = Boolean(installationTokenCache)
1386
+ // The active connection decides which capabilities the UI may offer.
1387
+ const authState = await resolveAuth().catch(() => ({ kind: 'none' }))
1388
+ const capabilities = capabilitiesOf(authState)
1389
+ let login = authState.account || ''
1390
+ let tokenScopes = []
1391
+ if ((authState.kind === 'pat' || authState.kind === 'env') && authState.token) {
1392
+ try {
1393
+ const me = await whoAmI(authState.token)
1394
+ login = me.login
1395
+ tokenScopes = me.scopes || []
1396
+ } catch (error) {
1397
+ installError.push(`当前令牌无效:${errorMessage(error)}`)
1398
+ }
1399
+ }
1400
+ const patToken = await readPat().catch(() => '')
1401
+ const oauthState = await readRecord(OAUTH_CRED).catch(() => undefined)
1402
+ const envToken = process.env[cfg.patEnvName] || ''
954
1403
  const base = {
955
1404
  version: PLUGIN_VERSION,
956
1405
  apiBase: cfg.baseUrl,
@@ -980,9 +1429,32 @@ function createGithub(ctx, cfg, transport) {
980
1429
  ? { expiresAt: new Date(installationTokenCache.expiresAt).toISOString() }
981
1430
  : null,
982
1431
  publish: { branch: cfg.publishBranch, topic: cfg.topic, marketIndexUrls: cfg.marketIndexUrls },
1432
+ authMode: cfg.authMode,
1433
+ auth: {
1434
+ kind: authState.kind,
1435
+ account: login,
1436
+ scopes: tokenScopes,
1437
+ capabilities,
1438
+ readOnly: cfg.readOnly || !capabilities.repoWrite,
1439
+ readOnlyReason: cfg.readOnly
1440
+ ? '配置里把 readOnly 设成了 true'
1441
+ : !capabilities.repoWrite
1442
+ ? '当前连接没有写权限(App 只读安装,或令牌是只读的)'
1443
+ : '',
1444
+ },
1445
+ connections: {
1446
+ app: Boolean(app),
1447
+ oauth: {
1448
+ configured: Boolean(oauthState && oauthState.accessToken),
1449
+ expiresAt: oauthState && oauthState.expiresAt ? new Date(oauthState.expiresAt).toISOString() : null,
1450
+ },
1451
+ pat: { configured: Boolean(patToken), fingerprint: patToken ? fingerprint(patToken) : '' },
1452
+ env: { name: cfg.patEnvName, present: Boolean(envToken), fingerprint: envToken ? fingerprint(envToken) : '' },
1453
+ },
983
1454
  errors,
984
1455
  network,
985
1456
  }
1457
+ if (authState.kind !== 'app') return base
986
1458
  if (!app || !installation) return base
987
1459
  try {
988
1460
  const viewer = await call('/installation/repositories?per_page=1')
@@ -1150,12 +1622,187 @@ function createGithub(ctx, cfg, transport) {
1150
1622
  return { ok: true, runId }
1151
1623
  }
1152
1624
 
1625
+ async function pullDetail(owner, name, number) {
1626
+ const repo = repoPath(owner, name)
1627
+ const [pull, files] = await Promise.all([
1628
+ call(`${repo}/pulls/${number}`),
1629
+ call(`${repo}/pulls/${number}/files?per_page=100`),
1630
+ ])
1631
+ return {
1632
+ number: pull.number,
1633
+ title: pull.title,
1634
+ state: pull.state,
1635
+ draft: Boolean(pull.draft),
1636
+ user: pull.user ? pull.user.login : '',
1637
+ head: pull.head ? pull.head.ref : '',
1638
+ base: pull.base ? pull.base.ref : '',
1639
+ mergeable: pull.mergeable,
1640
+ mergeableState: pull.mergeable_state || '',
1641
+ additions: pull.additions,
1642
+ deletions: pull.deletions,
1643
+ changedFiles: pull.changed_files,
1644
+ body: pull.body || '',
1645
+ htmlUrl: pull.html_url,
1646
+ updatedAt: pull.updated_at,
1647
+ files: (Array.isArray(files) ? files : []).map((file) => ({
1648
+ path: file.filename,
1649
+ status: file.status,
1650
+ additions: file.additions,
1651
+ deletions: file.deletions,
1652
+ patch: file.patch ? String(file.patch).slice(0, 6000) : '',
1653
+ })),
1654
+ }
1655
+ }
1656
+
1657
+ async function addPullComment(owner, name, number, body, line) {
1658
+ const repo = repoPath(owner, name)
1659
+ if (!body || !String(body).trim()) throw new Error('评论内容不能为空')
1660
+ if (line && line.path) {
1661
+ const json = await call(`${repo}/pulls/${number}/comments`, {
1662
+ method: 'POST',
1663
+ body: { body, path: line.path, line: Number(line.number), side: line.side || 'RIGHT' },
1664
+ })
1665
+ return { id: json.id, inline: true, htmlUrl: json.html_url }
1666
+ }
1667
+ const json = await call(`${repo}/issues/${number}/comments`, { method: 'POST', body: { body } })
1668
+ return { id: json.id, inline: false, htmlUrl: json.html_url }
1669
+ }
1670
+
1671
+ async function submitReview(owner, name, number, event, body) {
1672
+ const allowed = ['APPROVE', 'REQUEST_CHANGES', 'COMMENT']
1673
+ if (!allowed.includes(event)) throw new Error(`event 必须是 ${allowed.join(' / ')}`)
1674
+ if (event === 'REQUEST_CHANGES' && !String(body || '').trim()) {
1675
+ throw new Error('请求修改必须写理由')
1676
+ }
1677
+ const repo = repoPath(owner, name)
1678
+ const json = await call(`${repo}/pulls/${number}/reviews`, { method: 'POST', body: { event, body: body || '' } })
1679
+ return { id: json.id, state: json.state, htmlUrl: json.html_url }
1680
+ }
1681
+
1682
+ async function updateIssue(owner, name, number, patch) {
1683
+ const repo = repoPath(owner, name)
1684
+ const body = {}
1685
+ for (const key of ['title', 'body', 'state', 'state_reason', 'milestone']) {
1686
+ if (patch[key] !== undefined) body[key] = patch[key]
1687
+ }
1688
+ if (Array.isArray(patch.labels)) body.labels = patch.labels
1689
+ if (Array.isArray(patch.assignees)) body.assignees = patch.assignees
1690
+ if (Object.keys(body).length === 0) throw new Error('没有要修改的字段')
1691
+ const json = await call(`${repo}/issues/${number}`, { method: 'PATCH', body })
1692
+ return {
1693
+ number: json.number,
1694
+ title: json.title,
1695
+ state: json.state,
1696
+ labels: (json.labels || []).map((label) => (typeof label === 'string' ? label : label.name)),
1697
+ assignees: (json.assignees || []).map((item) => item.login),
1698
+ htmlUrl: json.html_url,
1699
+ }
1700
+ }
1701
+
1702
+ async function listWorkflows(owner, name) {
1703
+ const repo = repoPath(owner, name)
1704
+ const json = await call(`${repo}/actions/workflows?per_page=50`)
1705
+ return {
1706
+ items: (json.workflows || []).map((item) => ({
1707
+ id: item.id,
1708
+ name: item.name,
1709
+ path: item.path,
1710
+ state: item.state,
1711
+ htmlUrl: item.html_url,
1712
+ })),
1713
+ }
1714
+ }
1715
+
1716
+ async function dispatchNamedWorkflow(owner, name, workflow, ref, inputs) {
1717
+ const repo = repoPath(owner, name)
1718
+ if (!workflow) throw new Error('需要 workflow(文件名或 id)')
1719
+ await call(`${repo}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, {
1720
+ method: 'POST',
1721
+ body: { ref: ref || 'main', ...(inputs && Object.keys(inputs).length ? { inputs } : {}) },
1722
+ })
1723
+ return { dispatched: true, workflow, ref: ref || 'main', inputs: inputs || {} }
1724
+ }
1725
+
1726
+ async function runLog(owner, name, runId, tailLines = 120) {
1727
+ const repo = repoPath(owner, name)
1728
+ const token = await installationToken()
1729
+ // The archive answers 302 to a signed objects.githubusercontent.com URL, and
1730
+ // both hosts are hijacked on some machines, so follow the redirect through
1731
+ // the same resilient transport instead of global fetch.
1732
+ let url = `${cfg.baseUrl}${repo}/actions/runs/${runId}/logs`
1733
+ let withAuth = true
1734
+ let response = null
1735
+ for (let hop = 0; hop < 5; hop++) {
1736
+ response = await transport.request(url, {
1737
+ headers: withAuth ? { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json' } : { Accept: '*/*' },
1738
+ binary: true,
1739
+ })
1740
+ const location = response.headers && response.headers.location
1741
+ if (response.status >= 300 && response.status < 400 && location) {
1742
+ url = new URL(location, url).href
1743
+ withAuth = new URL(url).hostname === new URL(cfg.baseUrl).hostname
1744
+ continue
1745
+ }
1746
+ break
1747
+ }
1748
+ if (!response || response.status !== 200 || !response.buffer) {
1749
+ throw new GhError(response ? response.status : 0, 'LOG_UNAVAILABLE', `取日志失败(HTTP ${response ? response.status : '?'})`)
1750
+ }
1751
+ const entries = unzipEntries(response.buffer)
1752
+ const pick =
1753
+ entries.find((entry) => /Publish\.txt$/i.test(entry.name)) ||
1754
+ entries.find((entry) => /\.txt$/i.test(entry.name)) ||
1755
+ entries[entries.length - 1]
1756
+ const lines = pick ? pick.text.split('\n') : []
1757
+ return {
1758
+ runId,
1759
+ files: entries.map((entry) => entry.name),
1760
+ name: pick ? pick.name : '',
1761
+ tail: lines.slice(-Math.max(10, Math.min(2000, tailLines))).join('\n'),
1762
+ }
1763
+ }
1764
+
1153
1765
  return {
1154
1766
  call,
1155
1767
  installToken: installationToken,
1156
1768
  status,
1157
1769
  installations,
1158
1770
  selectedInstallation,
1771
+ resolveAuth,
1772
+ capabilitiesOf,
1773
+ whoAmI,
1774
+ fingerprint,
1775
+ useConnection: async (kind) => {
1776
+ if (!['app', 'oauth', 'pat', 'env'].includes(kind)) throw new Error(`未知连接类型:${kind}`)
1777
+ if (kind === 'app') {
1778
+ const app = await readApp()
1779
+ if (!app) throw new Error('还没有注册 GitHub App')
1780
+ const installation = await selectedInstallation()
1781
+ if (!installation) throw new Error('App 还没有安装到任何账号')
1782
+ }
1783
+ if (kind === 'oauth' && !(await oauthToken().catch(() => ''))) throw new Error('还没有完成 App 用户授权')
1784
+ if (kind === 'pat' && !(await readPat())) throw new Error('还没有保存个人访问令牌')
1785
+ if (kind === 'env' && !process.env[cfg.patEnvName]) throw new Error(`环境变量 ${cfg.patEnvName} 没有设置`)
1786
+ await writeRecord(AUTH_CRED, { kind })
1787
+ authCache = null
1788
+ return resolveAuth()
1789
+ },
1790
+ setPat: async (token) => {
1791
+ const value = String(token || '').trim()
1792
+ if (!value) throw new Error('令牌不能为空')
1793
+ const me = await whoAmI(value)
1794
+ await writeRecord(PAT_CRED, { token: value, login: me.login, scopes: me.scopes, addedAt: new Date().toISOString() })
1795
+ await writeRecord(AUTH_CRED, { kind: 'pat' })
1796
+ authCache = null
1797
+ return { login: me.login, fingerprint: fingerprint(value), scopes: me.scopes }
1798
+ },
1799
+ clearPat: async () => {
1800
+ await deleteRecord(PAT_CRED)
1801
+ const stored = await readRecord(AUTH_CRED).catch(() => undefined)
1802
+ if (stored && stored.kind === 'pat') await writeRecord(AUTH_CRED, { kind: 'app' })
1803
+ authCache = null
1804
+ return { ok: true }
1805
+ },
1159
1806
  selectInstallation: async (id) => {
1160
1807
  const list = await installations()
1161
1808
  const match = list.find((item) => String(item.id) === String(id))
@@ -1166,6 +1813,17 @@ function createGithub(ctx, cfg, transport) {
1166
1813
  },
1167
1814
  beginManifest,
1168
1815
  completeManifest,
1816
+ deviceStart,
1817
+ devicePoll,
1818
+ beginOAuth,
1819
+ completeOAuth,
1820
+ clearOAuth: async () => {
1821
+ await deleteRecord(OAUTH_CRED)
1822
+ const stored = await readRecord(AUTH_CRED).catch(() => undefined)
1823
+ if (stored && stored.kind === 'oauth') await writeRecord(AUTH_CRED, { kind: 'app' })
1824
+ authCache = null
1825
+ return { ok: true }
1826
+ },
1169
1827
  resetApp,
1170
1828
  appConfigured: async () => Boolean(await readApp()),
1171
1829
  waitForCredentials,
@@ -1183,6 +1841,13 @@ function createGithub(ctx, cfg, transport) {
1183
1841
  mergePull,
1184
1842
  listRuns,
1185
1843
  rerunWorkflow,
1844
+ pullDetail,
1845
+ addPullComment,
1846
+ submitReview,
1847
+ updateIssue,
1848
+ listWorkflows,
1849
+ dispatchNamedWorkflow,
1850
+ runLog,
1186
1851
  }
1187
1852
  }
1188
1853
 
@@ -1520,8 +2185,6 @@ async function createRelease(gh, owner, name, version, branch, notes) {
1520
2185
  return { skipped: false, tag, htmlUrl: release.html_url }
1521
2186
  }
1522
2187
 
1523
- const WORKFLOW_DIR = '.github/workflows'
1524
-
1525
2188
  function publishWorkflowYaml() {
1526
2189
  // npm cannot attach a trusted publisher to a package that does not exist yet,
1527
2190
  // so this workflow also accepts an optional NPM_TOKEN secret for the very
@@ -1560,6 +2223,194 @@ jobs:
1560
2223
  `
1561
2224
  }
1562
2225
 
2226
+ const WORKFLOW_DIR = '.github/workflows'
2227
+
2228
+ /**
2229
+ * Minimal ustar writer plus gzip, so a release asset can be produced without
2230
+ * depending on a system tar or an npm install.
2231
+ */
2232
+ function buildTarball(files, prefix = 'package') {
2233
+ const blocks = []
2234
+ const header = (name, size, mtime) => {
2235
+ const buffer = Buffer.alloc(512)
2236
+ const write = (value, offset, length) => buffer.write(value.slice(0, length), offset, length, 'utf8')
2237
+ write(name, 0, 100)
2238
+ write(`${(0o644).toString(8)}\0`, 100, 8)
2239
+ write(`${(0).toString(8)}\0`, 108, 8)
2240
+ write(`${(0).toString(8)}\0`, 116, 8)
2241
+ write(`${size.toString(8)}\0`, 124, 12)
2242
+ write(`${Math.floor(mtime / 1000).toString(8)}\0`, 136, 12)
2243
+ write(' ', 148, 8)
2244
+ write('0', 156, 1)
2245
+ write('ustar\0', 257, 6)
2246
+ write('00', 263, 2)
2247
+ let sum = 0
2248
+ for (const byte of buffer) sum += byte
2249
+ write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8)
2250
+ return buffer
2251
+ }
2252
+ const now = Date.now()
2253
+ for (const file of files) {
2254
+ // ustar splits long paths into prefix/name at a slash before byte 100.
2255
+ let name = `${prefix}/${file.path}`
2256
+ let tail = name
2257
+ if (Buffer.byteLength(name) > 100) {
2258
+ const slash = name.lastIndexOf('/', 155)
2259
+ if (slash > 0 && Buffer.byteLength(name.slice(slash + 1)) <= 100) {
2260
+ tail = name.slice(slash + 1)
2261
+ const dir = name.slice(0, slash)
2262
+ const buffer = Buffer.alloc(512)
2263
+ buffer.write(tail, 0, 100, 'utf8')
2264
+ buffer.write(`${(0o644).toString(8)}\0`, 100, 8)
2265
+ buffer.write('0000000\0', 108, 8)
2266
+ buffer.write('0000000\0', 116, 8)
2267
+ buffer.write(`${file.content.length.toString(8)}\0`, 124, 12)
2268
+ buffer.write(`${Math.floor(now / 1000).toString(8)}\0`, 136, 12)
2269
+ buffer.write(' ', 148, 8)
2270
+ buffer.write('0', 156, 1)
2271
+ buffer.write('ustar\0', 257, 6)
2272
+ buffer.write('00', 263, 2)
2273
+ buffer.write(dir, 345, Math.min(155, Buffer.byteLength(dir)))
2274
+ let sum = 0
2275
+ for (const byte of buffer) sum += byte
2276
+ buffer.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8)
2277
+ blocks.push(buffer)
2278
+ blocks.push(file.content)
2279
+ const pad = (512 - (file.content.length % 512)) % 512
2280
+ if (pad) blocks.push(Buffer.alloc(pad))
2281
+ continue
2282
+ }
2283
+ }
2284
+ blocks.push(header(name, file.content.length, now))
2285
+ blocks.push(file.content)
2286
+ const pad = (512 - (file.content.length % 512)) % 512
2287
+ if (pad) blocks.push(Buffer.alloc(pad))
2288
+ }
2289
+ blocks.push(Buffer.alloc(1024))
2290
+ return zlib.gzipSync(Buffer.concat(blocks), { level: 9 })
2291
+ }
2292
+
2293
+ async function attachReleaseAsset(gh, owner, repo, version, fileName, buffer) {
2294
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
2295
+ const tag = `v${version}`
2296
+ let release = await gh.call(`${repoPath}/releases/tags/${encodeURIComponent(tag)}`).catch(() => null)
2297
+ if (!release) return { uploaded: false, reason: `Release ${tag} 还不存在:先发布一次` }
2298
+ const upload = async (name) => {
2299
+ const assets = Array.isArray(release.assets) ? release.assets : []
2300
+ const existing = assets.find((asset) => asset.name === name)
2301
+ if (existing) {
2302
+ await gh.call(`${repoPath}/releases/assets/${existing.id}`, { method: 'DELETE' }).catch(() => {})
2303
+ }
2304
+ return gh.call(
2305
+ `https://uploads.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases/${release.id}/assets?name=${encodeURIComponent(name)}`,
2306
+ {
2307
+ method: 'POST',
2308
+ rawBody: true,
2309
+ headers: { 'Content-Type': 'application/gzip', Accept: 'application/vnd.github+json' },
2310
+ body: buffer,
2311
+ },
2312
+ )
2313
+ }
2314
+ const uploaded = await upload(fileName)
2315
+ // A version-free duplicate keeps releases/latest/download/<name> alive: the
2316
+ // storefront list warns that a versioned name rots on the next release.
2317
+ let versionFree = null
2318
+ const versionFreeName = fileName.replace(new RegExp(`-${version.replace(/\./g, '\\.')}(?=\\.tgz$)`), '')
2319
+ if (versionFreeName !== fileName) {
2320
+ versionFree = await upload(versionFreeName).catch(() => null)
2321
+ }
2322
+ return {
2323
+ uploaded: true,
2324
+ id: uploaded.id,
2325
+ name: uploaded.name,
2326
+ size: uploaded.size,
2327
+ url: uploaded.browser_download_url,
2328
+ tag,
2329
+ versionFreeName: versionFree ? versionFree.name : '',
2330
+ versionFreeUrl: versionFree ? versionFree.browser_download_url : '',
2331
+ }
2332
+ }
2333
+
2334
+ /** Preconditions the awesome-dsh-plugin list checks before a PR can merge. */
2335
+ async function marketReadiness(gh, cfg, { owner, repo, dir }) {
2336
+ const checks = []
2337
+ const add = (id, level, title, detail) => checks.push({ id, level, title, detail: detail || '' })
2338
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
2339
+ const meta = await gh.call(repoPath).catch(() => null)
2340
+
2341
+ if (!meta) {
2342
+ add('repo', 'block', '读不到仓库信息', `${owner}/${repo}`)
2343
+ return { ready: false, checks }
2344
+ }
2345
+ const created = meta.created_at ? Date.parse(meta.created_at) : 0
2346
+ const ageHours = created ? (Date.now() - created) / 3600000 : 0
2347
+ add('repo-age', ageHours >= 24 ? 'pass' : 'block', '仓库年龄 ≥ 1 天', `${ageHours.toFixed(1)} 小时`)
2348
+
2349
+ let pkg = null
2350
+ try {
2351
+ pkg = await readLocalPackage(dir)
2352
+ } catch (error) {
2353
+ add('package', 'block', '本地 package.json 读不到', errorMessage(error))
2354
+ }
2355
+ if (pkg) {
2356
+ const hasBundle = Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch)
2357
+ add('dsh.bundle', hasBundle ? 'pass' : 'block', 'package.json 声明 dsh.bundle', hasBundle ? pkg.dsh.bundle.patch : '只声明 dsh.client 会在这条失败')
2358
+ const officialDeps = Object.keys(pkg.dependencies || {}).filter((name) => name.startsWith('@deepseek-ai/'))
2359
+ add(
2360
+ 'peer-deps',
2361
+ officialDeps.length === 0 ? 'pass' : 'block',
2362
+ '@deepseek-ai/* 用 peerDependencies 而不是 dependencies',
2363
+ officialDeps.join(', '),
2364
+ )
2365
+ }
2366
+
2367
+ const iconCandidates = ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']
2368
+ let iconPath = ''
2369
+ for (const candidate of iconCandidates) {
2370
+ const file = await repoFile(gh, owner, repo, candidate, cfg.publishBranch).catch(() => null)
2371
+ if (file) {
2372
+ iconPath = candidate
2373
+ break
2374
+ }
2375
+ }
2376
+ add('icon', iconPath ? 'pass' : 'block', '仓库里有 GitHub 托管的 PNG 图标', iconPath || '列表拒收 SVG 与第三方图床')
2377
+
2378
+ const latest = await gh.call(`${repoPath}/releases/latest`).catch(() => null)
2379
+ const assets = latest && Array.isArray(latest.assets) ? latest.assets : []
2380
+ const versionFree = assets.find((asset) => /\.tgz$/i.test(asset.name) && !/\d+\.\d+\.\d+/.test(asset.name))
2381
+ add(
2382
+ 'tarball',
2383
+ versionFree ? 'pass' : 'block',
2384
+ '最新 Release 有不带版本号的 .tgz',
2385
+ versionFree ? versionFree.name : 'releases/latest/download/<固定名>.tgz 才能在每次发版后继续可用',
2386
+ )
2387
+
2388
+ let readme = ''
2389
+ try {
2390
+ readme = await fs.readFile(path.join(dir, 'README.md'), 'utf8')
2391
+ } catch {
2392
+ readme = ''
2393
+ }
2394
+ const bilingual = /[\u4e00-\u9fff]/.test(readme) && /[A-Za-z]{4,}/.test(readme)
2395
+ add('readme', bilingual ? 'pass' : 'warn', 'README 中英双语(列表条目也是双语)', bilingual ? '' : 'README 里至少要有中英两种文字')
2396
+
2397
+ add('screenshots', 'info', '截图可选', '想控制展示顺序就在仓库放 screenshots.json(1-8 张,路径不能跳出插件目录)')
2398
+ add('category', 'info', '分类建议', 'Git & Code Review(条目里写 category: git)')
2399
+
2400
+ const ready = !checks.some((check) => check.level === 'block')
2401
+ return {
2402
+ ready,
2403
+ checks,
2404
+ entry: {
2405
+ url: `https://github.com/${owner}/${repo}`,
2406
+ name: `${owner}/${repo}`,
2407
+ category: 'git',
2408
+ icon: iconPath ? `https://raw.githubusercontent.com/${owner}/${repo}/${cfg.publishBranch}/${iconPath}` : '',
2409
+ tarball: versionFree ? `https://github.com/${owner}/${repo}/releases/latest/download/${versionFree.name}` : '',
2410
+ },
2411
+ }
2412
+ }
2413
+
1563
2414
  async function repoFile(gh, owner, repo, filePath, ref) {
1564
2415
  try {
1565
2416
  return await gh.readFile(owner, repo, filePath, ref)
@@ -1740,11 +2591,76 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
1740
2591
  }
1741
2592
  }
1742
2593
 
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
-
2594
+ function unzipEntries(buffer) {
2595
+ // GitHub log archives use data descriptors, so sizes come from the central
2596
+ // directory rather than the local header. Minimal deflate-only reader.
2597
+ const entries = []
2598
+ let eocd = -1
2599
+ for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 70000); i--) {
2600
+ if (buffer.readUInt32LE(i) === 0x06054b50) {
2601
+ eocd = i
2602
+ break
2603
+ }
2604
+ }
2605
+ const read = (offset, nameLength, extraLength) => {
2606
+ const method = buffer.readUInt16LE(offset + 10)
2607
+ const compressed = buffer.readUInt32LE(offset + 20)
2608
+ const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
2609
+ const localOffset = buffer.readUInt32LE(offset + 42)
2610
+ const localNameLength = buffer.readUInt16LE(localOffset + 26)
2611
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28)
2612
+ const dataStart = localOffset + 30 + localNameLength + localExtraLength
2613
+ const data = buffer.subarray(dataStart, dataStart + compressed)
2614
+ let text = ''
2615
+ try {
2616
+ text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
2617
+ } catch {
2618
+ text = ''
2619
+ }
2620
+ entries.push({ name, text })
2621
+ void extraLength
2622
+ }
2623
+ if (eocd >= 0) {
2624
+ const count = buffer.readUInt16LE(eocd + 10)
2625
+ let offset = buffer.readUInt32LE(eocd + 16)
2626
+ for (let index = 0; index < count; index++) {
2627
+ if (buffer.readUInt32LE(offset) !== 0x02014b50) break
2628
+ const nameLength = buffer.readUInt16LE(offset + 28)
2629
+ const extraLength = buffer.readUInt16LE(offset + 30)
2630
+ const commentLength = buffer.readUInt16LE(offset + 32)
2631
+ read(offset, nameLength, extraLength)
2632
+ offset += 46 + nameLength + extraLength + commentLength
2633
+ }
2634
+ if (entries.length) return entries
2635
+ }
2636
+ // Fallback: walk local headers (works when sizes are present).
2637
+ let offset = 0
2638
+ while (offset + 30 <= buffer.length) {
2639
+ if (buffer.readUInt32LE(offset) !== 0x04034b50) break
2640
+ const method = buffer.readUInt16LE(offset + 8)
2641
+ const compressed = buffer.readUInt32LE(offset + 18)
2642
+ const nameLength = buffer.readUInt16LE(offset + 26)
2643
+ const extraLength = buffer.readUInt16LE(offset + 28)
2644
+ const name = buffer.subarray(offset + 30, offset + 30 + nameLength).toString('utf8')
2645
+ const dataStart = offset + 30 + nameLength + extraLength
2646
+ const data = buffer.subarray(dataStart, dataStart + compressed)
2647
+ let text = ''
2648
+ try {
2649
+ text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
2650
+ } catch {
2651
+ text = ''
2652
+ }
2653
+ entries.push({ name, text })
2654
+ offset = dataStart + compressed
2655
+ }
2656
+ return entries
2657
+ }
2658
+
2659
+ async function probeMarket(input, gh, cfg) {
2660
+ const checkedAt = new Date().toISOString()
2661
+ const results = []
2662
+ const push = (id, state, detail, extra = {}) => results.push({ id, state, detail, checkedAt, ...extra })
2663
+
1748
2664
  // 1. npm package presence
1749
2665
  try {
1750
2666
  const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(input.name)}/latest`)
@@ -2027,6 +2943,32 @@ export function apply(ctx, rawConfig) {
2027
2943
 
2028
2944
  const discover = (extra) => discoverPlugins(discoveryRoots(extra))
2029
2945
 
2946
+ // Every mutating path records who did what, so a console leaves a trail.
2947
+ const audited = async (action, target, run) => {
2948
+ const started = Date.now()
2949
+ try {
2950
+ const result = await run()
2951
+ await appendAudit({ action, target, ok: true, ms: Date.now() - started })
2952
+ return result
2953
+ } catch (error) {
2954
+ await appendAudit({ action, target, ok: false, detail: errorMessage(error).slice(0, 300), ms: Date.now() - started })
2955
+ throw error
2956
+ }
2957
+ }
2958
+
2959
+ // Write actions are refused up front when the active connection cannot write.
2960
+ const requireWrite = async (capability = 'repoWrite') => {
2961
+ if (cfg.readOnly) throw new Error('只读模式已开启(配置 readOnly: true),写操作已禁用')
2962
+ const auth = await gh.resolveAuth()
2963
+ const capabilities = gh.capabilitiesOf(auth)
2964
+ if (!capabilities[capability]) {
2965
+ throw new Error(
2966
+ `当前连接(${auth.kind})没有 ${capability} 权限:到「状态 → 连接方式」换一个带写权限的连接,或给 App 补权限`,
2967
+ )
2968
+ }
2969
+ return auth
2970
+ }
2971
+
2030
2972
  async function withToken() {
2031
2973
  if (!bridgeToken) {
2032
2974
  const credentials = await gh.waitForCredentials()
@@ -2195,6 +3137,38 @@ export function apply(ctx, rawConfig) {
2195
3137
  const route = `${request.method} ${url.pathname}`
2196
3138
  const args = body && typeof body === 'object' ? body : {}
2197
3139
 
3140
+ if (route === 'POST /github-console/api/auth/device/start') {
3141
+ return sendJson(response, 200, await gh.deviceStart())
3142
+ }
3143
+ if (route === 'POST /github-console/api/auth/device/poll') {
3144
+ return sendJson(response, 200, await gh.devicePoll(args.deviceCode))
3145
+ }
3146
+ if (route === 'POST /github-console/api/auth/oauth/start') {
3147
+ return sendJson(response, 200, await gh.beginOAuth(requestOrigin(request)))
3148
+ }
3149
+ if (route === 'POST /github-console/api/auth/oauth/clear') {
3150
+ await gh.clearOAuth()
3151
+ await appendAudit({ action: 'auth.oauth-clear', account: '', ok: true })
3152
+ return sendJson(response, 200, { ok: true })
3153
+ }
3154
+ if (route === 'POST /github-console/api/auth/use') {
3155
+ const auth = await gh.useConnection(args.kind)
3156
+ await appendAudit({ action: 'auth.use', account: auth.account || auth.fingerprint || '', detail: args.kind })
3157
+ return sendJson(response, 200, { active: auth.kind, ok: true })
3158
+ }
3159
+ if (route === 'POST /github-console/api/auth/pat') {
3160
+ const result = await gh.setPat(args.token)
3161
+ await appendAudit({ action: 'auth.pat-set', account: result.login, detail: result.fingerprint })
3162
+ return sendJson(response, 200, { ok: true, login: result.login, fingerprint: result.fingerprint, scopes: result.scopes })
3163
+ }
3164
+ if (route === 'POST /github-console/api/auth/pat/clear') {
3165
+ await gh.clearPat()
3166
+ await appendAudit({ action: 'auth.pat-clear', account: '', detail: '' })
3167
+ return sendJson(response, 200, { ok: true })
3168
+ }
3169
+ if (route === 'POST /github-console/api/audit') {
3170
+ return sendJson(response, 200, { path: auditPath(), items: await readAudit(args.limit || 50) })
3171
+ }
2198
3172
  if (route === 'POST /github-console/api/status') {
2199
3173
  return sendJson(response, 200, { ...(await gh.status()), bridge: bridgeStatus() })
2200
3174
  }
@@ -2236,10 +3210,77 @@ export function apply(ctx, rawConfig) {
2236
3210
  return sendJson(response, 200, await gh.readFile(args.owner, args.name, args.path, args.ref))
2237
3211
  }
2238
3212
  if (route === 'POST /github-console/api/file/write') {
3213
+ await requireWrite('repoWrite')
3214
+ return sendJson(
3215
+ response,
3216
+ 200,
3217
+ await audited('file.write', `${args.owner}/${args.name}:${args.path}`, () =>
3218
+ gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref),
3219
+ ),
3220
+ )
3221
+ }
3222
+ if (route === 'POST /github-console/api/pull/detail') {
3223
+ return sendJson(response, 200, await gh.pullDetail(args.owner, args.name, args.number))
3224
+ }
3225
+ if (route === 'POST /github-console/api/pull/comment') {
3226
+ await requireWrite('pullWrite')
3227
+ return sendJson(
3228
+ response,
3229
+ 200,
3230
+ await audited('pull.comment', `${args.owner}/${args.name}#${args.number}`, () =>
3231
+ gh.addPullComment(args.owner, args.name, args.number, args.body, args.path ? { path: args.path, number: args.line } : null),
3232
+ ),
3233
+ )
3234
+ }
3235
+ if (route === 'POST /github-console/api/pull/review') {
3236
+ await requireWrite('pullWrite')
3237
+ return sendJson(
3238
+ response,
3239
+ 200,
3240
+ await audited('pull.review', `${args.owner}/${args.name}#${args.number} ${args.event}`, () =>
3241
+ gh.submitReview(args.owner, args.name, args.number, args.event, args.body),
3242
+ ),
3243
+ )
3244
+ }
3245
+ if (route === 'POST /github-console/api/pull/merge') {
3246
+ await requireWrite('pullWrite')
3247
+ if (args.confirm !== true) return sendJson(response, 400, { error: '合并需要 confirm: true', code: 'INVALID' })
3248
+ return sendJson(
3249
+ response,
3250
+ 200,
3251
+ await audited('pull.merge', `${args.owner}/${args.name}#${args.number} ${args.method || 'squash'}`, () =>
3252
+ gh.mergePull(args.owner, args.name, args.number, args.method),
3253
+ ),
3254
+ )
3255
+ }
3256
+ if (route === 'POST /github-console/api/issue/update') {
3257
+ await requireWrite('issueWrite')
3258
+ const patch = {}
3259
+ for (const key of ['title', 'body', 'state', 'labels', 'assignees', 'milestone']) {
3260
+ if (args[key] !== undefined) patch[key] = args[key]
3261
+ }
3262
+ return sendJson(
3263
+ response,
3264
+ 200,
3265
+ await audited('issue.update', `${args.owner}/${args.name}#${args.number}`, () =>
3266
+ gh.updateIssue(args.owner, args.name, args.number, patch),
3267
+ ),
3268
+ )
3269
+ }
3270
+ if (route === 'POST /github-console/api/actions/log') {
3271
+ return sendJson(response, 200, await gh.runLog(args.owner, args.name, args.runId, args.tailLines || 120))
3272
+ }
3273
+ if (route === 'POST /github-console/api/workflows') {
3274
+ return sendJson(response, 200, await gh.listWorkflows(args.owner, args.name))
3275
+ }
3276
+ if (route === 'POST /github-console/api/workflows/dispatch') {
3277
+ await requireWrite('workflowsWrite')
2239
3278
  return sendJson(
2240
3279
  response,
2241
3280
  200,
2242
- await gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref),
3281
+ await audited('workflow.dispatch', `${args.owner}/${args.name}:${args.workflow}`, () =>
3282
+ gh.dispatchNamedWorkflow(args.owner, args.name, args.workflow, args.ref, args.inputs),
3283
+ ),
2243
3284
  )
2244
3285
  }
2245
3286
  if (route === 'POST /github-console/api/issues') {
@@ -2251,6 +3292,30 @@ export function apply(ctx, rawConfig) {
2251
3292
  if (route === 'POST /github-console/api/actions') {
2252
3293
  return sendJson(response, 200, await gh.listRuns(args.owner, args.name))
2253
3294
  }
3295
+ if (route === 'POST /github-console/api/release/asset') {
3296
+ const dir = resolveDir(args.dir)
3297
+ const pkg = await readLocalPackage(dir)
3298
+ const collected = await collectFiles(dir, cfg.maxPushBytes)
3299
+ const fileName =
3300
+ args.fileName || `${pkg.name.replace(/^@[^/]+\//, '')}-${pkg.version}.tgz`
3301
+ const asset = await attachReleaseAsset(
3302
+ gh,
3303
+ args.owner,
3304
+ args.repo,
3305
+ args.version || pkg.version,
3306
+ fileName,
3307
+ buildTarball(collected.files),
3308
+ )
3309
+ const ref = await gh
3310
+ .call(`/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/git/ref/heads/${encodeURIComponent(cfg.publishBranch)}`)
3311
+ .catch(() => null)
3312
+ return sendJson(response, 200, {
3313
+ package: `${pkg.name}@${pkg.version}`,
3314
+ files: collected.files.length,
3315
+ asset,
3316
+ gitInstall: ref && ref.object ? `git+https://github.com/${args.owner}/${args.repo}.git#${ref.object.sha}` : '',
3317
+ })
3318
+ }
2254
3319
  if (route === 'POST /github-console/api/npm/status') {
2255
3320
  return sendJson(
2256
3321
  response,
@@ -2262,6 +3327,9 @@ export function apply(ctx, rawConfig) {
2262
3327
  }),
2263
3328
  )
2264
3329
  }
3330
+ if (route === 'POST /github-console/api/market/readiness') {
3331
+ return sendJson(response, 200, await marketReadiness(gh, cfg, { owner: args.owner, repo: args.repo, dir: resolveDir(args.dir) }))
3332
+ }
2265
3333
  if (route === 'POST /github-console/api/market/attach') {
2266
3334
  return sendJson(
2267
3335
  response,
@@ -2333,8 +3401,10 @@ export function apply(ctx, rawConfig) {
2333
3401
  return sendJson(response, 200, await discover(args.root))
2334
3402
  }
2335
3403
  if (route === 'POST /github-console/api/publish/run') {
3404
+ await requireWrite('repoWrite')
2336
3405
  const dir = resolveDir(args.dir)
2337
3406
  const job = jobs.create({ dir, owner: args.owner, repo: args.repo })
3407
+ await appendAudit({ action: 'publish.run', target: `${args.owner}/${args.repo}`, ok: true })
2338
3408
  void runPublish({ job, gh, cfg, dir, owner: args.owner, repo: args.repo, version: args.version, notes: args.notes, opts: args })
2339
3409
  return sendJson(response, 200, { jobId: job.id })
2340
3410
  }
@@ -2370,6 +3440,22 @@ export function apply(ctx, rawConfig) {
2370
3440
  await handleCallback(request, response, url)
2371
3441
  return
2372
3442
  }
3443
+ if (url.pathname === `${PREFIX}/oauth/callback`) {
3444
+ const code = url.searchParams.get('code')
3445
+ const state = url.searchParams.get('state')
3446
+ if (!code) {
3447
+ sendHtml(response, 400, '授权失败', url.searchParams.get('error_description') || '没有收到 code')
3448
+ return
3449
+ }
3450
+ try {
3451
+ await gh.completeOAuth(code, state, requestOrigin(request))
3452
+ await appendAudit({ action: 'auth.oauth', account: '', ok: true })
3453
+ sendHtml(response, 200, '已授权', 'App 的用户授权已保存,可以关闭此页面回到 DSH:现在可以读取通知与做代码搜索了。')
3454
+ } catch (failure) {
3455
+ sendHtml(response, 400, '授权未完成', errorMessage(failure))
3456
+ }
3457
+ return
3458
+ }
2373
3459
  if (url.pathname === `${PREFIX}/icon.svg`) {
2374
3460
  // The index references ../icon.svg relative to /github-console/market/index.json.
2375
3461
  const svg = await fs.readFile(path.join(PLUGIN_DIR, 'icon.svg')).catch(() => null)
@@ -2484,12 +3570,18 @@ export function apply(ctx, rawConfig) {
2484
3570
  register({
2485
3571
  name: 'gh_auth',
2486
3572
  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.',
3573
+ 'GitHub connection management. action=start registers a GitHub App; installations/select manage App installations; use switches the active connection (app | pat | env); pat-set stores a user access token in the credential service and makes it active; pat-clear removes it; capabilities reports what the active connection may do (notifications and code search need a user token, not an installation token).',
2488
3574
  parameters: {
2489
3575
  type: 'object',
2490
3576
  properties: {
2491
- action: { type: 'string', enum: ['start', 'installations', 'select'] },
3577
+ action: {
3578
+ type: 'string',
3579
+ enum: ['start', 'installations', 'select', 'use', 'pat-set', 'pat-clear', 'oauth-start', 'oauth-clear', 'device-start', 'device-poll', 'capabilities'],
3580
+ },
2492
3581
  installationId: { type: 'string', description: 'Installation id, for action=select' },
3582
+ mode: { type: 'string', enum: ['app', 'oauth', 'pat', 'env'], description: 'Connection kind, for action=use' },
3583
+ token: { type: 'string', description: 'User access token (PAT), for action=pat-set. Stored in the credential service only.' },
3584
+ deviceCode: { type: 'string', description: 'device_code from action=device-start, for action=device-poll' },
2493
3585
  },
2494
3586
  required: ['action'],
2495
3587
  additionalProperties: false,
@@ -2498,6 +3590,8 @@ export function apply(ctx, rawConfig) {
2498
3590
  async execute(args) {
2499
3591
  if (args.action === 'start') {
2500
3592
  const base = String(process.env.DSH_WEB_URL || '').replace(/\/+$/, '')
3593
+ const state = gh.beginManifest()
3594
+ void state
2501
3595
  return {
2502
3596
  setupUrl: base ? `${base}${PREFIX}/setup` : `${PREFIX}/setup`,
2503
3597
  next: base
@@ -2507,10 +3601,72 @@ export function apply(ctx, rawConfig) {
2507
3601
  }
2508
3602
  if (args.action === 'installations') return { items: await gh.installations() }
2509
3603
  if (args.action === 'select') return gh.selectInstallation(args.installationId)
3604
+ if (args.action === 'use') {
3605
+ const auth = await gh.useConnection(args.mode)
3606
+ await appendAudit({ action: 'auth.use', account: auth.account || auth.fingerprint || '', detail: args.mode })
3607
+ return { active: auth.kind, capabilities: gh.capabilitiesOf(auth) }
3608
+ }
3609
+ if (args.action === 'pat-set') {
3610
+ if (!args.token) throw new Error('action=pat-set 需要 token')
3611
+ const result = await gh.setPat(args.token)
3612
+ await appendAudit({ action: 'auth.pat-set', account: result.login, detail: result.fingerprint })
3613
+ return { ...result, next: 'PAT 已保存并设为当前连接;不需要时用 action=pat-clear 删除' }
3614
+ }
3615
+ if (args.action === 'pat-clear') {
3616
+ await gh.clearPat()
3617
+ await appendAudit({ action: 'auth.pat-clear', account: '', detail: '' })
3618
+ return { ok: true }
3619
+ }
3620
+ if (args.action === 'oauth-start') {
3621
+ // Registers the App's OAuth callback, then returns the authorize URL.
3622
+ const origin = webOrigin()
3623
+ if (!origin) throw new Error('拿不到本机 web 地址:请在面板「状态 → 连接方式」里点授权')
3624
+ const result = await gh.beginOAuth(origin)
3625
+ return { ...result, next: '打开 url 授权;回调页会保存用户令牌,然后 action=use mode=oauth' }
3626
+ }
3627
+ if (args.action === 'oauth-clear') {
3628
+ await gh.clearOAuth()
3629
+ await appendAudit({ action: 'auth.oauth-clear', account: '', ok: true })
3630
+ return { ok: true }
3631
+ }
3632
+ if (args.action === 'device-start') {
3633
+ const result = await gh.deviceStart()
3634
+ return {
3635
+ ...result,
3636
+ next: `在浏览器打开 ${result.verificationUri},输入 ${result.userCode};然后反复调用 action=device-poll(同一个 deviceCode),直到 status=ok`,
3637
+ }
3638
+ }
3639
+ if (args.action === 'device-poll') {
3640
+ if (!args.deviceCode) throw new Error('action=device-poll 需要 deviceCode')
3641
+ const result = await gh.devicePoll(args.deviceCode)
3642
+ if (result.status === 'ok') {
3643
+ await appendAudit({ action: 'auth.device', account: '', ok: true })
3644
+ }
3645
+ return result
3646
+ }
3647
+ if (args.action === 'capabilities') {
3648
+ const state = await gh.status()
3649
+ return { auth: state.auth, connections: state.connections, authMode: state.authMode }
3650
+ }
2510
3651
  throw new Error(`未知 action:${args.action}`)
2511
3652
  },
2512
3653
  })
2513
3654
 
3655
+ register({
3656
+ name: 'gh_audit',
3657
+ description:
3658
+ 'Read the local audit trail of write actions this plugin performed: time, action, account, target and result. Newest last. Files stay on this machine.',
3659
+ parameters: {
3660
+ type: 'object',
3661
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many recent entries, default 50' } },
3662
+ additionalProperties: false,
3663
+ },
3664
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
3665
+ async execute(args) {
3666
+ return { path: auditPath(), items: await readAudit(args.limit || 50) }
3667
+ },
3668
+ })
3669
+
2514
3670
  register({
2515
3671
  name: 'gh_repos',
2516
3672
  description:
@@ -2970,6 +4126,240 @@ export function apply(ctx, rawConfig) {
2970
4126
  },
2971
4127
  })
2972
4128
 
4129
+ register({
4130
+ name: 'plugin_release_asset',
4131
+ description:
4132
+ 'Package the plugin directory into a .tgz and attach it to the GitHub Release for that version, so the plugin can be distributed without npm. Returns the download URL and the commit-pinned git install spec. Use this instead of npm when the user has no npm passkey or token.',
4133
+ parameters: {
4134
+ type: 'object',
4135
+ properties: {
4136
+ dir: { type: 'string', description: 'Local plugin directory' },
4137
+ owner: { type: 'string' },
4138
+ repo: { type: 'string' },
4139
+ version: { type: 'string', description: 'Release version to attach to; defaults to package.json version' },
4140
+ fileName: { type: 'string', description: 'Asset file name; defaults to <name>-<version>.tgz' },
4141
+ },
4142
+ required: ['dir', 'owner', 'repo'],
4143
+ additionalProperties: false,
4144
+ },
4145
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4146
+ async execute(args, exec) {
4147
+ const dir = resolveDir(args.dir, exec)
4148
+ const pkg = await readLocalPackage(dir)
4149
+ const collected = await collectFiles(dir, cfg.maxPushBytes)
4150
+ const version = args.version || pkg.version
4151
+ const fileName = args.fileName || `${pkg.name.replace(/^@[^/]+\//, '')}-${version}.tgz`
4152
+ const asset = await attachReleaseAsset(gh, args.owner, args.repo, version, fileName, buildTarball(collected.files))
4153
+ let commit = ''
4154
+ try {
4155
+ const ref = await gh.call(
4156
+ `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/git/ref/heads/${encodeURIComponent(cfg.publishBranch)}`,
4157
+ )
4158
+ commit = ref && ref.object ? ref.object.sha : ''
4159
+ } catch {
4160
+ commit = ''
4161
+ }
4162
+ return {
4163
+ package: `${pkg.name}@${version}`,
4164
+ files: collected.files.length,
4165
+ asset,
4166
+ gitInstall: commit ? `git+https://github.com/${args.owner}/${args.repo}.git#${commit}` : '',
4167
+ howToUse: [
4168
+ '下载 .tgz 解压后,用 Plugins → Add plugin 指向解压出来的目录;',
4169
+ '或直接把 gitInstall 那串交给 dsh plugin add;',
4170
+ '市场索引里已经用同一套 git 源,Discover 安装同样不需要 npm。',
4171
+ ],
4172
+ }
4173
+ },
4174
+ })
4175
+
4176
+ register({
4177
+ name: 'plugin_market_readiness',
4178
+ description:
4179
+ 'Check whether this plugin meets the awesome-dsh-plugin (dshmarket catalog) listing rules: repository older than one day, dsh.bundle declared, @deepseek-ai packages only in peerDependencies, a GitHub-hosted PNG icon, and a version-free .tgz on the latest release. Also returns a ready-to-paste entry (url/name/category/icon/tarball).',
4180
+ parameters: {
4181
+ type: 'object',
4182
+ properties: {
4183
+ dir: { type: 'string', description: 'Local plugin directory' },
4184
+ owner: { type: 'string' },
4185
+ repo: { type: 'string' },
4186
+ },
4187
+ required: ['dir', 'owner', 'repo'],
4188
+ additionalProperties: false,
4189
+ },
4190
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4191
+ async execute(args, exec) {
4192
+ return marketReadiness(gh, cfg, { owner: args.owner, repo: args.repo, dir: resolveDir(args.dir, exec) })
4193
+ },
4194
+ })
4195
+
4196
+ register({
4197
+ name: 'gh_pull_detail',
4198
+ description:
4199
+ 'Read one pull request with its per-file diff patches, review state and mergeability. Use it before reviewing or merging; the patches are plain unified diff text.',
4200
+ parameters: {
4201
+ type: 'object',
4202
+ properties: {
4203
+ owner: { type: 'string' },
4204
+ name: { type: 'string' },
4205
+ number: { type: 'integer', minimum: 1 },
4206
+ },
4207
+ required: ['owner', 'name', 'number'],
4208
+ additionalProperties: false,
4209
+ },
4210
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4211
+ async execute(args) {
4212
+ return gh.pullDetail(args.owner, args.name, args.number)
4213
+ },
4214
+ })
4215
+
4216
+ register({
4217
+ name: 'gh_pull_comment',
4218
+ description:
4219
+ 'Comment on a pull request. Pass path plus line for an inline review comment on the right side of the diff; omit them for a conversation comment.',
4220
+ parameters: {
4221
+ type: 'object',
4222
+ properties: {
4223
+ owner: { type: 'string' },
4224
+ name: { type: 'string' },
4225
+ number: { type: 'integer', minimum: 1 },
4226
+ body: { type: 'string' },
4227
+ path: { type: 'string', description: 'File path for an inline comment' },
4228
+ line: { type: 'integer', minimum: 1, description: 'Line number in the new file, for an inline comment' },
4229
+ },
4230
+ required: ['owner', 'name', 'number', 'body'],
4231
+ additionalProperties: false,
4232
+ },
4233
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4234
+ async execute(args) {
4235
+ await requireWrite('pullWrite')
4236
+ return audited('pull.comment', `${args.owner}/${args.name}#${args.number}`, () =>
4237
+ gh.addPullComment(args.owner, args.name, args.number, args.body, args.path ? { path: args.path, number: args.line } : null),
4238
+ )
4239
+ },
4240
+ })
4241
+
4242
+ register({
4243
+ name: 'gh_pull_review',
4244
+ description:
4245
+ 'Submit a pull request review: APPROVE, REQUEST_CHANGES (needs a reason) or COMMENT. Confirm with the user before approving or requesting changes when it is not their own request.',
4246
+ parameters: {
4247
+ type: 'object',
4248
+ properties: {
4249
+ owner: { type: 'string' },
4250
+ name: { type: 'string' },
4251
+ number: { type: 'integer', minimum: 1 },
4252
+ event: { type: 'string', enum: ['APPROVE', 'REQUEST_CHANGES', 'COMMENT'] },
4253
+ body: { type: 'string' },
4254
+ },
4255
+ required: ['owner', 'name', 'number', 'event'],
4256
+ additionalProperties: false,
4257
+ },
4258
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4259
+ async execute(args) {
4260
+ await requireWrite('pullWrite')
4261
+ return audited('pull.review', `${args.owner}/${args.name}#${args.number} ${args.event}`, () =>
4262
+ gh.submitReview(args.owner, args.name, args.number, args.event, args.body),
4263
+ )
4264
+ },
4265
+ })
4266
+
4267
+ register({
4268
+ name: 'gh_issue_update',
4269
+ description:
4270
+ 'Update an issue or pull request: title, body, state (open/closed), labels, assignees, milestone. Only the fields you pass are changed.',
4271
+ parameters: {
4272
+ type: 'object',
4273
+ properties: {
4274
+ owner: { type: 'string' },
4275
+ name: { type: 'string' },
4276
+ number: { type: 'integer', minimum: 1 },
4277
+ title: { type: 'string' },
4278
+ body: { type: 'string' },
4279
+ state: { type: 'string', enum: ['open', 'closed'] },
4280
+ labels: { type: 'array', items: { type: 'string' } },
4281
+ assignees: { type: 'array', items: { type: 'string' } },
4282
+ milestone: { type: 'integer', description: 'Milestone number, or null to clear' },
4283
+ },
4284
+ required: ['owner', 'name', 'number'],
4285
+ additionalProperties: false,
4286
+ },
4287
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4288
+ async execute(args) {
4289
+ await requireWrite('issueWrite')
4290
+ const patch = { ...args }
4291
+ delete patch.owner
4292
+ delete patch.name
4293
+ delete patch.number
4294
+ return audited('issue.update', `${args.owner}/${args.name}#${args.number}`, () =>
4295
+ gh.updateIssue(args.owner, args.name, args.number, patch),
4296
+ )
4297
+ },
4298
+ })
4299
+
4300
+ register({
4301
+ name: 'gh_workflows',
4302
+ description: 'List the repository workflows and their state, so a workflow can be dispatched by file name.',
4303
+ parameters: {
4304
+ type: 'object',
4305
+ properties: { owner: { type: 'string' }, name: { type: 'string' } },
4306
+ required: ['owner', 'name'],
4307
+ additionalProperties: false,
4308
+ },
4309
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4310
+ async execute(args) {
4311
+ return gh.listWorkflows(args.owner, args.name)
4312
+ },
4313
+ })
4314
+
4315
+ register({
4316
+ name: 'gh_workflow_dispatch',
4317
+ description:
4318
+ 'Manually trigger a workflow (workflow_dispatch) with optional inputs. Needs workflows: write and the workflow must declare workflow_dispatch. Confirm with the user first.',
4319
+ parameters: {
4320
+ type: 'object',
4321
+ properties: {
4322
+ owner: { type: 'string' },
4323
+ name: { type: 'string' },
4324
+ workflow: { type: 'string', description: 'Workflow file name (publish.yml) or id' },
4325
+ ref: { type: 'string', description: 'Branch or tag, default main' },
4326
+ inputs: { type: 'object', description: 'Inputs the workflow declares' },
4327
+ confirm: { type: 'boolean', description: 'Must be true' },
4328
+ },
4329
+ required: ['owner', 'name', 'workflow', 'confirm'],
4330
+ additionalProperties: false,
4331
+ },
4332
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4333
+ async execute(args) {
4334
+ if (args.confirm !== true) throw new Error('触发 workflow 需要确认:传 confirm: true')
4335
+ await requireWrite('workflowsWrite')
4336
+ return audited('workflow.dispatch', `${args.owner}/${args.name}:${args.workflow}`, () =>
4337
+ gh.dispatchNamedWorkflow(args.owner, args.name, args.workflow, args.ref, args.inputs),
4338
+ )
4339
+ },
4340
+ })
4341
+
4342
+ register({
4343
+ name: 'gh_actions_log',
4344
+ description:
4345
+ 'Read the end of a workflow run log (the archive is unzipped and the step log tail is returned). Useful to explain why a run failed.',
4346
+ parameters: {
4347
+ type: 'object',
4348
+ properties: {
4349
+ owner: { type: 'string' },
4350
+ name: { type: 'string' },
4351
+ runId: { type: 'integer', minimum: 1 },
4352
+ tailLines: { type: 'integer', minimum: 10, maximum: 2000, description: 'How many trailing lines, default 120' },
4353
+ },
4354
+ required: ['owner', 'name', 'runId'],
4355
+ additionalProperties: false,
4356
+ },
4357
+ output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: String(value.tail || value.name || '') }] },
4358
+ async execute(args) {
4359
+ return gh.runLog(args.owner, args.name, args.runId, args.tailLines || 120)
4360
+ },
4361
+ })
4362
+
2973
4363
  register({
2974
4364
  name: 'plugin_publish_status',
2975
4365
  description: 'Read a publish job by id, including each step state and detail.',