@deepseek-ai/dsh-experimental-forge-github 0.2.2-rc.1 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.i18n.yaml +6 -6
  2. package/README.md +27 -6
  3. package/README.zh.md +27 -6
  4. package/lib/index.js +1860 -112
  5. package/lib/types/commits.d.ts +24 -0
  6. package/lib/types/commits.d.ts.map +1 -0
  7. package/lib/types/commits.js.map +1 -0
  8. package/lib/types/compare.d.ts +23 -0
  9. package/lib/types/compare.d.ts.map +1 -0
  10. package/lib/types/compare.js.map +1 -0
  11. package/lib/types/gh.d.ts.map +1 -0
  12. package/lib/types/gh.js.map +1 -0
  13. package/lib/types/graphql.d.ts +66 -10
  14. package/lib/types/graphql.d.ts.map +1 -0
  15. package/lib/types/graphql.js.map +1 -0
  16. package/lib/types/index.d.ts +10 -1
  17. package/lib/types/index.d.ts.map +1 -0
  18. package/lib/types/index.js.map +1 -0
  19. package/lib/types/mutation.d.ts +40 -0
  20. package/lib/types/mutation.d.ts.map +1 -0
  21. package/lib/types/mutation.js.map +1 -0
  22. package/lib/types/overview.d.ts +51 -0
  23. package/lib/types/overview.d.ts.map +1 -0
  24. package/lib/types/overview.js.map +1 -0
  25. package/lib/types/provider.d.ts +71 -6
  26. package/lib/types/provider.d.ts.map +1 -0
  27. package/lib/types/provider.js.map +1 -0
  28. package/lib/types/pull-request-node.d.ts +15 -0
  29. package/lib/types/pull-request-node.d.ts.map +1 -0
  30. package/lib/types/pull-request-node.js.map +1 -0
  31. package/lib/types/review-writes.d.ts +44 -0
  32. package/lib/types/review-writes.d.ts.map +1 -0
  33. package/lib/types/review-writes.js.map +1 -0
  34. package/lib/types/review.d.ts.map +1 -0
  35. package/lib/types/review.js.map +1 -0
  36. package/lib/types/threads.d.ts +37 -0
  37. package/lib/types/threads.d.ts.map +1 -0
  38. package/lib/types/threads.js.map +1 -0
  39. package/lib/types/urls.d.ts +6 -0
  40. package/lib/types/urls.d.ts.map +1 -0
  41. package/lib/types/urls.js.map +1 -0
  42. package/lib/types/viewed.d.ts +37 -0
  43. package/lib/types/viewed.d.ts.map +1 -0
  44. package/lib/types/viewed.js.map +1 -0
  45. package/package.json +13 -9
  46. package/src/commits.ts +102 -0
  47. package/src/compare.ts +43 -0
  48. package/src/gh.ts +71 -0
  49. package/src/graphql.ts +685 -0
  50. package/src/index.ts +60 -0
  51. package/src/mutation.ts +86 -0
  52. package/src/overview.ts +197 -0
  53. package/src/provider.ts +534 -0
  54. package/src/pull-request-node.ts +42 -0
  55. package/src/review-writes.ts +192 -0
  56. package/src/review.ts +59 -0
  57. package/src/threads.ts +262 -0
  58. package/src/urls.ts +89 -0
  59. package/src/viewed.ts +132 -0
package/src/index.ts ADDED
@@ -0,0 +1,60 @@
1
+ /** Registers the GitHub provider of `ctx.forge`, which reads pull requests through the GitHub CLI on the host. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import type {} from '@deepseek-ai/dsh-experimental-forge'
6
+ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
7
+ import { ghRunner } from './gh.ts'
8
+ import { GitHubProvider } from './provider.ts'
9
+
10
+ export const name = 'forge-github'
11
+ export const inject = ['forge']
12
+
13
+ /** GitHub CLI executable, served hosts, and invocation limits. */
14
+ export interface Config {
15
+ /** GitHub CLI executable name or absolute host path. */
16
+ ghCommand?: string
17
+ /** Host names this provider serves; list GitHub Enterprise hosts explicitly. */
18
+ hosts?: string[]
19
+ /** Deadline in milliseconds for one `gh` invocation. */
20
+ timeoutMs?: number
21
+ /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */
22
+ maxOutputBytes?: number
23
+ /**
24
+ * Most review threads counted per pull request in one status read, which reports a lower bound past it, and read in
25
+ * one review read, which reports itself truncated past it.
26
+ */
27
+ maxReviewThreads?: number
28
+ /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
29
+ maxCommits?: number
30
+ /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
31
+ maxViewedFiles?: number
32
+ }
33
+
34
+ export const Config: z<Config> = z.object({
35
+ ghCommand: z.string().default('gh'),
36
+ hosts: z.array(z.string()).default(['github.com']),
37
+ timeoutMs: z.number().default(30_000),
38
+ maxOutputBytes: z.number().default(8_388_608),
39
+ maxReviewThreads: z.number().default(1_000),
40
+ maxCommits: z.number().default(250),
41
+ maxViewedFiles: z.number().default(3_000),
42
+ })
43
+
44
+ const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i
45
+
46
+ export function apply(ctx: Context, config: Config): void {
47
+ const resolved = config as Required<Config>
48
+ if (resolved.ghCommand.trim().length === 0) throw new Error('forge-github: ghCommand must not be empty')
49
+ if (resolved.hosts.length === 0) throw new Error('forge-github: hosts must list at least one host')
50
+ for (const host of resolved.hosts) {
51
+ if (!HOST.test(host)) throw new Error(`forge-github: invalid host ${JSON.stringify(host)}`)
52
+ }
53
+ if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) {
54
+ throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
55
+ }
56
+ for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits', 'maxViewedFiles'] as const) {
57
+ if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`)
58
+ }
59
+ ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved))
60
+ }
@@ -0,0 +1,86 @@
1
+ /** GitHub GraphQL mutations sent once through `gh`, with the document and variables as JSON on standard input. */
2
+
3
+ import type { ForgeActionFailure } from '@deepseek-ai/dsh-experimental-forge'
4
+ import { z } from 'zod'
5
+ import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts'
6
+
7
+ /** HTTP statuses that mean GitHub refused the request, so it changed nothing. */
8
+ const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/
9
+
10
+ /**
11
+ * GraphQL error types that mean GitHub refused a mutation before applying it. An error without one of them, such as
12
+ * GitHub's "Something went wrong … may be the result of a timeout", leaves the outcome unknown.
13
+ */
14
+ const REFUSALS: ReadonlySet<string> = new Set(['FORBIDDEN', 'INSUFFICIENT_SCOPES', 'NOT_FOUND', 'RATE_LIMITED', 'UNPROCESSABLE'])
15
+
16
+ const graphqlErrors = z.object({ errors: z.array(z.object({ message: z.string(), type: z.string().optional() })).min(1) })
17
+
18
+ /** One mutation and the payload field that holds its result. */
19
+ export interface GraphqlMutation {
20
+ /** GraphQL document with one mutation field. */
21
+ readonly query: string
22
+ /** Name of the mutation field, which holds the payload once GitHub applied the mutation. */
23
+ readonly field: string
24
+ /** Variables of the document. */
25
+ readonly variables: Readonly<Record<string, unknown>>
26
+ }
27
+
28
+ /**
29
+ * A mutation's result: the payload once GitHub applied it; else `failed` when GitHub refused it or `gh` could not start,
30
+ * so nothing changed, or `unknown` when the mutation may have been applied and must be checked on GitHub.
31
+ */
32
+ export type MutationResult =
33
+ | { readonly ok: true; readonly payload: unknown }
34
+ | { readonly ok: false; readonly code: 'failed' | 'unknown'; readonly message: string }
35
+
36
+ /**
37
+ * Runs one mutation on `host` through {@link sendMutation}; resolves to undefined once GitHub applied it, to a `failed`
38
+ * action failure when GitHub refused it, or to an `unknown` one when GitHub did not confirm it.
39
+ */
40
+ export type GraphqlWriter = (host: string, mutation: GraphqlMutation, signal: AbortSignal) => Promise<ForgeActionFailure | undefined>
41
+
42
+ /**
43
+ * Send one mutation with its query and variables as JSON on stdin. The mutation is never retried.
44
+ * @param gh - runs `gh` on the Host.
45
+ * @param host - GitHub host the mutation goes to.
46
+ * @param mutation - the document, its field, and its variables.
47
+ * @param signal - cancellation of the request.
48
+ * @returns the payload of `mutation.field`; `failed` when GitHub reports a refusal by its HTTP status or GraphQL error
49
+ * type, or `gh` cannot start, else `unknown`.
50
+ */
51
+ export async function sendMutation(gh: GhRunner, host: string, mutation: GraphqlMutation, signal: AbortSignal): Promise<MutationResult> {
52
+ let output: GhOutput
53
+ try {
54
+ output = await gh(['api', 'graphql', '--hostname', host, '--input', '-'], signal,
55
+ JSON.stringify({ query: mutation.query, variables: mutation.variables }))
56
+ } catch (error) {
57
+ const message = error instanceof Error ? error.message : String(error)
58
+ return { ok: false, code: error instanceof GhUnavailableError ? 'failed' : 'unknown', message }
59
+ }
60
+ const body = parse(output.stdout)
61
+ // A payload means GitHub applied the mutation, even beside errors about the fields it selects.
62
+ const payload = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body)
63
+ const value = payload.success ? payload.data.data[mutation.field] : undefined
64
+ if (value !== undefined && value !== null) return { ok: true, payload: value }
65
+ const errors = graphqlErrors.safeParse(body)
66
+ if (errors.success) {
67
+ const refused = errors.data.errors.every(error => error.type !== undefined && REFUSALS.has(error.type))
68
+ return { ok: false, code: refused ? 'failed' : 'unknown', message: errors.data.errors.map(error => error.message).join('; ') }
69
+ }
70
+ if (output.exitCode !== 0) {
71
+ const message = output.stderr.trim() || output.stdout.trim() || `gh exited with ${output.exitCode}`
72
+ return { ok: false, code: REFUSED.test(output.stderr) ? 'failed' : 'unknown', message }
73
+ }
74
+ return { ok: false, code: 'unknown', message: `unexpected GitHub response to ${mutation.field}` }
75
+ }
76
+
77
+ function parse(text: string): unknown {
78
+ let value: unknown
79
+ try {
80
+ value = JSON.parse(text)
81
+ } catch (error) {
82
+ void error // gh prints diagnostics instead of JSON when a request fails before GitHub answers.
83
+ return undefined
84
+ }
85
+ return value
86
+ }
@@ -0,0 +1,197 @@
1
+ /** GitHub writes and reads of the change request overview: review requests, reviewer candidates, and branch updates. */
2
+
3
+ import type {
4
+ BranchUpdateRequest, ChangeRequestRef, ForgeActionFailure, ForgeFailure, ForgeReviewerCandidate, ForgeReviewersRequest,
5
+ } from '@deepseek-ai/dsh-experimental-forge'
6
+ import { z } from 'zod'
7
+ import type { GraphqlReader } from './commits.ts'
8
+ import type { GraphqlWriter } from './mutation.ts'
9
+ import { pullRequestNode } from './pull-request-node.ts'
10
+ import { checkedRepository, isCommit } from './urls.ts'
11
+
12
+ /**
13
+ * Add review requests from users and teams by node id; variable `input` is a `RequestReviewsInput`. Every supported
14
+ * host has it, while GitHub Enterprise Server 3.19 and 3.20 lack `requestReviewsByLogin`.
15
+ */
16
+ export const REQUEST_REVIEWS_MUTATION = `mutation($input: RequestReviewsInput!) {
17
+ requestReviews(input: $input) { clientMutationId }
18
+ }`
19
+
20
+ /** Add review requests from bots by login, which only this mutation accepts; variable `input` is a `RequestReviewsByLoginInput`. */
21
+ export const REQUEST_BOT_REVIEWS_MUTATION = `mutation($input: RequestReviewsByLoginInput!) {
22
+ requestReviewsByLogin(input: $input) { clientMutationId }
23
+ }`
24
+
25
+ /**
26
+ * Split a team reviewer named `organization/slug`.
27
+ * @param login - the team's name.
28
+ * @returns the organization and the slug, or undefined for another name.
29
+ */
30
+ function teamOf(login: string): readonly [string, string] | undefined {
31
+ const [organization, slug, ...rest] = login.split('/')
32
+ return organization === undefined || organization === '' || slug === undefined || slug === '' || rest.length > 0 ? undefined
33
+ : [organization, slug]
34
+ }
35
+
36
+ /** Merge or rebase the base branch into the head branch; variable `input` is an `UpdatePullRequestBranchInput`. */
37
+ export const UPDATE_BRANCH_MUTATION = `mutation($input: UpdatePullRequestBranchInput!) {
38
+ updatePullRequestBranch(input: $input) { clientMutationId }
39
+ }`
40
+
41
+ /** Most accounts one candidate listing returns. */
42
+ const CANDIDATES = 20
43
+
44
+ /** Accounts that can review and GitHub's suggestions; variables `owner`, `name`, and `search` are strings, `number` is an integer. */
45
+ export const CANDIDATES_QUERY = `query($owner: String!, $name: String!, $number: Int!, $search: String!) {
46
+ repository(owner: $owner, name: $name) {
47
+ assignableUsers(first: ${CANDIDATES}, query: $search) { nodes { login name avatarUrl } }
48
+ pullRequest(number: $number) { author { login } suggestedReviewers { reviewer { login name avatarUrl } } }
49
+ }
50
+ }`
51
+
52
+ const account = z.object({ login: z.string(), name: z.string().nullable(), avatarUrl: z.string().nullable() })
53
+
54
+ const candidatesSchema = z.object({
55
+ data: z.object({
56
+ repository: z.object({
57
+ assignableUsers: z.object({ nodes: z.array(account) }),
58
+ pullRequest: z.object({
59
+ author: z.object({ login: z.string() }).nullable(),
60
+ suggestedReviewers: z.array(z.object({ reviewer: account })),
61
+ }).nullable(),
62
+ }).nullable(),
63
+ }),
64
+ })
65
+
66
+ /**
67
+ * Request reviews, adding to the requests GitHub holds. Users and teams are resolved to node ids in one query and asked
68
+ * with `requestReviews`; bots, named with or without GitHub's `[bot]` suffix, are asked with `requestReviewsByLogin`
69
+ * afterwards, which hosts without it refuse. A team is named `organization/slug`.
70
+ * @param read - runs one GraphQL query.
71
+ * @param write - runs one GraphQL mutation.
72
+ * @param ref - pull request address.
73
+ * @param request - the reviewers to ask.
74
+ * @param signal - cancellation of every request.
75
+ * @returns undefined once GitHub accepted every request, or why it refused; a refused bot request follows an accepted
76
+ * request of the users and teams.
77
+ */
78
+ export async function requestGitHubReviews(
79
+ read: GraphqlReader, write: GraphqlWriter, ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal,
80
+ ): Promise<ForgeActionFailure | undefined> {
81
+ if (request.reviewers.length === 0) return { code: 'failed', message: 'No reviewer was named' }
82
+ const logins = (kind: string): string[] => request.reviewers.filter(reviewer => reviewer.kind === kind).map(reviewer => reviewer.login)
83
+ const users = logins('user')
84
+ const teams: (readonly [string, string])[] = []
85
+ for (const login of logins('team')) {
86
+ const team = teamOf(login)
87
+ if (team === undefined) return { code: 'failed', message: `Team ${JSON.stringify(login)} is not named organization/slug` }
88
+ teams.push(team)
89
+ }
90
+ const bots = logins('bot').map(login => login.endsWith('[bot]') ? login : `${login}[bot]`)
91
+ const id = await pullRequestNode(read, ref, null, signal)
92
+ if (typeof id !== 'string') return id
93
+ const { host } = ref.repository
94
+ if (users.length > 0 || teams.length > 0) {
95
+ const ids = await reviewerIds(read, host, users, teams, signal)
96
+ if ('code' in ids) return ids
97
+ const failure = await write(host, { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviews', variables: {
98
+ input: { pullRequestId: id, union: true, ...ids.users.length > 0 ? { userIds: ids.users } : {},
99
+ ...ids.teams.length > 0 ? { teamIds: ids.teams } : {} },
100
+ } }, signal)
101
+ if (failure !== undefined) return failure
102
+ }
103
+ if (bots.length === 0) return undefined
104
+ return await write(host, { query: REQUEST_BOT_REVIEWS_MUTATION, field: 'requestReviewsByLogin',
105
+ variables: { input: { pullRequestId: id, union: true, botLogins: bots } } }, signal)
106
+ }
107
+
108
+ const idNode = z.object({ id: z.string() })
109
+
110
+ /**
111
+ * Resolve user logins and team slugs to node ids with one aliased query whose names are variables.
112
+ * @returns the ids in request order, or why GitHub did not resolve them, as for an unknown login.
113
+ */
114
+ async function reviewerIds(
115
+ read: GraphqlReader, host: string, users: readonly string[], teams: readonly (readonly [string, string])[], signal: AbortSignal,
116
+ ): Promise<{ readonly users: readonly string[]; readonly teams: readonly string[] } | ForgeActionFailure> {
117
+ const declarations = [...users.map((_, index) => `$u${index}: String!`), ...teams.flatMap((_, index) => [`$o${index}: String!`, `$t${index}: String!`])]
118
+ const fields = [...users.map((_, index) => `u${index}: user(login: $u${index}) { id }`),
119
+ ...teams.map((_, index) => `t${index}: organization(login: $o${index}) { team(slug: $t${index}) { id } }`)]
120
+ const query = `query(${declarations.join(', ')}) { ${fields.join(' ')} }`
121
+ const body = await read(['api', 'graphql', '--hostname', host, '-f', `query=${query}`,
122
+ ...users.flatMap((login, index) => ['-f', `u${index}=${login}`]),
123
+ ...teams.flatMap(([organization, slug], index) => ['-f', `o${index}=${organization}`, '-f', `t${index}=${slug}`])], signal)
124
+ if (!body.ok) return { code: body.failure.code === 'unauthenticated' ? 'unauthenticated' : 'failed', message: body.failure.message }
125
+ const parsed = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body.body)
126
+ if (!parsed.success) return { code: 'failed', message: 'unexpected GitHub response to the reviewer lookup' }
127
+ const { data } = parsed.data
128
+ const userIds: string[] = []
129
+ for (const [index, login] of users.entries()) {
130
+ const user = idNode.safeParse(data[`u${index}`])
131
+ if (!user.success) return { code: 'failed', message: `GitHub has no user ${login}` }
132
+ userIds.push(user.data.id)
133
+ }
134
+ const teamIds: string[] = []
135
+ for (const [index, [organization, slug]] of teams.entries()) {
136
+ const team = z.object({ team: idNode }).safeParse(data[`t${index}`])
137
+ if (!team.success) return { code: 'failed', message: `GitHub shows the signed-in user no team ${organization}/${slug}` }
138
+ teamIds.push(team.data.team.id)
139
+ }
140
+ return { users: userIds, teams: teamIds }
141
+ }
142
+
143
+ /**
144
+ * Update the head branch with `updatePullRequestBranch`. The head is read first and the update is refused once it is
145
+ * another commit; GitHub also checks `expectedHeadOid` itself.
146
+ * @param read - runs one GraphQL query.
147
+ * @param write - runs one GraphQL mutation.
148
+ * @param ref - pull request address.
149
+ * @param request - update method and the head commit the user confirmed.
150
+ * @param signal - cancellation of both requests.
151
+ * @returns undefined once GitHub accepted the update, `stale` when the head moved, or why GitHub refused.
152
+ * @throws when `request.headSha` is not a full commit object name.
153
+ */
154
+ export async function updateGitHubBranch(
155
+ read: GraphqlReader, write: GraphqlWriter, ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal,
156
+ ): Promise<ForgeActionFailure | undefined> {
157
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`)
158
+ const id = await pullRequestNode(read, ref, request.headSha, signal)
159
+ if (typeof id !== 'string') return id
160
+ return await write(ref.repository.host, { query: UPDATE_BRANCH_MUTATION, field: 'updatePullRequestBranch', variables: {
161
+ input: { pullRequestId: id, expectedHeadOid: request.headSha, updateMethod: request.method === 'rebase' ? 'REBASE' : 'MERGE' },
162
+ } }, signal)
163
+ }
164
+
165
+ /**
166
+ * List accounts a review can be requested from: GitHub's suggestions for the pull request when `query` is empty, then
167
+ * the accounts that can be assigned in the repository whose login or name matches `query`, without the author.
168
+ * @param read - runs one GraphQL query.
169
+ * @param ref - pull request address.
170
+ * @param query - text the login or name contains.
171
+ * @param signal - cancellation of the read.
172
+ * @returns at most 20 accounts, each once, or why GitHub did not list them.
173
+ */
174
+ export async function gitHubReviewerCandidates(
175
+ read: GraphqlReader, ref: ChangeRequestRef, query: string, signal: AbortSignal,
176
+ ): Promise<readonly ForgeReviewerCandidate[] | ForgeFailure> {
177
+ const { host, owner, name } = checkedRepository(ref)
178
+ const search = query.trim()
179
+ const body = await read([
180
+ 'api', 'graphql', '--hostname', host, '-f', `query=${CANDIDATES_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`,
181
+ '-F', `number=${ref.number}`, '-f', `search=${search}`,
182
+ ], signal)
183
+ if (!body.ok) return body.failure
184
+ const parsed = candidatesSchema.safeParse(body.body)
185
+ if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the reviewer listing' }
186
+ const repository = parsed.data.data.repository
187
+ if (repository === null) return { code: 'not-found', message: `repository ${owner}/${name} is not visible` }
188
+ const author = repository.pullRequest?.author?.login.toLowerCase()
189
+ const listed = new Map<string, ForgeReviewerCandidate>()
190
+ const add = (entry: z.infer<typeof account>, suggested: boolean): void => {
191
+ const key = entry.login.toLowerCase()
192
+ if (key !== author && !listed.has(key)) listed.set(key, { login: entry.login, name: entry.name, avatarUrl: entry.avatarUrl, suggested })
193
+ }
194
+ if (search === '') for (const suggestion of repository.pullRequest?.suggestedReviewers ?? []) add(suggestion.reviewer, true)
195
+ for (const user of repository.assignableUsers.nodes) add(user, false)
196
+ return [...listed.values()].slice(0, CANDIDATES)
197
+ }