@zhin.js/adapter-github 3.0.1 → 3.0.3

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 (84) hide show
  1. package/CHANGELOG.md +624 -0
  2. package/README.md +38 -190
  3. package/adapters/github.ts +51 -0
  4. package/{skills/github/SKILL.md → agent/skills/github.md} +22 -5
  5. package/agent/tools/bind.ts +12 -0
  6. package/agent/tools/create_pr.ts +19 -0
  7. package/agent/tools/install.ts +12 -0
  8. package/agent/tools/patch_file.ts +18 -0
  9. package/agent/tools/prepare_workspace.ts +14 -0
  10. package/agent/tools/push_branch.ts +17 -0
  11. package/agent/tools/star.ts +15 -0
  12. package/agent/tools/subscribe.ts +16 -0
  13. package/agent/tools/subscriptions.ts +13 -0
  14. package/agent/tools/unbind.ts +12 -0
  15. package/agent/tools/unsubscribe.ts +15 -0
  16. package/agent/tools/whoami.ts +12 -0
  17. package/lib/agent-prompt.d.ts +0 -1
  18. package/lib/agent-prompt.js +10 -9
  19. package/lib/endpoint.d.ts +46 -24
  20. package/lib/endpoint.js +144 -144
  21. package/lib/gh-client.d.ts +73 -1
  22. package/lib/gh-client.js +99 -1
  23. package/lib/github-agent-deps.d.ts +47 -0
  24. package/lib/github-agent-deps.js +43 -0
  25. package/lib/github-bot-handlers.d.ts +26 -0
  26. package/lib/github-bot-handlers.js +77 -0
  27. package/lib/github-channel-context.d.ts +16 -0
  28. package/lib/github-channel-context.js +31 -0
  29. package/lib/github-tool-handlers.d.ts +17 -0
  30. package/lib/github-tool-handlers.js +221 -0
  31. package/lib/index.d.ts +7 -32
  32. package/lib/index.js +7 -386
  33. package/lib/oauth-users.d.ts +33 -0
  34. package/lib/oauth-users.js +38 -0
  35. package/lib/protocol.d.ts +87 -0
  36. package/lib/protocol.js +241 -0
  37. package/lib/types.d.ts +6 -1
  38. package/lib/types.js +0 -1
  39. package/lib/webhook.d.ts +13 -0
  40. package/lib/webhook.js +87 -0
  41. package/lib/workspace-manager.d.ts +21 -0
  42. package/lib/workspace-manager.js +145 -0
  43. package/package.json +60 -23
  44. package/plugin.ts +52 -0
  45. package/schema.json +65 -0
  46. package/src/agent-prompt.ts +11 -10
  47. package/src/endpoint.ts +169 -150
  48. package/src/gh-client.ts +131 -0
  49. package/src/github-agent-deps.ts +82 -0
  50. package/src/github-bot-handlers.ts +109 -0
  51. package/src/github-channel-context.ts +46 -0
  52. package/src/github-tool-handlers.ts +257 -0
  53. package/src/index.ts +55 -431
  54. package/src/oauth-users.ts +47 -0
  55. package/src/protocol.ts +367 -0
  56. package/src/types.ts +6 -0
  57. package/src/webhook.ts +125 -0
  58. package/src/workspace-manager.ts +158 -0
  59. package/lib/adapter.d.ts +0 -66
  60. package/lib/adapter.d.ts.map +0 -1
  61. package/lib/adapter.js +0 -418
  62. package/lib/adapter.js.map +0 -1
  63. package/lib/agent-prompt.d.ts.map +0 -1
  64. package/lib/agent-prompt.js.map +0 -1
  65. package/lib/endpoint.d.ts.map +0 -1
  66. package/lib/endpoint.js.map +0 -1
  67. package/lib/gh-client.d.ts.map +0 -1
  68. package/lib/gh-client.js.map +0 -1
  69. package/lib/index.d.ts.map +0 -1
  70. package/lib/index.js.map +0 -1
  71. package/lib/register-github-mcp.d.ts +0 -7
  72. package/lib/register-github-mcp.d.ts.map +0 -1
  73. package/lib/register-github-mcp.js +0 -36
  74. package/lib/register-github-mcp.js.map +0 -1
  75. package/lib/segment-mapper.d.ts +0 -2
  76. package/lib/segment-mapper.d.ts.map +0 -1
  77. package/lib/segment-mapper.js +0 -2
  78. package/lib/segment-mapper.js.map +0 -1
  79. package/lib/types.d.ts.map +0 -1
  80. package/lib/types.js.map +0 -1
  81. package/plugin.yml +0 -3
  82. package/src/adapter.ts +0 -450
  83. package/src/register-github-mcp.ts +0 -62
  84. package/src/segment-mapper.ts +0 -1
@@ -0,0 +1,241 @@
1
+ /**
2
+ * GitHub webhook / comment helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+ import { createHmac, timingSafeEqual } from 'node:crypto';
6
+ import { pickCredential } from '@zhin.js/adapter';
7
+ import { buildChannelId, } from './types.js';
8
+ export { buildChannelId, parseChannelId } from './types.js';
9
+ export function resolveGithubConfig(config = {}) {
10
+ const entry = config.endpoints?.find((item) => item.context === 'github');
11
+ const appIdRaw = pickCredential(config.appId != null ? String(config.appId) : undefined, config.app_id != null ? String(config.app_id) : undefined, entry?.appId != null ? String(entry.appId) : undefined, entry?.app_id != null ? String(entry.app_id) : undefined, process.env.GITHUB_APP_ID);
12
+ const appId = appIdRaw ? (Number(appIdRaw) || appIdRaw) : undefined;
13
+ const privateKey = pickCredential(config.privateKey, config.private_key, entry?.privateKey, entry?.private_key) || undefined;
14
+ if (!appId || !privateKey) {
15
+ throw new TypeError('GitHub adapter requires app_id + private_key (plugins.<key> or GITHUB_APP_ID)');
16
+ }
17
+ const name = (typeof config.name === 'string' && config.name)
18
+ || (typeof entry?.name === 'string' && entry.name)
19
+ || process.env.GITHUB_BOT_NAME
20
+ || 'github-bot';
21
+ const webhookSecret = config.webhookSecret ?? config.webhook_secret
22
+ ?? entry?.webhookSecret ?? entry?.webhook_secret
23
+ ?? process.env.GITHUB_WEBHOOK_SECRET
24
+ ?? undefined;
25
+ const host = config.host ?? entry?.host;
26
+ const webhookPath = normalizeWebhookPath(config.webhookPath ?? config.webhook_path ?? entry?.webhookPath ?? entry?.webhook_path
27
+ ?? '/github/webhook');
28
+ const pollInterval = Number(config.pollInterval ?? config.poll_interval ?? entry?.pollInterval ?? entry?.poll_interval ?? 60) || 60;
29
+ const autoReplyRepos = [
30
+ ...(config.autoReplyRepos ?? config.auto_reply_repos
31
+ ?? entry?.autoReplyRepos ?? entry?.auto_reply_repos ?? []),
32
+ ];
33
+ const botLogin = config.botLogin ?? config.bot_login ?? entry?.botLogin ?? entry?.bot_login;
34
+ const workspaceRoot = config.workspaceRoot ?? config.workspace_root
35
+ ?? entry?.workspaceRoot ?? entry?.workspace_root;
36
+ return {
37
+ context: 'github',
38
+ name,
39
+ ...(host ? { host } : {}),
40
+ ...(appId != null ? { appId } : {}),
41
+ ...(privateKey ? { privateKey } : {}),
42
+ ...(webhookSecret ? { webhookSecret } : {}),
43
+ webhookPath,
44
+ pollInterval,
45
+ autoReplyRepos,
46
+ ...(botLogin ? { botLogin } : {}),
47
+ ...(workspaceRoot ? { workspaceRoot } : {}),
48
+ };
49
+ }
50
+ export function normalizeWebhookPath(path) {
51
+ const trimmed = path.trim() || '/github/webhook';
52
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
53
+ }
54
+ export function shouldAutoReplyRepo(config, repo) {
55
+ const list = config.autoReplyRepos;
56
+ if (!list.length)
57
+ return false;
58
+ const key = repo.toLowerCase();
59
+ return list.some((r) => r.toLowerCase() === key);
60
+ }
61
+ /** Prepend synthetic @bot for auto_reply repos (gateway text path). */
62
+ export function enrichInboundContent(content, config, botLogin, repo) {
63
+ const login = config.botLogin || botLogin;
64
+ if (!login || !shouldAutoReplyRepo(config, repo))
65
+ return content;
66
+ if (content.includes(`@${login}`))
67
+ return content;
68
+ return `@${login} ${content}`;
69
+ }
70
+ /** Build inbound text for MessageGateway.receive from markdown/comment body. */
71
+ export function formatInboundContent(body) {
72
+ return body;
73
+ }
74
+ /** Build markdown body for Issue/PR comment send. */
75
+ export function formatOutboundBody(payload) {
76
+ if (typeof payload === 'string')
77
+ return payload;
78
+ if (payload == null)
79
+ return '';
80
+ if (!Array.isArray(payload)) {
81
+ if (typeof payload === 'object' && payload !== null && 'text' in payload) {
82
+ return String(payload.text ?? '');
83
+ }
84
+ return String(payload);
85
+ }
86
+ return payload.map((seg) => {
87
+ if (typeof seg === 'string')
88
+ return seg;
89
+ const item = seg;
90
+ switch (item.type) {
91
+ case 'text':
92
+ return String(item.data?.text ?? '');
93
+ case 'mention':
94
+ case 'at':
95
+ return `@${item.data?.name || item.data?.id || item.data?.target || ''}`;
96
+ case 'image':
97
+ return item.data?.url ? `![image](${item.data.url})` : '[image]';
98
+ case 'link':
99
+ return `[${item.data?.text || item.data?.url || ''}](${item.data?.url || ''})`;
100
+ default:
101
+ return String(item.data?.text ?? `[${item.type}]`);
102
+ }
103
+ }).join('');
104
+ }
105
+ export function verifyWebhookSignature(secret, rawBody, signatureHeader) {
106
+ if (!signatureHeader?.startsWith('sha256='))
107
+ return false;
108
+ const expected = `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`;
109
+ try {
110
+ const a = Buffer.from(signatureHeader);
111
+ const b = Buffer.from(expected);
112
+ if (a.length !== b.length)
113
+ return false;
114
+ return timingSafeEqual(a, b);
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ }
120
+ export function headerValue(headers, name) {
121
+ const raw = headers[name] ?? headers[name.toLowerCase()];
122
+ if (Array.isArray(raw))
123
+ return raw[0] ?? '';
124
+ return raw ?? '';
125
+ }
126
+ export async function readTextBody(request, options = {}) {
127
+ const limit = options.limit ?? 1_048_576;
128
+ const chunks = [];
129
+ let size = 0;
130
+ for await (const chunk of request) {
131
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
132
+ size += buffer.length;
133
+ if (size > limit) {
134
+ request.destroy();
135
+ throw new Error(`Request body exceeds ${limit} bytes`);
136
+ }
137
+ chunks.push(buffer);
138
+ }
139
+ return Buffer.concat(chunks).toString('utf8');
140
+ }
141
+ export function parseIssueCommentInbound(payload) {
142
+ if (payload.action !== 'created' || !payload.comment)
143
+ return null;
144
+ const repo = payload.repository.full_name;
145
+ const isPR = 'pull_request' in payload.issue;
146
+ return {
147
+ id: String(payload.comment.id),
148
+ channelId: buildChannelId(repo, isPR ? 'pr' : 'issue', payload.issue.number),
149
+ sender: payload.sender.login,
150
+ content: payload.comment.body,
151
+ repo,
152
+ kind: 'issue_comment',
153
+ createdAt: new Date(payload.comment.created_at).getTime(),
154
+ };
155
+ }
156
+ export function parsePrReviewCommentInbound(payload) {
157
+ if (payload.action !== 'created' || !payload.comment)
158
+ return null;
159
+ const repo = payload.repository.full_name;
160
+ const body = payload.comment.path
161
+ ? `**${payload.comment.path}**\n${payload.comment.diff_hunk ? `\`\`\`diff\n${payload.comment.diff_hunk}\n\`\`\`\n` : ''}${payload.comment.body}`
162
+ : payload.comment.body;
163
+ return {
164
+ id: String(payload.comment.id),
165
+ channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
166
+ sender: payload.sender.login,
167
+ content: body,
168
+ repo,
169
+ kind: 'pr_review_comment',
170
+ createdAt: new Date(payload.comment.created_at).getTime(),
171
+ };
172
+ }
173
+ export function parsePrReviewInbound(payload) {
174
+ if (payload.action !== 'submitted' || !payload.review.body)
175
+ return null;
176
+ const repo = payload.repository.full_name;
177
+ const stateLabel = {
178
+ approved: '✅ APPROVED',
179
+ changes_requested: '🔄 CHANGES REQUESTED',
180
+ commented: '💬 COMMENTED',
181
+ dismissed: '❌ DISMISSED',
182
+ };
183
+ const body = `**[${stateLabel[payload.review.state] || payload.review.state}]**\n${payload.review.body}`;
184
+ return {
185
+ id: String(payload.review.id),
186
+ channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
187
+ sender: payload.sender.login,
188
+ content: body,
189
+ repo,
190
+ kind: 'pr_review',
191
+ createdAt: new Date(payload.review.submitted_at).getTime(),
192
+ };
193
+ }
194
+ export function formatNotification(event, p) {
195
+ const repo = p.repository.full_name;
196
+ const sender = p.sender.login;
197
+ const repoUrl = p.repository.html_url;
198
+ switch (event) {
199
+ case 'push': {
200
+ const branch = p.ref?.replace('refs/heads/', '') || '?';
201
+ const commits = p.commits || [];
202
+ const compareUrl = commits.length >= 2
203
+ ? `${repoUrl}/compare/${commits[0].id.substring(0, 12)}...${commits[commits.length - 1].id.substring(0, 12)}`
204
+ : commits.length === 1 ? `${repoUrl}/commit/${commits[0].id}` : '';
205
+ let msg = `📦 ${repo}\n🌿 ${sender} pushed ${commits.length} commit(s) to \`${branch}\`\n`;
206
+ if (commits.length) {
207
+ msg += '\n';
208
+ msg += commits.slice(0, 5).map((c) => ` • [\`${c.id.substring(0, 7)}\`](${repoUrl}/commit/${c.id}) ${c.message.split('\n')[0]}`).join('\n');
209
+ if (commits.length > 5)
210
+ msg += `\n ... +${commits.length - 5} more`;
211
+ }
212
+ if (compareUrl)
213
+ msg += `\n\n🔗 ${compareUrl}`;
214
+ return msg;
215
+ }
216
+ case 'issues': {
217
+ const i = p.issue;
218
+ const act = p.action === 'opened' ? '📝 opened' : p.action === 'closed' ? '✅ closed' : `🔄 ${p.action || 'updated'}`;
219
+ return `🐛 ${repo}\n👤 ${sender} ${act} issue #${i.number}\n📌 ${i.title}\n🔗 ${i.html_url}`;
220
+ }
221
+ case 'star': {
222
+ const starred = p.action !== 'deleted';
223
+ return `${starred ? '⭐' : '💔'} ${repo}\n👤 ${sender} ${starred ? 'starred' : 'unstarred'}\n🔗 ${repoUrl}`;
224
+ }
225
+ case 'fork':
226
+ return `🍴 ${repo}\n👤 ${sender} forked → ${p.forkee.full_name}\n🔗 ${p.forkee.html_url}`;
227
+ case 'pull_request': {
228
+ const pr = p.pull_request;
229
+ const act = p.action === 'opened' ? '📝 opened'
230
+ : p.action === 'closed' ? (pr.state === 'closed' ? '❌ closed' : '✅ merged')
231
+ : `🔄 ${p.action || 'updated'}`;
232
+ return `🔀 ${repo}\n👤 ${sender} ${act} PR #${pr.number}\n📌 ${pr.title}\n🌿 ${pr.head.ref} → ${pr.base.ref}\n🔗 ${pr.html_url}`;
233
+ }
234
+ default:
235
+ return `📬 ${repo}\n📡 ${event}${p.action ? ` (${p.action})` : ''} by ${sender}\n🔗 ${repoUrl}`;
236
+ }
237
+ }
238
+ /** Parse @mentions in markdown into a flat display string (gateway text path). */
239
+ export function parseMarkdownMentions(md) {
240
+ return md;
241
+ }
package/lib/types.d.ts CHANGED
@@ -14,6 +14,12 @@ export interface GitHubEndpointConfig {
14
14
  webhook_path?: string;
15
15
  /** 事件轮询间隔(秒,默认 60,Webhook 模式下作为降级备选) */
16
16
  poll_interval?: number;
17
+ /** 这些仓库的人类 Issue/PR 评论自动触发 AI(无需 @bot) */
18
+ auto_reply_repos?: string[];
19
+ /** 覆盖 App bot 登录名(默认 {slug}[bot]) */
20
+ bot_login?: string;
21
+ /** 托管 git 工作区根目录(默认 {cwd}/data/github-workspaces) */
22
+ workspace_root?: string;
17
23
  }
18
24
  export interface ParsedChannel {
19
25
  repo: string;
@@ -141,4 +147,3 @@ export interface GitHubOAuthUser {
141
147
  /** 绑定时间 (ms) */
142
148
  created_at: number;
143
149
  }
144
- //# sourceMappingURL=types.d.ts.map
package/lib/types.js CHANGED
@@ -13,4 +13,3 @@ export function parseChannelId(channelId) {
13
13
  export function buildChannelId(repo, type, number) {
14
14
  return type === 'issue' ? `${repo}/issues/${number}` : `${repo}/pull/${number}`;
15
15
  }
16
- //# sourceMappingURL=types.js.map
@@ -0,0 +1,13 @@
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 { type GithubInboundComment, type ResolvedGithubConfig } from './protocol.js';
7
+ export interface GithubWebhookHandler {
8
+ readonly config: ResolvedGithubConfig;
9
+ admit(comment: GithubInboundComment): void;
10
+ }
11
+ export declare function registerGithubWebhookRoutes(http: HttpHost, handler: GithubWebhookHandler): HttpRouteRegistration[];
12
+ export declare function handleGithubWebhookRequest(request: IncomingMessage, response: ServerResponse, handler: GithubWebhookHandler): Promise<void>;
13
+ export declare function dispatchGithubWebhookPayload(event: string, payload: unknown, handler: GithubWebhookHandler): Promise<void>;
package/lib/webhook.js ADDED
@@ -0,0 +1,87 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { headerValue, parseIssueCommentInbound, parsePrReviewCommentInbound, parsePrReviewInbound, readTextBody, verifyWebhookSignature, } from './protocol.js';
3
+ const logger = getLogger('github');
4
+ export function registerGithubWebhookRoutes(http, handler) {
5
+ const routePath = handler.config.webhookPath;
6
+ return [
7
+ http.route('POST', routePath, async (request, response) => {
8
+ await handleGithubWebhookRequest(request, response, handler);
9
+ }, { summary: 'GitHub webhook', tags: ['github'] }),
10
+ ];
11
+ }
12
+ export async function handleGithubWebhookRequest(request, response, handler) {
13
+ const secret = handler.config.webhookSecret;
14
+ if (!secret) {
15
+ response.writeHead(503, { 'Content-Type': 'application/json' });
16
+ response.end(JSON.stringify({ error: 'Webhook not configured' }));
17
+ return;
18
+ }
19
+ const signature = headerValue(request.headers, 'x-hub-signature-256');
20
+ const event = headerValue(request.headers, 'x-github-event');
21
+ const deliveryId = headerValue(request.headers, 'x-github-delivery');
22
+ if (!signature || !event) {
23
+ response.writeHead(400, { 'Content-Type': 'application/json' });
24
+ response.end(JSON.stringify({ error: 'Missing signature or event header' }));
25
+ return;
26
+ }
27
+ try {
28
+ const rawBody = await readTextBody(request);
29
+ if (!verifyWebhookSignature(secret, rawBody, signature)) {
30
+ logger.warn(formatCompact({
31
+ op: 'webhook',
32
+ ok: false,
33
+ error: 'invalid signature',
34
+ delivery: deliveryId,
35
+ }));
36
+ response.writeHead(401, { 'Content-Type': 'application/json' });
37
+ response.end(JSON.stringify({ error: 'Invalid signature' }));
38
+ return;
39
+ }
40
+ let payload;
41
+ try {
42
+ payload = rawBody ? JSON.parse(rawBody) : {};
43
+ }
44
+ catch {
45
+ response.writeHead(400, { 'Content-Type': 'application/json' });
46
+ response.end(JSON.stringify({ error: 'Invalid JSON' }));
47
+ return;
48
+ }
49
+ response.writeHead(200, { 'Content-Type': 'application/json' });
50
+ response.end(JSON.stringify({ ok: true }));
51
+ void dispatchGithubWebhookPayload(event, payload, handler).catch((e) => {
52
+ logger.error(`Webhook 事件处理失败 (${event}):`, e);
53
+ });
54
+ }
55
+ catch (error) {
56
+ logger.error('Webhook error:', error);
57
+ if (!response.headersSent) {
58
+ response.writeHead(500, { 'Content-Type': 'application/json' });
59
+ response.end(JSON.stringify({ error: 'Internal Server Error' }));
60
+ }
61
+ }
62
+ }
63
+ export async function dispatchGithubWebhookPayload(event, payload, handler) {
64
+ if (!payload || typeof payload !== 'object')
65
+ return;
66
+ const body = payload;
67
+ const repo = body.repository?.full_name;
68
+ logger.debug(`Webhook: ${event}${body.action ? `.${body.action}` : ''} ${repo || ''}`);
69
+ if (event === 'issue_comment') {
70
+ const inbound = parseIssueCommentInbound(payload);
71
+ if (inbound)
72
+ handler.admit(inbound);
73
+ return;
74
+ }
75
+ if (event === 'pull_request_review_comment') {
76
+ const inbound = parsePrReviewCommentInbound(payload);
77
+ if (inbound)
78
+ handler.admit(inbound);
79
+ return;
80
+ }
81
+ if (event === 'pull_request_review') {
82
+ const inbound = parsePrReviewInbound(payload);
83
+ if (inbound)
84
+ handler.admit(inbound);
85
+ }
86
+ // Cross-adapter subscription fan-out deferred (needs multi-adapter send in Runtime).
87
+ }
@@ -0,0 +1,21 @@
1
+ import type { GhClient, GitHubBotIdentity } from './gh-client.js';
2
+ /**
3
+ * 校验 GitHub "owner/name" 全名,防止路径穿越与 git 选项注入。
4
+ * 返回通过校验的原值,便于调用方直接使用「已消毒」的变量。
5
+ */
6
+ export declare function assertRepoFullName(repo: string): string;
7
+ /**
8
+ * 校验 git ref 名称,拒绝选项注入(`-` 前缀)与 git 非法字符。
9
+ */
10
+ export declare function assertGitRefName(ref: string): string;
11
+ export declare class WorkspaceManager {
12
+ private readonly gh;
13
+ private readonly rootDir;
14
+ constructor(gh: GhClient, rootDir: string);
15
+ getRepoPath(repo: string): string;
16
+ private runGit;
17
+ configureBotGit(repoPath: string, identity: GitHubBotIdentity): Promise<void>;
18
+ ensureRepo(repo: string): Promise<string>;
19
+ checkoutBranch(repo: string, branch: string, baseRef: string): Promise<string>;
20
+ commitAndPush(repo: string, branch: string, message: string): Promise<string>;
21
+ }
@@ -0,0 +1,145 @@
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
+ const REPO_FULL_NAME_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
8
+ const GIT_REF_ILLEGAL_RE = /[\s\x00-\x1f\x7f~^:?*[\\`;]/;
9
+ /**
10
+ * 校验 GitHub "owner/name" 全名,防止路径穿越与 git 选项注入。
11
+ * 返回通过校验的原值,便于调用方直接使用「已消毒」的变量。
12
+ */
13
+ export function assertRepoFullName(repo) {
14
+ if (typeof repo !== 'string' ||
15
+ !REPO_FULL_NAME_RE.test(repo) ||
16
+ repo.split('/').some((seg) => seg === '' || seg.startsWith('-') || /^\.+$/.test(seg))) {
17
+ throw new TypeError(`非法的仓库全名: ${JSON.stringify(repo)}`);
18
+ }
19
+ return repo;
20
+ }
21
+ /**
22
+ * 校验 git ref 名称,拒绝选项注入(`-` 前缀)与 git 非法字符。
23
+ */
24
+ export function assertGitRefName(ref) {
25
+ if (typeof ref !== 'string' || ref.length === 0) {
26
+ throw new TypeError(`非法的 git ref: ${JSON.stringify(ref)}`);
27
+ }
28
+ if (ref.startsWith('-') ||
29
+ ref.includes('..') ||
30
+ GIT_REF_ILLEGAL_RE.test(ref) ||
31
+ ref.endsWith('/') ||
32
+ ref.endsWith('.')) {
33
+ throw new TypeError(`非法的 git ref: ${JSON.stringify(ref)}`);
34
+ }
35
+ return ref;
36
+ }
37
+ export class WorkspaceManager {
38
+ gh;
39
+ rootDir;
40
+ constructor(gh, rootDir) {
41
+ this.gh = gh;
42
+ this.rootDir = rootDir;
43
+ }
44
+ getRepoPath(repo) {
45
+ repo = assertRepoFullName(repo);
46
+ const [owner, name] = repo.split('/');
47
+ return path.join(this.rootDir, owner, name);
48
+ }
49
+ runGit(cwd, args, env) {
50
+ return new Promise((resolve, reject) => {
51
+ const proc = spawn('git', args, {
52
+ cwd,
53
+ stdio: ['ignore', 'pipe', 'pipe'],
54
+ env: { ...process.env, ...env },
55
+ });
56
+ let stdout = '';
57
+ let stderr = '';
58
+ proc.stdout.on('data', (d) => { stdout += d.toString(); });
59
+ proc.stderr.on('data', (d) => { stderr += d.toString(); });
60
+ proc.on('error', (err) => {
61
+ if (err.code === 'ENOENT')
62
+ reject(new Error('git 未安装'));
63
+ else
64
+ reject(err);
65
+ });
66
+ proc.on('close', (code) => {
67
+ if (code === 0)
68
+ resolve(stdout);
69
+ else
70
+ reject(new Error(stderr.trim() || `git ${args.join(' ')} failed (${code})`));
71
+ });
72
+ });
73
+ }
74
+ configureBotGit(repoPath, identity) {
75
+ return Promise.all([
76
+ this.runGit(repoPath, ['config', 'user.name', identity.login]),
77
+ this.runGit(repoPath, ['config', 'user.email', identity.email]),
78
+ ]).then(() => undefined);
79
+ }
80
+ async ensureRepo(repo) {
81
+ repo = assertRepoFullName(repo);
82
+ if (!this.gh.isAppAuth) {
83
+ throw new Error('GitHub App 认证未配置,无法托管工作区');
84
+ }
85
+ const token = await this.gh.ensureInstallationTokenForRepo(repo);
86
+ if (!token)
87
+ throw new Error(`无法获取 ${repo} 的 Installation Token`);
88
+ const repoPath = this.getRepoPath(repo);
89
+ fs.mkdirSync(path.dirname(repoPath), { recursive: true });
90
+ const identity = await this.gh.getBotIdentity();
91
+ if (!identity)
92
+ throw new Error('无法解析 GitHub App Bot 身份');
93
+ const cloneUrl = this.gh.buildCloneUrl(repo, token);
94
+ if (!fs.existsSync(path.join(repoPath, '.git'))) {
95
+ await this.runGit(path.dirname(repoPath), ['clone', cloneUrl, path.basename(repoPath)]);
96
+ }
97
+ else {
98
+ await this.runGit(repoPath, ['remote', 'set-url', 'origin', cloneUrl]);
99
+ await this.runGit(repoPath, ['fetch', 'origin', '--prune']);
100
+ }
101
+ await this.configureBotGit(repoPath, identity);
102
+ return repoPath;
103
+ }
104
+ async checkoutBranch(repo, branch, baseRef) {
105
+ repo = assertRepoFullName(repo);
106
+ branch = assertGitRefName(branch);
107
+ baseRef = assertGitRefName(baseRef);
108
+ const repoPath = await this.ensureRepo(repo);
109
+ const localBranches = await this.runGit(repoPath, ['branch', '--list', branch]);
110
+ if (localBranches.trim()) {
111
+ await this.runGit(repoPath, ['checkout', branch]);
112
+ await this.runGit(repoPath, ['pull', '--rebase', 'origin', branch]).catch(async () => {
113
+ await this.runGit(repoPath, ['fetch', 'origin', branch]);
114
+ });
115
+ return repoPath;
116
+ }
117
+ const remoteBranch = await this.runGit(repoPath, ['ls-remote', '--heads', 'origin', branch]);
118
+ if (remoteBranch.trim()) {
119
+ await this.runGit(repoPath, ['checkout', '-B', branch, `origin/${branch}`]);
120
+ return repoPath;
121
+ }
122
+ await this.runGit(repoPath, ['fetch', 'origin', baseRef]);
123
+ await this.runGit(repoPath, ['checkout', '-B', branch, `origin/${baseRef}`]);
124
+ return repoPath;
125
+ }
126
+ async commitAndPush(repo, branch, message) {
127
+ repo = assertRepoFullName(repo);
128
+ branch = assertGitRefName(branch);
129
+ const repoPath = this.getRepoPath(repo);
130
+ if (!fs.existsSync(repoPath)) {
131
+ throw new Error(`工作区不存在: ${repoPath},请先 github_prepare_workspace`);
132
+ }
133
+ const token = await this.gh.ensureInstallationTokenForRepo(repo);
134
+ if (!token)
135
+ throw new Error('Installation Token 不可用');
136
+ await this.runGit(repoPath, ['remote', 'set-url', 'origin', this.gh.buildCloneUrl(repo, token)]);
137
+ const status = await this.runGit(repoPath, ['status', '--porcelain']);
138
+ if (!status.trim())
139
+ return '没有可提交的变更';
140
+ await this.runGit(repoPath, ['add', '-A']);
141
+ await this.runGit(repoPath, ['commit', '-m', message]);
142
+ await this.runGit(repoPath, ['push', '-u', 'origin', branch]);
143
+ return `已 push 到 origin/${branch}`;
144
+ }
145
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-github",
3
- "version": "3.0.1",
4
- "description": "Zhin.js adapter for GitHub (gh CLI) treat issues/PRs as chat channels, full repo management, webhook notifications",
3
+ "version": "3.0.3",
4
+ "description": "Zhin.js GitHub adapter for Plugin Runtime (App auth + webhook)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
7
7
  "types": "./lib/index.d.ts",
@@ -18,15 +18,6 @@
18
18
  },
19
19
  "./package.json": "./package.json"
20
20
  },
21
- "files": [
22
- "src",
23
- "lib",
24
- "client",
25
- "dist",
26
- "skills",
27
- "plugin.yml",
28
- "README.md"
29
- ],
30
21
  "keywords": [
31
22
  "zhin",
32
23
  "zhin.js",
@@ -44,25 +35,56 @@
44
35
  "url": "https://github.com/lc-cn"
45
36
  },
46
37
  "license": "MIT",
47
- "devDependencies": {
48
- "typescript": "^6.0.3",
49
- "@zhin.js/host-router": "2.0.2",
50
- "zhin.js": "4.1.1"
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/zhinjs/zhin.git",
41
+ "directory": "plugins/adapters/github"
42
+ },
43
+ "dependencies": {
44
+ "@zhin.js/adapter": "1.0.1",
45
+ "@zhin.js/core": "1.3.5",
46
+ "@zhin.js/host-http": "1.0.1",
47
+ "@zhin.js/logger": "1.0.75",
48
+ "@zhin.js/plugin-runtime": "1.0.1"
51
49
  },
52
50
  "peerDependencies": {
53
- "@zhin.js/host-router": "2.0.2",
54
- "zhin.js": "4.1.1"
51
+ "zod": "^4.0.0",
52
+ "@zhin.js/adapter": "1.0.1",
53
+ "@zhin.js/agent": "1.0.4",
54
+ "@zhin.js/core": "1.3.5",
55
+ "@zhin.js/host-http": "1.0.1",
56
+ "@zhin.js/plugin-runtime": "1.0.1",
57
+ "zhin.js": "4.1.3"
55
58
  },
56
59
  "peerDependenciesMeta": {
57
- "@zhin.js/host-router": {
60
+ "zhin.js": {
61
+ "optional": true
62
+ },
63
+ "@zhin.js/agent": {
64
+ "optional": true
65
+ },
66
+ "zod": {
58
67
  "optional": true
59
68
  }
60
69
  },
61
- "repository": {
62
- "type": "git",
63
- "url": "git+https://github.com/zhinjs/zhin.git",
64
- "directory": "plugins/adapters/github"
70
+ "devDependencies": {
71
+ "@types/node": "^26.1.0",
72
+ "typescript": "^6.0.3",
73
+ "vitest": "^4.1.10",
74
+ "zod": "^4.4.3",
75
+ "@zhin.js/agent": "1.0.4",
76
+ "zhin.js": "4.1.3"
65
77
  },
78
+ "files": [
79
+ "adapters",
80
+ "plugin.ts",
81
+ "schema.json",
82
+ "src",
83
+ "lib",
84
+ "agent",
85
+ "README.md",
86
+ "CHANGELOG.md"
87
+ ],
66
88
  "publishConfig": {
67
89
  "access": "public",
68
90
  "registry": "https://registry.npmjs.org"
@@ -70,8 +92,23 @@
70
92
  "engines": {
71
93
  "node": "^20.19.0 || >=22.12.0"
72
94
  },
95
+ "zhin": {
96
+ "protocol": 1,
97
+ "type": "plugin",
98
+ "entry": "./plugin.ts",
99
+ "engine": "^1.0.0",
100
+ "runtime": "trusted",
101
+ "features": [
102
+ {
103
+ "package": "@zhin.js/adapter",
104
+ "api": "^1.0.0"
105
+ }
106
+ ],
107
+ "plugins": []
108
+ },
73
109
  "scripts": {
74
110
  "build": "tsc",
75
- "clean": "rimraf lib"
111
+ "clean": "rimraf lib",
112
+ "test": "NODE_OPTIONS=--experimental-strip-types vitest run --root ../../.. plugins/adapters/github/tests"
76
113
  }
77
114
  }