@zhin.js/adapter-github 1.0.0 → 1.1.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/CHANGELOG.md +1118 -0
- package/README.md +70 -191
- package/adapters/github.js +51 -0
- package/adapters/github.ts +59 -0
- package/agent/prompt-sections/platform.ts +16 -0
- package/{skills/github/SKILL.md → agent/skills/github.md} +26 -9
- package/agent/tools/bind.ts +13 -0
- package/agent/tools/create_pr.ts +20 -0
- package/agent/tools/install.ts +13 -0
- package/agent/tools/patch_file.ts +19 -0
- package/agent/tools/prepare_workspace.ts +15 -0
- package/agent/tools/push_branch.ts +18 -0
- package/agent/tools/star.ts +16 -0
- package/agent/tools/subscribe.ts +16 -0
- package/agent/tools/subscriptions.ts +13 -0
- package/agent/tools/unbind.ts +13 -0
- package/agent/tools/unsubscribe.ts +15 -0
- package/agent/tools/whoami.ts +13 -0
- package/commands/endpoint/add/[id].js +3 -0
- package/commands/endpoint/add/[id].ts +3 -0
- package/commands/endpoint/list.js +3 -0
- package/commands/endpoint/list.ts +3 -0
- package/commands/endpoint/remove/[id].js +3 -0
- package/commands/endpoint/remove/[id].ts +3 -0
- package/lib/client.d.ts +36 -0
- package/lib/client.js +47 -0
- package/lib/endpoint.d.ts +36 -0
- package/lib/endpoint.js +140 -0
- package/lib/gh-client.d.ts +73 -1
- package/lib/gh-client.js +109 -7
- package/lib/github-bot-handlers.d.ts +27 -0
- package/lib/github-bot-handlers.js +76 -0
- package/lib/github-channel-context.d.ts +16 -0
- package/lib/github-channel-context.js +31 -0
- package/lib/github-endpoint-commands.d.ts +1 -0
- package/lib/github-endpoint-commands.js +22 -0
- package/lib/github-runtime-state.d.ts +1 -0
- package/lib/github-runtime-state.js +6 -0
- package/lib/github-tool-handlers.d.ts +18 -0
- package/lib/github-tool-handlers.js +214 -0
- package/lib/index.d.ts +7 -32
- package/lib/index.js +7 -385
- package/lib/oauth-users.d.ts +33 -0
- package/lib/oauth-users.js +38 -0
- package/lib/protocol.d.ts +94 -0
- package/lib/protocol.js +292 -0
- package/lib/types.d.ts +9 -4
- package/lib/types.js +1 -2
- package/lib/webhook.d.ts +14 -0
- package/lib/webhook.js +88 -0
- package/lib/workspace-manager.d.ts +21 -0
- package/lib/workspace-manager.js +154 -0
- package/package.json +77 -22
- package/plugin.js +38 -0
- package/schema.json +130 -0
- package/src/client.ts +65 -0
- package/src/endpoint.ts +169 -0
- package/src/gh-client.ts +147 -12
- package/src/github-bot-handlers.ts +113 -0
- package/src/github-channel-context.ts +46 -0
- package/src/github-endpoint-commands.ts +23 -0
- package/src/github-runtime-state.ts +7 -0
- package/src/github-tool-handlers.ts +252 -0
- package/src/index.ts +48 -431
- package/src/oauth-users.ts +47 -0
- package/src/protocol.ts +425 -0
- package/src/types.ts +10 -4
- package/src/webhook.ts +130 -0
- package/src/workspace-manager.ts +168 -0
- package/lib/adapter.d.ts +0 -63
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -415
- package/lib/adapter.js.map +0 -1
- package/lib/agent-prompt.d.ts +0 -3
- package/lib/agent-prompt.d.ts.map +0 -1
- package/lib/agent-prompt.js +0 -82
- package/lib/agent-prompt.js.map +0 -1
- package/lib/bot.d.ts +0 -26
- package/lib/bot.d.ts.map +0 -1
- package/lib/bot.js +0 -160
- package/lib/bot.js.map +0 -1
- package/lib/gh-client.d.ts.map +0 -1
- package/lib/gh-client.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/register-github-mcp.d.ts +0 -6
- package/lib/register-github-mcp.d.ts.map +0 -1
- package/lib/register-github-mcp.js +0 -35
- package/lib/register-github-mcp.js.map +0 -1
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js.map +0 -1
- package/plugin.yml +0 -3
- package/src/adapter.ts +0 -446
- package/src/agent-prompt.ts +0 -99
- package/src/bot.ts +0 -174
- package/src/register-github-mcp.ts +0 -60
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
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 { pickCredential } from 'zhin.js/adapter';
|
|
9
|
+
import { isMediaRef } from '@zhin.js/core';
|
|
10
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
11
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
12
|
+
|
|
13
|
+
const logger = getLogger('github');
|
|
14
|
+
import {
|
|
15
|
+
buildChannelId,
|
|
16
|
+
type GenericWebhookPayload,
|
|
17
|
+
type IssueCommentPayload,
|
|
18
|
+
type PRReviewCommentPayload,
|
|
19
|
+
type PRReviewPayload,
|
|
20
|
+
} from './types.js';
|
|
21
|
+
|
|
22
|
+
export type {
|
|
23
|
+
EventType,
|
|
24
|
+
GenericWebhookPayload,
|
|
25
|
+
GitHubComment,
|
|
26
|
+
GitHubEndpointConfig,
|
|
27
|
+
GitHubIssue,
|
|
28
|
+
GitHubOAuthUser,
|
|
29
|
+
GitHubPR,
|
|
30
|
+
GitHubRepo,
|
|
31
|
+
GitHubUser,
|
|
32
|
+
IssueCommentPayload,
|
|
33
|
+
ParsedChannel,
|
|
34
|
+
PRReviewCommentPayload,
|
|
35
|
+
PRReviewPayload,
|
|
36
|
+
Subscription,
|
|
37
|
+
} from './types.js';
|
|
38
|
+
|
|
39
|
+
export { buildChannelId, parseChannelId } from './types.js';
|
|
40
|
+
|
|
41
|
+
/** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
|
|
42
|
+
export interface GithubAdapterConfig {
|
|
43
|
+
readonly id?: string;
|
|
44
|
+
readonly host?: string;
|
|
45
|
+
readonly app_id?: string | number;
|
|
46
|
+
readonly appId?: string | number;
|
|
47
|
+
readonly private_key?: string;
|
|
48
|
+
readonly privateKey?: string;
|
|
49
|
+
readonly webhook_secret?: string;
|
|
50
|
+
readonly webhookSecret?: string;
|
|
51
|
+
readonly webhook_path?: string;
|
|
52
|
+
readonly webhookPath?: string;
|
|
53
|
+
readonly poll_interval?: number;
|
|
54
|
+
readonly pollInterval?: number;
|
|
55
|
+
readonly auto_reply_repos?: readonly string[];
|
|
56
|
+
readonly autoReplyRepos?: readonly string[];
|
|
57
|
+
readonly bot_login?: string;
|
|
58
|
+
readonly botLogin?: string;
|
|
59
|
+
readonly workspace_root?: string;
|
|
60
|
+
readonly workspaceRoot?: string;
|
|
61
|
+
/** Transitional: legacy root `endpoints[]` with `context: github`. */
|
|
62
|
+
readonly endpoints?: ReadonlyArray<Partial<ResolvedGithubConfig> & {
|
|
63
|
+
readonly context?: string;
|
|
64
|
+
readonly app_id?: string | number;
|
|
65
|
+
readonly private_key?: string;
|
|
66
|
+
readonly webhook_secret?: string;
|
|
67
|
+
readonly webhook_path?: string;
|
|
68
|
+
readonly poll_interval?: number;
|
|
69
|
+
readonly auto_reply_repos?: readonly string[];
|
|
70
|
+
readonly bot_login?: string;
|
|
71
|
+
readonly workspace_root?: string;
|
|
72
|
+
}>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ResolvedGithubConfig {
|
|
76
|
+
readonly context: 'github';
|
|
77
|
+
readonly id: string;
|
|
78
|
+
readonly host?: string;
|
|
79
|
+
readonly appId?: string | number;
|
|
80
|
+
readonly privateKey?: string;
|
|
81
|
+
readonly webhookSecret?: string;
|
|
82
|
+
readonly webhookPath: string;
|
|
83
|
+
readonly pollInterval: number;
|
|
84
|
+
readonly autoReplyRepos: readonly string[];
|
|
85
|
+
readonly botLogin?: string;
|
|
86
|
+
readonly workspaceRoot?: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface GithubWireSegment {
|
|
90
|
+
readonly type: string;
|
|
91
|
+
readonly data?: Record<string, unknown>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface GithubInboundComment {
|
|
95
|
+
readonly id: string;
|
|
96
|
+
readonly channelId: string;
|
|
97
|
+
readonly sender: string;
|
|
98
|
+
readonly content: string;
|
|
99
|
+
readonly repo: string;
|
|
100
|
+
readonly kind: 'issue_comment' | 'pr_review_comment' | 'pr_review';
|
|
101
|
+
readonly createdAt: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 入站归一化 → ConversationRef:Issue/PR 评论区即仓库容器内的 channel 会话,
|
|
106
|
+
* 仓库(owner/repo)进 `parent`。出站侧用 `parseChannelId(conversation.id)`
|
|
107
|
+
* 在平台边界还原 repo/type/number。
|
|
108
|
+
*/
|
|
109
|
+
export function githubInboundConversation(
|
|
110
|
+
endpointKey: string,
|
|
111
|
+
comment: GithubInboundComment,
|
|
112
|
+
): ConversationRef {
|
|
113
|
+
return {
|
|
114
|
+
endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
|
|
115
|
+
kind: 'channel',
|
|
116
|
+
id: comment.channelId,
|
|
117
|
+
parent: { kind: 'channel', id: comment.repo },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function resolveGithubConfig(config: GithubAdapterConfig = {}): ResolvedGithubConfig {
|
|
122
|
+
const entry = config.endpoints?.find((item) => item.context === 'github');
|
|
123
|
+
const appIdRaw = pickCredential(
|
|
124
|
+
config.appId != null ? String(config.appId) : undefined,
|
|
125
|
+
config.app_id != null ? String(config.app_id) : undefined,
|
|
126
|
+
entry?.appId != null ? String(entry.appId) : undefined,
|
|
127
|
+
entry?.app_id != null ? String(entry.app_id) : undefined,
|
|
128
|
+
process.env.GITHUB_APP_ID,
|
|
129
|
+
);
|
|
130
|
+
const appId = appIdRaw ? (Number(appIdRaw) || appIdRaw) : undefined;
|
|
131
|
+
const privateKey = pickCredential(
|
|
132
|
+
config.privateKey,
|
|
133
|
+
config.private_key,
|
|
134
|
+
entry?.privateKey,
|
|
135
|
+
entry?.private_key,
|
|
136
|
+
) || undefined;
|
|
137
|
+
if (!appId || !privateKey) {
|
|
138
|
+
throw new TypeError(
|
|
139
|
+
'GitHub adapter requires app_id + private_key (plugins.<key> or GITHUB_APP_ID)',
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
const id = (typeof config.id === 'string' && config.id)
|
|
143
|
+
|| (typeof entry?.id === 'string' && entry.id)
|
|
144
|
+
|| process.env.GITHUB_BOT_NAME
|
|
145
|
+
|| 'github-bot';
|
|
146
|
+
const webhookSecret = config.webhookSecret ?? config.webhook_secret
|
|
147
|
+
?? entry?.webhookSecret ?? entry?.webhook_secret
|
|
148
|
+
?? process.env.GITHUB_WEBHOOK_SECRET
|
|
149
|
+
?? undefined;
|
|
150
|
+
const host = config.host ?? entry?.host;
|
|
151
|
+
const webhookPath = normalizeWebhookPath(
|
|
152
|
+
config.webhookPath ?? config.webhook_path ?? entry?.webhookPath ?? entry?.webhook_path
|
|
153
|
+
?? '/github/webhook',
|
|
154
|
+
);
|
|
155
|
+
const pollInterval = Number(
|
|
156
|
+
config.pollInterval ?? config.poll_interval ?? entry?.pollInterval ?? entry?.poll_interval ?? 60,
|
|
157
|
+
) || 60;
|
|
158
|
+
const autoReplyRepos = [
|
|
159
|
+
...(config.autoReplyRepos ?? config.auto_reply_repos
|
|
160
|
+
?? entry?.autoReplyRepos ?? entry?.auto_reply_repos ?? []),
|
|
161
|
+
];
|
|
162
|
+
const botLogin = config.botLogin ?? config.bot_login ?? entry?.botLogin ?? entry?.bot_login;
|
|
163
|
+
const workspaceRoot = config.workspaceRoot ?? config.workspace_root
|
|
164
|
+
?? entry?.workspaceRoot ?? entry?.workspace_root;
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
context: 'github',
|
|
168
|
+
id,
|
|
169
|
+
...(host ? { host } : {}),
|
|
170
|
+
...(appId != null ? { appId } : {}),
|
|
171
|
+
...(privateKey ? { privateKey } : {}),
|
|
172
|
+
...(webhookSecret ? { webhookSecret } : {}),
|
|
173
|
+
webhookPath,
|
|
174
|
+
pollInterval,
|
|
175
|
+
autoReplyRepos,
|
|
176
|
+
...(botLogin ? { botLogin } : {}),
|
|
177
|
+
...(workspaceRoot ? { workspaceRoot } : {}),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function normalizeWebhookPath(path: string): string {
|
|
182
|
+
const trimmed = path.trim() || '/github/webhook';
|
|
183
|
+
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function shouldAutoReplyRepo(
|
|
187
|
+
config: Pick<ResolvedGithubConfig, 'autoReplyRepos'>,
|
|
188
|
+
repo: string,
|
|
189
|
+
): boolean {
|
|
190
|
+
const list = config.autoReplyRepos;
|
|
191
|
+
if (!list.length) return false;
|
|
192
|
+
const key = repo.toLowerCase();
|
|
193
|
+
return list.some((r) => r.toLowerCase() === key);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Prepend synthetic @bot for auto_reply repos (gateway text path). */
|
|
197
|
+
export function enrichInboundContent(
|
|
198
|
+
content: string,
|
|
199
|
+
config: Pick<ResolvedGithubConfig, 'autoReplyRepos' | 'botLogin'>,
|
|
200
|
+
botLogin: string | undefined,
|
|
201
|
+
repo: string,
|
|
202
|
+
): string {
|
|
203
|
+
const login = config.botLogin || botLogin;
|
|
204
|
+
if (!login || !shouldAutoReplyRepo(config, repo)) return content;
|
|
205
|
+
if (content.includes(`@${login}`)) return content;
|
|
206
|
+
return `@${login} ${content}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Build inbound text for OutboundMessageService.receive from markdown/comment body. */
|
|
210
|
+
export function formatInboundContent(body: string): string {
|
|
211
|
+
return body;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Build markdown body for Issue/PR comment send. */
|
|
215
|
+
export function formatOutboundBody(payload: unknown): string {
|
|
216
|
+
if (typeof payload === 'string') return payload;
|
|
217
|
+
if (payload == null) return '';
|
|
218
|
+
if (!Array.isArray(payload)) {
|
|
219
|
+
if (typeof payload === 'object' && payload !== null && 'text' in payload) {
|
|
220
|
+
return String((payload as { text?: unknown }).text ?? '');
|
|
221
|
+
}
|
|
222
|
+
return String(payload);
|
|
223
|
+
}
|
|
224
|
+
return payload.map((seg) => {
|
|
225
|
+
if (typeof seg === 'string') return seg;
|
|
226
|
+
const item = seg as GithubWireSegment;
|
|
227
|
+
switch (item.type) {
|
|
228
|
+
case 'text':
|
|
229
|
+
return String(item.data?.text ?? '');
|
|
230
|
+
case 'mention':
|
|
231
|
+
case 'at':
|
|
232
|
+
return `@${item.data?.name || item.data?.id || item.data?.target || ''}`;
|
|
233
|
+
case 'image':
|
|
234
|
+
case 'audio':
|
|
235
|
+
case 'video':
|
|
236
|
+
case 'file':
|
|
237
|
+
return formatMediaSegment(item);
|
|
238
|
+
case 'link':
|
|
239
|
+
return `[${item.data?.text || item.data?.url || ''}](${item.data?.url || ''})`;
|
|
240
|
+
default:
|
|
241
|
+
return String(item.data?.text ?? `[${item.type}]`);
|
|
242
|
+
}
|
|
243
|
+
}).join('');
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* 媒体段 → GitHub markdown(canonical MediaRef 唯一来源)。
|
|
248
|
+
* GitHub 评论只能消费远程 URL(无上传面),kind=url 直发;
|
|
249
|
+
* base64 / path / file 不可投递,warn + 丢弃。
|
|
250
|
+
*/
|
|
251
|
+
function formatMediaSegment(seg: GithubWireSegment): string {
|
|
252
|
+
const media = seg.data?.media;
|
|
253
|
+
if (!isMediaRef(media)) {
|
|
254
|
+
logger.warn(formatCompact({
|
|
255
|
+
op: 'github_outbound_media_dropped',
|
|
256
|
+
type: seg.type,
|
|
257
|
+
reason: 'missing_media_ref',
|
|
258
|
+
}));
|
|
259
|
+
return '';
|
|
260
|
+
}
|
|
261
|
+
if (media.kind !== 'url') {
|
|
262
|
+
logger.warn(formatCompact({
|
|
263
|
+
op: 'github_outbound_media_dropped',
|
|
264
|
+
type: seg.type,
|
|
265
|
+
reason: `unsupported_kind:${media.kind}`,
|
|
266
|
+
}));
|
|
267
|
+
return '';
|
|
268
|
+
}
|
|
269
|
+
if (seg.type === 'image') {
|
|
270
|
+
const alt = typeof seg.data?.alt === 'string' && seg.data.alt
|
|
271
|
+
? seg.data.alt
|
|
272
|
+
: media.file_name || 'image';
|
|
273
|
+
return ``;
|
|
274
|
+
}
|
|
275
|
+
const label = media.file_name || seg.type;
|
|
276
|
+
return `[${label}](${media.value})`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function verifyWebhookSignature(
|
|
280
|
+
secret: string,
|
|
281
|
+
rawBody: string,
|
|
282
|
+
signatureHeader: string | undefined,
|
|
283
|
+
): boolean {
|
|
284
|
+
if (!signatureHeader?.startsWith('sha256=')) return false;
|
|
285
|
+
const expected = `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`;
|
|
286
|
+
try {
|
|
287
|
+
const a = Buffer.from(signatureHeader);
|
|
288
|
+
const b = Buffer.from(expected);
|
|
289
|
+
if (a.length !== b.length) return false;
|
|
290
|
+
return timingSafeEqual(a, b);
|
|
291
|
+
} catch {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export function headerValue(
|
|
297
|
+
headers: IncomingMessage['headers'],
|
|
298
|
+
name: string,
|
|
299
|
+
): string {
|
|
300
|
+
const raw = headers[name] ?? headers[name.toLowerCase()];
|
|
301
|
+
if (Array.isArray(raw)) return raw[0] ?? '';
|
|
302
|
+
return raw ?? '';
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export async function readTextBody(
|
|
306
|
+
request: IncomingMessage,
|
|
307
|
+
options: { readonly limit?: number } = {},
|
|
308
|
+
): Promise<string> {
|
|
309
|
+
const limit = options.limit ?? 1_048_576;
|
|
310
|
+
const chunks: Buffer[] = [];
|
|
311
|
+
let size = 0;
|
|
312
|
+
for await (const chunk of request) {
|
|
313
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
314
|
+
size += buffer.length;
|
|
315
|
+
if (size > limit) {
|
|
316
|
+
request.destroy();
|
|
317
|
+
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
318
|
+
}
|
|
319
|
+
chunks.push(buffer);
|
|
320
|
+
}
|
|
321
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function parseIssueCommentInbound(payload: IssueCommentPayload): GithubInboundComment | null {
|
|
325
|
+
if (payload.action !== 'created' || !payload.comment) return null;
|
|
326
|
+
const repo = payload.repository.full_name;
|
|
327
|
+
const isPR = 'pull_request' in (payload.issue as object);
|
|
328
|
+
return {
|
|
329
|
+
id: String(payload.comment.id),
|
|
330
|
+
channelId: buildChannelId(repo, isPR ? 'pr' : 'issue', payload.issue.number),
|
|
331
|
+
sender: payload.sender.login,
|
|
332
|
+
content: payload.comment.body,
|
|
333
|
+
repo,
|
|
334
|
+
kind: 'issue_comment',
|
|
335
|
+
createdAt: new Date(payload.comment.created_at).getTime(),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function parsePrReviewCommentInbound(payload: PRReviewCommentPayload): GithubInboundComment | null {
|
|
340
|
+
if (payload.action !== 'created' || !payload.comment) return null;
|
|
341
|
+
const repo = payload.repository.full_name;
|
|
342
|
+
const body = payload.comment.path
|
|
343
|
+
? `**${payload.comment.path}**\n${payload.comment.diff_hunk ? `\`\`\`diff\n${payload.comment.diff_hunk}\n\`\`\`\n` : ''}${payload.comment.body}`
|
|
344
|
+
: payload.comment.body;
|
|
345
|
+
return {
|
|
346
|
+
id: String(payload.comment.id),
|
|
347
|
+
channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
|
|
348
|
+
sender: payload.sender.login,
|
|
349
|
+
content: body,
|
|
350
|
+
repo,
|
|
351
|
+
kind: 'pr_review_comment',
|
|
352
|
+
createdAt: new Date(payload.comment.created_at).getTime(),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function parsePrReviewInbound(payload: PRReviewPayload): GithubInboundComment | null {
|
|
357
|
+
if (payload.action !== 'submitted' || !payload.review.body) return null;
|
|
358
|
+
const repo = payload.repository.full_name;
|
|
359
|
+
const stateLabel: Record<string, string> = {
|
|
360
|
+
approved: '✅ APPROVED',
|
|
361
|
+
changes_requested: '🔄 CHANGES REQUESTED',
|
|
362
|
+
commented: '💬 COMMENTED',
|
|
363
|
+
dismissed: '❌ DISMISSED',
|
|
364
|
+
};
|
|
365
|
+
const body = `**[${stateLabel[payload.review.state] || payload.review.state}]**\n${payload.review.body}`;
|
|
366
|
+
return {
|
|
367
|
+
id: String(payload.review.id),
|
|
368
|
+
channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
|
|
369
|
+
sender: payload.sender.login,
|
|
370
|
+
content: body,
|
|
371
|
+
repo,
|
|
372
|
+
kind: 'pr_review',
|
|
373
|
+
createdAt: new Date(payload.review.submitted_at).getTime(),
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export function formatNotification(event: string, p: GenericWebhookPayload): string {
|
|
378
|
+
const repo = p.repository.full_name;
|
|
379
|
+
const sender = p.sender.login;
|
|
380
|
+
const repoUrl = p.repository.html_url;
|
|
381
|
+
switch (event) {
|
|
382
|
+
case 'push': {
|
|
383
|
+
const branch = p.ref?.replace('refs/heads/', '') || '?';
|
|
384
|
+
const commits = p.commits || [];
|
|
385
|
+
const compareUrl = commits.length >= 2
|
|
386
|
+
? `${repoUrl}/compare/${commits[0].id.substring(0, 12)}...${commits[commits.length - 1].id.substring(0, 12)}`
|
|
387
|
+
: commits.length === 1 ? `${repoUrl}/commit/${commits[0].id}` : '';
|
|
388
|
+
let msg = `📦 ${repo}\n🌿 ${sender} pushed ${commits.length} commit(s) to \`${branch}\`\n`;
|
|
389
|
+
if (commits.length) {
|
|
390
|
+
msg += '\n';
|
|
391
|
+
msg += commits.slice(0, 5).map((c) =>
|
|
392
|
+
` • [\`${c.id.substring(0, 7)}\`](${repoUrl}/commit/${c.id}) ${c.message.split('\n')[0]}`,
|
|
393
|
+
).join('\n');
|
|
394
|
+
if (commits.length > 5) msg += `\n ... +${commits.length - 5} more`;
|
|
395
|
+
}
|
|
396
|
+
if (compareUrl) msg += `\n\n🔗 ${compareUrl}`;
|
|
397
|
+
return msg;
|
|
398
|
+
}
|
|
399
|
+
case 'issues': {
|
|
400
|
+
const i = p.issue!;
|
|
401
|
+
const act = p.action === 'opened' ? '📝 opened' : p.action === 'closed' ? '✅ closed' : `🔄 ${p.action || 'updated'}`;
|
|
402
|
+
return `🐛 ${repo}\n👤 ${sender} ${act} issue #${i.number}\n📌 ${i.title}\n🔗 ${i.html_url}`;
|
|
403
|
+
}
|
|
404
|
+
case 'star': {
|
|
405
|
+
const starred = p.action !== 'deleted';
|
|
406
|
+
return `${starred ? '⭐' : '💔'} ${repo}\n👤 ${sender} ${starred ? 'starred' : 'unstarred'}\n🔗 ${repoUrl}`;
|
|
407
|
+
}
|
|
408
|
+
case 'fork':
|
|
409
|
+
return `🍴 ${repo}\n👤 ${sender} forked → ${p.forkee!.full_name}\n🔗 ${p.forkee!.html_url}`;
|
|
410
|
+
case 'pull_request': {
|
|
411
|
+
const pr = p.pull_request!;
|
|
412
|
+
const act = p.action === 'opened' ? '📝 opened'
|
|
413
|
+
: p.action === 'closed' ? (pr.state === 'closed' ? '❌ closed' : '✅ merged')
|
|
414
|
+
: `🔄 ${p.action || 'updated'}`;
|
|
415
|
+
return `🔀 ${repo}\n👤 ${sender} ${act} PR #${pr.number}\n📌 ${pr.title}\n🌿 ${pr.head.ref} → ${pr.base.ref}\n🔗 ${pr.html_url}`;
|
|
416
|
+
}
|
|
417
|
+
default:
|
|
418
|
+
return `📬 ${repo}\n📡 ${event}${p.action ? ` (${p.action})` : ''} by ${sender}\n🔗 ${repoUrl}`;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Parse @mentions in markdown into a flat display string (gateway text path). */
|
|
423
|
+
export function parseMarkdownMentions(md: string): string {
|
|
424
|
+
return md;
|
|
425
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// ──
|
|
1
|
+
// ── Endpoint 配置 ─────────────────────────────────────────────────────────
|
|
2
2
|
// 基于 gh CLI 认证:需要系统已安装并认证 gh CLI
|
|
3
3
|
// 认证方式:gh auth login
|
|
4
4
|
|
|
5
|
-
export interface
|
|
5
|
+
export interface GitHubEndpointConfig {
|
|
6
6
|
context: 'github';
|
|
7
|
-
/**
|
|
7
|
+
/** Endpoint 标识名称 */
|
|
8
8
|
name: string;
|
|
9
9
|
/** GitHub Enterprise 主机名(默认 github.com) */
|
|
10
10
|
host?: string;
|
|
@@ -18,6 +18,12 @@ export interface GitHubBotConfig {
|
|
|
18
18
|
webhook_path?: string;
|
|
19
19
|
/** 事件轮询间隔(秒,默认 60,Webhook 模式下作为降级备选) */
|
|
20
20
|
poll_interval?: number;
|
|
21
|
+
/** 这些仓库的人类 Issue/PR 评论自动触发 AI(无需 @bot) */
|
|
22
|
+
auto_reply_repos?: string[];
|
|
23
|
+
/** 覆盖 App bot 登录名(默认 {slug}[bot]) */
|
|
24
|
+
bot_login?: string;
|
|
25
|
+
/** 托管 git 工作区根目录(默认 {cwd}/data/github-workspaces) */
|
|
26
|
+
workspace_root?: string;
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
// ── Channel ID ───────────────────────────────────────────────────────
|
|
@@ -135,7 +141,7 @@ export interface Subscription {
|
|
|
135
141
|
target_id: string;
|
|
136
142
|
target_type: 'private' | 'group' | 'channel';
|
|
137
143
|
adapter: string;
|
|
138
|
-
|
|
144
|
+
endpoint: string;
|
|
139
145
|
}
|
|
140
146
|
|
|
141
147
|
// ── Tool Action Types ────────────────────────────────────────────────
|
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
|
+
}
|