dsh-github-console 0.2.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.5.0'
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
 
@@ -234,37 +279,51 @@ function readUntil(socket, separator, timeoutMs) {
234
279
  * system hosts file. GitHub accelerators rewrite hosts to 127.0.0.1 and answer
235
280
  * with their own CA, which Node does not trust; skipping hosts sidesteps both.
236
281
  */
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.
282
+ function makeBypassLookup(servers, goodIps) {
283
+ // Answers differ per public resolver (one may hand back an unroutable IP), so
284
+ // merge them all and prefer whatever address actually worked last.
246
285
  const cache = new Map()
247
286
  const ttlMs = 5 * 60 * 1000
287
+
288
+ const resolveAll = (hostname) =>
289
+ Promise.all(
290
+ servers.map(
291
+ (server) =>
292
+ new Promise((resolve) => {
293
+ const resolver = new Resolver({ timeout: 2500, tries: 1 })
294
+ try {
295
+ resolver.setServers([server])
296
+ } catch {
297
+ resolve([])
298
+ return
299
+ }
300
+ resolver.resolve4(hostname, (error, list) => resolve(error || !list ? [] : list))
301
+ }),
302
+ ),
303
+ ).then((lists) => {
304
+ const preferred = goodIps ? goodIps.get(hostname) : ''
305
+ const merged = [...new Set(lists.flat())]
306
+ if (preferred && merged.includes(preferred)) {
307
+ return [preferred, ...merged.filter((ip) => ip !== preferred)]
308
+ }
309
+ return merged
310
+ })
311
+
248
312
  return (hostname, options, callback) => {
249
313
  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]))
314
+ const settle = (ips) => {
315
+ cache.set(hostname, { ips, at: Date.now() })
316
+ if (wantAll) callback(null, ips.map((address) => ({ address, family: net.isIP(address) })))
317
+ else callback(null, ips[0], net.isIP(ips[0]))
254
318
  }
255
319
  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]))
320
+ if (cached && cached.ips.length && Date.now() - cached.at < ttlMs) {
321
+ settle(cached.ips)
259
322
  return
260
323
  }
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
- })
324
+ resolveAll(hostname)
325
+ .then((ips) => (ips.length ? settle(ips) : callback(new Error('DNS_LOOKUP_FAILED'))))
326
+ .catch((error) => callback(error))
268
327
  }
269
328
  }
270
329
 
@@ -279,7 +338,10 @@ function createTransport(cfg) {
279
338
  }
280
339
  let caPem
281
340
  let caLoaded = false
282
- const bypassLookup = makeBypassLookup(cfg.dnsServers)
341
+ // Remember which resolved address actually answered, so later requests to that
342
+ // host go straight to a working IP even when one resolver answers badly.
343
+ const goodIps = new Map()
344
+ const bypassLookup = makeBypassLookup(cfg.dnsServers, goodIps)
283
345
 
284
346
  async function loadCa() {
285
347
  if (caLoaded) return caPem
@@ -338,18 +400,28 @@ function createTransport(cfg) {
338
400
  return routes
339
401
  }
340
402
 
341
- function rawRequest(options, body, timeoutMs) {
403
+ function rawRequest(options, body, timeoutMs, binary = false, onAddress) {
342
404
  return new Promise((resolve, reject) => {
343
405
  const request = https.request(options, (response) => {
344
406
  const chunks = []
345
407
  response.on('data', (chunk) => chunks.push(chunk))
346
- response.on('end', () =>
408
+ response.on('end', () => {
409
+ const joined = Buffer.concat(chunks)
410
+ if (onAddress) {
411
+ try {
412
+ const address = response.socket ? response.socket.remoteAddress : ''
413
+ if (address) onAddress(String(address).replace(/^::ffff:/, ''))
414
+ } catch {
415
+ /* best effort */
416
+ }
417
+ }
347
418
  resolve({
348
419
  status: response.statusCode || 0,
349
420
  headers: response.headers,
350
- text: Buffer.concat(chunks).toString('utf8'),
351
- }),
352
- )
421
+ text: binary ? '' : joined.toString('utf8'),
422
+ buffer: binary ? joined : null,
423
+ })
424
+ })
353
425
  response.on('error', reject)
354
426
  })
355
427
  request.setTimeout(timeoutMs, () => request.destroy(new Error('ETIMEDOUT')))
@@ -415,6 +487,7 @@ function createTransport(cfg) {
415
487
  { method: options.method, host, port, path, headers, agent, servername: host },
416
488
  options.body,
417
489
  cfg.requestTimeoutMs,
490
+ options.binary === true,
418
491
  )
419
492
  } finally {
420
493
  tunnel.destroy()
@@ -436,6 +509,8 @@ function createTransport(cfg) {
436
509
  },
437
510
  options.body,
438
511
  cfg.requestTimeoutMs,
512
+ options.binary === true,
513
+ (address) => goodIps.set(host, address),
439
514
  )
440
515
  }
441
516
 
@@ -723,7 +798,7 @@ function createGithub(ctx, cfg, transport) {
723
798
  }
724
799
 
725
800
  async function call(pathname, options = {}) {
726
- const { method = 'GET', body, auth = 'installation', headers = {} } = options
801
+ const { method = 'GET', body, auth = 'auto', headers = {}, rawBody = false } = options
727
802
  const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
728
803
  if (auth === 'app') {
729
804
  const app = await readApp()
@@ -731,16 +806,36 @@ function createGithub(ctx, cfg, transport) {
731
806
  init.headers.Authorization = `Bearer ${appJwt(app)}`
732
807
  } else if (auth === 'installation') {
733
808
  init.headers.Authorization = `Bearer ${await installationToken()}`
734
- } else {
809
+ } else if (auth !== 'auto') {
735
810
  init.headers.Authorization = `Bearer ${auth}`
811
+ } else {
812
+ const current = await resolveAuth()
813
+ if (current.kind === 'app') {
814
+ init.headers.Authorization = `Bearer ${await installationToken()}`
815
+ } else if (current.kind === 'pat' || current.kind === 'env' || current.kind === 'oauth') {
816
+ init.headers.Authorization = `Bearer ${current.token}`
817
+ } else {
818
+ throw new GhError(
819
+ 401,
820
+ 'AUTH_MISSING',
821
+ '还没有可用的 GitHub 连接:在面板「状态」里选一种(GitHub App / 个人访问令牌 / 环境变量)',
822
+ )
823
+ }
736
824
  }
737
825
  if (body !== undefined) {
738
- init.headers['Content-Type'] = 'application/json'
739
- init.body = JSON.stringify(body)
826
+ if (rawBody) {
827
+ // Binary uploads (release assets) pass the bytes through unchanged.
828
+ init.body = body
829
+ } else {
830
+ init.headers['Content-Type'] = 'application/json'
831
+ init.body = JSON.stringify(body)
832
+ }
740
833
  }
834
+ // Absolute URLs reach another host (uploads.github.com for release assets).
835
+ const target = /^https?:\/\//i.test(pathname) ? pathname : `${cfg.baseUrl}${pathname}`
741
836
  let response
742
837
  try {
743
- response = await transport.request(`${cfg.baseUrl}${pathname}`, { method, headers: init.headers, body: init.body })
838
+ response = await transport.request(target, { method, headers: init.headers, body: init.body })
744
839
  } catch (failure) {
745
840
  if (failure instanceof GhError) throw failure
746
841
  const described = describeFetchFailure(failure)
@@ -908,6 +1003,385 @@ function createGithub(ctx, cfg, transport) {
908
1003
  return { ok: true }
909
1004
  }
910
1005
 
1006
+ async function readPat() {
1007
+ const record = await readRecord(PAT_CRED)
1008
+ return record && typeof record.token === 'string' ? record.token : ''
1009
+ }
1010
+
1011
+ function fingerprint(token) {
1012
+ const text = String(token || '')
1013
+ return text.length <= 4 ? '****' : `****${text.slice(-4)}`
1014
+ }
1015
+
1016
+ /** Ask GitHub who a token belongs to; used before storing a PAT. */
1017
+ async function whoAmI(token) {
1018
+ const response = await transport.request(`${cfg.baseUrl}/user`, {
1019
+ headers: {
1020
+ Accept: 'application/vnd.github+json',
1021
+ 'X-GitHub-Api-Version': '2022-11-28',
1022
+ Authorization: `Bearer ${token}`,
1023
+ },
1024
+ })
1025
+ if (response.status !== 200) {
1026
+ throw new GhError(response.status, response.status === 401 ? 'AUTH_EXPIRED' : 'HTTP_' + response.status, `令牌无效(HTTP ${response.status})`)
1027
+ }
1028
+ const data = JSON.parse(response.text || '{}')
1029
+ const scopes = String(response.headers['x-oauth-scopes'] || '')
1030
+ return { login: data.login || '', id: data.id, name: data.name || '', scopes: scopes ? scopes.split(',').map((item) => item.trim()) : [] }
1031
+ }
1032
+
1033
+ let authCache = null
1034
+
1035
+ /** The App's own OAuth callback must be registered before the authorize step. */
1036
+ async function ensureOAuthCallback(origin) {
1037
+ const app = await readApp()
1038
+ if (!app) throw new Error('还没有注册 GitHub App')
1039
+ if (!app.clientId) throw new Error('这个 App 没有 client_id:请重新注册一次 GitHub App')
1040
+ const callbackUrl = `${origin}${PREFIX}/oauth/callback`
1041
+ let current = null
1042
+ try {
1043
+ current = await call('/app', { auth: 'app' })
1044
+ } catch {
1045
+ current = null
1046
+ }
1047
+ const existing = current && Array.isArray(current.callback_urls) ? current.callback_urls : []
1048
+ let registered = existing.includes(callbackUrl)
1049
+ if (!registered) {
1050
+ // `PATCH /app` is not available for every app type; when it fails the user
1051
+ // registers the callback once in the App settings instead.
1052
+ try {
1053
+ await call('/app', { method: 'PATCH', auth: 'app', body: { callback_urls: [...existing, callbackUrl] } })
1054
+ registered = true
1055
+ } catch {
1056
+ registered = false
1057
+ }
1058
+ }
1059
+ return { callbackUrl, clientId: app.clientId, clientSecret: app.clientSecret, registered }
1060
+ }
1061
+
1062
+ function beginOAuth(origin) {
1063
+ return ensureOAuthCallback(origin).then(({ callbackUrl, clientId, registered }) => {
1064
+ const state = crypto.randomBytes(16).toString('hex')
1065
+ pendingManifests.set(`oauth:${state}`, Date.now())
1066
+ const url = new URL('https://github.com/login/oauth/authorize')
1067
+ url.searchParams.set('client_id', clientId)
1068
+ url.searchParams.set('redirect_uri', callbackUrl)
1069
+ url.searchParams.set('state', state)
1070
+ return {
1071
+ url: url.toString(),
1072
+ state,
1073
+ callbackUrl,
1074
+ callbackRegistered: registered,
1075
+ note: registered
1076
+ ? '打开 url 授权即可'
1077
+ : `先把 ${callbackUrl} 加到 App 设置页(User authorization callback URL)再打开 url,否则 GitHub 会报 redirect_uri 不匹配`,
1078
+ }
1079
+ })
1080
+ }
1081
+
1082
+ async function completeOAuth(code, state, origin) {
1083
+ const key = `oauth:${state}`
1084
+ const startedAt = pendingManifests.get(key)
1085
+ if (!startedAt) throw new Error('OAuth state 不匹配或已过期,请重新发起授权')
1086
+ if (Date.now() - startedAt > 30 * 60 * 1000) {
1087
+ pendingManifests.delete(key)
1088
+ throw new Error('OAuth 授权超时(30 分钟),请重新发起')
1089
+ }
1090
+ const app = await readApp()
1091
+ if (!app || !app.clientId || !app.clientSecret) throw new Error('缺少 App 的 client_id / client_secret')
1092
+ const callbackUrl = `${origin}${PREFIX}/oauth/callback`
1093
+ const response = await transport.request('https://github.com/login/oauth/access_token', {
1094
+ method: 'POST',
1095
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1096
+ body: JSON.stringify({
1097
+ client_id: app.clientId,
1098
+ client_secret: app.clientSecret,
1099
+ code,
1100
+ redirect_uri: callbackUrl,
1101
+ }),
1102
+ })
1103
+ const data = (() => {
1104
+ try {
1105
+ return JSON.parse(response.text || '{}')
1106
+ } catch {
1107
+ return {}
1108
+ }
1109
+ })()
1110
+ if (!data.access_token) {
1111
+ throw new Error(`换取用户令牌失败:${data.error_description || data.error || `HTTP ${response.status}`}`)
1112
+ }
1113
+ pendingManifests.delete(key)
1114
+ const now = Date.now()
1115
+ await writeRecord(OAUTH_CRED, {
1116
+ accessToken: data.access_token,
1117
+ refreshToken: data.refresh_token || '',
1118
+ expiresAt: now + Number(data.expires_in || 28800) * 1000,
1119
+ refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : null,
1120
+ scope: data.scope || '',
1121
+ addedAt: new Date().toISOString(),
1122
+ })
1123
+ authCache = null
1124
+ return { ok: true }
1125
+ }
1126
+
1127
+ async function refreshOAuth() {
1128
+ const record = await readRecord(OAUTH_CRED)
1129
+ if (!record || !record.refreshToken) throw new Error('用户授权已失效且没有 refresh token,请重新授权')
1130
+ const app = await readApp()
1131
+ const response = await transport.request('https://github.com/login/oauth/access_token', {
1132
+ method: 'POST',
1133
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1134
+ body: JSON.stringify({
1135
+ client_id: app.clientId,
1136
+ client_secret: app.clientSecret,
1137
+ grant_type: 'refresh_token',
1138
+ refresh_token: record.refreshToken,
1139
+ }),
1140
+ })
1141
+ const data = (() => {
1142
+ try {
1143
+ return JSON.parse(response.text || '{}')
1144
+ } catch {
1145
+ return {}
1146
+ }
1147
+ })()
1148
+ if (!data.access_token) throw new Error(`刷新用户令牌失败:${data.error_description || data.error || response.status}`)
1149
+ const now = Date.now()
1150
+ await writeRecord(OAUTH_CRED, {
1151
+ ...record,
1152
+ accessToken: data.access_token,
1153
+ refreshToken: data.refresh_token || record.refreshToken,
1154
+ expiresAt: now + Number(data.expires_in || 28800) * 1000,
1155
+ refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : record.refreshExpiresAt,
1156
+ })
1157
+ return readRecord(OAUTH_CRED)
1158
+ }
1159
+
1160
+ async function oauthToken() {
1161
+ const record = await readRecord(OAUTH_CRED)
1162
+ if (!record || !record.accessToken) return ''
1163
+ if (record.expiresAt && Date.now() > record.expiresAt - 120000) {
1164
+ const fresh = await refreshOAuth().catch(() => null)
1165
+ if (fresh && fresh.accessToken) return fresh.accessToken
1166
+ }
1167
+ return record.accessToken
1168
+ }
1169
+
1170
+ const pendingDevices = new Map()
1171
+
1172
+ /**
1173
+ * Device flow: no redirect URI, so no port to pin and nothing to register in
1174
+ * the App settings beyond enabling "Device Flow" once.
1175
+ */
1176
+ async function deviceStart() {
1177
+ const app = await readApp()
1178
+ if (!app || !app.clientId) throw new Error('需要先注册 GitHub App(缺少 client_id)')
1179
+ const response = await transport.request('https://github.com/login/device/code', {
1180
+ method: 'POST',
1181
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1182
+ body: JSON.stringify({ client_id: app.clientId }),
1183
+ })
1184
+ const data = (() => {
1185
+ try {
1186
+ return JSON.parse(response.text || '{}')
1187
+ } catch {
1188
+ return {}
1189
+ }
1190
+ })()
1191
+ if (!data.device_code) {
1192
+ const reason = /device flow/i.test(`${data.error || ''} ${data.error_description || ''}`)
1193
+ ? 'App 没有启用 Device Flow:到 App 设置页勾选「Enable Device Flow」保存后再试'
1194
+ : `申请设备码失败:${data.error_description || data.error || `HTTP ${response.status}`}`
1195
+ throw new Error(reason)
1196
+ }
1197
+ pendingDevices.set(data.device_code, {
1198
+ interval: Number(data.interval) || 5,
1199
+ startedAt: Date.now(),
1200
+ expiresIn: Number(data.expires_in) || 900,
1201
+ })
1202
+ return {
1203
+ deviceCode: data.device_code,
1204
+ userCode: data.user_code,
1205
+ verificationUri: data.verification_uri,
1206
+ expiresIn: Number(data.expires_in) || 900,
1207
+ interval: Number(data.interval) || 5,
1208
+ }
1209
+ }
1210
+
1211
+ async function devicePoll(deviceCode) {
1212
+ const app = await readApp()
1213
+ const entry = pendingDevices.get(deviceCode)
1214
+ if (!entry) throw new Error('这个设备码不在本进程里(插件可能重载过),请重新发起设备码授权')
1215
+ const response = await transport.request('https://github.com/login/oauth/access_token', {
1216
+ method: 'POST',
1217
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
1218
+ body: JSON.stringify({
1219
+ client_id: app.clientId,
1220
+ device_code: deviceCode,
1221
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
1222
+ }),
1223
+ })
1224
+ const data = (() => {
1225
+ try {
1226
+ return JSON.parse(response.text || '{}')
1227
+ } catch {
1228
+ return {}
1229
+ }
1230
+ })()
1231
+ if (data.access_token) {
1232
+ const now = Date.now()
1233
+ await writeRecord(OAUTH_CRED, {
1234
+ accessToken: data.access_token,
1235
+ refreshToken: data.refresh_token || '',
1236
+ expiresAt: now + Number(data.expires_in || 28800) * 1000,
1237
+ refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : null,
1238
+ scope: data.scope || '',
1239
+ via: 'device',
1240
+ addedAt: new Date().toISOString(),
1241
+ })
1242
+ pendingDevices.delete(deviceCode)
1243
+ await writeRecord(AUTH_CRED, { kind: 'oauth' })
1244
+ authCache = null
1245
+ return { status: 'ok' }
1246
+ }
1247
+ const state = data.error || 'unknown'
1248
+ if (state === 'authorization_pending') return { status: 'pending' }
1249
+ if (state === 'slow_down') {
1250
+ pendingDevices.set(deviceCode, { ...entry, interval: entry.interval + 2 })
1251
+ return { status: 'pending', slowDown: true }
1252
+ }
1253
+ if (state === 'expired_token') {
1254
+ pendingDevices.delete(deviceCode)
1255
+ return { status: 'expired' }
1256
+ }
1257
+ if (state === 'access_denied') {
1258
+ pendingDevices.delete(deviceCode)
1259
+ return { status: 'denied' }
1260
+ }
1261
+ throw new Error(`设备码轮询失败:${data.error_description || state}`)
1262
+ }
1263
+
1264
+ /**
1265
+ * Pick the connection to use. Order is App → PAT → environment unless the
1266
+ * profile pins one; the active choice is remembered in credentials.
1267
+ */
1268
+ async function resolveAuth() {
1269
+ if (authCache && Date.now() - authCache.at < 30000) return authCache.value
1270
+ const stored = await readRecord(AUTH_CRED).catch(() => undefined)
1271
+ const storedKind = stored && typeof stored.kind === 'string' ? stored.kind : ''
1272
+ const preferred = cfg.authMode !== 'auto' ? cfg.authMode : storedKind || 'auto'
1273
+ const order =
1274
+ preferred === 'app'
1275
+ ? ['app']
1276
+ : preferred === 'oauth'
1277
+ ? ['oauth']
1278
+ : preferred === 'pat'
1279
+ ? ['pat']
1280
+ : preferred === 'env'
1281
+ ? ['env']
1282
+ : ['app', 'oauth', 'pat', 'env']
1283
+ let value = { kind: 'none' }
1284
+ for (const kind of order) {
1285
+ if (kind === 'app') {
1286
+ const app = await readApp()
1287
+ if (!app) continue
1288
+ const installation = await selectedInstallation().catch(() => undefined)
1289
+ if (!installation) continue
1290
+ value = {
1291
+ kind: 'app',
1292
+ account: installation.account,
1293
+ installationId: installation.id,
1294
+ permissions: installation.permissions || {},
1295
+ }
1296
+ break
1297
+ }
1298
+ if (kind === 'oauth') {
1299
+ const token = await oauthToken().catch(() => '')
1300
+ if (!token) continue
1301
+ value = { kind: 'oauth', token, fingerprint: fingerprint(token) }
1302
+ break
1303
+ }
1304
+ if (kind === 'pat') {
1305
+ const token = await readPat()
1306
+ if (!token) continue
1307
+ value = { kind: 'pat', token, fingerprint: fingerprint(token) }
1308
+ break
1309
+ }
1310
+ if (kind === 'env') {
1311
+ const token = process.env[cfg.patEnvName] || ''
1312
+ if (!token) continue
1313
+ value = { kind: 'env', token, fingerprint: fingerprint(token), envName: cfg.patEnvName }
1314
+ break
1315
+ }
1316
+ }
1317
+ authCache = { at: Date.now(), value }
1318
+ return value
1319
+ }
1320
+
1321
+ /**
1322
+ * What the active connection can do. An installation token is scoped by the
1323
+ * App's permissions and cannot read notifications or search code; a user token
1324
+ * can do both.
1325
+ */
1326
+ function capabilitiesOf(auth) {
1327
+ const none = {
1328
+ repoRead: false,
1329
+ repoWrite: false,
1330
+ pullWrite: false,
1331
+ issueWrite: false,
1332
+ actionsWrite: false,
1333
+ workflowsWrite: false,
1334
+ adminWrite: false,
1335
+ notifications: false,
1336
+ codeSearch: false,
1337
+ userLevel: false,
1338
+ }
1339
+ if (auth.kind === 'app') {
1340
+ const p = auth.permissions || {}
1341
+ return {
1342
+ ...none,
1343
+ repoRead: true,
1344
+ repoWrite: p.contents === 'write',
1345
+ pullWrite: p.pull_requests === 'write',
1346
+ issueWrite: p.issues === 'write',
1347
+ actionsWrite: p.actions === 'write',
1348
+ workflowsWrite: p.workflows === 'write',
1349
+ adminWrite: p.administration === 'write',
1350
+ }
1351
+ }
1352
+ if (auth.kind === 'oauth') {
1353
+ // A GitHub App user token is still an App token: it can search code, but
1354
+ // GitHub exposes notifications only to OAuth-app/PAT tokens.
1355
+ return {
1356
+ repoRead: true,
1357
+ repoWrite: true,
1358
+ pullWrite: true,
1359
+ issueWrite: true,
1360
+ actionsWrite: true,
1361
+ workflowsWrite: true,
1362
+ adminWrite: true,
1363
+ notifications: false,
1364
+ codeSearch: true,
1365
+ userLevel: true,
1366
+ }
1367
+ }
1368
+ if (auth.kind === 'pat' || auth.kind === 'env') {
1369
+ return {
1370
+ repoRead: true,
1371
+ repoWrite: true,
1372
+ pullWrite: true,
1373
+ issueWrite: true,
1374
+ actionsWrite: true,
1375
+ workflowsWrite: true,
1376
+ adminWrite: true,
1377
+ notifications: true,
1378
+ codeSearch: true,
1379
+ userLevel: true,
1380
+ }
1381
+ }
1382
+ return none
1383
+ }
1384
+
911
1385
  async function status() {
912
1386
  const app = await readApp()
913
1387
  const installError = []
@@ -951,6 +1425,23 @@ function createGithub(ctx, cfg, transport) {
951
1425
  network.hint = ''
952
1426
  }
953
1427
  const tokenReady = Boolean(installationTokenCache)
1428
+ // The active connection decides which capabilities the UI may offer.
1429
+ const authState = await resolveAuth().catch(() => ({ kind: 'none' }))
1430
+ const capabilities = capabilitiesOf(authState)
1431
+ let login = authState.account || ''
1432
+ let tokenScopes = []
1433
+ if ((authState.kind === 'pat' || authState.kind === 'env') && authState.token) {
1434
+ try {
1435
+ const me = await whoAmI(authState.token)
1436
+ login = me.login
1437
+ tokenScopes = me.scopes || []
1438
+ } catch (error) {
1439
+ installError.push(`当前令牌无效:${errorMessage(error)}`)
1440
+ }
1441
+ }
1442
+ const patToken = await readPat().catch(() => '')
1443
+ const oauthState = await readRecord(OAUTH_CRED).catch(() => undefined)
1444
+ const envToken = process.env[cfg.patEnvName] || ''
954
1445
  const base = {
955
1446
  version: PLUGIN_VERSION,
956
1447
  apiBase: cfg.baseUrl,
@@ -980,9 +1471,32 @@ function createGithub(ctx, cfg, transport) {
980
1471
  ? { expiresAt: new Date(installationTokenCache.expiresAt).toISOString() }
981
1472
  : null,
982
1473
  publish: { branch: cfg.publishBranch, topic: cfg.topic, marketIndexUrls: cfg.marketIndexUrls },
1474
+ authMode: cfg.authMode,
1475
+ auth: {
1476
+ kind: authState.kind,
1477
+ account: login,
1478
+ scopes: tokenScopes,
1479
+ capabilities,
1480
+ readOnly: cfg.readOnly || !capabilities.repoWrite,
1481
+ readOnlyReason: cfg.readOnly
1482
+ ? '配置里把 readOnly 设成了 true'
1483
+ : !capabilities.repoWrite
1484
+ ? '当前连接没有写权限(App 只读安装,或令牌是只读的)'
1485
+ : '',
1486
+ },
1487
+ connections: {
1488
+ app: Boolean(app),
1489
+ oauth: {
1490
+ configured: Boolean(oauthState && oauthState.accessToken),
1491
+ expiresAt: oauthState && oauthState.expiresAt ? new Date(oauthState.expiresAt).toISOString() : null,
1492
+ },
1493
+ pat: { configured: Boolean(patToken), fingerprint: patToken ? fingerprint(patToken) : '' },
1494
+ env: { name: cfg.patEnvName, present: Boolean(envToken), fingerprint: envToken ? fingerprint(envToken) : '' },
1495
+ },
983
1496
  errors,
984
1497
  network,
985
1498
  }
1499
+ if (authState.kind !== 'app') return base
986
1500
  if (!app || !installation) return base
987
1501
  try {
988
1502
  const viewer = await call('/installation/repositories?per_page=1')
@@ -1150,12 +1664,284 @@ function createGithub(ctx, cfg, transport) {
1150
1664
  return { ok: true, runId }
1151
1665
  }
1152
1666
 
1667
+ async function listNotifications(options = {}) {
1668
+ const query = new URLSearchParams({ per_page: String(Math.min(100, options.limit || 30)) })
1669
+ if (options.all) query.set('all', 'true')
1670
+ if (options.participating) query.set('participating', 'true')
1671
+ const json = await call(`/notifications?${query.toString()}`)
1672
+ const items = (Array.isArray(json) ? json : []).map((item) => ({
1673
+ id: item.id,
1674
+ reason: item.reason,
1675
+ unread: item.unread,
1676
+ title: item.subject ? item.subject.title : '',
1677
+ type: item.subject ? item.subject.type : '',
1678
+ apiUrl: item.subject ? item.subject.url : '',
1679
+ htmlUrl: item.subject && item.subject.latest_comment_url ? item.subject.latest_comment_url.replace('/pulls/', '/pull/').replace(/\/comments\/.*$/, '') : '',
1680
+ repo: item.repository ? item.repository.full_name : '',
1681
+ updatedAt: item.updated_at,
1682
+ }))
1683
+ return { count: items.length, unread: items.filter((item) => item.unread).length, items }
1684
+ }
1685
+
1686
+ async function markNotificationsRead(options = {}) {
1687
+ if (options.all) {
1688
+ await call('/notifications', { method: 'PUT', body: { last_read_at: new Date().toISOString(), read: true } })
1689
+ return { ok: true, scope: 'all' }
1690
+ }
1691
+ const ids = Array.isArray(options.ids) ? options.ids : []
1692
+ if (!ids.length) throw new Error('需要 ids 或 all: true')
1693
+ for (const id of ids) {
1694
+ await call(`/notifications/threads/${encodeURIComponent(id)}`, { method: 'PATCH' })
1695
+ }
1696
+ return { ok: true, scope: 'ids', count: ids.length }
1697
+ }
1698
+
1699
+ async function searchCode(query, options = {}) {
1700
+ const text = String(query || '').trim()
1701
+ if (!text) throw new Error('搜索词不能为空')
1702
+ const scope = options.owner && options.name ? ` repo:${options.owner}/${options.name}` : ''
1703
+ const response = await call(`/search/code?q=${encodeURIComponent(text + scope)}&per_page=${Math.min(50, options.limit || 20)}`)
1704
+ const items = (response.items || []).map((item) => ({
1705
+ path: item.path,
1706
+ repo: item.repository ? item.repository.full_name : '',
1707
+ htmlUrl: item.html_url,
1708
+ sha: item.sha,
1709
+ }))
1710
+ return { total: response.total_count || items.length, returned: items.length, items }
1711
+ }
1712
+
1713
+ async function listReleases(owner, name) {
1714
+ const repo = repoPath(owner, name)
1715
+ const json = await call(`${repo}/releases?per_page=30`)
1716
+ return {
1717
+ items: (Array.isArray(json) ? json : []).map((item) => ({
1718
+ id: item.id,
1719
+ tag: item.tag_name,
1720
+ name: item.name || item.tag_name,
1721
+ draft: Boolean(item.draft),
1722
+ prerelease: Boolean(item.prerelease),
1723
+ publishedAt: item.published_at,
1724
+ htmlUrl: item.html_url,
1725
+ assets: (item.assets || []).map((asset) => ({ name: asset.name, size: asset.size, url: asset.browser_download_url })),
1726
+ })),
1727
+ }
1728
+ }
1729
+
1730
+ async function listCommits(owner, name, options = {}) {
1731
+ const repo = repoPath(owner, name)
1732
+ const query = new URLSearchParams({ per_page: String(Math.min(100, options.limit || 20)) })
1733
+ if (options.ref) query.set('sha', options.ref)
1734
+ const json = await call(`${repo}/commits?${query.toString()}`)
1735
+ return {
1736
+ items: (Array.isArray(json) ? json : []).map((item) => ({
1737
+ sha: item.sha,
1738
+ short: String(item.sha || '').slice(0, 7),
1739
+ message: item.commit ? String(item.commit.message || '').split('\n')[0] : '',
1740
+ author: item.commit && item.commit.author ? item.commit.author.name : '',
1741
+ date: item.commit && item.commit.author ? item.commit.author.date : '',
1742
+ htmlUrl: item.html_url,
1743
+ })),
1744
+ }
1745
+ }
1746
+
1747
+ async function compareRefs(owner, name, base, head) {
1748
+ const repo = repoPath(owner, name)
1749
+ if (!base || !head) throw new Error('需要 base 与 head')
1750
+ const json = await call(`${repo}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`)
1751
+ return {
1752
+ status: json.status,
1753
+ aheadBy: json.ahead_by,
1754
+ behindBy: json.behind_by,
1755
+ totalCommits: json.total_commits,
1756
+ commits: (json.commits || []).map((item) => ({
1757
+ short: String(item.sha || '').slice(0, 7),
1758
+ message: item.commit ? String(item.commit.message || '').split('\n')[0] : '',
1759
+ })),
1760
+ files: (json.files || []).map((file) => ({ path: file.filename, additions: file.additions, deletions: file.deletions })),
1761
+ }
1762
+ }
1763
+
1764
+ async function pullDetail(owner, name, number) {
1765
+ const repo = repoPath(owner, name)
1766
+ const [pull, files] = await Promise.all([
1767
+ call(`${repo}/pulls/${number}`),
1768
+ call(`${repo}/pulls/${number}/files?per_page=100`),
1769
+ ])
1770
+ return {
1771
+ number: pull.number,
1772
+ title: pull.title,
1773
+ state: pull.state,
1774
+ draft: Boolean(pull.draft),
1775
+ user: pull.user ? pull.user.login : '',
1776
+ head: pull.head ? pull.head.ref : '',
1777
+ base: pull.base ? pull.base.ref : '',
1778
+ mergeable: pull.mergeable,
1779
+ mergeableState: pull.mergeable_state || '',
1780
+ additions: pull.additions,
1781
+ deletions: pull.deletions,
1782
+ changedFiles: pull.changed_files,
1783
+ body: pull.body || '',
1784
+ htmlUrl: pull.html_url,
1785
+ updatedAt: pull.updated_at,
1786
+ files: (Array.isArray(files) ? files : []).map((file) => ({
1787
+ path: file.filename,
1788
+ status: file.status,
1789
+ additions: file.additions,
1790
+ deletions: file.deletions,
1791
+ patch: file.patch ? String(file.patch).slice(0, 6000) : '',
1792
+ })),
1793
+ }
1794
+ }
1795
+
1796
+ async function addPullComment(owner, name, number, body, line) {
1797
+ const repo = repoPath(owner, name)
1798
+ if (!body || !String(body).trim()) throw new Error('评论内容不能为空')
1799
+ if (line && line.path) {
1800
+ const json = await call(`${repo}/pulls/${number}/comments`, {
1801
+ method: 'POST',
1802
+ body: { body, path: line.path, line: Number(line.number), side: line.side || 'RIGHT' },
1803
+ })
1804
+ return { id: json.id, inline: true, htmlUrl: json.html_url }
1805
+ }
1806
+ const json = await call(`${repo}/issues/${number}/comments`, { method: 'POST', body: { body } })
1807
+ return { id: json.id, inline: false, htmlUrl: json.html_url }
1808
+ }
1809
+
1810
+ async function submitReview(owner, name, number, event, body) {
1811
+ const allowed = ['APPROVE', 'REQUEST_CHANGES', 'COMMENT']
1812
+ if (!allowed.includes(event)) throw new Error(`event 必须是 ${allowed.join(' / ')}`)
1813
+ if (event === 'REQUEST_CHANGES' && !String(body || '').trim()) {
1814
+ throw new Error('请求修改必须写理由')
1815
+ }
1816
+ const repo = repoPath(owner, name)
1817
+ const json = await call(`${repo}/pulls/${number}/reviews`, { method: 'POST', body: { event, body: body || '' } })
1818
+ return { id: json.id, state: json.state, htmlUrl: json.html_url }
1819
+ }
1820
+
1821
+ async function updateIssue(owner, name, number, patch) {
1822
+ const repo = repoPath(owner, name)
1823
+ const body = {}
1824
+ for (const key of ['title', 'body', 'state', 'state_reason', 'milestone']) {
1825
+ if (patch[key] !== undefined) body[key] = patch[key]
1826
+ }
1827
+ if (Array.isArray(patch.labels)) body.labels = patch.labels
1828
+ if (Array.isArray(patch.assignees)) body.assignees = patch.assignees
1829
+ if (Object.keys(body).length === 0) throw new Error('没有要修改的字段')
1830
+ const json = await call(`${repo}/issues/${number}`, { method: 'PATCH', body })
1831
+ return {
1832
+ number: json.number,
1833
+ title: json.title,
1834
+ state: json.state,
1835
+ labels: (json.labels || []).map((label) => (typeof label === 'string' ? label : label.name)),
1836
+ assignees: (json.assignees || []).map((item) => item.login),
1837
+ htmlUrl: json.html_url,
1838
+ }
1839
+ }
1840
+
1841
+ async function listWorkflows(owner, name) {
1842
+ const repo = repoPath(owner, name)
1843
+ const json = await call(`${repo}/actions/workflows?per_page=50`)
1844
+ return {
1845
+ items: (json.workflows || []).map((item) => ({
1846
+ id: item.id,
1847
+ name: item.name,
1848
+ path: item.path,
1849
+ state: item.state,
1850
+ htmlUrl: item.html_url,
1851
+ })),
1852
+ }
1853
+ }
1854
+
1855
+ async function dispatchNamedWorkflow(owner, name, workflow, ref, inputs) {
1856
+ const repo = repoPath(owner, name)
1857
+ if (!workflow) throw new Error('需要 workflow(文件名或 id)')
1858
+ await call(`${repo}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, {
1859
+ method: 'POST',
1860
+ body: { ref: ref || 'main', ...(inputs && Object.keys(inputs).length ? { inputs } : {}) },
1861
+ })
1862
+ return { dispatched: true, workflow, ref: ref || 'main', inputs: inputs || {} }
1863
+ }
1864
+
1865
+ async function runLog(owner, name, runId, tailLines = 120) {
1866
+ const repo = repoPath(owner, name)
1867
+ const token = await installationToken()
1868
+ // The archive answers 302 to a signed objects.githubusercontent.com URL, and
1869
+ // both hosts are hijacked on some machines, so follow the redirect through
1870
+ // the same resilient transport instead of global fetch.
1871
+ let url = `${cfg.baseUrl}${repo}/actions/runs/${runId}/logs`
1872
+ let withAuth = true
1873
+ let response = null
1874
+ for (let hop = 0; hop < 5; hop++) {
1875
+ response = await transport.request(url, {
1876
+ headers: withAuth ? { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json' } : { Accept: '*/*' },
1877
+ binary: true,
1878
+ })
1879
+ const location = response.headers && response.headers.location
1880
+ if (response.status >= 300 && response.status < 400 && location) {
1881
+ url = new URL(location, url).href
1882
+ withAuth = new URL(url).hostname === new URL(cfg.baseUrl).hostname
1883
+ continue
1884
+ }
1885
+ break
1886
+ }
1887
+ if (!response || response.status !== 200 || !response.buffer) {
1888
+ throw new GhError(response ? response.status : 0, 'LOG_UNAVAILABLE', `取日志失败(HTTP ${response ? response.status : '?'})`)
1889
+ }
1890
+ const entries = unzipEntries(response.buffer)
1891
+ const pick =
1892
+ entries.find((entry) => /Publish\.txt$/i.test(entry.name)) ||
1893
+ entries.find((entry) => /\.txt$/i.test(entry.name)) ||
1894
+ entries[entries.length - 1]
1895
+ const lines = pick ? pick.text.split('\n') : []
1896
+ return {
1897
+ runId,
1898
+ files: entries.map((entry) => entry.name),
1899
+ name: pick ? pick.name : '',
1900
+ tail: lines.slice(-Math.max(10, Math.min(2000, tailLines))).join('\n'),
1901
+ }
1902
+ }
1903
+
1153
1904
  return {
1154
1905
  call,
1155
1906
  installToken: installationToken,
1156
1907
  status,
1157
1908
  installations,
1158
1909
  selectedInstallation,
1910
+ resolveAuth,
1911
+ capabilitiesOf,
1912
+ whoAmI,
1913
+ fingerprint,
1914
+ useConnection: async (kind) => {
1915
+ if (!['app', 'oauth', 'pat', 'env'].includes(kind)) throw new Error(`未知连接类型:${kind}`)
1916
+ if (kind === 'app') {
1917
+ const app = await readApp()
1918
+ if (!app) throw new Error('还没有注册 GitHub App')
1919
+ const installation = await selectedInstallation()
1920
+ if (!installation) throw new Error('App 还没有安装到任何账号')
1921
+ }
1922
+ if (kind === 'oauth' && !(await oauthToken().catch(() => ''))) throw new Error('还没有完成 App 用户授权')
1923
+ if (kind === 'pat' && !(await readPat())) throw new Error('还没有保存个人访问令牌')
1924
+ if (kind === 'env' && !process.env[cfg.patEnvName]) throw new Error(`环境变量 ${cfg.patEnvName} 没有设置`)
1925
+ await writeRecord(AUTH_CRED, { kind })
1926
+ authCache = null
1927
+ return resolveAuth()
1928
+ },
1929
+ setPat: async (token) => {
1930
+ const value = String(token || '').trim()
1931
+ if (!value) throw new Error('令牌不能为空')
1932
+ const me = await whoAmI(value)
1933
+ await writeRecord(PAT_CRED, { token: value, login: me.login, scopes: me.scopes, addedAt: new Date().toISOString() })
1934
+ await writeRecord(AUTH_CRED, { kind: 'pat' })
1935
+ authCache = null
1936
+ return { login: me.login, fingerprint: fingerprint(value), scopes: me.scopes }
1937
+ },
1938
+ clearPat: async () => {
1939
+ await deleteRecord(PAT_CRED)
1940
+ const stored = await readRecord(AUTH_CRED).catch(() => undefined)
1941
+ if (stored && stored.kind === 'pat') await writeRecord(AUTH_CRED, { kind: 'app' })
1942
+ authCache = null
1943
+ return { ok: true }
1944
+ },
1159
1945
  selectInstallation: async (id) => {
1160
1946
  const list = await installations()
1161
1947
  const match = list.find((item) => String(item.id) === String(id))
@@ -1166,6 +1952,17 @@ function createGithub(ctx, cfg, transport) {
1166
1952
  },
1167
1953
  beginManifest,
1168
1954
  completeManifest,
1955
+ deviceStart,
1956
+ devicePoll,
1957
+ beginOAuth,
1958
+ completeOAuth,
1959
+ clearOAuth: async () => {
1960
+ await deleteRecord(OAUTH_CRED)
1961
+ const stored = await readRecord(AUTH_CRED).catch(() => undefined)
1962
+ if (stored && stored.kind === 'oauth') await writeRecord(AUTH_CRED, { kind: 'app' })
1963
+ authCache = null
1964
+ return { ok: true }
1965
+ },
1169
1966
  resetApp,
1170
1967
  appConfigured: async () => Boolean(await readApp()),
1171
1968
  waitForCredentials,
@@ -1183,6 +1980,19 @@ function createGithub(ctx, cfg, transport) {
1183
1980
  mergePull,
1184
1981
  listRuns,
1185
1982
  rerunWorkflow,
1983
+ pullDetail,
1984
+ addPullComment,
1985
+ submitReview,
1986
+ updateIssue,
1987
+ listWorkflows,
1988
+ dispatchNamedWorkflow,
1989
+ runLog,
1990
+ listNotifications,
1991
+ markNotificationsRead,
1992
+ searchCode,
1993
+ listReleases,
1994
+ listCommits,
1995
+ compareRefs,
1186
1996
  }
1187
1997
  }
1188
1998
 
@@ -1520,8 +2330,6 @@ async function createRelease(gh, owner, name, version, branch, notes) {
1520
2330
  return { skipped: false, tag, htmlUrl: release.html_url }
1521
2331
  }
1522
2332
 
1523
- const WORKFLOW_DIR = '.github/workflows'
1524
-
1525
2333
  function publishWorkflowYaml() {
1526
2334
  // npm cannot attach a trusted publisher to a package that does not exist yet,
1527
2335
  // so this workflow also accepts an optional NPM_TOKEN secret for the very
@@ -1560,18 +2368,206 @@ jobs:
1560
2368
  `
1561
2369
  }
1562
2370
 
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
- }
2371
+ const WORKFLOW_DIR = '.github/workflows'
1571
2372
 
1572
- async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
1573
- const filePath = `${WORKFLOW_DIR}/${workflowFile}`
1574
- const desired = publishWorkflowYaml()
2373
+ /**
2374
+ * Minimal ustar writer plus gzip, so a release asset can be produced without
2375
+ * depending on a system tar or an npm install.
2376
+ */
2377
+ function buildTarball(files, prefix = 'package') {
2378
+ const blocks = []
2379
+ const header = (name, size, mtime) => {
2380
+ const buffer = Buffer.alloc(512)
2381
+ const write = (value, offset, length) => buffer.write(value.slice(0, length), offset, length, 'utf8')
2382
+ write(name, 0, 100)
2383
+ write(`${(0o644).toString(8)}\0`, 100, 8)
2384
+ write(`${(0).toString(8)}\0`, 108, 8)
2385
+ write(`${(0).toString(8)}\0`, 116, 8)
2386
+ write(`${size.toString(8)}\0`, 124, 12)
2387
+ write(`${Math.floor(mtime / 1000).toString(8)}\0`, 136, 12)
2388
+ write(' ', 148, 8)
2389
+ write('0', 156, 1)
2390
+ write('ustar\0', 257, 6)
2391
+ write('00', 263, 2)
2392
+ let sum = 0
2393
+ for (const byte of buffer) sum += byte
2394
+ write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8)
2395
+ return buffer
2396
+ }
2397
+ const now = Date.now()
2398
+ for (const file of files) {
2399
+ // ustar splits long paths into prefix/name at a slash before byte 100.
2400
+ let name = `${prefix}/${file.path}`
2401
+ let tail = name
2402
+ if (Buffer.byteLength(name) > 100) {
2403
+ const slash = name.lastIndexOf('/', 155)
2404
+ if (slash > 0 && Buffer.byteLength(name.slice(slash + 1)) <= 100) {
2405
+ tail = name.slice(slash + 1)
2406
+ const dir = name.slice(0, slash)
2407
+ const buffer = Buffer.alloc(512)
2408
+ buffer.write(tail, 0, 100, 'utf8')
2409
+ buffer.write(`${(0o644).toString(8)}\0`, 100, 8)
2410
+ buffer.write('0000000\0', 108, 8)
2411
+ buffer.write('0000000\0', 116, 8)
2412
+ buffer.write(`${file.content.length.toString(8)}\0`, 124, 12)
2413
+ buffer.write(`${Math.floor(now / 1000).toString(8)}\0`, 136, 12)
2414
+ buffer.write(' ', 148, 8)
2415
+ buffer.write('0', 156, 1)
2416
+ buffer.write('ustar\0', 257, 6)
2417
+ buffer.write('00', 263, 2)
2418
+ buffer.write(dir, 345, Math.min(155, Buffer.byteLength(dir)))
2419
+ let sum = 0
2420
+ for (const byte of buffer) sum += byte
2421
+ buffer.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8)
2422
+ blocks.push(buffer)
2423
+ blocks.push(file.content)
2424
+ const pad = (512 - (file.content.length % 512)) % 512
2425
+ if (pad) blocks.push(Buffer.alloc(pad))
2426
+ continue
2427
+ }
2428
+ }
2429
+ blocks.push(header(name, file.content.length, now))
2430
+ blocks.push(file.content)
2431
+ const pad = (512 - (file.content.length % 512)) % 512
2432
+ if (pad) blocks.push(Buffer.alloc(pad))
2433
+ }
2434
+ blocks.push(Buffer.alloc(1024))
2435
+ return zlib.gzipSync(Buffer.concat(blocks), { level: 9 })
2436
+ }
2437
+
2438
+ async function attachReleaseAsset(gh, owner, repo, version, fileName, buffer) {
2439
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
2440
+ const tag = `v${version}`
2441
+ let release = await gh.call(`${repoPath}/releases/tags/${encodeURIComponent(tag)}`).catch(() => null)
2442
+ if (!release) return { uploaded: false, reason: `Release ${tag} 还不存在:先发布一次` }
2443
+ const upload = async (name) => {
2444
+ const assets = Array.isArray(release.assets) ? release.assets : []
2445
+ const existing = assets.find((asset) => asset.name === name)
2446
+ if (existing) {
2447
+ await gh.call(`${repoPath}/releases/assets/${existing.id}`, { method: 'DELETE' }).catch(() => {})
2448
+ }
2449
+ return gh.call(
2450
+ `https://uploads.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases/${release.id}/assets?name=${encodeURIComponent(name)}`,
2451
+ {
2452
+ method: 'POST',
2453
+ rawBody: true,
2454
+ headers: { 'Content-Type': 'application/gzip', Accept: 'application/vnd.github+json' },
2455
+ body: buffer,
2456
+ },
2457
+ )
2458
+ }
2459
+ const uploaded = await upload(fileName)
2460
+ // A version-free duplicate keeps releases/latest/download/<name> alive: the
2461
+ // storefront list warns that a versioned name rots on the next release.
2462
+ let versionFree = null
2463
+ const versionFreeName = fileName.replace(new RegExp(`-${version.replace(/\./g, '\\.')}(?=\\.tgz$)`), '')
2464
+ if (versionFreeName !== fileName) {
2465
+ versionFree = await upload(versionFreeName).catch(() => null)
2466
+ }
2467
+ return {
2468
+ uploaded: true,
2469
+ id: uploaded.id,
2470
+ name: uploaded.name,
2471
+ size: uploaded.size,
2472
+ url: uploaded.browser_download_url,
2473
+ tag,
2474
+ versionFreeName: versionFree ? versionFree.name : '',
2475
+ versionFreeUrl: versionFree ? versionFree.browser_download_url : '',
2476
+ }
2477
+ }
2478
+
2479
+ /** Preconditions the awesome-dsh-plugin list checks before a PR can merge. */
2480
+ async function marketReadiness(gh, cfg, { owner, repo, dir }) {
2481
+ const checks = []
2482
+ const add = (id, level, title, detail) => checks.push({ id, level, title, detail: detail || '' })
2483
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
2484
+ const meta = await gh.call(repoPath).catch(() => null)
2485
+
2486
+ if (!meta) {
2487
+ add('repo', 'block', '读不到仓库信息', `${owner}/${repo}`)
2488
+ return { ready: false, checks }
2489
+ }
2490
+ const created = meta.created_at ? Date.parse(meta.created_at) : 0
2491
+ const ageHours = created ? (Date.now() - created) / 3600000 : 0
2492
+ add('repo-age', ageHours >= 24 ? 'pass' : 'block', '仓库年龄 ≥ 1 天', `${ageHours.toFixed(1)} 小时`)
2493
+
2494
+ let pkg = null
2495
+ try {
2496
+ pkg = await readLocalPackage(dir)
2497
+ } catch (error) {
2498
+ add('package', 'block', '本地 package.json 读不到', errorMessage(error))
2499
+ }
2500
+ if (pkg) {
2501
+ const hasBundle = Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch)
2502
+ add('dsh.bundle', hasBundle ? 'pass' : 'block', 'package.json 声明 dsh.bundle', hasBundle ? pkg.dsh.bundle.patch : '只声明 dsh.client 会在这条失败')
2503
+ const officialDeps = Object.keys(pkg.dependencies || {}).filter((name) => name.startsWith('@deepseek-ai/'))
2504
+ add(
2505
+ 'peer-deps',
2506
+ officialDeps.length === 0 ? 'pass' : 'block',
2507
+ '@deepseek-ai/* 用 peerDependencies 而不是 dependencies',
2508
+ officialDeps.join(', '),
2509
+ )
2510
+ }
2511
+
2512
+ const iconCandidates = ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']
2513
+ let iconPath = ''
2514
+ for (const candidate of iconCandidates) {
2515
+ const file = await repoFile(gh, owner, repo, candidate, cfg.publishBranch).catch(() => null)
2516
+ if (file) {
2517
+ iconPath = candidate
2518
+ break
2519
+ }
2520
+ }
2521
+ add('icon', iconPath ? 'pass' : 'block', '仓库里有 GitHub 托管的 PNG 图标', iconPath || '列表拒收 SVG 与第三方图床')
2522
+
2523
+ const latest = await gh.call(`${repoPath}/releases/latest`).catch(() => null)
2524
+ const assets = latest && Array.isArray(latest.assets) ? latest.assets : []
2525
+ const versionFree = assets.find((asset) => /\.tgz$/i.test(asset.name) && !/\d+\.\d+\.\d+/.test(asset.name))
2526
+ add(
2527
+ 'tarball',
2528
+ versionFree ? 'pass' : 'block',
2529
+ '最新 Release 有不带版本号的 .tgz',
2530
+ versionFree ? versionFree.name : 'releases/latest/download/<固定名>.tgz 才能在每次发版后继续可用',
2531
+ )
2532
+
2533
+ let readme = ''
2534
+ try {
2535
+ readme = await fs.readFile(path.join(dir, 'README.md'), 'utf8')
2536
+ } catch {
2537
+ readme = ''
2538
+ }
2539
+ const bilingual = /[\u4e00-\u9fff]/.test(readme) && /[A-Za-z]{4,}/.test(readme)
2540
+ add('readme', bilingual ? 'pass' : 'warn', 'README 中英双语(列表条目也是双语)', bilingual ? '' : 'README 里至少要有中英两种文字')
2541
+
2542
+ add('screenshots', 'info', '截图可选', '想控制展示顺序就在仓库放 screenshots.json(1-8 张,路径不能跳出插件目录)')
2543
+ add('category', 'info', '分类建议', 'Git & Code Review(条目里写 category: git)')
2544
+
2545
+ const ready = !checks.some((check) => check.level === 'block')
2546
+ return {
2547
+ ready,
2548
+ checks,
2549
+ entry: {
2550
+ url: `https://github.com/${owner}/${repo}`,
2551
+ name: `${owner}/${repo}`,
2552
+ category: 'git',
2553
+ icon: iconPath ? `https://raw.githubusercontent.com/${owner}/${repo}/${cfg.publishBranch}/${iconPath}` : '',
2554
+ tarball: versionFree ? `https://github.com/${owner}/${repo}/releases/latest/download/${versionFree.name}` : '',
2555
+ },
2556
+ }
2557
+ }
2558
+
2559
+ async function repoFile(gh, owner, repo, filePath, ref) {
2560
+ try {
2561
+ return await gh.readFile(owner, repo, filePath, ref)
2562
+ } catch (error) {
2563
+ if (error.status === 404) return null
2564
+ throw error
2565
+ }
2566
+ }
2567
+
2568
+ async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
2569
+ const filePath = `${WORKFLOW_DIR}/${workflowFile}`
2570
+ const desired = publishWorkflowYaml()
1575
2571
  const existing = await repoFile(gh, owner, repo, filePath, branch)
1576
2572
  if (existing && String(existing.text).trim() === desired.trim()) {
1577
2573
  return { path: filePath, changed: false }
@@ -1740,6 +2736,71 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
1740
2736
  }
1741
2737
  }
1742
2738
 
2739
+ function unzipEntries(buffer) {
2740
+ // GitHub log archives use data descriptors, so sizes come from the central
2741
+ // directory rather than the local header. Minimal deflate-only reader.
2742
+ const entries = []
2743
+ let eocd = -1
2744
+ for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 70000); i--) {
2745
+ if (buffer.readUInt32LE(i) === 0x06054b50) {
2746
+ eocd = i
2747
+ break
2748
+ }
2749
+ }
2750
+ const read = (offset, nameLength, extraLength) => {
2751
+ const method = buffer.readUInt16LE(offset + 10)
2752
+ const compressed = buffer.readUInt32LE(offset + 20)
2753
+ const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
2754
+ const localOffset = buffer.readUInt32LE(offset + 42)
2755
+ const localNameLength = buffer.readUInt16LE(localOffset + 26)
2756
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28)
2757
+ const dataStart = localOffset + 30 + localNameLength + localExtraLength
2758
+ const data = buffer.subarray(dataStart, dataStart + compressed)
2759
+ let text = ''
2760
+ try {
2761
+ text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
2762
+ } catch {
2763
+ text = ''
2764
+ }
2765
+ entries.push({ name, text })
2766
+ void extraLength
2767
+ }
2768
+ if (eocd >= 0) {
2769
+ const count = buffer.readUInt16LE(eocd + 10)
2770
+ let offset = buffer.readUInt32LE(eocd + 16)
2771
+ for (let index = 0; index < count; index++) {
2772
+ if (buffer.readUInt32LE(offset) !== 0x02014b50) break
2773
+ const nameLength = buffer.readUInt16LE(offset + 28)
2774
+ const extraLength = buffer.readUInt16LE(offset + 30)
2775
+ const commentLength = buffer.readUInt16LE(offset + 32)
2776
+ read(offset, nameLength, extraLength)
2777
+ offset += 46 + nameLength + extraLength + commentLength
2778
+ }
2779
+ if (entries.length) return entries
2780
+ }
2781
+ // Fallback: walk local headers (works when sizes are present).
2782
+ let offset = 0
2783
+ while (offset + 30 <= buffer.length) {
2784
+ if (buffer.readUInt32LE(offset) !== 0x04034b50) break
2785
+ const method = buffer.readUInt16LE(offset + 8)
2786
+ const compressed = buffer.readUInt32LE(offset + 18)
2787
+ const nameLength = buffer.readUInt16LE(offset + 26)
2788
+ const extraLength = buffer.readUInt16LE(offset + 28)
2789
+ const name = buffer.subarray(offset + 30, offset + 30 + nameLength).toString('utf8')
2790
+ const dataStart = offset + 30 + nameLength + extraLength
2791
+ const data = buffer.subarray(dataStart, dataStart + compressed)
2792
+ let text = ''
2793
+ try {
2794
+ text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
2795
+ } catch {
2796
+ text = ''
2797
+ }
2798
+ entries.push({ name, text })
2799
+ offset = dataStart + compressed
2800
+ }
2801
+ return entries
2802
+ }
2803
+
1743
2804
  async function probeMarket(input, gh, cfg) {
1744
2805
  const checkedAt = new Date().toISOString()
1745
2806
  const results = []
@@ -2027,6 +3088,32 @@ export function apply(ctx, rawConfig) {
2027
3088
 
2028
3089
  const discover = (extra) => discoverPlugins(discoveryRoots(extra))
2029
3090
 
3091
+ // Every mutating path records who did what, so a console leaves a trail.
3092
+ const audited = async (action, target, run) => {
3093
+ const started = Date.now()
3094
+ try {
3095
+ const result = await run()
3096
+ await appendAudit({ action, target, ok: true, ms: Date.now() - started })
3097
+ return result
3098
+ } catch (error) {
3099
+ await appendAudit({ action, target, ok: false, detail: errorMessage(error).slice(0, 300), ms: Date.now() - started })
3100
+ throw error
3101
+ }
3102
+ }
3103
+
3104
+ // Write actions are refused up front when the active connection cannot write.
3105
+ const requireWrite = async (capability = 'repoWrite') => {
3106
+ if (cfg.readOnly) throw new Error('只读模式已开启(配置 readOnly: true),写操作已禁用')
3107
+ const auth = await gh.resolveAuth()
3108
+ const capabilities = gh.capabilitiesOf(auth)
3109
+ if (!capabilities[capability]) {
3110
+ throw new Error(
3111
+ `当前连接(${auth.kind})没有 ${capability} 权限:到「状态 → 连接方式」换一个带写权限的连接,或给 App 补权限`,
3112
+ )
3113
+ }
3114
+ return auth
3115
+ }
3116
+
2030
3117
  async function withToken() {
2031
3118
  if (!bridgeToken) {
2032
3119
  const credentials = await gh.waitForCredentials()
@@ -2195,6 +3282,38 @@ export function apply(ctx, rawConfig) {
2195
3282
  const route = `${request.method} ${url.pathname}`
2196
3283
  const args = body && typeof body === 'object' ? body : {}
2197
3284
 
3285
+ if (route === 'POST /github-console/api/auth/device/start') {
3286
+ return sendJson(response, 200, await gh.deviceStart())
3287
+ }
3288
+ if (route === 'POST /github-console/api/auth/device/poll') {
3289
+ return sendJson(response, 200, await gh.devicePoll(args.deviceCode))
3290
+ }
3291
+ if (route === 'POST /github-console/api/auth/oauth/start') {
3292
+ return sendJson(response, 200, await gh.beginOAuth(requestOrigin(request)))
3293
+ }
3294
+ if (route === 'POST /github-console/api/auth/oauth/clear') {
3295
+ await gh.clearOAuth()
3296
+ await appendAudit({ action: 'auth.oauth-clear', account: '', ok: true })
3297
+ return sendJson(response, 200, { ok: true })
3298
+ }
3299
+ if (route === 'POST /github-console/api/auth/use') {
3300
+ const auth = await gh.useConnection(args.kind)
3301
+ await appendAudit({ action: 'auth.use', account: auth.account || auth.fingerprint || '', detail: args.kind })
3302
+ return sendJson(response, 200, { active: auth.kind, ok: true })
3303
+ }
3304
+ if (route === 'POST /github-console/api/auth/pat') {
3305
+ const result = await gh.setPat(args.token)
3306
+ await appendAudit({ action: 'auth.pat-set', account: result.login, detail: result.fingerprint })
3307
+ return sendJson(response, 200, { ok: true, login: result.login, fingerprint: result.fingerprint, scopes: result.scopes })
3308
+ }
3309
+ if (route === 'POST /github-console/api/auth/pat/clear') {
3310
+ await gh.clearPat()
3311
+ await appendAudit({ action: 'auth.pat-clear', account: '', detail: '' })
3312
+ return sendJson(response, 200, { ok: true })
3313
+ }
3314
+ if (route === 'POST /github-console/api/audit') {
3315
+ return sendJson(response, 200, { path: auditPath(), items: await readAudit(args.limit || 50) })
3316
+ }
2198
3317
  if (route === 'POST /github-console/api/status') {
2199
3318
  return sendJson(response, 200, { ...(await gh.status()), bridge: bridgeStatus() })
2200
3319
  }
@@ -2236,10 +3355,99 @@ export function apply(ctx, rawConfig) {
2236
3355
  return sendJson(response, 200, await gh.readFile(args.owner, args.name, args.path, args.ref))
2237
3356
  }
2238
3357
  if (route === 'POST /github-console/api/file/write') {
3358
+ await requireWrite('repoWrite')
3359
+ return sendJson(
3360
+ response,
3361
+ 200,
3362
+ await audited('file.write', `${args.owner}/${args.name}:${args.path}`, () =>
3363
+ gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref),
3364
+ ),
3365
+ )
3366
+ }
3367
+ if (route === 'POST /github-console/api/notifications') {
3368
+ return sendJson(response, 200, await gh.listNotifications(args))
3369
+ }
3370
+ if (route === 'POST /github-console/api/notifications/read') {
3371
+ return sendJson(
3372
+ response,
3373
+ 200,
3374
+ await audited('notifications.read', args.all ? 'all' : (args.ids || []).join(','), () => gh.markNotificationsRead(args)),
3375
+ )
3376
+ }
3377
+ if (route === 'POST /github-console/api/search/code') {
3378
+ return sendJson(response, 200, await gh.searchCode(args.q, args))
3379
+ }
3380
+ if (route === 'POST /github-console/api/releases') {
3381
+ return sendJson(response, 200, await gh.listReleases(args.owner, args.name))
3382
+ }
3383
+ if (route === 'POST /github-console/api/commits') {
3384
+ return sendJson(response, 200, await gh.listCommits(args.owner, args.name, args))
3385
+ }
3386
+ if (route === 'POST /github-console/api/compare') {
3387
+ return sendJson(response, 200, await gh.compareRefs(args.owner, args.name, args.base, args.head))
3388
+ }
3389
+ if (route === 'POST /github-console/api/pull/detail') {
3390
+ return sendJson(response, 200, await gh.pullDetail(args.owner, args.name, args.number))
3391
+ }
3392
+ if (route === 'POST /github-console/api/pull/comment') {
3393
+ await requireWrite('pullWrite')
3394
+ return sendJson(
3395
+ response,
3396
+ 200,
3397
+ await audited('pull.comment', `${args.owner}/${args.name}#${args.number}`, () =>
3398
+ gh.addPullComment(args.owner, args.name, args.number, args.body, args.path ? { path: args.path, number: args.line } : null),
3399
+ ),
3400
+ )
3401
+ }
3402
+ if (route === 'POST /github-console/api/pull/review') {
3403
+ await requireWrite('pullWrite')
3404
+ return sendJson(
3405
+ response,
3406
+ 200,
3407
+ await audited('pull.review', `${args.owner}/${args.name}#${args.number} ${args.event}`, () =>
3408
+ gh.submitReview(args.owner, args.name, args.number, args.event, args.body),
3409
+ ),
3410
+ )
3411
+ }
3412
+ if (route === 'POST /github-console/api/pull/merge') {
3413
+ await requireWrite('pullWrite')
3414
+ if (args.confirm !== true) return sendJson(response, 400, { error: '合并需要 confirm: true', code: 'INVALID' })
3415
+ return sendJson(
3416
+ response,
3417
+ 200,
3418
+ await audited('pull.merge', `${args.owner}/${args.name}#${args.number} ${args.method || 'squash'}`, () =>
3419
+ gh.mergePull(args.owner, args.name, args.number, args.method),
3420
+ ),
3421
+ )
3422
+ }
3423
+ if (route === 'POST /github-console/api/issue/update') {
3424
+ await requireWrite('issueWrite')
3425
+ const patch = {}
3426
+ for (const key of ['title', 'body', 'state', 'labels', 'assignees', 'milestone']) {
3427
+ if (args[key] !== undefined) patch[key] = args[key]
3428
+ }
3429
+ return sendJson(
3430
+ response,
3431
+ 200,
3432
+ await audited('issue.update', `${args.owner}/${args.name}#${args.number}`, () =>
3433
+ gh.updateIssue(args.owner, args.name, args.number, patch),
3434
+ ),
3435
+ )
3436
+ }
3437
+ if (route === 'POST /github-console/api/actions/log') {
3438
+ return sendJson(response, 200, await gh.runLog(args.owner, args.name, args.runId, args.tailLines || 120))
3439
+ }
3440
+ if (route === 'POST /github-console/api/workflows') {
3441
+ return sendJson(response, 200, await gh.listWorkflows(args.owner, args.name))
3442
+ }
3443
+ if (route === 'POST /github-console/api/workflows/dispatch') {
3444
+ await requireWrite('workflowsWrite')
2239
3445
  return sendJson(
2240
3446
  response,
2241
3447
  200,
2242
- await gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref),
3448
+ await audited('workflow.dispatch', `${args.owner}/${args.name}:${args.workflow}`, () =>
3449
+ gh.dispatchNamedWorkflow(args.owner, args.name, args.workflow, args.ref, args.inputs),
3450
+ ),
2243
3451
  )
2244
3452
  }
2245
3453
  if (route === 'POST /github-console/api/issues') {
@@ -2251,6 +3459,30 @@ export function apply(ctx, rawConfig) {
2251
3459
  if (route === 'POST /github-console/api/actions') {
2252
3460
  return sendJson(response, 200, await gh.listRuns(args.owner, args.name))
2253
3461
  }
3462
+ if (route === 'POST /github-console/api/release/asset') {
3463
+ const dir = resolveDir(args.dir)
3464
+ const pkg = await readLocalPackage(dir)
3465
+ const collected = await collectFiles(dir, cfg.maxPushBytes)
3466
+ const fileName =
3467
+ args.fileName || `${pkg.name.replace(/^@[^/]+\//, '')}-${pkg.version}.tgz`
3468
+ const asset = await attachReleaseAsset(
3469
+ gh,
3470
+ args.owner,
3471
+ args.repo,
3472
+ args.version || pkg.version,
3473
+ fileName,
3474
+ buildTarball(collected.files),
3475
+ )
3476
+ const ref = await gh
3477
+ .call(`/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/git/ref/heads/${encodeURIComponent(cfg.publishBranch)}`)
3478
+ .catch(() => null)
3479
+ return sendJson(response, 200, {
3480
+ package: `${pkg.name}@${pkg.version}`,
3481
+ files: collected.files.length,
3482
+ asset,
3483
+ gitInstall: ref && ref.object ? `git+https://github.com/${args.owner}/${args.repo}.git#${ref.object.sha}` : '',
3484
+ })
3485
+ }
2254
3486
  if (route === 'POST /github-console/api/npm/status') {
2255
3487
  return sendJson(
2256
3488
  response,
@@ -2262,6 +3494,9 @@ export function apply(ctx, rawConfig) {
2262
3494
  }),
2263
3495
  )
2264
3496
  }
3497
+ if (route === 'POST /github-console/api/market/readiness') {
3498
+ return sendJson(response, 200, await marketReadiness(gh, cfg, { owner: args.owner, repo: args.repo, dir: resolveDir(args.dir) }))
3499
+ }
2265
3500
  if (route === 'POST /github-console/api/market/attach') {
2266
3501
  return sendJson(
2267
3502
  response,
@@ -2333,8 +3568,10 @@ export function apply(ctx, rawConfig) {
2333
3568
  return sendJson(response, 200, await discover(args.root))
2334
3569
  }
2335
3570
  if (route === 'POST /github-console/api/publish/run') {
3571
+ await requireWrite('repoWrite')
2336
3572
  const dir = resolveDir(args.dir)
2337
3573
  const job = jobs.create({ dir, owner: args.owner, repo: args.repo })
3574
+ await appendAudit({ action: 'publish.run', target: `${args.owner}/${args.repo}`, ok: true })
2338
3575
  void runPublish({ job, gh, cfg, dir, owner: args.owner, repo: args.repo, version: args.version, notes: args.notes, opts: args })
2339
3576
  return sendJson(response, 200, { jobId: job.id })
2340
3577
  }
@@ -2370,6 +3607,76 @@ export function apply(ctx, rawConfig) {
2370
3607
  await handleCallback(request, response, url)
2371
3608
  return
2372
3609
  }
3610
+ if (url.pathname === `${PREFIX}/oauth/callback`) {
3611
+ const code = url.searchParams.get('code')
3612
+ const state = url.searchParams.get('state')
3613
+ if (!code) {
3614
+ sendHtml(response, 400, '授权失败', url.searchParams.get('error_description') || '没有收到 code')
3615
+ return
3616
+ }
3617
+ try {
3618
+ await gh.completeOAuth(code, state, requestOrigin(request))
3619
+ await appendAudit({ action: 'auth.oauth', account: '', ok: true })
3620
+ sendHtml(response, 200, '已授权', 'App 的用户授权已保存,可以关闭此页面回到 DSH:现在可以读取通知与做代码搜索了。')
3621
+ } catch (failure) {
3622
+ sendHtml(response, 400, '授权未完成', errorMessage(failure))
3623
+ }
3624
+ return
3625
+ }
3626
+ if (url.pathname === `${PREFIX}/device`) {
3627
+ // A plain HTML page: the panel may be stale or a popup blocked, but this
3628
+ // URL always shows the code and the verification link.
3629
+ try {
3630
+ const started = await gh.deviceStart()
3631
+ const checkUrl = `${PREFIX}/device/check?code=${encodeURIComponent(started.deviceCode)}`
3632
+ sendHtml(
3633
+ response,
3634
+ 200,
3635
+ 'GitHub 设备码授权',
3636
+ `在 GitHub 打开下面的页面,输入这个码并确认(${Math.round(started.expiresIn / 60)} 分钟内有效):`,
3637
+ `<p style="font:600 30px/1.3 ui-monospace,Consolas,monospace;letter-spacing:3px;margin:14px 0 6px">` +
3638
+ `${escapeHtml(started.userCode)}</p>` +
3639
+ `<p style="margin:0 0 16px"><a href="${escapeHtml(started.verificationUri)}" target="_blank" rel="noreferrer" ` +
3640
+ `style="display:inline-block;padding:9px 18px;border-radius:8px;background:#3E6FD8;color:#fff;text-decoration:none;font-size:14px">` +
3641
+ `打开 ${escapeHtml(started.verificationUri)}</a></p>` +
3642
+ `<p style="font-size:13px;color:#57606a">输入码并点 Authorize 之后,回到这里点下面的按钮确认:</p>` +
3643
+ `<p><a href="${escapeHtml(checkUrl)}" style="display:inline-block;padding:8px 16px;border:1px solid #3E6FD8;` +
3644
+ `border-radius:8px;color:#3E6FD8;text-decoration:none;font-size:13px">我已授权,检查状态</a></p>`,
3645
+ )
3646
+ } catch (failure) {
3647
+ const appRecord = await gh.readRecord(APP_CRED).catch(() => undefined)
3648
+ const appSlug = appRecord && appRecord.slug ? appRecord.slug : ''
3649
+ sendHtml(
3650
+ response,
3651
+ 200,
3652
+ '拿不到设备码',
3653
+ errorMessage(failure),
3654
+ `<p style="font-size:13px;color:#57606a;line-height:1.8">· 若是「App 没有启用 Device Flow」:到 ` +
3655
+ `<a href="${escapeHtml(appSlug ? `https://github.com/settings/apps/${appSlug}` : 'https://github.com/settings/apps')}">` +
3656
+ `GitHub App 设置页</a> 勾选 Enable Device Flow → 底部 Save changes。<br>` +
3657
+ `· 若是网络错误:这台机器连 GitHub 不稳定,请在网络正常时重试。</p>`,
3658
+ )
3659
+ }
3660
+ return
3661
+ }
3662
+ if (url.pathname === `${PREFIX}/device/check`) {
3663
+ const code = url.searchParams.get('code') || ''
3664
+ try {
3665
+ const result = await gh.devicePoll(code)
3666
+ if (result.status === 'ok') {
3667
+ sendHtml(response, 200, '授权成功', '已保存用户令牌,并切换为「App 用户授权」连接。可以关闭此页面。')
3668
+ } else if (result.status === 'pending') {
3669
+ sendHtml(response, 200, '还在等待确认', 'GitHub 那边还没点 Authorize,稍等几秒再点一次检查。')
3670
+ } else if (result.status === 'expired') {
3671
+ sendHtml(response, 200, '设备码已过期', '重新打开 /github-console/device 生成新码。')
3672
+ } else {
3673
+ sendHtml(response, 200, '授权被拒绝', '你在 GitHub 上取消了授权。')
3674
+ }
3675
+ } catch (failure) {
3676
+ sendHtml(response, 200, '检查失败', errorMessage(failure))
3677
+ }
3678
+ return
3679
+ }
2373
3680
  if (url.pathname === `${PREFIX}/icon.svg`) {
2374
3681
  // The index references ../icon.svg relative to /github-console/market/index.json.
2375
3682
  const svg = await fs.readFile(path.join(PLUGIN_DIR, 'icon.svg')).catch(() => null)
@@ -2484,12 +3791,18 @@ export function apply(ctx, rawConfig) {
2484
3791
  register({
2485
3792
  name: 'gh_auth',
2486
3793
  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.',
3794
+ '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
3795
  parameters: {
2489
3796
  type: 'object',
2490
3797
  properties: {
2491
- action: { type: 'string', enum: ['start', 'installations', 'select'] },
3798
+ action: {
3799
+ type: 'string',
3800
+ enum: ['start', 'installations', 'select', 'use', 'pat-set', 'pat-clear', 'oauth-start', 'oauth-clear', 'device-start', 'device-poll', 'capabilities'],
3801
+ },
2492
3802
  installationId: { type: 'string', description: 'Installation id, for action=select' },
3803
+ mode: { type: 'string', enum: ['app', 'oauth', 'pat', 'env'], description: 'Connection kind, for action=use' },
3804
+ token: { type: 'string', description: 'User access token (PAT), for action=pat-set. Stored in the credential service only.' },
3805
+ deviceCode: { type: 'string', description: 'device_code from action=device-start, for action=device-poll' },
2493
3806
  },
2494
3807
  required: ['action'],
2495
3808
  additionalProperties: false,
@@ -2498,6 +3811,8 @@ export function apply(ctx, rawConfig) {
2498
3811
  async execute(args) {
2499
3812
  if (args.action === 'start') {
2500
3813
  const base = String(process.env.DSH_WEB_URL || '').replace(/\/+$/, '')
3814
+ const state = gh.beginManifest()
3815
+ void state
2501
3816
  return {
2502
3817
  setupUrl: base ? `${base}${PREFIX}/setup` : `${PREFIX}/setup`,
2503
3818
  next: base
@@ -2507,10 +3822,72 @@ export function apply(ctx, rawConfig) {
2507
3822
  }
2508
3823
  if (args.action === 'installations') return { items: await gh.installations() }
2509
3824
  if (args.action === 'select') return gh.selectInstallation(args.installationId)
3825
+ if (args.action === 'use') {
3826
+ const auth = await gh.useConnection(args.mode)
3827
+ await appendAudit({ action: 'auth.use', account: auth.account || auth.fingerprint || '', detail: args.mode })
3828
+ return { active: auth.kind, capabilities: gh.capabilitiesOf(auth) }
3829
+ }
3830
+ if (args.action === 'pat-set') {
3831
+ if (!args.token) throw new Error('action=pat-set 需要 token')
3832
+ const result = await gh.setPat(args.token)
3833
+ await appendAudit({ action: 'auth.pat-set', account: result.login, detail: result.fingerprint })
3834
+ return { ...result, next: 'PAT 已保存并设为当前连接;不需要时用 action=pat-clear 删除' }
3835
+ }
3836
+ if (args.action === 'pat-clear') {
3837
+ await gh.clearPat()
3838
+ await appendAudit({ action: 'auth.pat-clear', account: '', detail: '' })
3839
+ return { ok: true }
3840
+ }
3841
+ if (args.action === 'oauth-start') {
3842
+ // Registers the App's OAuth callback, then returns the authorize URL.
3843
+ const origin = webOrigin()
3844
+ if (!origin) throw new Error('拿不到本机 web 地址:请在面板「状态 → 连接方式」里点授权')
3845
+ const result = await gh.beginOAuth(origin)
3846
+ return { ...result, next: '打开 url 授权;回调页会保存用户令牌,然后 action=use mode=oauth' }
3847
+ }
3848
+ if (args.action === 'oauth-clear') {
3849
+ await gh.clearOAuth()
3850
+ await appendAudit({ action: 'auth.oauth-clear', account: '', ok: true })
3851
+ return { ok: true }
3852
+ }
3853
+ if (args.action === 'device-start') {
3854
+ const result = await gh.deviceStart()
3855
+ return {
3856
+ ...result,
3857
+ next: `在浏览器打开 ${result.verificationUri},输入 ${result.userCode};然后反复调用 action=device-poll(同一个 deviceCode),直到 status=ok`,
3858
+ }
3859
+ }
3860
+ if (args.action === 'device-poll') {
3861
+ if (!args.deviceCode) throw new Error('action=device-poll 需要 deviceCode')
3862
+ const result = await gh.devicePoll(args.deviceCode)
3863
+ if (result.status === 'ok') {
3864
+ await appendAudit({ action: 'auth.device', account: '', ok: true })
3865
+ }
3866
+ return result
3867
+ }
3868
+ if (args.action === 'capabilities') {
3869
+ const state = await gh.status()
3870
+ return { auth: state.auth, connections: state.connections, authMode: state.authMode }
3871
+ }
2510
3872
  throw new Error(`未知 action:${args.action}`)
2511
3873
  },
2512
3874
  })
2513
3875
 
3876
+ register({
3877
+ name: 'gh_audit',
3878
+ description:
3879
+ 'Read the local audit trail of write actions this plugin performed: time, action, account, target and result. Newest last. Files stay on this machine.',
3880
+ parameters: {
3881
+ type: 'object',
3882
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many recent entries, default 50' } },
3883
+ additionalProperties: false,
3884
+ },
3885
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
3886
+ async execute(args) {
3887
+ return { path: auditPath(), items: await readAudit(args.limit || 50) }
3888
+ },
3889
+ })
3890
+
2514
3891
  register({
2515
3892
  name: 'gh_repos',
2516
3893
  description:
@@ -2970,6 +4347,352 @@ export function apply(ctx, rawConfig) {
2970
4347
  },
2971
4348
  })
2972
4349
 
4350
+ register({
4351
+ name: 'plugin_release_asset',
4352
+ description:
4353
+ '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.',
4354
+ parameters: {
4355
+ type: 'object',
4356
+ properties: {
4357
+ dir: { type: 'string', description: 'Local plugin directory' },
4358
+ owner: { type: 'string' },
4359
+ repo: { type: 'string' },
4360
+ version: { type: 'string', description: 'Release version to attach to; defaults to package.json version' },
4361
+ fileName: { type: 'string', description: 'Asset file name; defaults to <name>-<version>.tgz' },
4362
+ },
4363
+ required: ['dir', 'owner', 'repo'],
4364
+ additionalProperties: false,
4365
+ },
4366
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4367
+ async execute(args, exec) {
4368
+ const dir = resolveDir(args.dir, exec)
4369
+ const pkg = await readLocalPackage(dir)
4370
+ const collected = await collectFiles(dir, cfg.maxPushBytes)
4371
+ const version = args.version || pkg.version
4372
+ const fileName = args.fileName || `${pkg.name.replace(/^@[^/]+\//, '')}-${version}.tgz`
4373
+ const asset = await attachReleaseAsset(gh, args.owner, args.repo, version, fileName, buildTarball(collected.files))
4374
+ let commit = ''
4375
+ try {
4376
+ const ref = await gh.call(
4377
+ `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/git/ref/heads/${encodeURIComponent(cfg.publishBranch)}`,
4378
+ )
4379
+ commit = ref && ref.object ? ref.object.sha : ''
4380
+ } catch {
4381
+ commit = ''
4382
+ }
4383
+ return {
4384
+ package: `${pkg.name}@${version}`,
4385
+ files: collected.files.length,
4386
+ asset,
4387
+ gitInstall: commit ? `git+https://github.com/${args.owner}/${args.repo}.git#${commit}` : '',
4388
+ howToUse: [
4389
+ '下载 .tgz 解压后,用 Plugins → Add plugin 指向解压出来的目录;',
4390
+ '或直接把 gitInstall 那串交给 dsh plugin add;',
4391
+ '市场索引里已经用同一套 git 源,Discover 安装同样不需要 npm。',
4392
+ ],
4393
+ }
4394
+ },
4395
+ })
4396
+
4397
+ register({
4398
+ name: 'plugin_market_readiness',
4399
+ description:
4400
+ '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).',
4401
+ parameters: {
4402
+ type: 'object',
4403
+ properties: {
4404
+ dir: { type: 'string', description: 'Local plugin directory' },
4405
+ owner: { type: 'string' },
4406
+ repo: { type: 'string' },
4407
+ },
4408
+ required: ['dir', 'owner', 'repo'],
4409
+ additionalProperties: false,
4410
+ },
4411
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4412
+ async execute(args, exec) {
4413
+ return marketReadiness(gh, cfg, { owner: args.owner, repo: args.repo, dir: resolveDir(args.dir, exec) })
4414
+ },
4415
+ })
4416
+
4417
+ register({
4418
+ name: 'gh_pull_detail',
4419
+ description:
4420
+ '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.',
4421
+ parameters: {
4422
+ type: 'object',
4423
+ properties: {
4424
+ owner: { type: 'string' },
4425
+ name: { type: 'string' },
4426
+ number: { type: 'integer', minimum: 1 },
4427
+ },
4428
+ required: ['owner', 'name', 'number'],
4429
+ additionalProperties: false,
4430
+ },
4431
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4432
+ async execute(args) {
4433
+ return gh.pullDetail(args.owner, args.name, args.number)
4434
+ },
4435
+ })
4436
+
4437
+ register({
4438
+ name: 'gh_pull_comment',
4439
+ description:
4440
+ '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.',
4441
+ parameters: {
4442
+ type: 'object',
4443
+ properties: {
4444
+ owner: { type: 'string' },
4445
+ name: { type: 'string' },
4446
+ number: { type: 'integer', minimum: 1 },
4447
+ body: { type: 'string' },
4448
+ path: { type: 'string', description: 'File path for an inline comment' },
4449
+ line: { type: 'integer', minimum: 1, description: 'Line number in the new file, for an inline comment' },
4450
+ },
4451
+ required: ['owner', 'name', 'number', 'body'],
4452
+ additionalProperties: false,
4453
+ },
4454
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4455
+ async execute(args) {
4456
+ await requireWrite('pullWrite')
4457
+ return audited('pull.comment', `${args.owner}/${args.name}#${args.number}`, () =>
4458
+ gh.addPullComment(args.owner, args.name, args.number, args.body, args.path ? { path: args.path, number: args.line } : null),
4459
+ )
4460
+ },
4461
+ })
4462
+
4463
+ register({
4464
+ name: 'gh_pull_review',
4465
+ description:
4466
+ '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.',
4467
+ parameters: {
4468
+ type: 'object',
4469
+ properties: {
4470
+ owner: { type: 'string' },
4471
+ name: { type: 'string' },
4472
+ number: { type: 'integer', minimum: 1 },
4473
+ event: { type: 'string', enum: ['APPROVE', 'REQUEST_CHANGES', 'COMMENT'] },
4474
+ body: { type: 'string' },
4475
+ },
4476
+ required: ['owner', 'name', 'number', 'event'],
4477
+ additionalProperties: false,
4478
+ },
4479
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4480
+ async execute(args) {
4481
+ await requireWrite('pullWrite')
4482
+ return audited('pull.review', `${args.owner}/${args.name}#${args.number} ${args.event}`, () =>
4483
+ gh.submitReview(args.owner, args.name, args.number, args.event, args.body),
4484
+ )
4485
+ },
4486
+ })
4487
+
4488
+ register({
4489
+ name: 'gh_issue_update',
4490
+ description:
4491
+ 'Update an issue or pull request: title, body, state (open/closed), labels, assignees, milestone. Only the fields you pass are changed.',
4492
+ parameters: {
4493
+ type: 'object',
4494
+ properties: {
4495
+ owner: { type: 'string' },
4496
+ name: { type: 'string' },
4497
+ number: { type: 'integer', minimum: 1 },
4498
+ title: { type: 'string' },
4499
+ body: { type: 'string' },
4500
+ state: { type: 'string', enum: ['open', 'closed'] },
4501
+ labels: { type: 'array', items: { type: 'string' } },
4502
+ assignees: { type: 'array', items: { type: 'string' } },
4503
+ milestone: { type: 'integer', description: 'Milestone number, or null to clear' },
4504
+ },
4505
+ required: ['owner', 'name', 'number'],
4506
+ additionalProperties: false,
4507
+ },
4508
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4509
+ async execute(args) {
4510
+ await requireWrite('issueWrite')
4511
+ const patch = { ...args }
4512
+ delete patch.owner
4513
+ delete patch.name
4514
+ delete patch.number
4515
+ return audited('issue.update', `${args.owner}/${args.name}#${args.number}`, () =>
4516
+ gh.updateIssue(args.owner, args.name, args.number, patch),
4517
+ )
4518
+ },
4519
+ })
4520
+
4521
+ register({
4522
+ name: 'gh_workflows',
4523
+ description: 'List the repository workflows and their state, so a workflow can be dispatched by file name.',
4524
+ parameters: {
4525
+ type: 'object',
4526
+ properties: { owner: { type: 'string' }, name: { type: 'string' } },
4527
+ required: ['owner', 'name'],
4528
+ additionalProperties: false,
4529
+ },
4530
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4531
+ async execute(args) {
4532
+ return gh.listWorkflows(args.owner, args.name)
4533
+ },
4534
+ })
4535
+
4536
+ register({
4537
+ name: 'gh_workflow_dispatch',
4538
+ description:
4539
+ 'Manually trigger a workflow (workflow_dispatch) with optional inputs. Needs workflows: write and the workflow must declare workflow_dispatch. Confirm with the user first.',
4540
+ parameters: {
4541
+ type: 'object',
4542
+ properties: {
4543
+ owner: { type: 'string' },
4544
+ name: { type: 'string' },
4545
+ workflow: { type: 'string', description: 'Workflow file name (publish.yml) or id' },
4546
+ ref: { type: 'string', description: 'Branch or tag, default main' },
4547
+ inputs: { type: 'object', description: 'Inputs the workflow declares' },
4548
+ confirm: { type: 'boolean', description: 'Must be true' },
4549
+ },
4550
+ required: ['owner', 'name', 'workflow', 'confirm'],
4551
+ additionalProperties: false,
4552
+ },
4553
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4554
+ async execute(args) {
4555
+ if (args.confirm !== true) throw new Error('触发 workflow 需要确认:传 confirm: true')
4556
+ await requireWrite('workflowsWrite')
4557
+ return audited('workflow.dispatch', `${args.owner}/${args.name}:${args.workflow}`, () =>
4558
+ gh.dispatchNamedWorkflow(args.owner, args.name, args.workflow, args.ref, args.inputs),
4559
+ )
4560
+ },
4561
+ })
4562
+
4563
+ register({
4564
+ name: 'gh_actions_log',
4565
+ description:
4566
+ '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.',
4567
+ parameters: {
4568
+ type: 'object',
4569
+ properties: {
4570
+ owner: { type: 'string' },
4571
+ name: { type: 'string' },
4572
+ runId: { type: 'integer', minimum: 1 },
4573
+ tailLines: { type: 'integer', minimum: 10, maximum: 2000, description: 'How many trailing lines, default 120' },
4574
+ },
4575
+ required: ['owner', 'name', 'runId'],
4576
+ additionalProperties: false,
4577
+ },
4578
+ output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: String(value.tail || value.name || '') }] },
4579
+ async execute(args) {
4580
+ return gh.runLog(args.owner, args.name, args.runId, args.tailLines || 120)
4581
+ },
4582
+ })
4583
+
4584
+ register({
4585
+ name: 'gh_notifications',
4586
+ description:
4587
+ 'List GitHub notifications (mentions, review requests, CI failures, assigned issues). Requires a user connection (App user authorization, PAT or environment token): an installation token cannot read notifications. Set all=true for read threads too.',
4588
+ parameters: {
4589
+ type: 'object',
4590
+ properties: {
4591
+ all: { type: 'boolean', description: 'Include already-read threads' },
4592
+ participating: { type: 'boolean', description: 'Only threads you participate in' },
4593
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
4594
+ },
4595
+ additionalProperties: false,
4596
+ },
4597
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4598
+ async execute(args) {
4599
+ return gh.listNotifications(args)
4600
+ },
4601
+ })
4602
+
4603
+ register({
4604
+ name: 'gh_notifications_read',
4605
+ description: 'Mark notifications read: pass ids for selected threads, or all=true to mark everything read. Writes are audited.',
4606
+ parameters: {
4607
+ type: 'object',
4608
+ properties: {
4609
+ ids: { type: 'array', items: { type: 'string' }, description: 'Notification thread ids' },
4610
+ all: { type: 'boolean', description: 'Mark every thread read' },
4611
+ },
4612
+ additionalProperties: false,
4613
+ },
4614
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4615
+ async execute(args) {
4616
+ return audited('notifications.read', args.all ? 'all' : (args.ids || []).join(','), () => gh.markNotificationsRead(args))
4617
+ },
4618
+ })
4619
+
4620
+ register({
4621
+ name: 'gh_code_search',
4622
+ description:
4623
+ 'Search code across GitHub or inside one repository. Requires a user connection (an installation token cannot use the code search API). Rate limited to about 10 requests per minute.',
4624
+ parameters: {
4625
+ type: 'object',
4626
+ properties: {
4627
+ q: { type: 'string', description: 'Search terms, GitHub code search syntax' },
4628
+ owner: { type: 'string', description: 'Restrict to this owner' },
4629
+ name: { type: 'string', description: 'Restrict to this repository' },
4630
+ limit: { type: 'integer', minimum: 1, maximum: 50 },
4631
+ },
4632
+ required: ['q'],
4633
+ additionalProperties: false,
4634
+ },
4635
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4636
+ async execute(args) {
4637
+ return gh.searchCode(args.q, args)
4638
+ },
4639
+ })
4640
+
4641
+ register({
4642
+ name: 'gh_releases',
4643
+ description: 'List repository releases with their assets and download URLs.',
4644
+ parameters: {
4645
+ type: 'object',
4646
+ properties: { owner: { type: 'string' }, name: { type: 'string' } },
4647
+ required: ['owner', 'name'],
4648
+ additionalProperties: false,
4649
+ },
4650
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4651
+ async execute(args) {
4652
+ return gh.listReleases(args.owner, args.name)
4653
+ },
4654
+ })
4655
+
4656
+ register({
4657
+ name: 'gh_commits',
4658
+ description: 'List recent commits of a branch or ref with author, date and message subject.',
4659
+ parameters: {
4660
+ type: 'object',
4661
+ properties: {
4662
+ owner: { type: 'string' },
4663
+ name: { type: 'string' },
4664
+ ref: { type: 'string', description: 'Branch, tag or sha; default the repository default branch' },
4665
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
4666
+ },
4667
+ required: ['owner', 'name'],
4668
+ additionalProperties: false,
4669
+ },
4670
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4671
+ async execute(args) {
4672
+ return gh.listCommits(args.owner, args.name, args)
4673
+ },
4674
+ })
4675
+
4676
+ register({
4677
+ name: 'gh_compare',
4678
+ description: 'Compare two refs: ahead/behind counts, commits and changed files. Use it to review a branch before opening a pull request.',
4679
+ parameters: {
4680
+ type: 'object',
4681
+ properties: {
4682
+ owner: { type: 'string' },
4683
+ name: { type: 'string' },
4684
+ base: { type: 'string', description: 'Base ref, for example main' },
4685
+ head: { type: 'string', description: 'Head ref, for example feature/x' },
4686
+ },
4687
+ required: ['owner', 'name', 'base', 'head'],
4688
+ additionalProperties: false,
4689
+ },
4690
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4691
+ async execute(args) {
4692
+ return gh.compareRefs(args.owner, args.name, args.base, args.head)
4693
+ },
4694
+ })
4695
+
2973
4696
  register({
2974
4697
  name: 'plugin_publish_status',
2975
4698
  description: 'Read a publish job by id, including each step state and detail.',