@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -0,0 +1,1255 @@
1
+ /**
2
+ * GitHub, behind the provider-agnostic issue interface.
3
+ *
4
+ * This file is the proof that the interface is the right shape: everything
5
+ * GitHub-specific — that issues and pull requests share a number space, that
6
+ * `/issues` also returns pull requests, that a fine-grained token 404s on a
7
+ * repo it cannot see — is absorbed here, and none of it reaches the panel.
8
+ */
9
+
10
+ import type {
11
+ CheckLogBundle,
12
+ CheckRun,
13
+ CheckStatus,
14
+ CommentSource,
15
+ WorkRateLimit,
16
+ TimelineEventKind,
17
+ WorkItemEvent,
18
+ CommitDetail,
19
+ CommitRef,
20
+ FileContent,
21
+ FileChange,
22
+ WorkProviderCapabilities,
23
+ MergeMethod,
24
+ PullRequestDraft,
25
+ PullRequestMergeability,
26
+ WorkItem,
27
+ WorkItemComment,
28
+ WorkItemDetail,
29
+ WorkItemKind,
30
+ WorkItemPage,
31
+ WorkItemQuery,
32
+ WorkItemStateOption
33
+ } from '$shared/types/work';
34
+ import type { WorkContext, WorkProviderAdapter, ResolvedBinding, UnboundContext } from '../../types';
35
+ import {
36
+ GITHUB_WEB_BASE,
37
+ GitHubError,
38
+ githubPaged,
39
+ githubRequest,
40
+ invalidateGitHubCache,
41
+ tokenKindOf,
42
+ webBaseOf,
43
+ type GitHubCredentials
44
+ } from './client';
45
+ import { buildRunLogBundle } from './actions-logs';
46
+ import { debug } from '$shared/utils/logger';
47
+
48
+ const CAPABILITIES: WorkProviderCapabilities = {
49
+ pullRequests: true,
50
+ checks: true,
51
+ comments: true,
52
+ editComments: true,
53
+ transitions: true,
54
+ editTitle: true,
55
+ createPullRequest: true,
56
+ createIssue: true,
57
+ merge: true,
58
+ assign: true,
59
+ diff: true
60
+ };
61
+
62
+ /**
63
+ * Per-file patch cap.
64
+ *
65
+ * The files endpoint inlines the diff, and a single generated file can carry
66
+ * megabytes of it. The list is for reading a change, not for reconstructing it,
67
+ * so anything past this is dropped with the counts left intact.
68
+ */
69
+ const MAX_PATCH_BYTES = 60 * 1024;
70
+
71
+ /**
72
+ * What the whole-file viewer will RENDER. Past this, the text is cut and the
73
+ * viewer says so — a partial file answers "what does this look like" far better
74
+ * than a refusal does.
75
+ */
76
+ const MAX_RENDER_BYTES = 2 * 1024 * 1024;
77
+
78
+ /**
79
+ * What it will DOWNLOAD. The blobs endpoint returns base64 in JSON, so a file
80
+ * this size is already a ~27 MB response; past it the honest answer really is
81
+ * the web view.
82
+ */
83
+ const MAX_FILE_BYTES = 20 * 1024 * 1024;
84
+
85
+ function credentialsOf(context: UnboundContext | WorkContext): GitHubCredentials {
86
+ return {
87
+ token: context.credentials.token ?? '',
88
+ baseUrl: context.credentials.baseUrl
89
+ };
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Wire shapes. Only the fields the surface reads.
94
+ // ---------------------------------------------------------------------------
95
+
96
+ interface GitHubUser { login: string }
97
+
98
+ interface GitHubIssue {
99
+ id: number;
100
+ number: number;
101
+ title: string;
102
+ body: string | null;
103
+ html_url: string;
104
+ state: string;
105
+ state_reason?: string | null;
106
+ draft?: boolean;
107
+ labels: (string | { name?: string })[];
108
+ assignees: GitHubUser[] | null;
109
+ user: GitHubUser | null;
110
+ comments?: number;
111
+ created_at: string;
112
+ updated_at: string;
113
+ merged_at?: string | null;
114
+ /** Present only when this "issue" is really a pull request. */
115
+ pull_request?: unknown;
116
+ head?: { ref: string; sha?: string };
117
+ base?: { ref: string };
118
+ merged?: boolean;
119
+ mergeable?: boolean | null;
120
+ mergeable_state?: string;
121
+ }
122
+
123
+ interface GitHubComment {
124
+ id: number;
125
+ body: string | null;
126
+ user: GitHubUser | null;
127
+ created_at: string;
128
+ html_url: string;
129
+ /** Review comments carry the file they were left on. */
130
+ path?: string;
131
+ line?: number | null;
132
+ }
133
+
134
+ interface GitHubReview {
135
+ id: number;
136
+ body: string | null;
137
+ state: string;
138
+ user: GitHubUser | null;
139
+ submitted_at: string | null;
140
+ html_url: string;
141
+ }
142
+
143
+ interface GitHubTimelineEntry {
144
+ id?: number;
145
+ node_id?: string;
146
+ event: string;
147
+ created_at?: string;
148
+ actor?: GitHubUser | null;
149
+ label?: { name: string };
150
+ assignee?: GitHubUser;
151
+ requested_reviewer?: GitHubUser;
152
+ rename?: { from: string; to: string };
153
+ source?: { issue?: { number: number; title: string; html_url: string } };
154
+ }
155
+
156
+ interface GitHubRepo {
157
+ default_branch?: string;
158
+ permissions?: { admin?: boolean; push?: boolean; maintain?: boolean };
159
+ allow_merge_commit?: boolean;
160
+ allow_squash_merge?: boolean;
161
+ allow_rebase_merge?: boolean;
162
+ }
163
+
164
+ interface GitHubCommit {
165
+ sha: string;
166
+ html_url: string;
167
+ commit: { message: string; author: { name?: string; date?: string } | null };
168
+ author: GitHubUser | null;
169
+ stats?: { additions?: number; deletions?: number };
170
+ files?: GitHubFile[];
171
+ }
172
+
173
+ interface GitHubFile {
174
+ filename: string;
175
+ status: string;
176
+ additions: number;
177
+ deletions: number;
178
+ patch?: string;
179
+ blob_url?: string;
180
+ /** Blob id of the file at this revision — what the content viewer reads. */
181
+ sha?: string;
182
+ previous_filename?: string;
183
+ }
184
+
185
+ interface GitHubRun {
186
+ id: number;
187
+ name: string | null;
188
+ display_title?: string | null;
189
+ status: string;
190
+ conclusion: string | null;
191
+ html_url: string;
192
+ head_branch: string | null;
193
+ head_sha: string;
194
+ event: string;
195
+ run_started_at: string | null;
196
+ updated_at: string | null;
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // Normalisation
201
+ // ---------------------------------------------------------------------------
202
+
203
+ function labelNames(labels: GitHubIssue['labels']): string[] {
204
+ return (labels ?? [])
205
+ .map((label) => (typeof label === 'string' ? label : label?.name ?? ''))
206
+ .filter(Boolean);
207
+ }
208
+
209
+ /**
210
+ * GitHub has exactly two states, so the interesting information is in the
211
+ * neighbouring fields: a merged PR is `closed` with `merged_at` set, and a draft
212
+ * PR is `open` with `draft`. Flattening those into one category is what lets the
213
+ * panel colour a merged PR differently from an abandoned one without knowing
214
+ * anything about GitHub.
215
+ */
216
+ function categorise(raw: GitHubIssue, kind: WorkItemKind) {
217
+ if (kind === 'pull-request') {
218
+ if (raw.merged_at) return 'merged' as const;
219
+ if (raw.state === 'open' && raw.draft) return 'draft' as const;
220
+ }
221
+ return raw.state === 'closed' ? ('closed' as const) : ('open' as const);
222
+ }
223
+
224
+ /** The state name shown to the user — GitHub's own word, plus the reason. */
225
+ function stateName(raw: GitHubIssue, kind: WorkItemKind): string {
226
+ if (kind === 'pull-request' && raw.merged_at) return 'merged';
227
+ if (kind === 'pull-request' && raw.state === 'open' && raw.draft) return 'draft';
228
+ if (raw.state === 'closed' && raw.state_reason === 'not_planned') return 'closed (not planned)';
229
+ return raw.state;
230
+ }
231
+
232
+ function toWorkItem(raw: GitHubIssue, kind: WorkItemKind): WorkItem {
233
+ return {
234
+ id: String(raw.number),
235
+ identifier: String(raw.number),
236
+ kind,
237
+ title: raw.title,
238
+ url: raw.html_url,
239
+ state: stateName(raw, kind),
240
+ stateCategory: categorise(raw, kind),
241
+ labels: labelNames(raw.labels),
242
+ assignees: (raw.assignees ?? []).map((user) => user.login),
243
+ author: raw.user?.login ?? null,
244
+ commentCount: raw.comments ?? 0,
245
+ createdAt: raw.created_at,
246
+ updatedAt: raw.updated_at,
247
+ ...(kind === 'pull-request' && {
248
+ headBranch: raw.head?.ref,
249
+ ...(raw.head?.sha && { headSha: raw.head.sha }),
250
+ baseBranch: raw.base?.ref,
251
+ isDraft: raw.draft === true
252
+ })
253
+ };
254
+ }
255
+
256
+ /**
257
+ * `viewer` and `canWrite` decide what the user is offered.
258
+ *
259
+ * GitHub does not report per-comment permissions, so this reconstructs the two
260
+ * rules it actually applies: an author may always edit and delete their own
261
+ * comment, and anyone with write access to the repository may delete anyone's.
262
+ * Offering an action that will 403 is worse than not offering it.
263
+ */
264
+ function toComment(
265
+ raw: GitHubComment,
266
+ source: CommentSource,
267
+ viewer: string | null,
268
+ canWrite: boolean
269
+ ): WorkItemComment {
270
+ const isAuthor = viewer !== null && raw.user?.login === viewer;
271
+ // A review's summary body is edited through the reviews endpoint with
272
+ // different rules, so it is read-only here rather than offering an edit that
273
+ // would 404.
274
+ const editable = source !== 'review-summary' && (isAuthor || canWrite);
275
+ return {
276
+ id: String(raw.id),
277
+ author: raw.user?.login ?? 'unknown',
278
+ // The location is NOT folded into the body any more: it has its own
279
+ // fields now, and burying it in the text made editing a review comment
280
+ // send the heading back to GitHub as part of the comment.
281
+ body: raw.body ?? '',
282
+ createdAt: raw.created_at,
283
+ url: raw.html_url,
284
+ source,
285
+ canModify: editable,
286
+ ...(raw.path && { path: raw.path, line: raw.line ?? null })
287
+ };
288
+ }
289
+
290
+ function toCommit(raw: GitHubCommit): CommitRef {
291
+ const message = raw.commit?.message ?? '';
292
+ return {
293
+ hash: raw.sha.slice(0, 7),
294
+ subject: message.split('\n')[0] ?? '',
295
+ author: raw.author?.login ?? raw.commit?.author?.name ?? null,
296
+ date: raw.commit?.author?.date ?? '',
297
+ url: raw.html_url
298
+ };
299
+ }
300
+
301
+ function toFileChange(raw: GitHubFile): FileChange {
302
+ const patch = raw.patch;
303
+ return {
304
+ path: raw.filename,
305
+ status: raw.status,
306
+ additions: raw.additions,
307
+ deletions: raw.deletions,
308
+ ...(patch && patch.length <= MAX_PATCH_BYTES && { patch }),
309
+ url: raw.blob_url ?? '',
310
+ ...(raw.sha && { sha: raw.sha }),
311
+ ...(raw.previous_filename && { previousPath: raw.previous_filename })
312
+ };
313
+ }
314
+
315
+ function toMergeability(raw: GitHubIssue, repo: GitHubRepo | null): PullRequestMergeability {
316
+ const allowed: MergeMethod[] = [];
317
+ // A repository can switch any of the three off, and offering a disabled one
318
+ // produces a 405 the moment the user commits to it.
319
+ if (repo?.allow_merge_commit !== false) allowed.push('merge');
320
+ if (repo?.allow_squash_merge !== false) allowed.push('squash');
321
+ if (repo?.allow_rebase_merge !== false) allowed.push('rebase');
322
+
323
+ return {
324
+ mergeable: raw.mergeable ?? null,
325
+ state: raw.mergeable_state ?? 'unknown',
326
+ allowedMethods: allowed,
327
+ merged: raw.merged === true || Boolean(raw.merged_at)
328
+ };
329
+ }
330
+
331
+ function toCheckStatus(run: GitHubRun): CheckStatus {
332
+ if (run.status === 'queued' || run.status === 'waiting' || run.status === 'pending') return 'queued';
333
+ if (run.status !== 'completed') return 'running';
334
+ switch (run.conclusion) {
335
+ case 'success': return 'success';
336
+ case 'failure': return 'failure';
337
+ case 'timed_out': return 'failure';
338
+ case 'startup_failure': return 'failure';
339
+ case 'cancelled': return 'cancelled';
340
+ case 'skipped': return 'skipped';
341
+ case 'neutral': return 'success';
342
+ default: return 'unknown';
343
+ }
344
+ }
345
+
346
+ function toCheckRun(run: GitHubRun): CheckRun {
347
+ const status = toCheckStatus(run);
348
+ return {
349
+ id: String(run.id),
350
+ name: run.name || run.display_title || `Run ${run.id}`,
351
+ status,
352
+ url: run.html_url,
353
+ headBranch: run.head_branch,
354
+ headSha: run.head_sha,
355
+ event: run.event,
356
+ startedAt: run.run_started_at,
357
+ finishedAt: run.status === 'completed' ? run.updated_at : null,
358
+ // Only a finished run has logs worth pulling, and only a failed one has
359
+ // logs worth reading.
360
+ canFetchLogs: status === 'failure'
361
+ };
362
+ }
363
+
364
+ /**
365
+ * The timeline events worth drawing.
366
+ *
367
+ * Anything not listed is dropped. GitHub emits dozens of event types, many of
368
+ * them internal bookkeeping ("subscribed", "mentioned", "head_ref_deleted"),
369
+ * and rendering all of them buries the comments the thread is actually about.
370
+ */
371
+ const TIMELINE_KINDS: Record<string, TimelineEventKind> = {
372
+ labeled: 'labeled',
373
+ unlabeled: 'unlabeled',
374
+ assigned: 'assigned',
375
+ unassigned: 'unassigned',
376
+ renamed: 'renamed',
377
+ referenced: 'referenced',
378
+ cross_referenced: 'cross-referenced',
379
+ closed: 'closed',
380
+ reopened: 'reopened',
381
+ merged: 'merged',
382
+ review_requested: 'review-requested'
383
+ };
384
+
385
+ function toEvent(raw: GitHubTimelineEntry, index: number): WorkItemEvent | null {
386
+ const kind = TIMELINE_KINDS[raw.event];
387
+ if (!kind) return null;
388
+
389
+ const reference = raw.source?.issue;
390
+ return {
391
+ // `id` is absent on some entries (cross-references carry only a node id),
392
+ // so the index is the tiebreaker that keeps keys unique.
393
+ id: String(raw.id ?? raw.node_id ?? `${raw.event}-${index}`),
394
+ kind,
395
+ actor: raw.actor?.login ?? null,
396
+ createdAt: raw.created_at ?? '',
397
+ ...(raw.label && { subject: raw.label.name }),
398
+ ...(raw.assignee && { subject: raw.assignee.login }),
399
+ ...(raw.requested_reviewer && { subject: raw.requested_reviewer.login }),
400
+ ...(raw.rename && { subject: raw.rename.to }),
401
+ ...(reference && {
402
+ referenceTitle: reference.title,
403
+ referenceUrl: reference.html_url,
404
+ referenceIdentifier: String(reference.number)
405
+ })
406
+ };
407
+ }
408
+
409
+ // ---------------------------------------------------------------------------
410
+ // Remote-URL parsing
411
+ // ---------------------------------------------------------------------------
412
+
413
+ /**
414
+ * Host of the instance these credentials talk to.
415
+ *
416
+ * Enterprise Server is why this is derived rather than hardcoded: the same
417
+ * adapter serves `github.com` and `ghe.internal`, and the only thing that
418
+ * distinguishes "this remote is mine" is the host the account points at.
419
+ */
420
+ function hostOf(credentials: GitHubCredentials): string {
421
+ const base = webBaseOf(credentials);
422
+ try {
423
+ return new URL(base).host.toLowerCase();
424
+ } catch {
425
+ return new URL(GITHUB_WEB_BASE).host;
426
+ }
427
+ }
428
+
429
+ function locatorFromRemote(url: string, credentials: Record<string, string>): string | null {
430
+ const trimmed = (url ?? '').trim();
431
+ if (!trimmed) return null;
432
+ const host = hostOf({ token: '', baseUrl: credentials.baseUrl });
433
+
434
+ // scp-style: git@host:owner/repo.git
435
+ const scp = trimmed.match(/^[\w.-]+@([^:]+):(.+?)(?:\.git)?\/?$/);
436
+ if (scp) {
437
+ return scp[1].toLowerCase() === host ? normaliseLocator(scp[2]) : null;
438
+ }
439
+
440
+ try {
441
+ const parsed = new URL(trimmed);
442
+ if (parsed.host.toLowerCase() !== host) return null;
443
+ return normaliseLocator(parsed.pathname.replace(/^\/+/, '').replace(/\.git$/, ''));
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+
449
+ /** `owner/repo` and nothing else — a deeper path is a URL to a file, not a repo. */
450
+ function normaliseLocator(path: string): string | null {
451
+ const parts = path.replace(/\.git$/, '').split('/').filter(Boolean);
452
+ if (parts.length < 2) return null;
453
+ return `${parts[0]}/${parts[1]}`;
454
+ }
455
+
456
+ // ---------------------------------------------------------------------------
457
+ // Diagnosing repository access
458
+ // ---------------------------------------------------------------------------
459
+
460
+ /**
461
+ * Turn "Not Found" into something the user can act on.
462
+ *
463
+ * GitHub answers 404 for a repository that does not exist AND for one the token
464
+ * is not permitted to see — it will not confirm a private repository exists. So
465
+ * the bare message ("the repository does not exist, or the token cannot see
466
+ * it") is true and useless, and it is the message a collaborator on someone
467
+ * else's repository hits every single time.
468
+ *
469
+ * The reason is almost never that the repository is missing. It is that a
470
+ * FINE-GRAINED token is scoped to one resource owner:
471
+ *
472
+ * - repositories owned by another PERSON are unreachable, full stop — being a
473
+ * collaborator does not help, because the token was never granted by that
474
+ * owner;
475
+ * - repositories owned by an ORGANISATION are unreachable until an owner
476
+ * approves the token, and organisations that have not opted into
477
+ * fine-grained tokens at all can never approve one.
478
+ *
479
+ * A classic token with `repo` has neither limit, which is why it is the
480
+ * recommendation here rather than a footnote.
481
+ */
482
+ function explainRepoFailure(
483
+ error: unknown,
484
+ credentials: GitHubCredentials,
485
+ locator: string
486
+ ): unknown {
487
+ if (!(error instanceof GitHubError) || error.kind !== 'config') return error;
488
+
489
+ const owner = locator.split('/')[0] ?? 'the owner';
490
+ const kind = tokenKindOf(credentials.token);
491
+
492
+ if (kind === 'fine-grained') {
493
+ return new GitHubError(
494
+ `${locator} is not reachable with this fine-grained token. Fine-grained tokens only see repositories their resource owner granted: if ${owner} is an organisation, an owner must approve this token under its Settings → Personal access tokens; if ${owner} is another person, fine-grained tokens cannot reach their repositories at all, even as a collaborator. Replace it with a CLASSIC token carrying the "repo" scope — that is what Clopen recommends, and it reaches everything you can reach.`,
495
+ error.status,
496
+ 'config'
497
+ );
498
+ }
499
+
500
+ if (kind === 'classic') {
501
+ return new GitHubError(
502
+ `${locator} is not reachable with this token. A classic token needs the "repo" scope to see private repositories, and if ${owner} enforces SAML single sign-on the token has to be authorised for that organisation on your token settings page.`,
503
+ error.status,
504
+ 'config'
505
+ );
506
+ }
507
+
508
+ return new GitHubError(
509
+ `${locator} is not reachable with this token. Check that it grants access to ${owner} and carries repository read permission.`,
510
+ error.status,
511
+ 'config'
512
+ );
513
+ }
514
+
515
+ /** Run a repository-scoped call, replacing an access failure with a reason. */
516
+ async function onRepo<T>(context: WorkContext, run: () => Promise<T>): Promise<T> {
517
+ try {
518
+ return await run();
519
+ } catch (error) {
520
+ throw explainRepoFailure(error, credentialsOf(context), context.binding.locator);
521
+ }
522
+ }
523
+
524
+ // ---------------------------------------------------------------------------
525
+ // Adapter
526
+ // ---------------------------------------------------------------------------
527
+
528
+ /**
529
+ * Who the token belongs to.
530
+ *
531
+ * Needed for the "assigned to me" filter, and free in practice: the response is
532
+ * ETag-cached, so every call after the first is a 304 that GitHub does not
533
+ * charge against the rate limit.
534
+ */
535
+ async function viewerLogin(credentials: GitHubCredentials): Promise<string> {
536
+ const response = await githubRequest<GitHubUser>(credentials, '/user');
537
+ return response.data?.login ?? '';
538
+ }
539
+
540
+ /** The repository record. ETag-cached, so repeated reads cost nothing. */
541
+ async function repoInfo(credentials: GitHubCredentials, locator: string): Promise<GitHubRepo | null> {
542
+ try {
543
+ const response = await githubRequest<GitHubRepo>(credentials, `/repos/${locator}`);
544
+ return response.data ?? null;
545
+ } catch {
546
+ // A failure here only costs a capability, never the page: the caller
547
+ // falls back to "no write access, all merge methods offered".
548
+ return null;
549
+ }
550
+ }
551
+
552
+ function canWriteTo(repo: GitHubRepo | null): boolean {
553
+ return repo?.permissions?.push === true || repo?.permissions?.admin === true;
554
+ }
555
+
556
+ /** One page. Load-more asks for the next; the list appends rather than replaces. */
557
+ const PAGE_SIZE = 50;
558
+
559
+ /**
560
+ * Keep pulling provider pages until the FILTERED page is full.
561
+ *
562
+ * Both endpoints hand back rows that this surface then discards — `/issues`
563
+ * returns pull requests (they are issues in GitHub's data model, and showing
564
+ * them here would duplicate the pull-request tab), and `/pulls` has no
565
+ * people or label parameters so those are applied locally. Taking one provider
566
+ * page and filtering it means the user sees however many happened to survive.
567
+ *
568
+ * That is not a hypothetical: on a busy repository with `state=all`, the fifty
569
+ * most recently updated items are almost all closed pull requests, so the
570
+ * issues list rendered a single row and looked broken.
571
+ *
572
+ * Bounded at `MAX_FETCH_PAGES` so a repository where nothing matches cannot
573
+ * spend the whole rate limit looking.
574
+ */
575
+ const MAX_FETCH_PAGES = 5;
576
+
577
+ /**
578
+ * The budget when a date range is set.
579
+ *
580
+ * Both listings are sorted newest-first and neither takes an end date, so
581
+ * everything updated after the range has to be paged PAST before the range is
582
+ * reached. Five pages is 250 items — on an active repository that is a few
583
+ * days of activity, and any range older than that came back empty no matter
584
+ * how many items matched. Twenty pages is the reach; `pastEnd` below is what
585
+ * keeps a range that has already been passed from spending it.
586
+ */
587
+ const MAX_RANGE_PAGES = 20;
588
+
589
+ /**
590
+ * A date the user picked, as the instant their day starts and ends.
591
+ *
592
+ * The picker hands over `2026-09-11`, which parses as midnight UTC — not
593
+ * midnight where the user is. Reading it literally shifted the window by the
594
+ * timezone offset at both ends, so items from the first hours of the range
595
+ * were outside it and items from the last hours were inside the next day.
596
+ */
597
+ function startOfDay(date: string): string {
598
+ const value = new Date(date);
599
+ value.setHours(0, 0, 0, 0);
600
+ return value.toISOString();
601
+ }
602
+
603
+ function endOfDay(date: string): string {
604
+ const value = new Date(date);
605
+ value.setHours(23, 59, 59, 999);
606
+ return value.toISOString();
607
+ }
608
+
609
+ async function fillPage(
610
+ credentials: GitHubCredentials,
611
+ buildUrl: (page: number) => string,
612
+ keep: (raw: GitHubIssue) => boolean,
613
+ kind: WorkItemKind,
614
+ startPage: number,
615
+ /**
616
+ * True once a row proves no later page can match.
617
+ *
618
+ * Every listing here is sorted by update time, newest first, so a row older
619
+ * than the range's start means the rest of the history is older still.
620
+ * Without it, a range that ended weeks ago would spend its whole budget
621
+ * walking backwards through history it has already left behind.
622
+ */
623
+ pastEnd?: (raw: GitHubIssue) => boolean,
624
+ maxPages = MAX_FETCH_PAGES
625
+ ): Promise<WorkItemPage> {
626
+ const items: WorkItem[] = [];
627
+ let rateLimit: WorkRateLimit | null = null;
628
+ let page = startPage;
629
+ let hasMore = false;
630
+
631
+ for (let fetched = 0; fetched < maxPages; fetched += 1) {
632
+ const response = await githubRequest<GitHubIssue[]>(credentials, buildUrl(page));
633
+ rateLimit = response.rateLimit ?? rateLimit;
634
+
635
+ const rows = response.data ?? [];
636
+ items.push(...rows.filter(keep).map((raw) => toWorkItem(raw, kind)));
637
+
638
+ hasMore = response.nextUrl !== null;
639
+ if (pastEnd && rows.some(pastEnd)) {
640
+ hasMore = false;
641
+ break;
642
+ }
643
+ if (!hasMore || items.length >= PAGE_SIZE) break;
644
+ page += 1;
645
+ }
646
+
647
+ // The NEXT call must resume after the last page actually consumed, or
648
+ // load-more would re-request pages this one already drained.
649
+ return { items, rateLimit, hasMore, nextPage: hasMore ? page + 1 : null };
650
+ }
651
+
652
+ async function listIssues(
653
+ credentials: GitHubCredentials,
654
+ locator: string,
655
+ query: WorkItemQuery
656
+ ): Promise<WorkItemPage> {
657
+ const base = new URLSearchParams({
658
+ state: query.state,
659
+ per_page: String(PAGE_SIZE),
660
+ sort: 'updated',
661
+ direction: 'desc'
662
+ });
663
+
664
+ // Pushed to the provider where it supports them, because filtering server
665
+ // side is the difference between "the first 50 items, then filtered" and
666
+ // "the first 50 matching items".
667
+ if (query.mineOnly) base.set('assignee', await viewerLogin(credentials));
668
+ if (query.author) base.set('creator', query.author);
669
+ if (query.labels?.length) base.set('labels', query.labels.join(','));
670
+ const since = query.since ? startOfDay(query.since) : null;
671
+ if (since) base.set('since', since);
672
+
673
+ // `until` has no provider-side equivalent, so it is applied HERE rather than
674
+ // to the finished page. Applied afterwards it read as "of the fifty most
675
+ // recently updated items, show the ones older than this date" — which for
676
+ // any range not ending today is none of them, and the list came back empty
677
+ // with matching items sitting on page two.
678
+ const until = query.until ? endOfDay(query.until) : null;
679
+
680
+ return fillPage(
681
+ credentials,
682
+ (page) => `/repos/${locator}/issues?${base.toString()}&page=${page}`,
683
+ (raw) => !raw.pull_request && (!until || raw.updated_at <= until),
684
+ 'issue',
685
+ query.page ?? 1,
686
+ since ? (raw) => raw.updated_at < since : undefined,
687
+ until ? MAX_RANGE_PAGES : MAX_FETCH_PAGES
688
+ );
689
+ }
690
+
691
+ async function listPulls(
692
+ credentials: GitHubCredentials,
693
+ locator: string,
694
+ query: WorkItemQuery
695
+ ): Promise<WorkItemPage> {
696
+ const params = new URLSearchParams({
697
+ state: query.state,
698
+ per_page: String(PAGE_SIZE),
699
+ sort: 'updated',
700
+ direction: 'desc'
701
+ });
702
+
703
+ // The pulls endpoint takes none of the people, label or date parameters, so
704
+ // all of those are applied here — which is why this goes through the same
705
+ // fill loop, and why the loop keeps fetching until it has a full page of
706
+ // MATCHES rather than a page it then filters down to nothing.
707
+ const login = query.mineOnly ? await viewerLogin(credentials) : '';
708
+ const since = query.since ? startOfDay(query.since) : null;
709
+ const until = query.until ? endOfDay(query.until) : null;
710
+
711
+ return fillPage(
712
+ credentials,
713
+ (page) => `/repos/${locator}/pulls?${params.toString()}&page=${page}`,
714
+ (raw) => {
715
+ if (query.mineOnly) {
716
+ const mine = (raw.assignees ?? []).some((user) => user.login === login)
717
+ || raw.user?.login === login;
718
+ if (!mine) return false;
719
+ }
720
+ if (query.author && raw.user?.login !== query.author) return false;
721
+ if (query.labels?.length) {
722
+ const names = labelNames(raw.labels);
723
+ if (!query.labels.every((label) => names.includes(label))) return false;
724
+ }
725
+ if (since && raw.updated_at < since) return false;
726
+ if (until && raw.updated_at > until) return false;
727
+ return true;
728
+ },
729
+ 'pull-request',
730
+ query.page ?? 1,
731
+ since ? (raw) => raw.updated_at < since : undefined,
732
+ until ? MAX_RANGE_PAGES : MAX_FETCH_PAGES
733
+ );
734
+ }
735
+
736
+ function matchesSearch(item: WorkItem, needle: string): boolean {
737
+ if (!needle) return true;
738
+ const haystack = [item.identifier, item.title, ...item.labels, ...item.assignees, item.author ?? '']
739
+ .join(' ')
740
+ .toLowerCase();
741
+ return haystack.includes(needle);
742
+ }
743
+
744
+ export const githubWorkAdapter: WorkProviderAdapter = {
745
+ provider: 'github',
746
+ capabilities: CAPABILITIES,
747
+ locatorFromRemote,
748
+
749
+ describeLocator(locator: string): string {
750
+ return locator;
751
+ },
752
+
753
+ async probe(context: UnboundContext, binding: ResolvedBinding | null) {
754
+ const credentials = credentialsOf(context);
755
+ if (!credentials.token) {
756
+ return { status: 'needs_config' as const, detail: 'No token stored' };
757
+ }
758
+
759
+ try {
760
+ const login = await viewerLogin(credentials);
761
+ if (!binding) {
762
+ // A valid token with nowhere to point is a real, reportable state:
763
+ // the account works, the project has not been bound to a repo yet.
764
+ return { status: 'needs_config' as const, detail: `Signed in as ${login}. No repository selected yet.` };
765
+ }
766
+
767
+ try {
768
+ await githubRequest(credentials, `/repos/${binding.locator}`);
769
+ } catch (error) {
770
+ throw explainRepoFailure(error, credentials, binding.locator);
771
+ }
772
+ return { status: 'ok' as const, detail: `${login} → ${binding.locator}` };
773
+ } catch (error) {
774
+ if (error instanceof GitHubError) {
775
+ const status = error.kind === 'auth' ? 'needs_auth' as const
776
+ : error.kind === 'config' ? 'needs_config' as const
777
+ : 'error' as const;
778
+ return { status, detail: error.message };
779
+ }
780
+ return { status: 'error' as const, detail: error instanceof Error ? error.message : String(error) };
781
+ }
782
+ },
783
+
784
+ async listStates(_context: WorkContext, kind: WorkItemKind): Promise<WorkItemStateOption[]> {
785
+ // Static, because GitHub's states are. A tracker with a real workflow
786
+ // fetches them; this one would be lying if it pretended to.
787
+ if (kind === 'pull-request') {
788
+ return [
789
+ { value: 'open', label: 'Open', category: 'open' },
790
+ { value: 'closed', label: 'Closed', category: 'closed' }
791
+ ];
792
+ }
793
+ return [
794
+ { value: 'open', label: 'Open', category: 'open' },
795
+ { value: 'closed', label: 'Closed as completed', category: 'closed' },
796
+ { value: 'not_planned', label: 'Closed as not planned', category: 'closed' }
797
+ ];
798
+ },
799
+
800
+ async list(context: WorkContext, query: WorkItemQuery): Promise<WorkItemPage> {
801
+ const credentials = credentialsOf(context);
802
+ const locator = context.binding.locator;
803
+ const page = await onRepo(context, () => query.kind === 'pull-request'
804
+ ? listPulls(credentials, locator, query)
805
+ : listIssues(credentials, locator, query));
806
+
807
+ // Search is applied locally against the page we already hold. Going to
808
+ // GitHub's search API instead would cost a separate, much smaller rate
809
+ // limit (30/min) and return a different, less complete object shape.
810
+ const needle = (query.search ?? '').trim().toLowerCase();
811
+ return {
812
+ items: page.items.filter((item) => matchesSearch(item, needle)),
813
+ rateLimit: page.rateLimit,
814
+ hasMore: page.hasMore,
815
+ nextPage: page.nextPage
816
+ };
817
+ },
818
+
819
+ async get(context: WorkContext, kind: WorkItemKind, id: string): Promise<WorkItemDetail> {
820
+ const credentials = credentialsOf(context);
821
+ const locator = context.binding.locator;
822
+
823
+ // The issues endpoint serves both kinds, but only the pulls endpoint
824
+ // carries head/base/draft/merged — so a PR is fetched from both.
825
+ const issue = await onRepo(context, () =>
826
+ githubRequest<GitHubIssue>(credentials, `/repos/${locator}/issues/${id}`));
827
+ let raw = issue.data;
828
+
829
+ if (kind === 'pull-request') {
830
+ const pull = await githubRequest<GitHubIssue>(credentials, `/repos/${locator}/pulls/${id}`);
831
+ raw = { ...raw, ...pull.data, comments: raw.comments };
832
+ }
833
+
834
+ // Who we are and what we may do here, resolved once so every comment can
835
+ // be told whether its edit and delete controls should exist.
836
+ const [viewer, repo] = await Promise.all([
837
+ viewerLogin(credentials).catch(() => ''),
838
+ repoInfo(credentials, locator)
839
+ ]);
840
+ const canWrite = canWriteTo(repo);
841
+
842
+ const conversation = await githubPaged<GitHubComment>(
843
+ credentials,
844
+ `/repos/${locator}/issues/${id}/comments?per_page=100`,
845
+ 3
846
+ );
847
+
848
+ const comments = conversation.items.map((entry) =>
849
+ toComment(entry, 'conversation', viewer || null, canWrite));
850
+
851
+ if (kind === 'pull-request') {
852
+ // A pull request's discussion is spread over THREE endpoints, and
853
+ // missing any of them makes Clopen's thread disagree with the
854
+ // provider's own. `/issues/{n}/comments` is the conversation,
855
+ // `/pulls/{n}/comments` is line-level review feedback, and
856
+ // `/pulls/{n}/reviews` is the summary a reviewer submits — which is
857
+ // where review bots put their findings. Reading only the first two is
858
+ // what made a bot's review look like it had been deleted.
859
+ const [review, reviews] = await Promise.all([
860
+ githubPaged<GitHubComment>(
861
+ credentials,
862
+ `/repos/${locator}/pulls/${id}/comments?per_page=100`,
863
+ 3
864
+ ),
865
+ githubPaged<GitHubReview>(
866
+ credentials,
867
+ `/repos/${locator}/pulls/${id}/reviews?per_page=100`,
868
+ 2
869
+ )
870
+ ]);
871
+
872
+ comments.push(...review.items.map((entry) =>
873
+ toComment(entry, 'review', viewer || null, canWrite)));
874
+
875
+ comments.push(
876
+ ...reviews.items
877
+ // A review with no body is just the act of approving; its
878
+ // line comments already arrived above.
879
+ .filter((entry) => (entry.body ?? '').trim().length > 0)
880
+ .map((entry) => toComment(
881
+ {
882
+ id: entry.id,
883
+ body: entry.body,
884
+ user: entry.user,
885
+ created_at: entry.submitted_at ?? '',
886
+ html_url: entry.html_url
887
+ },
888
+ 'review-summary',
889
+ viewer || null,
890
+ canWrite
891
+ ))
892
+ );
893
+ }
894
+
895
+ comments.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
896
+
897
+ // Best effort: the timeline is a preview-era media type on some
898
+ // installs and a missing history is a poorer page, not a broken one.
899
+ const timeline = await githubPaged<GitHubTimelineEntry>(
900
+ credentials,
901
+ `/repos/${locator}/issues/${id}/timeline?per_page=100`,
902
+ 2
903
+ ).catch(() => ({ items: [] as GitHubTimelineEntry[], rateLimit: null }));
904
+
905
+ const events = timeline.items
906
+ .map((entry, index) => toEvent(entry, index))
907
+ .filter((entry): entry is WorkItemEvent => entry !== null)
908
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
909
+
910
+ return {
911
+ ...toWorkItem(raw, kind),
912
+ body: raw.body ?? '',
913
+ comments,
914
+ events,
915
+ ...(kind === 'pull-request' && { mergeability: toMergeability(raw, repo) })
916
+ };
917
+ },
918
+
919
+ async comment(context: WorkContext, _kind: WorkItemKind, id: string, body: string): Promise<WorkItemComment> {
920
+ const credentials = credentialsOf(context);
921
+ const response = await onRepo(context, () => githubRequest<GitHubComment>(
922
+ credentials,
923
+ `/repos/${context.binding.locator}/issues/${id}/comments`,
924
+ { method: 'POST', body: { body } }
925
+ ));
926
+ // The list we just changed is cached by ETag; without this the panel
927
+ // would refresh into a 304 and appear to have dropped the comment.
928
+ invalidateGitHubCache(credentials.token);
929
+ // The comment we just wrote is ours, so it is editable by definition.
930
+ return toComment(response.data, 'conversation', response.data?.user?.login ?? null, true);
931
+ },
932
+
933
+ async transition(context: WorkContext, _kind: WorkItemKind, id: string, state: string): Promise<void> {
934
+ const credentials = credentialsOf(context);
935
+ // `not_planned` is not a state, it is a reason attached to `closed`.
936
+ // Flattening the two into one selectable value is what keeps the panel
937
+ // from needing a GitHub-shaped second dropdown.
938
+ const body = state === 'not_planned'
939
+ ? { state: 'closed', state_reason: 'not_planned' }
940
+ : state === 'closed'
941
+ ? { state: 'closed', state_reason: 'completed' }
942
+ : { state: 'open' };
943
+
944
+ await onRepo(context, () =>
945
+ githubRequest(credentials, `/repos/${context.binding.locator}/issues/${id}`, {
946
+ method: 'PATCH',
947
+ body
948
+ }));
949
+ invalidateGitHubCache(credentials.token);
950
+ },
951
+
952
+ async defaultBranch(context: WorkContext): Promise<string> {
953
+ const response = await onRepo(context, () => githubRequest<{ default_branch?: string }>(
954
+ credentialsOf(context),
955
+ `/repos/${context.binding.locator}`
956
+ ));
957
+ return response.data?.default_branch || 'main';
958
+ },
959
+
960
+ async listChecks(context: WorkContext, branch: string): Promise<CheckRun[]> {
961
+ const params = new URLSearchParams({ branch, per_page: '20' });
962
+ const response = await onRepo(context, () => githubRequest<{ workflow_runs: GitHubRun[] }>(
963
+ credentialsOf(context),
964
+ `/repos/${context.binding.locator}/actions/runs?${params.toString()}`
965
+ ));
966
+ return (response.data?.workflow_runs ?? []).map(toCheckRun);
967
+ },
968
+
969
+ async fetchCheckLogs(context: WorkContext, runId: string): Promise<CheckLogBundle> {
970
+ const credentials = credentialsOf(context);
971
+ const run = await githubRequest<GitHubRun>(
972
+ credentials,
973
+ `/repos/${context.binding.locator}/actions/runs/${runId}`
974
+ );
975
+ const name = run.data?.name || run.data?.display_title || `Run ${runId}`;
976
+ return buildRunLogBundle(credentials, context.binding.locator, runId, name);
977
+ },
978
+
979
+ async createPullRequest(context: WorkContext, draft: PullRequestDraft): Promise<WorkItem> {
980
+ const credentials = credentialsOf(context);
981
+ const response = await onRepo(context, () => githubRequest<GitHubIssue>(
982
+ credentials,
983
+ `/repos/${context.binding.locator}/pulls`,
984
+ {
985
+ method: 'POST',
986
+ body: {
987
+ title: draft.title,
988
+ body: draft.body,
989
+ base: draft.base,
990
+ head: draft.head,
991
+ draft: draft.isDraft
992
+ }
993
+ }
994
+ ));
995
+ invalidateGitHubCache(credentials.token);
996
+ return toWorkItem(response.data, 'pull-request');
997
+ },
998
+
999
+ async updateItem(
1000
+ context: WorkContext,
1001
+ _kind: WorkItemKind,
1002
+ id: string,
1003
+ patch: { title?: string; body?: string }
1004
+ ): Promise<void> {
1005
+ const credentials = credentialsOf(context);
1006
+ await onRepo(context, () => githubRequest(
1007
+ credentials,
1008
+ `/repos/${context.binding.locator}/issues/${id}`,
1009
+ { method: 'PATCH', body: patch }
1010
+ ));
1011
+ invalidateGitHubCache(credentials.token);
1012
+ },
1013
+
1014
+ async listLabels(context: WorkContext): Promise<string[]> {
1015
+ const result = await onRepo(context, () => githubPaged<{ name: string }>(
1016
+ credentialsOf(context),
1017
+ `/repos/${context.binding.locator}/labels?per_page=100`,
1018
+ 2
1019
+ ));
1020
+ return result.items.map((label) => label.name);
1021
+ },
1022
+
1023
+ async viewer(context: UnboundContext): Promise<string | null> {
1024
+ try {
1025
+ return (await viewerLogin(credentialsOf(context))) || null;
1026
+ } catch {
1027
+ return null;
1028
+ }
1029
+ },
1030
+
1031
+ async updateComment(
1032
+ context: WorkContext,
1033
+ comment: { id: string; source: 'conversation' | 'review' },
1034
+ body: string
1035
+ ): Promise<WorkItemComment> {
1036
+ const credentials = credentialsOf(context);
1037
+ // The two comment kinds live on different paths, and PATCHing a review
1038
+ // comment through the issues path is a 404 rather than a clear refusal.
1039
+ const path = comment.source === 'review'
1040
+ ? `/repos/${context.binding.locator}/pulls/comments/${comment.id}`
1041
+ : `/repos/${context.binding.locator}/issues/comments/${comment.id}`;
1042
+
1043
+ const response = await onRepo(context, () =>
1044
+ githubRequest<GitHubComment>(credentials, path, { method: 'PATCH', body: { body } }));
1045
+ invalidateGitHubCache(credentials.token);
1046
+ return toComment(response.data, comment.source, response.data?.user?.login ?? null, true);
1047
+ },
1048
+
1049
+ async deleteComment(
1050
+ context: WorkContext,
1051
+ comment: { id: string; source: 'conversation' | 'review' }
1052
+ ): Promise<void> {
1053
+ const credentials = credentialsOf(context);
1054
+ const path = comment.source === 'review'
1055
+ ? `/repos/${context.binding.locator}/pulls/comments/${comment.id}`
1056
+ : `/repos/${context.binding.locator}/issues/comments/${comment.id}`;
1057
+
1058
+ await onRepo(context, () => githubRequest(credentials, path, { method: 'DELETE' }));
1059
+ invalidateGitHubCache(credentials.token);
1060
+ },
1061
+
1062
+ async mergePullRequest(
1063
+ context: WorkContext,
1064
+ id: string,
1065
+ options: { method: MergeMethod; title?: string; message?: string }
1066
+ ): Promise<void> {
1067
+ const credentials = credentialsOf(context);
1068
+ await onRepo(context, () => githubRequest(
1069
+ credentials,
1070
+ `/repos/${context.binding.locator}/pulls/${id}/merge`,
1071
+ {
1072
+ method: 'PUT',
1073
+ body: {
1074
+ merge_method: options.method,
1075
+ ...(options.title && { commit_title: options.title }),
1076
+ ...(options.message && { commit_message: options.message })
1077
+ }
1078
+ }
1079
+ ));
1080
+ invalidateGitHubCache(credentials.token);
1081
+ },
1082
+
1083
+ async listCommits(context: WorkContext, id: string): Promise<CommitRef[]> {
1084
+ const result = await onRepo(context, () => githubPaged<GitHubCommit>(
1085
+ credentialsOf(context),
1086
+ `/repos/${context.binding.locator}/pulls/${id}/commits?per_page=100`,
1087
+ 2
1088
+ ));
1089
+ // Newest first, matching how the list and the log everywhere else read.
1090
+ return result.items.map(toCommit).reverse();
1091
+ },
1092
+
1093
+ async listFiles(context: WorkContext, id: string): Promise<FileChange[]> {
1094
+ const result = await onRepo(context, () => githubPaged<GitHubFile>(
1095
+ credentialsOf(context),
1096
+ `/repos/${context.binding.locator}/pulls/${id}/files?per_page=100`,
1097
+ 3
1098
+ ));
1099
+ return result.items.map(toFileChange);
1100
+ },
1101
+
1102
+ /**
1103
+ * One file's full text.
1104
+ *
1105
+ * A diff shows what changed and hides what it changed WITHIN, which is
1106
+ * usually the question a reviewer has next.
1107
+ *
1108
+ * Read by BLOB ID when the caller has one, and only fall back to path + ref
1109
+ * when it does not. The contents endpoint resolves a path inside a named
1110
+ * ref of THIS repository, and three ordinary situations have no such ref:
1111
+ * a pull request from a fork (the branch lives in the fork), a merged pull
1112
+ * request (the branch is usually deleted), and a file the pull request
1113
+ * deleted (the path is gone from the head). All three answered 404, which
1114
+ * the panel reported as the repository being unreachable — a message about
1115
+ * token scopes for something that was never a permission problem. A blob id
1116
+ * is reachable from the base repository in every one of those cases,
1117
+ * because a pull request's objects are fetched into it.
1118
+ *
1119
+ * Capped either way: the endpoint will happily return a 5 MB minified
1120
+ * bundle.
1121
+ */
1122
+ async fetchFileContent(
1123
+ context: WorkContext,
1124
+ path: string,
1125
+ ref: string,
1126
+ blobSha?: string
1127
+ ): Promise<FileContent> {
1128
+ const credentials = credentialsOf(context);
1129
+ const locator = context.binding.locator;
1130
+
1131
+ const read = async (endpoint: string): Promise<FileContent> => {
1132
+ const response = await githubRequest<{ content?: string; encoding?: string; size?: number }>(
1133
+ credentials,
1134
+ endpoint
1135
+ );
1136
+ const data = response.data;
1137
+ if ((data?.size ?? 0) > MAX_FILE_BYTES) {
1138
+ throw new Error('That file is too large to download. Open it on the web instead.');
1139
+ }
1140
+ if (!data?.content || data.encoding !== 'base64') {
1141
+ throw new Error('That file has no readable text — it may be binary or too large.');
1142
+ }
1143
+
1144
+ const bytes = Buffer.from(data.content, 'base64');
1145
+ if (bytes.byteLength <= MAX_RENDER_BYTES) {
1146
+ return { content: bytes.toString('utf8'), truncated: false };
1147
+ }
1148
+ // Cut on a byte boundary and drop the last line, which the cut may
1149
+ // have left as half a multi-byte character or half a statement.
1150
+ const head = bytes.subarray(0, MAX_RENDER_BYTES).toString('utf8');
1151
+ return { content: head.slice(0, head.lastIndexOf('\n') + 1 || head.length), truncated: true };
1152
+ };
1153
+
1154
+ if (blobSha) {
1155
+ try {
1156
+ return await read(`/repos/${locator}/git/blobs/${encodeURIComponent(blobSha)}`);
1157
+ } catch (error) {
1158
+ // A blob id the base repository has never heard of is the one case
1159
+ // worth a second attempt; anything else (too large, binary) would
1160
+ // fail the same way twice.
1161
+ debug.warn('work', `Blob ${blobSha.slice(0, 7)} unreadable, falling back to ${ref}:`, error);
1162
+ }
1163
+ }
1164
+
1165
+ return onRepo(context, () => read(
1166
+ `/repos/${locator}/contents/${path.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(ref)}`
1167
+ ));
1168
+ },
1169
+
1170
+ /**
1171
+ * One commit, with the rest of its message and everything it touched.
1172
+ *
1173
+ * The list endpoint carries neither, so a commit list without this is a row
1174
+ * of subjects and a large empty pane — which is what it was.
1175
+ */
1176
+ async commitDetail(context: WorkContext, sha: string): Promise<CommitDetail> {
1177
+ const response = await onRepo(context, () => githubRequest<GitHubCommit>(
1178
+ credentialsOf(context),
1179
+ `/repos/${context.binding.locator}/commits/${encodeURIComponent(sha)}`
1180
+ ));
1181
+
1182
+ const raw = response.data;
1183
+ const message = raw.commit?.message ?? '';
1184
+ return {
1185
+ commit: toCommit(raw),
1186
+ body: message.split('\n').slice(1).join('\n').trim(),
1187
+ additions: raw.stats?.additions ?? 0,
1188
+ deletions: raw.stats?.deletions ?? 0,
1189
+ files: (raw.files ?? []).map(toFileChange)
1190
+ };
1191
+ },
1192
+
1193
+ async listAssignees(context: WorkContext): Promise<string[]> {
1194
+ const result = await onRepo(context, () => githubPaged<GitHubUser>(
1195
+ credentialsOf(context),
1196
+ `/repos/${context.binding.locator}/assignees?per_page=100`,
1197
+ 2
1198
+ ));
1199
+ return result.items.map((user) => user.login);
1200
+ },
1201
+
1202
+ async setAssignees(
1203
+ context: WorkContext,
1204
+ _kind: WorkItemKind,
1205
+ id: string,
1206
+ logins: string[]
1207
+ ): Promise<void> {
1208
+ const credentials = credentialsOf(context);
1209
+ // PATCH replaces the whole set, which is what the picker means: the two
1210
+ // add/remove endpoints would need a diff and would race a concurrent edit.
1211
+ await onRepo(context, () => githubRequest(
1212
+ credentials,
1213
+ `/repos/${context.binding.locator}/issues/${id}`,
1214
+ { method: 'PATCH', body: { assignees: logins } }
1215
+ ));
1216
+ invalidateGitHubCache(credentials.token);
1217
+ },
1218
+
1219
+ async createIssue(
1220
+ context: WorkContext,
1221
+ draft: { title: string; body: string; assignees: string[]; labels: string[] }
1222
+ ): Promise<WorkItem> {
1223
+ const credentials = credentialsOf(context);
1224
+ const response = await onRepo(context, () => githubRequest<GitHubIssue>(
1225
+ credentials,
1226
+ `/repos/${context.binding.locator}/issues`,
1227
+ {
1228
+ method: 'POST',
1229
+ body: {
1230
+ title: draft.title,
1231
+ body: draft.body,
1232
+ ...(draft.assignees.length > 0 && { assignees: draft.assignees }),
1233
+ ...(draft.labels.length > 0 && { labels: draft.labels })
1234
+ }
1235
+ }
1236
+ ));
1237
+ invalidateGitHubCache(credentials.token);
1238
+ return toWorkItem(response.data, 'issue');
1239
+ },
1240
+
1241
+ async findPullRequestForBranch(context: WorkContext, branch: string): Promise<WorkItem | null> {
1242
+ const credentials = credentialsOf(context);
1243
+ const owner = context.binding.locator.split('/')[0];
1244
+ // `head` is qualified with the owner because a fork's branch can share a
1245
+ // name with one in the base repo, and an unqualified match returns both.
1246
+ const params = new URLSearchParams({ head: `${owner}:${branch}`, state: 'open', per_page: '5' });
1247
+ const response = await githubRequest<GitHubIssue[]>(
1248
+ credentials,
1249
+ `/repos/${context.binding.locator}/pulls?${params.toString()}`,
1250
+ { noCache: true }
1251
+ );
1252
+ const found = (response.data ?? [])[0];
1253
+ return found ? toWorkItem(found, 'pull-request') : null;
1254
+ }
1255
+ };