@zhin.js/adapter-github 1.0.1 → 1.1.2

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +1212 -0
  2. package/README.md +73 -195
  3. package/adapters/github/index.js +51 -0
  4. package/adapters/github/index.ts +59 -0
  5. package/agents/github/agent.json +20 -0
  6. package/agents/github/boundaries.md +3 -0
  7. package/agents/github/conventions.md +3 -0
  8. package/agents/github/skills/github-account/SKILL.md +20 -0
  9. package/agents/github/skills/github-account/handlers.js +116 -0
  10. package/agents/github/skills/github-account/handlers.ts +136 -0
  11. package/agents/github/skills/github-account/tools/bind/index.js +13 -0
  12. package/agents/github/skills/github-account/tools/bind/index.ts +13 -0
  13. package/agents/github/skills/github-account/tools/install/index.js +13 -0
  14. package/agents/github/skills/github-account/tools/install/index.ts +13 -0
  15. package/agents/github/skills/github-account/tools/unbind/index.js +13 -0
  16. package/agents/github/skills/github-account/tools/unbind/index.ts +13 -0
  17. package/agents/github/skills/github-account/tools/whoami/index.js +13 -0
  18. package/agents/github/skills/github-account/tools/whoami/index.ts +13 -0
  19. package/agents/github/skills/github-cli/SKILL.md +47 -0
  20. package/agents/github/skills/github-repository/SKILL.md +21 -0
  21. package/agents/github/skills/github-repository/handlers.js +77 -0
  22. package/agents/github/skills/github-repository/handlers.ts +113 -0
  23. package/agents/github/skills/github-repository/tools/create_pr/index.js +20 -0
  24. package/agents/github/skills/github-repository/tools/create_pr/index.ts +20 -0
  25. package/agents/github/skills/github-repository/tools/patch_file/index.js +19 -0
  26. package/agents/github/skills/github-repository/tools/patch_file/index.ts +19 -0
  27. package/agents/github/skills/github-repository/tools/prepare_workspace/index.js +15 -0
  28. package/agents/github/skills/github-repository/tools/prepare_workspace/index.ts +15 -0
  29. package/agents/github/skills/github-repository/tools/push_branch/index.js +18 -0
  30. package/agents/github/skills/github-repository/tools/push_branch/index.ts +18 -0
  31. package/agents/github/skills/github-subscriptions/SKILL.md +20 -0
  32. package/agents/github/skills/github-subscriptions/handlers.js +101 -0
  33. package/agents/github/skills/github-subscriptions/handlers.ts +119 -0
  34. package/agents/github/skills/github-subscriptions/tools/star/index.js +16 -0
  35. package/agents/github/skills/github-subscriptions/tools/star/index.ts +16 -0
  36. package/agents/github/skills/github-subscriptions/tools/subscribe/index.js +16 -0
  37. package/agents/github/skills/github-subscriptions/tools/subscribe/index.ts +16 -0
  38. package/agents/github/skills/github-subscriptions/tools/subscriptions/index.js +13 -0
  39. package/agents/github/skills/github-subscriptions/tools/subscriptions/index.ts +13 -0
  40. package/agents/github/skills/github-subscriptions/tools/unsubscribe/index.js +15 -0
  41. package/agents/github/skills/github-subscriptions/tools/unsubscribe/index.ts +15 -0
  42. package/agents/github/system.md +3 -0
  43. package/commands/github/endpoint/add/[id]/index.js +3 -0
  44. package/commands/github/endpoint/add/[id]/index.ts +3 -0
  45. package/commands/github/endpoint/definition.js +23 -0
  46. package/commands/github/endpoint/definition.ts +23 -0
  47. package/commands/github/endpoint/list/index.js +3 -0
  48. package/commands/github/endpoint/list/index.ts +3 -0
  49. package/commands/github/endpoint/remove/[id]/index.js +3 -0
  50. package/commands/github/endpoint/remove/[id]/index.ts +3 -0
  51. package/lib/client.d.ts +36 -0
  52. package/lib/client.js +44 -0
  53. package/lib/endpoint.d.ts +32 -22
  54. package/lib/endpoint.js +125 -145
  55. package/lib/gh-client.d.ts +73 -1
  56. package/lib/gh-client.js +99 -1
  57. package/lib/github-channel-context.d.ts +16 -0
  58. package/lib/github-channel-context.js +31 -0
  59. package/lib/github-runtime-state.d.ts +1 -0
  60. package/lib/github-runtime-state.js +6 -0
  61. package/lib/index.d.ts +7 -32
  62. package/lib/index.js +7 -385
  63. package/lib/oauth-users.d.ts +33 -0
  64. package/lib/oauth-users.js +38 -0
  65. package/lib/protocol.d.ts +72 -0
  66. package/lib/protocol.js +281 -0
  67. package/lib/types.d.ts +0 -18
  68. package/lib/types.js +2 -4
  69. package/lib/webhook.d.ts +14 -0
  70. package/lib/webhook.js +88 -0
  71. package/lib/workspace-manager.d.ts +21 -0
  72. package/lib/workspace-manager.js +154 -0
  73. package/package.json +93 -23
  74. package/plugin.js +38 -0
  75. package/prompt-sections/platform/index.js +16 -0
  76. package/prompt-sections/platform/index.ts +16 -0
  77. package/schema.json +137 -0
  78. package/src/client.ts +62 -0
  79. package/src/endpoint.ts +145 -150
  80. package/src/gh-client.ts +131 -0
  81. package/src/github-channel-context.ts +46 -0
  82. package/src/github-runtime-state.ts +7 -0
  83. package/src/index.ts +48 -431
  84. package/src/oauth-users.ts +47 -0
  85. package/src/protocol.ts +372 -0
  86. package/src/types.ts +0 -22
  87. package/src/webhook.ts +130 -0
  88. package/src/workspace-manager.ts +168 -0
  89. package/lib/adapter.d.ts +0 -64
  90. package/lib/adapter.d.ts.map +0 -1
  91. package/lib/adapter.js +0 -416
  92. package/lib/adapter.js.map +0 -1
  93. package/lib/agent-prompt.d.ts +0 -3
  94. package/lib/agent-prompt.d.ts.map +0 -1
  95. package/lib/agent-prompt.js +0 -82
  96. package/lib/agent-prompt.js.map +0 -1
  97. package/lib/endpoint.d.ts.map +0 -1
  98. package/lib/endpoint.js.map +0 -1
  99. package/lib/gh-client.d.ts.map +0 -1
  100. package/lib/gh-client.js.map +0 -1
  101. package/lib/index.d.ts.map +0 -1
  102. package/lib/index.js.map +0 -1
  103. package/lib/register-github-mcp.d.ts +0 -6
  104. package/lib/register-github-mcp.d.ts.map +0 -1
  105. package/lib/register-github-mcp.js +0 -35
  106. package/lib/register-github-mcp.js.map +0 -1
  107. package/lib/types.d.ts.map +0 -1
  108. package/lib/types.js.map +0 -1
  109. package/plugin.yml +0 -3
  110. package/skills/github/SKILL.md +0 -266
  111. package/src/adapter.ts +0 -448
  112. package/src/agent-prompt.ts +0 -99
  113. package/src/register-github-mcp.ts +0 -60
@@ -0,0 +1,372 @@
1
+ /**
2
+ * GitHub webhook / comment helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+
6
+ import { createHmac, timingSafeEqual } from 'node:crypto';
7
+ import type { IncomingMessage } from 'node:http';
8
+ import { isMediaRef, type ConversationRef } from '@zhin.js/im-contract';
9
+ import { formatCompact, getLogger } from '@zhin.js/logger';
10
+
11
+ const logger = getLogger('github');
12
+ import {
13
+ buildChannelId,
14
+ type GenericWebhookPayload,
15
+ type IssueCommentPayload,
16
+ type PRReviewCommentPayload,
17
+ type PRReviewPayload,
18
+ } from './types.js';
19
+
20
+ export type {
21
+ EventType,
22
+ GenericWebhookPayload,
23
+ GitHubComment,
24
+ GitHubIssue,
25
+ GitHubOAuthUser,
26
+ GitHubPR,
27
+ GitHubRepo,
28
+ GitHubUser,
29
+ IssueCommentPayload,
30
+ ParsedChannel,
31
+ PRReviewCommentPayload,
32
+ PRReviewPayload,
33
+ Subscription,
34
+ } from './types.js';
35
+
36
+ export { buildChannelId, parseChannelId } from './types.js';
37
+
38
+ /** One expanded GitHub endpoint configuration produced by AdapterIndex. */
39
+ export interface GithubEndpointConfig {
40
+ readonly id: string;
41
+ readonly host?: string;
42
+ readonly app_id: string | number;
43
+ readonly private_key: string;
44
+ readonly webhook_secret?: string;
45
+ readonly webhook_path?: string;
46
+ readonly auto_reply_repos?: readonly string[];
47
+ readonly bot_login?: string;
48
+ readonly workspace_root?: string;
49
+ }
50
+
51
+ export interface ResolvedGithubConfig {
52
+ readonly context: 'github';
53
+ readonly id: string;
54
+ readonly host?: string;
55
+ readonly appId: string | number;
56
+ readonly privateKey: string;
57
+ readonly webhookSecret?: string;
58
+ readonly webhookPath: string;
59
+ readonly autoReplyRepos: readonly string[];
60
+ readonly botLogin?: string;
61
+ readonly workspaceRoot: string;
62
+ }
63
+
64
+ export interface GithubWireSegment {
65
+ readonly type: string;
66
+ readonly data?: Record<string, unknown>;
67
+ }
68
+
69
+ export interface GithubInboundComment {
70
+ readonly id: string;
71
+ readonly channelId: string;
72
+ readonly sender: string;
73
+ readonly content: string;
74
+ readonly repo: string;
75
+ readonly kind: 'issue_comment' | 'pr_review_comment' | 'pr_review';
76
+ readonly createdAt: number;
77
+ }
78
+
79
+ /**
80
+ * 入站归一化 → ConversationRef:Issue/PR 评论区即仓库容器内的 channel 会话,
81
+ * 仓库(owner/repo)进 `parent`。出站侧用 `parseChannelId(conversation.id)`
82
+ * 在平台边界还原 repo/type/number。
83
+ */
84
+ export function githubInboundConversation(
85
+ endpointKey: string,
86
+ comment: GithubInboundComment,
87
+ ): ConversationRef {
88
+ return {
89
+ endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
90
+ kind: 'channel',
91
+ id: comment.channelId,
92
+ parent: { kind: 'channel', id: comment.repo },
93
+ };
94
+ }
95
+
96
+ export function resolveGithubConfig(config: GithubEndpointConfig): ResolvedGithubConfig {
97
+ const id = typeof config.id === 'string' ? config.id.trim() : '';
98
+ if (!id) throw new TypeError('GitHub endpoint requires a non-empty id');
99
+ const appIdRaw = config.app_id != null ? String(config.app_id).trim() : '';
100
+ const appId = appIdRaw ? (Number(appIdRaw) || appIdRaw) : undefined;
101
+ const privateKey = typeof config.private_key === 'string'
102
+ ? config.private_key.trim()
103
+ : '';
104
+ if (!appId || !privateKey) {
105
+ throw new TypeError('GitHub endpoint requires app_id and private_key');
106
+ }
107
+ const webhookSecret = config.webhook_secret;
108
+ const host = config.host;
109
+ const webhookPath = normalizeWebhookPath(config.webhook_path ?? '/github/webhook');
110
+ const autoReplyRepos = [...(config.auto_reply_repos ?? [])];
111
+ const botLogin = config.bot_login;
112
+ const workspaceRoot = config.workspace_root ?? 'data/github-workspaces';
113
+
114
+ return {
115
+ context: 'github',
116
+ id,
117
+ ...(host ? { host } : {}),
118
+ appId,
119
+ privateKey,
120
+ ...(webhookSecret ? { webhookSecret } : {}),
121
+ webhookPath,
122
+ autoReplyRepos,
123
+ ...(botLogin ? { botLogin } : {}),
124
+ workspaceRoot,
125
+ };
126
+ }
127
+
128
+ export function normalizeWebhookPath(path: string): string {
129
+ const trimmed = path.trim() || '/github/webhook';
130
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
131
+ }
132
+
133
+ export function shouldAutoReplyRepo(
134
+ config: Pick<ResolvedGithubConfig, 'autoReplyRepos'>,
135
+ repo: string,
136
+ ): boolean {
137
+ const list = config.autoReplyRepos;
138
+ if (!list.length) return false;
139
+ const key = repo.toLowerCase();
140
+ return list.some((r) => r.toLowerCase() === key);
141
+ }
142
+
143
+ /** Prepend synthetic @bot for auto_reply repos (gateway text path). */
144
+ export function enrichInboundContent(
145
+ content: string,
146
+ config: Pick<ResolvedGithubConfig, 'autoReplyRepos' | 'botLogin'>,
147
+ botLogin: string | undefined,
148
+ repo: string,
149
+ ): string {
150
+ const login = config.botLogin || botLogin;
151
+ if (!login || !shouldAutoReplyRepo(config, repo)) return content;
152
+ if (content.includes(`@${login}`)) return content;
153
+ return `@${login} ${content}`;
154
+ }
155
+
156
+ /** Build inbound text for OutboundMessageService.receive from markdown/comment body. */
157
+ export function formatInboundContent(body: string): string {
158
+ return body;
159
+ }
160
+
161
+ /** Build markdown body for Issue/PR comment send. */
162
+ export function formatOutboundBody(payload: unknown): string {
163
+ if (typeof payload === 'string') return payload;
164
+ if (payload == null) return '';
165
+ if (!Array.isArray(payload)) {
166
+ if (typeof payload === 'object' && payload !== null && 'text' in payload) {
167
+ return String((payload as { text?: unknown }).text ?? '');
168
+ }
169
+ return String(payload);
170
+ }
171
+ return payload.map((seg) => {
172
+ if (typeof seg === 'string') return seg;
173
+ const item = seg as GithubWireSegment;
174
+ switch (item.type) {
175
+ case 'text':
176
+ return String(item.data?.text ?? '');
177
+ case 'mention':
178
+ case 'at':
179
+ return `@${item.data?.name || item.data?.id || item.data?.target || ''}`;
180
+ case 'image':
181
+ case 'audio':
182
+ case 'video':
183
+ case 'file':
184
+ return formatMediaSegment(item);
185
+ case 'link':
186
+ return `[${item.data?.text || item.data?.url || ''}](${item.data?.url || ''})`;
187
+ default:
188
+ return String(item.data?.text ?? `[${item.type}]`);
189
+ }
190
+ }).join('');
191
+ }
192
+
193
+ /**
194
+ * 媒体段 → GitHub markdown(canonical MediaRef 唯一来源)。
195
+ * GitHub 评论只能消费远程 URL(无上传面),kind=url 直发;
196
+ * base64 / path / file 不可投递,warn + 丢弃。
197
+ */
198
+ function formatMediaSegment(seg: GithubWireSegment): string {
199
+ const media = seg.data?.media;
200
+ if (!isMediaRef(media)) {
201
+ logger.warn(formatCompact({
202
+ op: 'github_outbound_media_dropped',
203
+ type: seg.type,
204
+ reason: 'missing_media_ref',
205
+ }));
206
+ return '';
207
+ }
208
+ if (media.kind !== 'url') {
209
+ logger.warn(formatCompact({
210
+ op: 'github_outbound_media_dropped',
211
+ type: seg.type,
212
+ reason: `unsupported_kind:${media.kind}`,
213
+ }));
214
+ return '';
215
+ }
216
+ if (seg.type === 'image') {
217
+ const alt = typeof seg.data?.alt === 'string' && seg.data.alt
218
+ ? seg.data.alt
219
+ : media.file_name || 'image';
220
+ return `![${alt}](${media.value})`;
221
+ }
222
+ const label = media.file_name || seg.type;
223
+ return `[${label}](${media.value})`;
224
+ }
225
+
226
+ export function verifyWebhookSignature(
227
+ secret: string,
228
+ rawBody: string,
229
+ signatureHeader: string | undefined,
230
+ ): boolean {
231
+ if (!signatureHeader?.startsWith('sha256=')) return false;
232
+ const expected = `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`;
233
+ try {
234
+ const a = Buffer.from(signatureHeader);
235
+ const b = Buffer.from(expected);
236
+ if (a.length !== b.length) return false;
237
+ return timingSafeEqual(a, b);
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ export function headerValue(
244
+ headers: IncomingMessage['headers'],
245
+ name: string,
246
+ ): string {
247
+ const raw = headers[name] ?? headers[name.toLowerCase()];
248
+ if (Array.isArray(raw)) return raw[0] ?? '';
249
+ return raw ?? '';
250
+ }
251
+
252
+ export async function readTextBody(
253
+ request: IncomingMessage,
254
+ options: { readonly limit?: number } = {},
255
+ ): Promise<string> {
256
+ const limit = options.limit ?? 1_048_576;
257
+ const chunks: Buffer[] = [];
258
+ let size = 0;
259
+ for await (const chunk of request) {
260
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
261
+ size += buffer.length;
262
+ if (size > limit) {
263
+ request.destroy();
264
+ throw new Error(`Request body exceeds ${limit} bytes`);
265
+ }
266
+ chunks.push(buffer);
267
+ }
268
+ return Buffer.concat(chunks).toString('utf8');
269
+ }
270
+
271
+ export function parseIssueCommentInbound(payload: IssueCommentPayload): GithubInboundComment | null {
272
+ if (payload.action !== 'created' || !payload.comment) return null;
273
+ const repo = payload.repository.full_name;
274
+ const isPR = 'pull_request' in (payload.issue as object);
275
+ return {
276
+ id: String(payload.comment.id),
277
+ channelId: buildChannelId(repo, isPR ? 'pr' : 'issue', payload.issue.number),
278
+ sender: payload.sender.login,
279
+ content: payload.comment.body,
280
+ repo,
281
+ kind: 'issue_comment',
282
+ createdAt: new Date(payload.comment.created_at).getTime(),
283
+ };
284
+ }
285
+
286
+ export function parsePrReviewCommentInbound(payload: PRReviewCommentPayload): GithubInboundComment | null {
287
+ if (payload.action !== 'created' || !payload.comment) return null;
288
+ const repo = payload.repository.full_name;
289
+ const body = payload.comment.path
290
+ ? `**${payload.comment.path}**\n${payload.comment.diff_hunk ? `\`\`\`diff\n${payload.comment.diff_hunk}\n\`\`\`\n` : ''}${payload.comment.body}`
291
+ : payload.comment.body;
292
+ return {
293
+ id: String(payload.comment.id),
294
+ channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
295
+ sender: payload.sender.login,
296
+ content: body,
297
+ repo,
298
+ kind: 'pr_review_comment',
299
+ createdAt: new Date(payload.comment.created_at).getTime(),
300
+ };
301
+ }
302
+
303
+ export function parsePrReviewInbound(payload: PRReviewPayload): GithubInboundComment | null {
304
+ if (payload.action !== 'submitted' || !payload.review.body) return null;
305
+ const repo = payload.repository.full_name;
306
+ const stateLabel: Record<string, string> = {
307
+ approved: '✅ APPROVED',
308
+ changes_requested: '🔄 CHANGES REQUESTED',
309
+ commented: '💬 COMMENTED',
310
+ dismissed: '❌ DISMISSED',
311
+ };
312
+ const body = `**[${stateLabel[payload.review.state] || payload.review.state}]**\n${payload.review.body}`;
313
+ return {
314
+ id: String(payload.review.id),
315
+ channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
316
+ sender: payload.sender.login,
317
+ content: body,
318
+ repo,
319
+ kind: 'pr_review',
320
+ createdAt: new Date(payload.review.submitted_at).getTime(),
321
+ };
322
+ }
323
+
324
+ export function formatNotification(event: string, p: GenericWebhookPayload): string {
325
+ const repo = p.repository.full_name;
326
+ const sender = p.sender.login;
327
+ const repoUrl = p.repository.html_url;
328
+ switch (event) {
329
+ case 'push': {
330
+ const branch = p.ref?.replace('refs/heads/', '') || '?';
331
+ const commits = p.commits || [];
332
+ const compareUrl = commits.length >= 2
333
+ ? `${repoUrl}/compare/${commits[0].id.substring(0, 12)}...${commits[commits.length - 1].id.substring(0, 12)}`
334
+ : commits.length === 1 ? `${repoUrl}/commit/${commits[0].id}` : '';
335
+ let msg = `📦 ${repo}\n🌿 ${sender} pushed ${commits.length} commit(s) to \`${branch}\`\n`;
336
+ if (commits.length) {
337
+ msg += '\n';
338
+ msg += commits.slice(0, 5).map((c) =>
339
+ ` • [\`${c.id.substring(0, 7)}\`](${repoUrl}/commit/${c.id}) ${c.message.split('\n')[0]}`,
340
+ ).join('\n');
341
+ if (commits.length > 5) msg += `\n ... +${commits.length - 5} more`;
342
+ }
343
+ if (compareUrl) msg += `\n\n🔗 ${compareUrl}`;
344
+ return msg;
345
+ }
346
+ case 'issues': {
347
+ const i = p.issue!;
348
+ const act = p.action === 'opened' ? '📝 opened' : p.action === 'closed' ? '✅ closed' : `🔄 ${p.action || 'updated'}`;
349
+ return `🐛 ${repo}\n👤 ${sender} ${act} issue #${i.number}\n📌 ${i.title}\n🔗 ${i.html_url}`;
350
+ }
351
+ case 'star': {
352
+ const starred = p.action !== 'deleted';
353
+ return `${starred ? '⭐' : '💔'} ${repo}\n👤 ${sender} ${starred ? 'starred' : 'unstarred'}\n🔗 ${repoUrl}`;
354
+ }
355
+ case 'fork':
356
+ return `🍴 ${repo}\n👤 ${sender} forked → ${p.forkee!.full_name}\n🔗 ${p.forkee!.html_url}`;
357
+ case 'pull_request': {
358
+ const pr = p.pull_request!;
359
+ const act = p.action === 'opened' ? '📝 opened'
360
+ : p.action === 'closed' ? (pr.state === 'closed' ? '❌ closed' : '✅ merged')
361
+ : `🔄 ${p.action || 'updated'}`;
362
+ return `🔀 ${repo}\n👤 ${sender} ${act} PR #${pr.number}\n📌 ${pr.title}\n🌿 ${pr.head.ref} → ${pr.base.ref}\n🔗 ${pr.html_url}`;
363
+ }
364
+ default:
365
+ return `📬 ${repo}\n📡 ${event}${p.action ? ` (${p.action})` : ''} by ${sender}\n🔗 ${repoUrl}`;
366
+ }
367
+ }
368
+
369
+ /** Parse @mentions in markdown into a flat display string (gateway text path). */
370
+ export function parseMarkdownMentions(md: string): string {
371
+ return md;
372
+ }
package/src/types.ts CHANGED
@@ -1,25 +1,3 @@
1
- // ── Endpoint 配置 ─────────────────────────────────────────────────────────
2
- // 基于 gh CLI 认证:需要系统已安装并认证 gh CLI
3
- // 认证方式:gh auth login
4
-
5
- export interface GitHubEndpointConfig {
6
- context: 'github';
7
- /** Endpoint 标识名称 */
8
- name: string;
9
- /** GitHub Enterprise 主机名(默认 github.com) */
10
- host?: string;
11
- /** GitHub App ID */
12
- app_id?: string | number;
13
- /** GitHub App 私钥(PEM 内容或文件路径) */
14
- private_key?: string;
15
- /** Webhook Secret(配置后启用 Webhook 接收事件,不配置则使用轮询) */
16
- webhook_secret?: string;
17
- /** Webhook 路由路径(默认 /github/webhook) */
18
- webhook_path?: string;
19
- /** 事件轮询间隔(秒,默认 60,Webhook 模式下作为降级备选) */
20
- poll_interval?: number;
21
- }
22
-
23
1
  // ── Channel ID ───────────────────────────────────────────────────────
24
2
  // 格式: {owner}/{repo}/issues/{number} 或 {owner}/{repo}/pull/{number}
25
3
 
package/src/webhook.ts ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * GitHub webhook HTTP: verify → parse → admit inbound comments.
3
+ */
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
6
+ import { formatCompact, getLogger } from '@zhin.js/logger';
7
+ import {
8
+ headerValue,
9
+ parseIssueCommentInbound,
10
+ parsePrReviewCommentInbound,
11
+ parsePrReviewInbound,
12
+ readTextBody,
13
+ verifyWebhookSignature,
14
+ type GithubInboundComment,
15
+ type IssueCommentPayload,
16
+ type PRReviewCommentPayload,
17
+ type PRReviewPayload,
18
+ type ResolvedGithubConfig,
19
+ } from './protocol.js';
20
+
21
+ const logger = getLogger('github');
22
+
23
+ export interface GithubWebhookHandler {
24
+ readonly config: ResolvedGithubConfig;
25
+ admitPlatform(name: string, event: unknown): void;
26
+ admit(comment: GithubInboundComment): void;
27
+ }
28
+
29
+ export function registerGithubWebhookRoutes(
30
+ http: HttpHost,
31
+ handler: GithubWebhookHandler,
32
+ ): HttpRouteRegistration[] {
33
+ const routePath = handler.config.webhookPath;
34
+ return [
35
+ http.route('POST', routePath, async (request, response) => {
36
+ await handleGithubWebhookRequest(request, response, handler);
37
+ }, { summary: 'GitHub webhook', tags: ['github'] }),
38
+ ];
39
+ }
40
+
41
+ export async function handleGithubWebhookRequest(
42
+ request: IncomingMessage,
43
+ response: ServerResponse,
44
+ handler: GithubWebhookHandler,
45
+ ): Promise<void> {
46
+ const secret = handler.config.webhookSecret;
47
+ if (!secret) {
48
+ response.writeHead(503, { 'Content-Type': 'application/json' });
49
+ response.end(JSON.stringify({ error: 'Webhook not configured' }));
50
+ return;
51
+ }
52
+
53
+ const signature = headerValue(request.headers, 'x-hub-signature-256');
54
+ const event = headerValue(request.headers, 'x-github-event');
55
+ const deliveryId = headerValue(request.headers, 'x-github-delivery');
56
+
57
+ if (!signature || !event) {
58
+ response.writeHead(400, { 'Content-Type': 'application/json' });
59
+ response.end(JSON.stringify({ error: 'Missing signature or event header' }));
60
+ return;
61
+ }
62
+
63
+ try {
64
+ const rawBody = await readTextBody(request);
65
+ if (!verifyWebhookSignature(secret, rawBody, signature)) {
66
+ logger.warn(formatCompact({
67
+ op: 'webhook',
68
+ ok: false,
69
+ error: 'invalid signature',
70
+ delivery: deliveryId,
71
+ }));
72
+ response.writeHead(401, { 'Content-Type': 'application/json' });
73
+ response.end(JSON.stringify({ error: 'Invalid signature' }));
74
+ return;
75
+ }
76
+
77
+ let payload: unknown;
78
+ try {
79
+ payload = rawBody ? JSON.parse(rawBody) : {};
80
+ } catch {
81
+ response.writeHead(400, { 'Content-Type': 'application/json' });
82
+ response.end(JSON.stringify({ error: 'Invalid JSON' }));
83
+ return;
84
+ }
85
+
86
+ response.writeHead(200, { 'Content-Type': 'application/json' });
87
+ response.end(JSON.stringify({ ok: true }));
88
+
89
+ void dispatchGithubWebhookPayload(event, payload, handler).catch((e) => {
90
+ logger.error(`Webhook 事件处理失败 (${event}):`, e);
91
+ });
92
+ } catch (error) {
93
+ logger.error('Webhook error:', error);
94
+ if (!response.headersSent) {
95
+ response.writeHead(500, { 'Content-Type': 'application/json' });
96
+ response.end(JSON.stringify({ error: 'Internal Server Error' }));
97
+ }
98
+ }
99
+ }
100
+
101
+ export async function dispatchGithubWebhookPayload(
102
+ event: string,
103
+ payload: unknown,
104
+ handler: GithubWebhookHandler,
105
+ ): Promise<void> {
106
+ if (!payload || typeof payload !== 'object') return;
107
+ const body = payload as Record<string, unknown>;
108
+ const repo = (body.repository as { full_name?: string } | undefined)?.full_name;
109
+ logger.debug(`Webhook: ${event}${(body.action as string) ? `.${body.action}` : ''} ${repo || ''}`);
110
+ handler.admitPlatform(
111
+ typeof body.action === 'string' && body.action ? `${event}.${body.action}` : event,
112
+ payload,
113
+ );
114
+
115
+ if (event === 'issue_comment') {
116
+ const inbound = parseIssueCommentInbound(payload as IssueCommentPayload);
117
+ if (inbound) handler.admit(inbound);
118
+ return;
119
+ }
120
+ if (event === 'pull_request_review_comment') {
121
+ const inbound = parsePrReviewCommentInbound(payload as PRReviewCommentPayload);
122
+ if (inbound) handler.admit(inbound);
123
+ return;
124
+ }
125
+ if (event === 'pull_request_review') {
126
+ const inbound = parsePrReviewInbound(payload as PRReviewPayload);
127
+ if (inbound) handler.admit(inbound);
128
+ }
129
+ // Cross-adapter subscription fan-out deferred (needs multi-adapter send in Runtime).
130
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Managed git workspaces for GitHub App Bot development flow.
3
+ */
4
+ import { spawn } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import type { GhClient, GitHubBotIdentity } from './gh-client.js';
8
+
9
+ const REPO_FULL_NAME_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
10
+ const GIT_REF_ILLEGAL_CHARS = new Set('~^:?*[\\`;');
11
+
12
+ function containsIllegalGitRefCharacter(ref: string): boolean {
13
+ return [...ref].some((character) => {
14
+ const code = character.charCodeAt(0);
15
+ return code <= 31
16
+ || code === 127
17
+ || /\s/u.test(character)
18
+ || GIT_REF_ILLEGAL_CHARS.has(character);
19
+ });
20
+ }
21
+
22
+ /**
23
+ * 校验 GitHub "owner/name" 全名,防止路径穿越与 git 选项注入。
24
+ * 返回通过校验的原值,便于调用方直接使用「已消毒」的变量。
25
+ */
26
+ export function assertRepoFullName(repo: string): string {
27
+ if (
28
+ typeof repo !== 'string' ||
29
+ !REPO_FULL_NAME_RE.test(repo) ||
30
+ repo.split('/').some((seg) => seg === '' || seg.startsWith('-') || /^\.+$/.test(seg))
31
+ ) {
32
+ throw new TypeError(`非法的仓库全名: ${JSON.stringify(repo)}`);
33
+ }
34
+ return repo;
35
+ }
36
+
37
+ /**
38
+ * 校验 git ref 名称,拒绝选项注入(`-` 前缀)与 git 非法字符。
39
+ */
40
+ export function assertGitRefName(ref: string): string {
41
+ if (typeof ref !== 'string' || ref.length === 0) {
42
+ throw new TypeError(`非法的 git ref: ${JSON.stringify(ref)}`);
43
+ }
44
+ if (
45
+ ref.startsWith('-') ||
46
+ ref.includes('..') ||
47
+ containsIllegalGitRefCharacter(ref) ||
48
+ ref.endsWith('/') ||
49
+ ref.endsWith('.')
50
+ ) {
51
+ throw new TypeError(`非法的 git ref: ${JSON.stringify(ref)}`);
52
+ }
53
+ return ref;
54
+ }
55
+
56
+ export class WorkspaceManager {
57
+ constructor(
58
+ private readonly gh: GhClient,
59
+ private readonly rootDir: string,
60
+ ) {}
61
+
62
+ getRepoPath(repo: string): string {
63
+ repo = assertRepoFullName(repo);
64
+ const [owner, name] = repo.split('/');
65
+ return path.join(this.rootDir, owner, name);
66
+ }
67
+
68
+ private runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): Promise<string> {
69
+ return new Promise((resolve, reject) => {
70
+ const proc = spawn('git', args, {
71
+ cwd,
72
+ stdio: ['ignore', 'pipe', 'pipe'],
73
+ env: { ...process.env, ...env },
74
+ });
75
+ let stdout = '';
76
+ let stderr = '';
77
+ proc.stdout.on('data', (d: Buffer) => { stdout += d.toString(); });
78
+ proc.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });
79
+ proc.on('error', (err: NodeJS.ErrnoException) => {
80
+ if (err.code === 'ENOENT') reject(new Error('git 未安装'));
81
+ else reject(err);
82
+ });
83
+ proc.on('close', (code) => {
84
+ if (code === 0) resolve(stdout);
85
+ else reject(new Error(stderr.trim() || `git ${args.join(' ')} failed (${code})`));
86
+ });
87
+ });
88
+ }
89
+
90
+ configureBotGit(repoPath: string, identity: GitHubBotIdentity): Promise<void> {
91
+ return Promise.all([
92
+ this.runGit(repoPath, ['config', 'user.name', identity.login]),
93
+ this.runGit(repoPath, ['config', 'user.email', identity.email]),
94
+ ]).then(() => undefined);
95
+ }
96
+
97
+ async ensureRepo(repo: string): Promise<string> {
98
+ repo = assertRepoFullName(repo);
99
+ if (!this.gh.isAppAuth) {
100
+ throw new Error('GitHub App 认证未配置,无法托管工作区');
101
+ }
102
+ const token = await this.gh.ensureInstallationTokenForRepo(repo);
103
+ if (!token) throw new Error(`无法获取 ${repo} 的 Installation Token`);
104
+
105
+ const repoPath = this.getRepoPath(repo);
106
+ fs.mkdirSync(path.dirname(repoPath), { recursive: true });
107
+
108
+ const identity = await this.gh.getBotIdentity();
109
+ if (!identity) throw new Error('无法解析 GitHub App Bot 身份');
110
+
111
+ const cloneUrl = this.gh.buildCloneUrl(repo, token);
112
+ if (!fs.existsSync(path.join(repoPath, '.git'))) {
113
+ await this.runGit(path.dirname(repoPath), ['clone', cloneUrl, path.basename(repoPath)]);
114
+ } else {
115
+ await this.runGit(repoPath, ['remote', 'set-url', 'origin', cloneUrl]);
116
+ await this.runGit(repoPath, ['fetch', 'origin', '--prune']);
117
+ }
118
+
119
+ await this.configureBotGit(repoPath, identity);
120
+ return repoPath;
121
+ }
122
+
123
+ async checkoutBranch(repo: string, branch: string, baseRef: string): Promise<string> {
124
+ repo = assertRepoFullName(repo);
125
+ branch = assertGitRefName(branch);
126
+ baseRef = assertGitRefName(baseRef);
127
+ const repoPath = await this.ensureRepo(repo);
128
+ const localBranches = await this.runGit(repoPath, ['branch', '--list', branch]);
129
+ if (localBranches.trim()) {
130
+ await this.runGit(repoPath, ['checkout', branch]);
131
+ await this.runGit(repoPath, ['pull', '--rebase', 'origin', branch]).catch(async () => {
132
+ await this.runGit(repoPath, ['fetch', 'origin', branch]);
133
+ });
134
+ return repoPath;
135
+ }
136
+
137
+ const remoteBranch = await this.runGit(repoPath, ['ls-remote', '--heads', 'origin', branch]);
138
+ if (remoteBranch.trim()) {
139
+ await this.runGit(repoPath, ['checkout', '-B', branch, `origin/${branch}`]);
140
+ return repoPath;
141
+ }
142
+
143
+ await this.runGit(repoPath, ['fetch', 'origin', baseRef]);
144
+ await this.runGit(repoPath, ['checkout', '-B', branch, `origin/${baseRef}`]);
145
+ return repoPath;
146
+ }
147
+
148
+ async commitAndPush(repo: string, branch: string, message: string): Promise<string> {
149
+ repo = assertRepoFullName(repo);
150
+ branch = assertGitRefName(branch);
151
+ const repoPath = this.getRepoPath(repo);
152
+ if (!fs.existsSync(repoPath)) {
153
+ throw new Error(`工作区不存在: ${repoPath},请先 github_prepare_workspace`);
154
+ }
155
+
156
+ const token = await this.gh.ensureInstallationTokenForRepo(repo);
157
+ if (!token) throw new Error('Installation Token 不可用');
158
+ await this.runGit(repoPath, ['remote', 'set-url', 'origin', this.gh.buildCloneUrl(repo, token)]);
159
+
160
+ const status = await this.runGit(repoPath, ['status', '--porcelain']);
161
+ if (!status.trim()) return '没有可提交的变更';
162
+
163
+ await this.runGit(repoPath, ['add', '-A']);
164
+ await this.runGit(repoPath, ['commit', '-m', message]);
165
+ await this.runGit(repoPath, ['push', '-u', 'origin', branch]);
166
+ return `已 push 到 origin/${branch}`;
167
+ }
168
+ }