Personal Telegram developer console for GitHub

feat/studio-g0-foundation
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 886 lines 30.1 KB
Raw
1 import { DEFAULT_CONFIG } from './config.js';
2
3 const clampPage = (value) => Math.max(1, Math.min(100, Number(value) || 1));
4 const clampPerPage = (value, fallback = 10) =>
5 Math.max(1, Math.min(20, Number(value) || fallback));
6 const boundedPatch = (value) => String(value || '').slice(0, 1200);
7 const numericId = (value, label) => {
8 const text = String(value ?? '');
9 if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`);
10 return text;
11 };
12 const fullSha = (value, label = 'Git commit') => {
13 const text = String(value || '');
14 if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`);
15 return text;
16 };
17 const gitBranch = (value) => {
18 const branch = String(value || '');
19 if (
20 !branch ||
21 branch.includes('..') ||
22 branch.startsWith('/') ||
23 branch.endsWith('/') ||
24 branch.includes('\0')
25 )
26 throw new Error('Invalid Git branch');
27 return branch;
28 };
29 const encodedBranch = (value) =>
30 gitBranch(value).split('/').map(encodeURIComponent).join('/');
31 const encodedPath = (value) =>
32 String(value || '')
33 .split('/')
34 .filter(Boolean)
35 .map(encodeURIComponent)
36 .join('/');
37 const decodeBase64Utf8 = (value) => {
38 let binary;
39 try {
40 binary = atob(String(value || '').replace(/\s/g, ''));
41 } catch {
42 throw new Error('GitHub file content is not valid base64');
43 }
44 const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
45 try {
46 return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
47 } catch {
48 throw new Error('GitHub file content is not valid UTF-8 text');
49 }
50 };
51
52 export class GitHubService {
53 constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
54 this.token = token;
55 this.owner = owner;
56 this.baseUrl = 'https://api.github.com';
57 }
58 requireToken() {
59 if (!this.token) throw new Error('GITHUB_TOKEN is not configured');
60 }
61 getHeaders() {
62 this.requireToken();
63 return {
64 'User-Agent': 'Nexa-Dev-Bot-v1.1',
65 'Accept': 'application/vnd.github+json',
66 'Authorization': `Bearer ${this.token}`,
67 'X-GitHub-Api-Version': '2022-11-28'
68 };
69 }
70 async requestJson(
71 url,
72 label,
73 {
74 method = 'GET',
75 body,
76 allowEmpty = false,
77 allowNotFound = false,
78 includeHeaders = false
79 } = {}
80 ) {
81 const headers = this.getHeaders();
82 const options = { method, headers };
83 if (body !== undefined) {
84 options.body = JSON.stringify(body);
85 options.headers = { ...headers, 'Content-Type': 'application/json' };
86 }
87 const res = await fetch(url, options);
88 const raw = await res.text();
89 let parsed = null;
90 if (raw) {
91 try {
92 parsed = JSON.parse(raw);
93 } catch {
94 parsed = null;
95 }
96 }
97 if (!res.ok) {
98 if (allowNotFound && res.status === 404) return null;
99 const providerMessage = parsed?.message || raw.slice(0, 240);
100 const detail = providerMessage ? ` ${providerMessage}` : '';
101 const error = new Error(`${label} failed: ${res.status}${detail}`);
102 error.status = res.status;
103 throw error;
104 }
105 if (allowEmpty) return { accepted: true, status: res.status };
106 if (!raw) return null;
107 if (parsed === null)
108 throw new Error(`${label} failed: invalid JSON response`);
109 return includeHeaders ? { data: parsed, headers: res.headers } : parsed;
110 }
111 async requestText(url, label, { maxChars = 12000 } = {}) {
112 const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
113 const raw = await res.text();
114 if (!res.ok) {
115 const detail = raw ? ` ${raw.slice(0, 240)}` : '';
116 throw new Error(`${label} failed: ${res.status}${detail}`);
117 }
118 const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
119 return {
120 text: raw.length > limit ? raw.slice(-limit) : raw,
121 truncated: raw.length > limit
122 };
123 }
124 repoUrl(repo, suffix = '') {
125 return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
126 }
127 repositoryLookupUrl(repoRef) {
128 const value = String(repoRef || '');
129 return /^\d+$/.test(value)
130 ? `${this.baseUrl}/repositories/${value}`
131 : this.repoUrl(value);
132 }
133 repositoryApiBase(fullName) {
134 const parts = String(fullName || '')
135 .split('/')
136 .filter(Boolean);
137 if (parts.length !== 2)
138 throw new Error('GitHub repository full_name is invalid');
139 return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
140 }
141 async getRepositoryContext(repoRef) {
142 const value = String(repoRef || '');
143 try {
144 const raw = await this.requestJson(
145 this.repositoryLookupUrl(value),
146 'GitHub repository'
147 );
148 return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
149 } catch (error) {
150 if (!/^\d+$/.test(value) || error?.status !== 404) throw error;
151 const repositories = await this.listRepositories();
152 const match = repositories.find((repo) => repo.id === value);
153 if (!match?.fullName) throw error;
154 const apiBase = this.repositoryApiBase(match.fullName);
155 const raw = await this.requestJson(apiBase, 'GitHub repository');
156 return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
157 }
158 }
159 mapRepository(r) {
160 return {
161 id: String(r.id ?? r.name),
162 name: r.name,
163 fullName: r.full_name,
164 private: !!r.private,
165 description: r.description || '',
166 defaultBranch: r.default_branch || 'main',
167 archived: !!r.archived,
168 htmlUrl: r.html_url || '',
169 stars: r.stargazers_count ?? 0,
170 forks: r.forks_count ?? 0
171 };
172 }
173 mapWorkflowRun(run = {}) {
174 const headSha = String(run.head_sha || '');
175 const mapped = {
176 id: run.id,
177 name: run.name || 'Workflow',
178 status: run.status || '',
179 conclusion: run.conclusion || null,
180 event: run.event || '',
181 branch: run.head_branch || '',
182 sha: headSha.slice(0, 7),
183 runNumber: run.run_number ?? null,
184 url: run.html_url || '',
185 createdAt: run.created_at || '',
186 updatedAt: run.updated_at || ''
187 };
188 if (/^[a-f0-9]{40}$/i.test(headSha)) mapped.fullSha = headSha.toLowerCase();
189 if (Number.isSafeInteger(Number(run.workflow_id)))
190 mapped.workflowId = Number(run.workflow_id);
191 return mapped;
192 }
193 mapWorkflowJob(job = {}) {
194 return {
195 id: job.id,
196 name: job.name || 'Job',
197 status: job.status || '',
198 conclusion: job.conclusion || null,
199 startedAt: job.started_at || '',
200 completedAt: job.completed_at || '',
201 url: job.html_url || '',
202 steps: (job.steps || []).slice(0, 30).map((step) => ({
203 number: step.number,
204 name: step.name || 'Step',
205 status: step.status || '',
206 conclusion: step.conclusion || null
207 }))
208 };
209 }
210 mapPullRequestFile(file = {}) {
211 return {
212 filename: file.filename || '',
213 status: file.status || '',
214 additions: file.additions ?? 0,
215 deletions: file.deletions ?? 0,
216 changes: file.changes ?? 0,
217 patch: boundedPatch(file.patch)
218 };
219 }
220 mapIssue(issue = {}) {
221 return {
222 number: issue.number,
223 title: issue.title || '',
224 state: issue.state || '',
225 author: issue.user?.login || 'unknown',
226 comments: issue.comments ?? 0,
227 url: issue.html_url || ''
228 };
229 }
230 async listRepositories() {
231 const endpoint = new URL(`${this.baseUrl}/user/repos`);
232 let next = `${endpoint.href}?sort=updated&per_page=100&affiliation=owner,collaborator,organization_member`;
233 let page = 1;
234 const repositories = [];
235 const visited = new Set();
236 while (next) {
237 if (visited.has(next))
238 throw new Error('GitHub repository pagination repeated a page');
239 visited.add(next);
240 const { data, headers } = await this.requestJson(
241 next,
242 'GitHub repositories',
243 { includeHeaders: true }
244 );
245 if (!Array.isArray(data))
246 throw new Error('GitHub repository page is not a repository listing');
247 repositories.push(
248 ...data.map((r) => {
249 const repo = this.mapRepository(r);
250 return {
251 ...repo,
252 title: `${repo.name} ${repo.private ? '🔒' : '🌐'}`
253 };
254 })
255 );
256 const link = headers.get('link');
257 next = '';
258 if (!link) continue;
259 for (const part of link.split(/,(?=\s*<)/)) {
260 const match = part.trim().match(/^<([^>]+)>\s*((?:;[^<>]*)*)$/);
261 if (!match)
262 throw new Error('GitHub repository pagination Link is invalid');
263 const relation = match[2].match(
264 /(?:^|;)\s*rel\s*=\s*(?:"([^"]*)"|([^;\s]+))/i
265 );
266 if (
267 !relation ||
268 !(relation[1] || relation[2]).split(/\s+/).includes('next')
269 )
270 continue;
271 if (next)
272 throw new Error(
273 'GitHub repository pagination has multiple next pages'
274 );
275 let target;
276 try {
277 target = new URL(match[1], endpoint);
278 } catch {
279 throw new Error('GitHub repository pagination URL is invalid');
280 }
281 const nextPage = target.searchParams.get('page') || '';
282 if (
283 target.origin !== endpoint.origin ||
284 target.pathname !== endpoint.pathname ||
285 target.username ||
286 target.password ||
287 target.hash ||
288 target.searchParams.get('per_page') !== '100' ||
289 !/^[1-9][0-9]*$/.test(nextPage) ||
290 !Number.isSafeInteger(Number(nextPage)) ||
291 Number(nextPage) <= page
292 )
293 throw new Error('GitHub repository pagination target is invalid');
294 page = Number(nextPage);
295 next = target.href;
296 }
297 }
298 return repositories;
299 }
300 async getRepository(repoRef) {
301 const { raw } = await this.getRepositoryContext(repoRef);
302 return this.mapRepository(raw);
303 }
304 async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
305 const count = clampPerPage(perPage, 10);
306 const pageNumber = clampPage(page);
307 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
308 const { apiBase } = await this.getRepositoryContext(repoRef);
309 const data = await this.requestJson(
310 `${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`,
311 'GitHub pull requests'
312 );
313 return data.map((pr) => ({
314 number: pr.number,
315 title: pr.title,
316 author: pr.user?.login || 'unknown',
317 state: pr.state,
318 merged: !!pr.merged_at,
319 createdAt: pr.created_at,
320 url: pr.html_url
321 }));
322 }
323 async getPullRequest(repoRef, prNumber) {
324 const number = numericId(prNumber, 'pull request');
325 const { apiBase } = await this.getRepositoryContext(repoRef);
326 const pr = await this.requestJson(
327 `${apiBase}/pulls/${number}`,
328 'GitHub pull request'
329 );
330 return {
331 number: pr.number,
332 title: pr.title || '',
333 author: pr.user?.login || 'unknown',
334 state: pr.state || '',
335 draft: !!pr.draft,
336 merged: !!(pr.merged ?? pr.merged_at),
337 body: pr.body || '',
338 url: pr.html_url || '',
339 head: pr.head?.ref || '',
340 headSha: pr.head?.sha || '',
341 base: pr.base?.ref || '',
342 additions: pr.additions ?? 0,
343 deletions: pr.deletions ?? 0,
344 changedFiles: pr.changed_files ?? 0
345 };
346 }
347 async listPullRequestFiles(
348 repoRef,
349 prNumber,
350 { perPage = 20, page = 1 } = {}
351 ) {
352 const number = numericId(prNumber, 'pull request');
353 const count = clampPerPage(perPage, 20);
354 const pageNumber = clampPage(page);
355 const { apiBase } = await this.getRepositoryContext(repoRef);
356 const data = await this.requestJson(
357 `${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`,
358 'GitHub pull request files'
359 );
360 return data.map((file) => this.mapPullRequestFile(file));
361 }
362 async listCommits(repoRef) {
363 const { apiBase } = await this.getRepositoryContext(repoRef);
364 const data = await this.requestJson(
365 `${apiBase}/commits?per_page=5`,
366 'GitHub commits'
367 );
368 return data.map((c) => ({
369 sha: String(c.sha || '').slice(0, 7),
370 fullSha: String(c.sha || ''),
371 message: String(c.commit?.message || '').split('\n')[0],
372 author: c.author?.login || c.commit?.author?.name || 'Unknown',
373 date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
374 }));
375 }
376 async getCommit(repoRef, sha) {
377 const commitSha = fullSha(sha);
378 const { apiBase } = await this.getRepositoryContext(repoRef);
379 const c = await this.requestJson(
380 `${apiBase}/commits/${commitSha}`,
381 'GitHub commit'
382 );
383 const files = (c.files || []).slice(0, 20).map((file) => ({
384 filename: file.filename || '',
385 status: file.status || '',
386 additions: file.additions ?? 0,
387 deletions: file.deletions ?? 0,
388 changes: file.changes ?? 0
389 }));
390 return {
391 sha: commitSha,
392 shortSha: commitSha.slice(0, 7),
393 message: String(c.commit?.message || ''),
394 author: c.author?.login || c.commit?.author?.name || 'Unknown',
395 date: c.commit?.author?.date || '',
396 additions: c.stats?.additions ?? 0,
397 deletions: c.stats?.deletions ?? 0,
398 changedFiles: files.length,
399 files
400 };
401 }
402 async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
403 const commitSha = fullSha(sha);
404 const count = clampPerPage(perPage, 20);
405 const pageNumber = clampPage(page);
406 const { apiBase } = await this.getRepositoryContext(repoRef);
407 const data = await this.requestJson(
408 `${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`,
409 'GitHub check runs'
410 );
411 return (data.check_runs || []).map((check) => ({
412 id: check.id,
413 name: check.name || 'Check',
414 status: check.status || '',
415 conclusion: check.conclusion || null,
416 url: check.html_url || ''
417 }));
418 }
419 async listFiles(repoRef, path = '', { ref } = {}) {
420 const { apiBase } = await this.getRepositoryContext(repoRef);
421 const suffix = path ? `/contents/${encodedPath(path)}` : '/contents';
422 const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : '';
423 const data = await this.requestJson(
424 `${apiBase}${suffix}${query}`,
425 'GitHub contents'
426 );
427 if (!Array.isArray(data))
428 throw new Error('GitHub contents response is not a directory listing');
429 return data.map((item) => ({
430 name: item.name,
431 path: item.path,
432 type: item.type === 'dir' ? 'dir' : 'file',
433 size: item.size ?? 0,
434 sha: item.sha || ''
435 }));
436 }
437 async getGitRef(repoRef, branch, { allowMissing = false } = {}) {
438 const branchName = gitBranch(branch);
439 const { apiBase } = await this.getRepositoryContext(repoRef);
440 const data = await this.requestJson(
441 `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
442 'GitHub branch ref',
443 { allowNotFound: allowMissing }
444 );
445 if (data === null) return null;
446 return {
447 branch: branchName,
448 sha: fullSha(data?.object?.sha, 'Git branch head')
449 };
450 }
451 async getBranchSnapshot(repoRef, branch) {
452 const branchName = gitBranch(branch);
453 const { apiBase } = await this.getRepositoryContext(repoRef);
454 const ref = await this.requestJson(
455 `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
456 'GitHub branch ref'
457 );
458 const headSha = fullSha(ref?.object?.sha, 'Git branch head');
459 const commit = await this.requestJson(
460 `${apiBase}/git/commits/${headSha}`,
461 'GitHub branch commit'
462 );
463 const treeSha = fullSha(commit?.tree?.sha, 'Git tree');
464 return { branch: branchName, headSha, treeSha };
465 }
466 async getFileAtRef(repoRef, path, ref) {
467 const filePath = String(path || '');
468 if (!filePath || filePath.startsWith('/') || filePath.includes('\0'))
469 throw new Error('Invalid GitHub file path');
470 const commitRef = fullSha(ref);
471 const { apiBase } = await this.getRepositoryContext(repoRef);
472 const data = await this.requestJson(
473 `${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`,
474 'GitHub file'
475 );
476 if (!data || Array.isArray(data) || data.type !== 'file')
477 throw new Error('GitHub contents response is not a file');
478 if (data.encoding !== 'base64')
479 throw new Error('GitHub file encoding is not supported');
480 const content = decodeBase64Utf8(data.content || '');
481 return {
482 path: data.path || filePath,
483 sha: String(data.sha || ''),
484 size: Number(data.size) || 0,
485 encoding: 'utf-8',
486 content
487 };
488 }
489 async createGitBlob(repoRef, text) {
490 const { apiBase } = await this.getRepositoryContext(repoRef);
491 const data = await this.requestJson(
492 `${apiBase}/git/blobs`,
493 'GitHub create blob',
494 {
495 method: 'POST',
496 body: { content: String(text ?? ''), encoding: 'utf-8' }
497 }
498 );
499 return { sha: fullSha(data?.sha, 'Git blob') };
500 }
501 async createGitTree(repoRef, { baseTreeSha, entries } = {}) {
502 const base = fullSha(baseTreeSha, 'Git base tree');
503 if (!Array.isArray(entries))
504 throw new Error('Git tree entries are required');
505 const tree = entries.map((entry) => {
506 const path = String(entry?.path || '');
507 if (!path || path.startsWith('/') || path.includes('\0'))
508 throw new Error('Invalid Git tree path');
509 if (entry?.mode !== '100644' || entry?.type !== 'blob')
510 throw new Error('Unsupported Git tree entry');
511 return {
512 path,
513 mode: '100644',
514 type: 'blob',
515 sha: fullSha(entry.sha, 'Git blob')
516 };
517 });
518 const { apiBase } = await this.getRepositoryContext(repoRef);
519 const data = await this.requestJson(
520 `${apiBase}/git/trees`,
521 'GitHub create tree',
522 { method: 'POST', body: { base_tree: base, tree } }
523 );
524 return { sha: fullSha(data?.sha, 'Git tree') };
525 }
526 async createGitCommit(
527 repoRef,
528 { message, treeSha, parentSha, timestamp } = {}
529 ) {
530 const commitMessage = String(message || '');
531 if (!commitMessage) throw new Error('Git commit message is required');
532 const tree = fullSha(treeSha, 'Git tree');
533 const parent = fullSha(parentSha, 'Git parent commit');
534 const date = new Date(String(timestamp || ''));
535 if (
536 Number.isNaN(date.getTime()) ||
537 date.toISOString() !== String(timestamp)
538 )
539 throw new Error('Invalid Git commit timestamp');
540 const identity = {
541 name: 'Nexa Dev Bot',
542 email: 'nexa-dev-bot@users.noreply.github.com',
543 date: String(timestamp)
544 };
545 const { apiBase } = await this.getRepositoryContext(repoRef);
546 const data = await this.requestJson(
547 `${apiBase}/git/commits`,
548 'GitHub create commit',
549 {
550 method: 'POST',
551 body: {
552 message: commitMessage,
553 tree,
554 parents: [parent],
555 author: identity,
556 committer: identity
557 }
558 }
559 );
560 return { sha: fullSha(data?.sha, 'Git commit') };
561 }
562 async createGitBranchRef(repoRef, { branch, sha } = {}) {
563 const branchName = gitBranch(branch);
564 const commitSha = fullSha(sha, 'Git commit');
565 const { apiBase } = await this.getRepositoryContext(repoRef);
566 const data = await this.requestJson(
567 `${apiBase}/git/refs`,
568 'GitHub create branch ref',
569 {
570 method: 'POST',
571 body: { ref: `refs/heads/${branchName}`, sha: commitSha }
572 }
573 );
574 return {
575 ref: String(data?.ref || `refs/heads/${branchName}`),
576 sha: fullSha(data?.object?.sha || commitSha, 'Git commit')
577 };
578 }
579 async listTree(repoRef, sha) {
580 if (!/^[a-f0-9]{40}$/i.test(String(sha || '')))
581 throw new Error('Invalid Git tree SHA');
582 const { apiBase } = await this.getRepositoryContext(repoRef);
583 const data = await this.requestJson(
584 `${apiBase}/git/trees/${encodeURIComponent(sha)}`,
585 'GitHub tree'
586 );
587 return (data.tree || [])
588 .filter((item) => item.type === 'tree' || item.type === 'blob')
589 .map((item) => ({
590 name: item.path,
591 path: item.path,
592 type: item.type === 'tree' ? 'dir' : 'file',
593 size: item.size ?? 0,
594 sha: item.sha || ''
595 }));
596 }
597 async getBlob(repoRef, sha) {
598 if (!/^[a-f0-9]{40}$/i.test(String(sha || '')))
599 throw new Error('Invalid Git blob SHA');
600 const { apiBase } = await this.getRepositoryContext(repoRef);
601 const data = await this.requestJson(
602 `${apiBase}/git/blobs/${encodeURIComponent(sha)}`,
603 'GitHub blob'
604 );
605 return {
606 encoding: data.encoding || '',
607 size: data.size ?? 0,
608 content: data.content || ''
609 };
610 }
611 async getRepoStatus(repoRef) {
612 const { raw, apiBase } = await this.getRepositoryContext(repoRef);
613 const runsData = await this.requestJson(
614 `${apiBase}/actions/runs?per_page=3`,
615 'GitHub Actions runs'
616 );
617 const runs = runsData.workflow_runs || [];
618 return {
619 repo: String(repoRef),
620 repoName: raw.name,
621 defaultBranch: raw.default_branch || 'main',
622 lastRuns: runs.map((r) => ({
623 name: r.name,
624 status: r.status,
625 conclusion: r.conclusion,
626 commit: r.head_commit?.message?.slice(0, 80) || '',
627 url: r.html_url || ''
628 }))
629 };
630 }
631 async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
632 const count = clampPerPage(perPage, 10);
633 const pageNumber = clampPage(page);
634 const { apiBase } = await this.getRepositoryContext(repoRef);
635 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
636 const data = await this.requestJson(
637 `${apiBase}/actions/runs?per_page=${count}${pageQuery}`,
638 'GitHub workflow runs'
639 );
640 return (data.workflow_runs || []).map((run) => this.mapWorkflowRun(run));
641 }
642 async getWorkflowRun(repoRef, runId) {
643 const id = numericId(runId, 'workflow run');
644 const { apiBase } = await this.getRepositoryContext(repoRef);
645 return this.mapWorkflowRun(
646 await this.requestJson(
647 `${apiBase}/actions/runs/${id}`,
648 'GitHub workflow run'
649 )
650 );
651 }
652 async listWorkflowJobs(repoRef, runId) {
653 const id = numericId(runId, 'workflow run');
654 const { apiBase } = await this.getRepositoryContext(repoRef);
655 const data = await this.requestJson(
656 `${apiBase}/actions/runs/${id}/jobs?per_page=20`,
657 'GitHub workflow jobs'
658 );
659 return (data.jobs || []).map((job) => this.mapWorkflowJob(job));
660 }
661 async getWorkflowJob(repoRef, jobId) {
662 const id = numericId(jobId, 'workflow job');
663 const { apiBase } = await this.getRepositoryContext(repoRef);
664 return this.mapWorkflowJob(
665 await this.requestJson(
666 `${apiBase}/actions/jobs/${id}`,
667 'GitHub workflow job'
668 )
669 );
670 }
671 async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
672 const id = numericId(jobId, 'workflow job');
673 const { apiBase } = await this.getRepositoryContext(repoRef);
674 return this.requestText(
675 `${apiBase}/actions/jobs/${id}/logs`,
676 'GitHub workflow job log',
677 { maxChars }
678 );
679 }
680 async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
681 const id = numericId(runId, 'workflow run');
682 const count = clampPerPage(perPage, 20);
683 const pageNumber = clampPage(page);
684 const { apiBase } = await this.getRepositoryContext(repoRef);
685 const data = await this.requestJson(
686 `${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`,
687 'GitHub workflow artifacts'
688 );
689 return (data.artifacts || []).map((artifact) => ({
690 id: artifact.id,
691 name: artifact.name || 'Artifact',
692 size: artifact.size_in_bytes ?? 0,
693 expired: !!artifact.expired,
694 createdAt: artifact.created_at || '',
695 expiresAt: artifact.expires_at || '',
696 downloadUrl: artifact.archive_download_url || ''
697 }));
698 }
699 async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
700 const count = clampPerPage(perPage, 20);
701 const pageNumber = clampPage(page);
702 const { apiBase } = await this.getRepositoryContext(repoRef);
703 const data = await this.requestJson(
704 `${apiBase}/branches?per_page=${count}&page=${pageNumber}`,
705 'GitHub branches'
706 );
707 return data.map((branch) => ({
708 name: branch.name || '',
709 sha: branch.commit?.sha || '',
710 protected: !!branch.protected
711 }));
712 }
713 async compareWithDefault(repoRef, headSha) {
714 const head = fullSha(headSha);
715 const { raw, apiBase } = await this.getRepositoryContext(repoRef);
716 const base = raw.default_branch || 'main';
717 const data = await this.requestJson(
718 `${apiBase}/compare/${encodeURIComponent(base)}...${head}`,
719 'GitHub compare'
720 );
721 return {
722 base,
723 head,
724 status: data.status || '',
725 aheadBy: data.ahead_by ?? 0,
726 behindBy: data.behind_by ?? 0,
727 totalCommits: data.total_commits ?? 0,
728 baseSha: data.base_commit?.sha || '',
729 mergeBaseSha: data.merge_base_commit?.sha || '',
730 files: (data.files || [])
731 .slice(0, 20)
732 .map((file) => this.mapPullRequestFile(file))
733 };
734 }
735 async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
736 const count = clampPerPage(perPage, 10);
737 const pageNumber = clampPage(page);
738 const { apiBase } = await this.getRepositoryContext(repoRef);
739 const data = await this.requestJson(
740 `${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`,
741 'GitHub issues'
742 );
743 return data
744 .filter((issue) => !issue.pull_request)
745 .map((issue) => this.mapIssue(issue));
746 }
747 async listIssuesPage(repoRef, { page = 1 } = {}) {
748 const pageNumber = clampPage(page);
749 const { apiBase } = await this.getRepositoryContext(repoRef);
750 const data = await this.requestJson(
751 `${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`,
752 'GitHub issues'
753 );
754 return {
755 items: data
756 .filter((issue) => !issue.pull_request)
757 .map((issue) => this.mapIssue(issue)),
758 hasMore: data.length === 20
759 };
760 }
761 async getIssue(repoRef, issueNumber) {
762 const number = numericId(issueNumber, 'issue');
763 const { apiBase } = await this.getRepositoryContext(repoRef);
764 const issue = await this.requestJson(
765 apiBase + '/issues/' + number,
766 'GitHub issue'
767 );
768 return {
769 ...this.mapIssue(issue),
770 body: issue.body || '',
771 labels: (issue.labels || [])
772 .map((label) => (typeof label === 'string' ? label : label.name))
773 .filter(Boolean),
774 assignees: (issue.assignees || [])
775 .map((user) => user.login)
776 .filter(Boolean),
777 createdAt: issue.created_at || '',
778 updatedAt: issue.updated_at || ''
779 };
780 }
781 async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
782 const count = clampPerPage(perPage, 10);
783 const pageNumber = clampPage(page);
784 const { apiBase } = await this.getRepositoryContext(repoRef);
785 const data = await this.requestJson(
786 `${apiBase}/releases?per_page=${count}&page=${pageNumber}`,
787 'GitHub releases'
788 );
789 return data.map((release) => ({
790 id: release.id,
791 tag: release.tag_name || '',
792 name: release.name || release.tag_name || 'Release',
793 draft: !!release.draft,
794 prerelease: !!release.prerelease,
795 publishedAt: release.published_at || release.created_at || '',
796 url: release.html_url || ''
797 }));
798 }
799 async getRelease(repoRef, releaseId) {
800 const id = numericId(releaseId, 'release');
801 const { apiBase } = await this.getRepositoryContext(repoRef);
802 const release = await this.requestJson(
803 apiBase + '/releases/' + id,
804 'GitHub release'
805 );
806 return {
807 id: release.id,
808 tag: release.tag_name || '',
809 name: release.name || release.tag_name || 'Release',
810 body: release.body || '',
811 draft: !!release.draft,
812 prerelease: !!release.prerelease,
813 publishedAt: release.published_at || release.created_at || '',
814 author: release.author?.login || 'unknown',
815 target: release.target_commitish || '',
816 url: release.html_url || ''
817 };
818 }
819 async mergePullRequest(
820 repoRef,
821 prNumber,
822 { expectedHeadSha, mergeMethod = 'squash' } = {}
823 ) {
824 const number = numericId(prNumber, 'pull request');
825 const method = String(mergeMethod || 'squash');
826 if (!['merge', 'squash', 'rebase'].includes(method))
827 throw new Error('Unsupported merge method');
828 const expected = fullSha(expectedHeadSha, 'expected pull request head');
829 const { apiBase } = await this.getRepositoryContext(repoRef);
830 const result = await this.requestJson(
831 `${apiBase}/pulls/${number}/merge`,
832 'GitHub pull request merge',
833 { method: 'PUT', body: { sha: expected, merge_method: method } }
834 );
835 if (!result?.merged)
836 throw new Error(
837 `GitHub pull request merge failed: ${String(result?.message || 'not merged').slice(0, 240)}`
838 );
839 return {
840 merged: true,
841 sha: String(result.sha || ''),
842 message: String(result.message || '')
843 };
844 }
845 async dispatchWorkflow(repoRef, workflowId, { ref, inputs = {} } = {}) {
846 const id = numericId(workflowId, 'workflow');
847 const targetRef = String(ref || '');
848 if (!targetRef || targetRef.includes('\0'))
849 throw new Error('Workflow dispatch ref is required');
850 if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs))
851 throw new Error('Workflow dispatch inputs must be an object');
852 const { apiBase } = await this.getRepositoryContext(repoRef);
853 return this.requestJson(
854 `${apiBase}/actions/workflows/${id}/dispatches`,
855 'GitHub workflow dispatch',
856 { method: 'POST', body: { ref: targetRef, inputs }, allowEmpty: true }
857 );
858 }
859 async rerunJob(repoRef, jobId) {
860 const id = numericId(jobId, 'workflow job');
861 const { apiBase } = await this.getRepositoryContext(repoRef);
862 return this.requestJson(
863 `${apiBase}/actions/jobs/${id}/rerun`,
864 'GitHub rerun workflow job',
865 { method: 'POST', allowEmpty: true }
866 );
867 }
868 async rerunFailedWorkflowRun(repoRef, runId) {
869 const id = numericId(runId, 'workflow run');
870 const { apiBase } = await this.getRepositoryContext(repoRef);
871 return this.requestJson(
872 `${apiBase}/actions/runs/${id}/rerun-failed-jobs`,
873 'GitHub rerun failed jobs',
874 { method: 'POST', allowEmpty: true }
875 );
876 }
877 async cancelWorkflowRun(repoRef, runId) {
878 const id = numericId(runId, 'workflow run');
879 const { apiBase } = await this.getRepositoryContext(repoRef);
880 return this.requestJson(
881 `${apiBase}/actions/runs/${id}/cancel`,
882 'GitHub cancel workflow run',
883 { method: 'POST', allowEmpty: true }
884 );
885 }
886 }