@andorra-labs/code 0.1.14 → 0.1.16

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 (180) hide show
  1. package/dist/src/acp-agent.d.ts +54 -0
  2. package/dist/src/acp-agent.js +991 -0
  3. package/dist/src/agent-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +8 -2
  5. package/dist/src/agent-mcp-catalog.js +2 -0
  6. package/dist/src/agent-mcp.d.ts +3 -1
  7. package/dist/src/agent-mcp.js +97 -11
  8. package/dist/src/andorra/entry.js +21 -3
  9. package/dist/src/andorra/hosted.d.ts +3 -0
  10. package/dist/src/andorra/hosted.js +5 -1
  11. package/dist/src/andorra/notices.d.ts +10 -1
  12. package/dist/src/andorra/notices.js +25 -2
  13. package/dist/src/andorra/terminal.d.ts +2 -0
  14. package/dist/src/andorra/terminal.js +2 -2
  15. package/dist/src/app-server/protocol.d.ts +9 -2
  16. package/dist/src/app-server/protocol.js +1 -1
  17. package/dist/src/app-server/workspace.d.ts +1 -0
  18. package/dist/src/app-server/workspace.js +141 -10
  19. package/dist/src/app-server.d.ts +115 -0
  20. package/dist/src/app-server.js +980 -63
  21. package/dist/src/auth/AuthManager.js +4 -4
  22. package/dist/src/auth/deployment.js +2 -2
  23. package/dist/src/browser-bridge.d.ts +1 -0
  24. package/dist/src/browser-bridge.js +5 -2
  25. package/dist/src/browser-external-app.d.ts +27 -0
  26. package/dist/src/browser-external-app.js +60 -0
  27. package/dist/src/browser-panel-tool.d.ts +6 -0
  28. package/dist/src/browser-panel-tool.js +36 -0
  29. package/dist/src/browser-runner.js +1 -0
  30. package/dist/src/browser-server.d.ts +5 -0
  31. package/dist/src/browser-server.js +27 -3
  32. package/dist/src/browser-ui/style.css +3 -3
  33. package/dist/src/browser-ui/tokens.css +27 -16
  34. package/dist/src/browser-view.d.ts +16 -0
  35. package/dist/src/browser-view.js +60 -2
  36. package/dist/src/bug-report.d.ts +81 -0
  37. package/dist/src/bug-report.js +235 -0
  38. package/dist/src/claude-provider.d.ts +2 -1
  39. package/dist/src/claude-provider.js +13 -9
  40. package/dist/src/cli-sign-in.d.ts +3 -1
  41. package/dist/src/cli-sign-in.js +4 -1
  42. package/dist/src/cli.js +184 -40
  43. package/dist/src/codex-errors.js +4 -1
  44. package/dist/src/coding-tools.js +7 -7
  45. package/dist/src/command-screens.d.ts +9 -2
  46. package/dist/src/command-screens.js +166 -97
  47. package/dist/src/commands.d.ts +3 -2
  48. package/dist/src/commands.js +1 -0
  49. package/dist/src/compaction-phrases.d.ts +4 -0
  50. package/dist/src/compaction-phrases.js +20 -0
  51. package/dist/src/completion-gates.d.ts +22 -0
  52. package/dist/src/completion-gates.js +11 -0
  53. package/dist/src/config.d.ts +5 -0
  54. package/dist/src/config.js +48 -0
  55. package/dist/src/context-compaction.js +2 -1
  56. package/dist/src/decision/DecisionManager.js +3 -2
  57. package/dist/src/decision/requestPhrases.d.ts +4 -0
  58. package/dist/src/decision/requestPhrases.js +23 -0
  59. package/dist/src/github-inbox.d.ts +55 -0
  60. package/dist/src/github-inbox.js +153 -0
  61. package/dist/src/google-provider.d.ts +31 -0
  62. package/dist/src/google-provider.js +153 -0
  63. package/dist/src/graph-health.js +8 -4
  64. package/dist/src/graph-manager-chat.js +6 -1
  65. package/dist/src/graph-provider-portability.js +32 -10
  66. package/dist/src/graph-quota.d.ts +29 -2
  67. package/dist/src/graph-quota.js +68 -10
  68. package/dist/src/graph-runner.js +24 -7
  69. package/dist/src/graph-server.d.ts +1 -1
  70. package/dist/src/graph-server.js +9 -7
  71. package/dist/src/graph-sync.d.ts +1 -0
  72. package/dist/src/graph-sync.js +93 -34
  73. package/dist/src/graph-tool.d.ts +2 -0
  74. package/dist/src/graph-tool.js +2 -2
  75. package/dist/src/graph-ui/app.js +177 -41
  76. package/dist/src/graph-ui/controls.css +1 -0
  77. package/dist/src/graph-ui/edge-router.js +121 -53
  78. package/dist/src/graph-ui/embed.js +2 -2
  79. package/dist/src/graph-ui/icons.js +1 -0
  80. package/dist/src/graph-ui/index.html +1 -1
  81. package/dist/src/graph-ui/manager.css +1 -1
  82. package/dist/src/graph-ui/manager.js +2 -2
  83. package/dist/src/graph-ui/sidebar.js +30 -0
  84. package/dist/src/graph-ui/studio-canvas.js +26 -13
  85. package/dist/src/graph-ui/studio.css +15 -7
  86. package/dist/src/graph-ui/studio.js +11 -4
  87. package/dist/src/graph-ui/style.css +77 -45
  88. package/dist/src/graph-ui/theme.js +3 -36
  89. package/dist/src/graph-ui/tokens.css +27 -19
  90. package/dist/src/graph-visibility.d.ts +31 -0
  91. package/dist/src/graph-visibility.js +102 -0
  92. package/dist/src/graphs.js +4 -3
  93. package/dist/src/live-model.d.ts +24 -0
  94. package/dist/src/live-model.js +37 -0
  95. package/dist/src/managed-sign-in.d.ts +1 -0
  96. package/dist/src/managed-sign-in.js +13 -0
  97. package/dist/src/membership-errors.d.ts +2 -0
  98. package/dist/src/membership-errors.js +5 -1
  99. package/dist/src/membership.d.ts +23 -1
  100. package/dist/src/membership.js +48 -6
  101. package/dist/src/model-health-cache.js +1 -1
  102. package/dist/src/model-metadata.d.ts +1 -1
  103. package/dist/src/model-metadata.js +12 -3
  104. package/dist/src/paged-transcript.d.ts +2 -0
  105. package/dist/src/paged-transcript.js +16 -0
  106. package/dist/src/plan-pass.d.ts +59 -0
  107. package/dist/src/plan-pass.js +165 -0
  108. package/dist/src/provider-connection.js +17 -0
  109. package/dist/src/provider-engine.d.ts +5 -0
  110. package/dist/src/provider-engine.js +6 -3
  111. package/dist/src/provider-import.js +3 -1
  112. package/dist/src/provider-settings.js +14 -2
  113. package/dist/src/providers.d.ts +33 -2
  114. package/dist/src/providers.js +101 -28
  115. package/dist/src/pull-request-checks.d.ts +26 -0
  116. package/dist/src/pull-request-checks.js +56 -0
  117. package/dist/src/pull-request-conversation.d.ts +134 -0
  118. package/dist/src/pull-request-conversation.js +221 -0
  119. package/dist/src/pull-request-create.d.ts +175 -0
  120. package/dist/src/pull-request-create.js +392 -0
  121. package/dist/src/pull-request-details.d.ts +242 -0
  122. package/dist/src/pull-request-details.js +614 -0
  123. package/dist/src/pull-request-edit.d.ts +23 -0
  124. package/dist/src/pull-request-edit.js +91 -0
  125. package/dist/src/pull-request-logs.d.ts +76 -0
  126. package/dist/src/pull-request-logs.js +172 -0
  127. package/dist/src/pull-request-merge.d.ts +112 -0
  128. package/dist/src/pull-request-merge.js +258 -0
  129. package/dist/src/pull-request-review.d.ts +137 -0
  130. package/dist/src/pull-request-review.js +401 -0
  131. package/dist/src/pull-requests.d.ts +43 -2
  132. package/dist/src/pull-requests.js +112 -21
  133. package/dist/src/react-runtime.js +58 -9
  134. package/dist/src/read-document-tool.d.ts +2 -0
  135. package/dist/src/read-document-tool.js +6 -6
  136. package/dist/src/remote/engine-pool.js +42 -6
  137. package/dist/src/run-control.d.ts +10 -0
  138. package/dist/src/run-control.js +24 -0
  139. package/dist/src/run-progress.d.ts +10 -0
  140. package/dist/src/run-progress.js +122 -0
  141. package/dist/src/run-records.d.ts +2 -2
  142. package/dist/src/runtime-environment.d.ts +1 -0
  143. package/dist/src/runtime-environment.js +13 -0
  144. package/dist/src/runtime.d.ts +5 -1
  145. package/dist/src/runtime.js +14 -2
  146. package/dist/src/save-lock.js +14 -7
  147. package/dist/src/session-title.d.ts +3 -0
  148. package/dist/src/session-title.js +5 -2
  149. package/dist/src/sign-in-detection.d.ts +1 -1
  150. package/dist/src/sign-in-detection.js +10 -3
  151. package/dist/src/sign-in-offer.js +1 -1
  152. package/dist/src/skill-commands.js +1 -1
  153. package/dist/src/skills/bundled/bug-report/SKILL.md +80 -0
  154. package/dist/src/skills/bundled/graph-manager/SKILL.md +9 -1
  155. package/dist/src/skills/bundled/graph-manager/errors.md +1 -0
  156. package/dist/src/skills/bundled/provenance.json +7 -2
  157. package/dist/src/skills/runtime-skills.js +1 -0
  158. package/dist/src/subagent-run.js +1 -0
  159. package/dist/src/telemetry/capture-core.d.ts +17 -0
  160. package/dist/src/telemetry/capture-core.js +59 -1
  161. package/dist/src/telemetry/classify.d.ts +3 -1
  162. package/dist/src/telemetry/classify.js +37 -0
  163. package/dist/src/telemetry/emitter.d.ts +2 -0
  164. package/dist/src/telemetry/emitter.js +42 -5
  165. package/dist/src/telemetry/schema.d.ts +22 -0
  166. package/dist/src/telemetry/schema.js +68 -1
  167. package/dist/src/telemetry/surface.d.ts +1 -0
  168. package/dist/src/telemetry/uploader.d.ts +12 -1
  169. package/dist/src/telemetry/uploader.js +30 -2
  170. package/dist/src/terminal-links.d.ts +16 -0
  171. package/dist/src/terminal-links.js +113 -0
  172. package/dist/src/terminal-ui.d.ts +8 -1
  173. package/dist/src/terminal-ui.js +40 -14
  174. package/dist/src/tool-catalog.js +1 -1
  175. package/dist/src/trajectory.js +6 -1
  176. package/dist/src/transcript.d.ts +2 -0
  177. package/dist/src/transcript.js +10 -3
  178. package/dist/src/types.d.ts +9 -0
  179. package/dist/src/usage-analytics.js +18 -10
  180. package/package.json +2 -1
@@ -0,0 +1,134 @@
1
+ import type { GhRunner } from './pull-requests.js';
2
+ /** GitHub's reactions, in GitHub's order. */
3
+ export declare const REACTION_CONTENTS: readonly ["THUMBS_UP", "THUMBS_DOWN", "LAUGH", "HOORAY", "CONFUSED", "HEART", "ROCKET", "EYES"];
4
+ export type PullRequestReactionContent = typeof REACTION_CONTENTS[number];
5
+ export interface PullRequestReaction {
6
+ content: PullRequestReactionContent;
7
+ count: number;
8
+ /** The viewer reacted with this one. */
9
+ mine: boolean;
10
+ }
11
+ /** What the viewer may do with a comment, as GitHub says. */
12
+ export interface PullRequestCommentAbilities {
13
+ canEdit: boolean;
14
+ canDelete: boolean;
15
+ canReact: boolean;
16
+ }
17
+ /** A comment on the PR's conversation (an issue comment), not on a line. */
18
+ export interface PullRequestTimelineComment extends PullRequestCommentAbilities {
19
+ id: string;
20
+ author: string;
21
+ body: string;
22
+ createdAt?: string;
23
+ editedAt?: string;
24
+ url?: string;
25
+ /** Hidden on GitHub (spam, outdated, off-topic …): GitHub's reason, lower case. */
26
+ hidden?: string;
27
+ viewerIsAuthor: boolean;
28
+ reactions: PullRequestReaction[];
29
+ }
30
+ export type PullRequestReviewBodyState = 'approved' | 'changes-requested' | 'commented' | 'dismissed';
31
+ /** A submitted review, with what the timeline needs to show, react to and edit it. */
32
+ export interface PullRequestReviewBody extends PullRequestCommentAbilities {
33
+ id: string;
34
+ author: string;
35
+ state: PullRequestReviewBodyState;
36
+ body: string;
37
+ submittedAt?: string;
38
+ url?: string;
39
+ /** Line comments the review carried, which sit in the Files diff. */
40
+ comments: number;
41
+ viewerIsAuthor: boolean;
42
+ reactions: PullRequestReaction[];
43
+ }
44
+ export interface PullRequestLabel {
45
+ id: string;
46
+ name: string;
47
+ color?: string;
48
+ description?: string;
49
+ }
50
+ export interface PullRequestAssignee {
51
+ id: string;
52
+ login: string;
53
+ }
54
+ /** The PR's own text and metadata, which the tab can edit. */
55
+ export interface PullRequestMeta {
56
+ title: string;
57
+ body: string;
58
+ canUpdate: boolean;
59
+ canClose: boolean;
60
+ canReopen: boolean;
61
+ headRefName: string;
62
+ headSha: string;
63
+ /** Where the head branch lives (`owner/name`); a suggestion is committed there. */
64
+ headRepository?: string;
65
+ labels: PullRequestLabel[];
66
+ assignees: PullRequestAssignee[];
67
+ /** The repository's labels the PR can take (the first 100, by name). */
68
+ repositoryLabels: PullRequestLabel[];
69
+ /** People the PR can be assigned to (the first 100), with the ids GitHub's mutations take. */
70
+ assignable: PullRequestAssignee[];
71
+ reactions: PullRequestReaction[];
72
+ }
73
+ export declare const REACTION_FIELDS = "reactionGroups { content viewerHasReacted reactors { totalCount } }";
74
+ /** The timeline's comments and reviews and the PR's metadata, asked for inside the review read's `pullRequest`. */
75
+ export declare const CONVERSATION_FIELDS = "title body viewerCanUpdate viewerCanClose viewerCanReopen headRefName headRefOid headRepository { nameWithOwner } reactionGroups { content viewerHasReacted reactors { totalCount } } labels(first: 50) { nodes { id name color description } } assignees(first: 20) { nodes { id login } } comments(last: 100) { totalCount nodes { id author { login } body createdAt lastEditedAt url isMinimized minimizedReason viewerDidAuthor viewerCanUpdate viewerCanDelete viewerCanReact reactionGroups { content viewerHasReacted reactors { totalCount } } } } timelineReviews: reviews(last: 100, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) { nodes { id author { login } state body submittedAt url viewerDidAuthor viewerCanUpdate viewerCanReact comments { totalCount } reactionGroups { content viewerHasReacted reactors { totalCount } } } }";
76
+ /** The repository's side of the conversation read, inside `repository`. */
77
+ export declare const REPOSITORY_LABEL_FIELDS = "labels(first: 100, orderBy: { field: NAME, direction: ASC }) { nodes { id name color description } }";
78
+ /** What a review thread's comments add for reactions, editing and suggestions. */
79
+ export declare const THREAD_COMMENT_FIELDS = "author { login ... on User { databaseId } ... on Bot { databaseId } } viewerCanUpdate viewerCanDelete viewerCanReact reactionGroups { content viewerHasReacted reactors { totalCount } }";
80
+ export declare function parseReactions(value: unknown): PullRequestReaction[];
81
+ export declare function abilitiesOf(node: Record<string, unknown>): PullRequestCommentAbilities;
82
+ export declare function parseTimelineComment(value: unknown): PullRequestTimelineComment | undefined;
83
+ export declare function parseReviewBody(value: unknown): PullRequestReviewBody | undefined;
84
+ /** The conversation part of the review read: timeline comments, review bodies and the PR's metadata. */
85
+ export declare function parseConversation(pullRequest: unknown, repository: unknown): {
86
+ comments: PullRequestTimelineComment[];
87
+ moreComments?: number;
88
+ reviewBodies: PullRequestReviewBody[];
89
+ meta: PullRequestMeta;
90
+ } | undefined;
91
+ /**
92
+ * The replacement lines of a comment's ```suggestion block, when it has exactly one; GitHub offers to
93
+ * commit a comment's suggestion only then. An empty block suggests deleting the lines (no lines); a
94
+ * block holding one blank line suggests a blank line (one empty line), as on GitHub.
95
+ */
96
+ export declare function suggestionOf(body: string): string[] | undefined;
97
+ /** Whether a file uses one kind of line ending throughout; a suggestion is committed only into such a file. */
98
+ export declare function uniformLineEndings(file: string): boolean;
99
+ /**
100
+ * The file with lines `start`..`end` (1-based, inclusive) replaced by `replacement`, in the file's own
101
+ * line endings. Undefined when the file has fewer lines than that.
102
+ */
103
+ export declare function applySuggestionText(file: string, start: number, end: number, replacement: readonly string[]): string | undefined;
104
+ /** GitHub's commit trailer for the person who suggested the change. */
105
+ export declare function coAuthorTrailer(login: string, databaseId: number | undefined): string | undefined;
106
+ export declare function addComment(gh: GhRunner, subjectId: string, body: string): Promise<{
107
+ id?: string;
108
+ url?: string;
109
+ }>;
110
+ /** Where a comment the tab can change lives on GitHub, which decides the mutation. */
111
+ export type PullRequestCommentKind = 'issue' | 'review' | 'thread';
112
+ export declare function editComment(gh: GhRunner, kind: PullRequestCommentKind, id: string, body: string): Promise<void>;
113
+ export declare function deleteComment(gh: GhRunner, kind: Exclude<PullRequestCommentKind, 'review'>, id: string): Promise<void>;
114
+ export declare function setReaction(gh: GhRunner, subjectId: string, content: PullRequestReactionContent, add: boolean): Promise<void>;
115
+ /**
116
+ * The file at `ref` in `repository` (`owner/name`): its text and blob sha, which an update names so
117
+ * GitHub refuses one when the file changed since (`409`).
118
+ */
119
+ export declare function readFileAt(gh: GhRunner, repository: string, path: string, ref: string): Promise<{
120
+ text: string;
121
+ sha: string;
122
+ utf8: boolean;
123
+ }>;
124
+ /** Commits `content` as `path` on `branch` (`PUT /repos/{o}/{r}/contents/{path}`), the message and file on standard input. */
125
+ export declare function commitFile(gh: GhRunner, repository: string, change: {
126
+ path: string;
127
+ branch: string;
128
+ sha: string;
129
+ content: string;
130
+ message: string;
131
+ }): Promise<{
132
+ commit?: string;
133
+ }>;
134
+ export declare function reactionContent(value: unknown): PullRequestReactionContent;
@@ -0,0 +1,221 @@
1
+ // The PR tab's conversation (phase 4): the pull request's timeline comments and review bodies with
2
+ // their reactions, read with the review; and the writes that act on them: post a comment, edit or
3
+ // delete one, react, and commit a reviewer's suggestion. Everything goes through the GitHub CLI as the
4
+ // account that reads the PR; text the person wrote travels in a JSON body on gh's standard input.
5
+ /** GitHub's reactions, in GitHub's order. */
6
+ export const REACTION_CONTENTS = ['THUMBS_UP', 'THUMBS_DOWN', 'LAUGH', 'HOORAY', 'CONFUSED', 'HEART', 'ROCKET', 'EYES'];
7
+ export const REACTION_FIELDS = 'reactionGroups { content viewerHasReacted reactors { totalCount } }';
8
+ const ABILITY_FIELDS = 'viewerCanUpdate viewerCanDelete viewerCanReact';
9
+ /** The timeline's comments and reviews and the PR's metadata, asked for inside the review read's `pullRequest`. */
10
+ export const CONVERSATION_FIELDS = `title body viewerCanUpdate viewerCanClose viewerCanReopen headRefName headRefOid headRepository { nameWithOwner } ${REACTION_FIELDS} labels(first: 50) { nodes { id name color description } } assignees(first: 20) { nodes { id login } } comments(last: 100) { totalCount nodes { id author { login } body createdAt lastEditedAt url isMinimized minimizedReason viewerDidAuthor ${ABILITY_FIELDS} ${REACTION_FIELDS} } } timelineReviews: reviews(last: 100, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) { nodes { id author { login } state body submittedAt url viewerDidAuthor viewerCanUpdate viewerCanReact comments { totalCount } ${REACTION_FIELDS} } }`;
11
+ /** The repository's side of the conversation read, inside `repository`. */
12
+ export const REPOSITORY_LABEL_FIELDS = 'labels(first: 100, orderBy: { field: NAME, direction: ASC }) { nodes { id name color description } }';
13
+ /** What a review thread's comments add for reactions, editing and suggestions. */
14
+ export const THREAD_COMMENT_FIELDS = `author { login ... on User { databaseId } ... on Bot { databaseId } } ${ABILITY_FIELDS} ${REACTION_FIELDS}`;
15
+ const text = (value) => typeof value === 'string' && value !== '' ? value : undefined;
16
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
17
+ const list = (value) => Array.isArray(value) ? value : [];
18
+ const loginOf = (value) => text(record(value).login)?.replace(/^app\//, '');
19
+ export function parseReactions(value) {
20
+ return list(value).map(record).flatMap((group) => {
21
+ const content = group.content;
22
+ if (typeof content !== 'string' || !REACTION_CONTENTS.includes(content))
23
+ return [];
24
+ const total = record(group.reactors).totalCount ?? record(group.users).totalCount;
25
+ const count = typeof total === 'number' && Number.isSafeInteger(total) && total > 0 ? total : 0;
26
+ const mine = group.viewerHasReacted === true;
27
+ return count > 0 || mine ? [{ content: content, count: Math.max(count, mine ? 1 : 0), mine }] : [];
28
+ });
29
+ }
30
+ export function abilitiesOf(node) {
31
+ return { canEdit: node.viewerCanUpdate === true, canDelete: node.viewerCanDelete === true, canReact: node.viewerCanReact === true };
32
+ }
33
+ export function parseTimelineComment(value) {
34
+ const node = record(value);
35
+ const id = text(node.id);
36
+ if (id === undefined)
37
+ return undefined;
38
+ const hidden = node.isMinimized === true ? (text(node.minimizedReason)?.toLowerCase().replace(/_/g, ' ') ?? 'hidden') : undefined;
39
+ return {
40
+ id, author: loginOf(node.author) ?? 'ghost', body: typeof node.body === 'string' ? node.body : '',
41
+ ...defined({ createdAt: text(node.createdAt), editedAt: text(node.lastEditedAt), url: text(node.url), hidden }),
42
+ viewerIsAuthor: node.viewerDidAuthor === true,
43
+ ...abilitiesOf(node),
44
+ reactions: parseReactions(node.reactionGroups),
45
+ };
46
+ }
47
+ const REVIEW_STATES = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', COMMENTED: 'commented', DISMISSED: 'dismissed' };
48
+ export function parseReviewBody(value) {
49
+ const node = record(value);
50
+ const id = text(node.id);
51
+ const state = typeof node.state === 'string' ? REVIEW_STATES[node.state] : undefined;
52
+ if (id === undefined || state === undefined)
53
+ return undefined;
54
+ const total = record(node.comments).totalCount;
55
+ return {
56
+ id, author: loginOf(node.author) ?? 'ghost', state, body: typeof node.body === 'string' ? node.body : '',
57
+ ...defined({ submittedAt: text(node.submittedAt), url: text(node.url) }),
58
+ comments: typeof total === 'number' && Number.isSafeInteger(total) && total > 0 ? total : 0,
59
+ viewerIsAuthor: node.viewerDidAuthor === true,
60
+ // A submitted review's text can be edited, never deleted.
61
+ canEdit: node.viewerCanUpdate === true, canDelete: false, canReact: node.viewerCanReact === true,
62
+ reactions: parseReactions(node.reactionGroups),
63
+ };
64
+ }
65
+ function labelOf(value) {
66
+ const node = record(value);
67
+ const id = text(node.id);
68
+ const name = text(node.name);
69
+ if (id === undefined || name === undefined)
70
+ return undefined;
71
+ const color = text(node.color);
72
+ return { id, name, ...defined({ color: color !== undefined && /^[0-9a-f]{6}$/i.test(color) ? color.toLowerCase() : undefined, description: text(node.description) }) };
73
+ }
74
+ function assigneeOf(value) {
75
+ const node = record(value);
76
+ const id = text(node.id);
77
+ const login = loginOf(node);
78
+ return id === undefined || login === undefined ? undefined : { id, login };
79
+ }
80
+ const present = (entry) => entry !== undefined;
81
+ /** The conversation part of the review read: timeline comments, review bodies and the PR's metadata. */
82
+ export function parseConversation(pullRequest, repository) {
83
+ const pull = record(pullRequest);
84
+ if (!('comments' in pull) || !('title' in pull))
85
+ return undefined;
86
+ const comments = list(record(pull.comments).nodes).map(parseTimelineComment).filter(present);
87
+ const total = record(pull.comments).totalCount;
88
+ const more = typeof total === 'number' && Number.isSafeInteger(total) && total > comments.length ? total - comments.length : undefined;
89
+ return {
90
+ comments,
91
+ ...(more === undefined ? {} : { moreComments: more }),
92
+ reviewBodies: list(record(pull.timelineReviews).nodes).map(parseReviewBody).filter(present),
93
+ meta: {
94
+ title: typeof pull.title === 'string' ? pull.title : '',
95
+ body: typeof pull.body === 'string' ? pull.body : '',
96
+ canUpdate: pull.viewerCanUpdate === true,
97
+ canClose: pull.viewerCanClose === true,
98
+ canReopen: pull.viewerCanReopen === true,
99
+ headRefName: text(pull.headRefName) ?? '',
100
+ headSha: text(pull.headRefOid) ?? '',
101
+ ...defined({ headRepository: text(record(pull.headRepository).nameWithOwner) }),
102
+ labels: list(record(pull.labels).nodes).map(labelOf).filter(present),
103
+ assignees: list(record(pull.assignees).nodes).map(assigneeOf).filter(present),
104
+ repositoryLabels: list(record(record(repository).labels).nodes).map(labelOf).filter(present),
105
+ assignable: list(record(record(repository).assignableUsers).nodes).map(assigneeOf).filter(present),
106
+ reactions: parseReactions(pull.reactionGroups),
107
+ },
108
+ };
109
+ }
110
+ // Suggestions.
111
+ /**
112
+ * The replacement lines of a comment's ```suggestion block, when it has exactly one; GitHub offers to
113
+ * commit a comment's suggestion only then. An empty block suggests deleting the lines (no lines); a
114
+ * block holding one blank line suggests a blank line (one empty line), as on GitHub.
115
+ */
116
+ export function suggestionOf(body) {
117
+ const blocks = [...body.replace(/\r\n/g, '\n').matchAll(/^[ \t]*(`{3,}|~{3,})[ \t]*suggestion[ \t]*\n([\s\S]*?)^[ \t]*\1[ \t]*$/gm)];
118
+ if (blocks.length !== 1)
119
+ return undefined;
120
+ const content = blocks[0][2];
121
+ return content === '' ? [] : content.replace(/\n$/, '').split('\n');
122
+ }
123
+ /** Whether a file uses one kind of line ending throughout; a suggestion is committed only into such a file. */
124
+ export function uniformLineEndings(file) {
125
+ return !(file.includes('\r\n') && /(^|[^\r])\n/.test(file));
126
+ }
127
+ /**
128
+ * The file with lines `start`..`end` (1-based, inclusive) replaced by `replacement`, in the file's own
129
+ * line endings. Undefined when the file has fewer lines than that.
130
+ */
131
+ export function applySuggestionText(file, start, end, replacement) {
132
+ const eol = file.includes('\r\n') ? '\r\n' : '\n';
133
+ const lines = file.split(/\r?\n/);
134
+ // A file that ends with a newline splits into a last empty entry, which is not a line.
135
+ const count = lines.length - (lines[lines.length - 1] === '' ? 1 : 0);
136
+ if (start < 1 || end < start || end > count)
137
+ return undefined;
138
+ return [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)].join(eol);
139
+ }
140
+ /** GitHub's commit trailer for the person who suggested the change. */
141
+ export function coAuthorTrailer(login, databaseId) {
142
+ if (databaseId === undefined || !/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})(?:\[bot\])?$/.test(login))
143
+ return undefined;
144
+ return `Co-authored-by: ${login} <${databaseId}+${login}@users.noreply.github.com>`;
145
+ }
146
+ // Writes.
147
+ function graphqlErrors(value) {
148
+ const errors = list(value.errors).map(entry => text(record(entry).message)).filter((message) => message !== undefined);
149
+ if (errors.length > 0)
150
+ throw new Error(`GraphQL: ${errors.join('; ')}`);
151
+ }
152
+ async function mutate(gh, query, variables) {
153
+ const raw = await gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], { input: JSON.stringify({ query, variables }) });
154
+ const value = JSON.parse(raw);
155
+ try {
156
+ graphqlErrors(value);
157
+ }
158
+ catch (error) {
159
+ throw Object.assign(error, { stdout: raw });
160
+ }
161
+ return record(value.data);
162
+ }
163
+ export async function addComment(gh, subjectId, body) {
164
+ const data = await mutate(gh, 'mutation($subject: ID!, $body: String!) { addComment(input: { subjectId: $subject, body: $body }) { commentEdge { node { id url } } } }', { subject: subjectId, body });
165
+ const node = record(record(record(data.addComment).commentEdge).node);
166
+ return defined({ id: text(node.id), url: text(node.url) });
167
+ }
168
+ const UPDATE = {
169
+ issue: 'mutation($id: ID!, $body: String!) { updateIssueComment(input: { id: $id, body: $body }) { issueComment { id } } }',
170
+ review: 'mutation($id: ID!, $body: String!) { updatePullRequestReview(input: { pullRequestReviewId: $id, body: $body }) { pullRequestReview { id } } }',
171
+ thread: 'mutation($id: ID!, $body: String!) { updatePullRequestReviewComment(input: { pullRequestReviewCommentId: $id, body: $body }) { pullRequestReviewComment { id } } }',
172
+ };
173
+ export async function editComment(gh, kind, id, body) {
174
+ await mutate(gh, UPDATE[kind], { id, body });
175
+ }
176
+ export async function deleteComment(gh, kind, id) {
177
+ await mutate(gh, kind === 'issue'
178
+ ? 'mutation($id: ID!) { deleteIssueComment(input: { id: $id }) { clientMutationId } }'
179
+ : 'mutation($id: ID!) { deletePullRequestReviewComment(input: { id: $id }) { clientMutationId } }', { id });
180
+ }
181
+ export async function setReaction(gh, subjectId, content, add) {
182
+ const field = add ? 'addReaction' : 'removeReaction';
183
+ await mutate(gh, `mutation($subject: ID!, $content: ReactionContent!) { ${field}(input: { subjectId: $subject, content: $content }) { reaction { content } } }`, { subject: subjectId, content });
184
+ }
185
+ const encodePath = (path) => path.split('/').map(encodeURIComponent).join('/');
186
+ /**
187
+ * The file at `ref` in `repository` (`owner/name`): its text and blob sha, which an update names so
188
+ * GitHub refuses one when the file changed since (`409`).
189
+ */
190
+ export async function readFileAt(gh, repository, path, ref) {
191
+ const raw = await gh(['api', '--hostname', 'github.com', `repos/${repository}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`], { maxBuffer: 16 * 1024 * 1024 });
192
+ const value = record(JSON.parse(raw));
193
+ const sha = text(value.sha);
194
+ if (value.type !== 'file' || sha === undefined || value.encoding !== 'base64' || typeof value.content !== 'string') {
195
+ throw new Error(`GitHub did not send ${path} as a file (it may be larger than 1 MB).`);
196
+ }
197
+ const bytes = Buffer.from(value.content.replace(/\s/g, ''), 'base64');
198
+ const decoded = bytes.toString('utf8');
199
+ // `utf8` false: the file's bytes do not survive a round trip through text, so rewriting it would change them.
200
+ return { text: decoded, sha, utf8: Buffer.from(decoded, 'utf8').equals(bytes) };
201
+ }
202
+ /** Commits `content` as `path` on `branch` (`PUT /repos/{o}/{r}/contents/{path}`), the message and file on standard input. */
203
+ export async function commitFile(gh, repository, change) {
204
+ const raw = await gh(['api', '--hostname', 'github.com', '-X', 'PUT', `repos/${repository}/contents/${encodePath(change.path)}`, '--input', '-'], {
205
+ input: JSON.stringify({ message: change.message, content: Buffer.from(change.content, 'utf8').toString('base64'), sha: change.sha, branch: change.branch }),
206
+ });
207
+ return defined({ commit: text(record(record(JSON.parse(raw)).commit).sha) });
208
+ }
209
+ // What the app-server accepts, checked before anything reaches gh.
210
+ export function reactionContent(value) {
211
+ if (typeof value === 'string' && REACTION_CONTENTS.includes(value))
212
+ return value;
213
+ throw new Error(`content must be one of ${REACTION_CONTENTS.join(', ')}`);
214
+ }
215
+ function defined(values) {
216
+ const kept = {};
217
+ for (const [key, value] of Object.entries(values))
218
+ if (value !== undefined)
219
+ kept[key] = value;
220
+ return kept;
221
+ }
@@ -0,0 +1,175 @@
1
+ import { PullRequestRefusal } from './pull-request-details.js';
2
+ import { type GhRunner } from './pull-requests.js';
3
+ /** One git command in the task's folder. Never prompts: a push that needs a password fails instead. */
4
+ export type GitRunner = (args: readonly string[], options?: {
5
+ timeoutMs?: number;
6
+ env?: Record<string, string>;
7
+ }) => Promise<{
8
+ code: number;
9
+ stdout: string;
10
+ stderr: string;
11
+ }>;
12
+ export declare function gitIn(folder: string): GitRunner;
13
+ export interface PullRequestCreateCommit {
14
+ oid: string;
15
+ headline: string;
16
+ }
17
+ export interface PullRequestCreateDraft {
18
+ /** The account the PR is opened as: the first signed-in account that can push to the repository. */
19
+ viewer: string;
20
+ owner: string;
21
+ repo: string;
22
+ /** The task folder's branch, which becomes the PR's head. */
23
+ head: string;
24
+ /** Its commit, which the person confirms; a create is refused when the branch moved since. */
25
+ headSha: string;
26
+ base: string;
27
+ defaultBranch: string;
28
+ /** Branches on GitHub the PR could go into, the default first. */
29
+ branches: string[];
30
+ title: string;
31
+ body: string;
32
+ /** Where the body came from: the repository's PR template (its path) or the commits. */
33
+ template?: string;
34
+ /** The branch's commits that the base lacks, newest first (at most 50); empty with `commitsUnknown` when the folder lacks the base. */
35
+ commits: PullRequestCreateCommit[];
36
+ commitsUnknown?: true;
37
+ moreCommits?: true;
38
+ /** What the create pushes first: nothing, the whole branch (GitHub lacks it), or commits GitHub lacks. */
39
+ push: 'none' | 'new' | 'ahead';
40
+ /** Files changed in the folder but not committed; they stay out of the PR. */
41
+ uncommitted: number;
42
+ /** An open PR on GitHub already has this branch as its head; it is attached instead of opening another. */
43
+ existing?: {
44
+ url: string;
45
+ number: number;
46
+ title: string;
47
+ };
48
+ /**
49
+ * The repository origin was forked from, which GitHub opens a fork's pull request into by default:
50
+ * its default branch and other branches, and a PR already open there from this branch.
51
+ */
52
+ parent?: PullRequestCreateParent;
53
+ }
54
+ export interface PullRequestCreateParent {
55
+ owner: string;
56
+ repo: string;
57
+ defaultBranch: string;
58
+ branches: string[];
59
+ existing?: {
60
+ url: string;
61
+ number: number;
62
+ title: string;
63
+ };
64
+ }
65
+ export type PullRequestCreateBlockKind = 'no-repository' | 'detached' | 'default-branch' | 'no-github-remote' | 'no-commits' | 'no-push-access' | 'diverged';
66
+ /** Why this task's folder has no pull request to open, in words for the person. */
67
+ export interface PullRequestCreateBlock {
68
+ kind: PullRequestCreateBlockKind;
69
+ message: string;
70
+ branch?: string;
71
+ }
72
+ export declare class PullRequestCreateBlocked extends Error {
73
+ readonly block: PullRequestCreateBlock;
74
+ constructor(block: PullRequestCreateBlock);
75
+ }
76
+ /** The GitHub repository a remote URL names: https, ssh or scp-like, with or without `.git`. */
77
+ export declare function githubRepositoryOf(url: string): {
78
+ owner: string;
79
+ repo: string;
80
+ } | undefined;
81
+ /**
82
+ * The title and body a new PR starts with. One commit: its subject, and its message as the body. More:
83
+ * the task's name, and the commits as a list. The repository's template, when it has one, is the body.
84
+ */
85
+ export declare function draftText(commits: readonly (PullRequestCreateCommit & {
86
+ body?: string;
87
+ })[], taskName: string | undefined, branch: string, template?: string): {
88
+ title: string;
89
+ body: string;
90
+ };
91
+ /**
92
+ * What a Create Pull Request from the task's folder would open. Refused with a `PullRequestCreateBlocked`
93
+ * when there is nothing to open: not a Git repository, a detached head, the default branch itself, no
94
+ * GitHub remote, no commits past the base, a branch GitHub has commits of that the folder lacks, or no
95
+ * signed-in account that can push.
96
+ */
97
+ export declare function readCreateDraft(gh: GhRunner, git: GitRunner, folder: string, options?: {
98
+ taskName?: string;
99
+ base?: string;
100
+ closesIssue?: (owner: string, repo: string) => number | undefined;
101
+ }): Promise<PullRequestCreateDraft>;
102
+ /**
103
+ * The confirmed account's own token, for git to push as it: gh's token for that login, or, where gh
104
+ * cannot name one (it signs in with GH_TOKEN, or is too old for --user), the token gh itself uses, whose
105
+ * account the caller already checked answers as `login` (`runAsAccount`).
106
+ */
107
+ export declare function accountToken(gh: GhRunner, login: string): Promise<string>;
108
+ /**
109
+ * How git signs in as the confirmed account for one push or fetch: a credential helper that hands git
110
+ * the account's token, in place of every helper git would otherwise ask (its stored credentials, gh's
111
+ * own helper). The token travels in the environment of that one git command, never in an argument.
112
+ */
113
+ export declare function tokenCredentials(token: string): Record<string, string>;
114
+ /** A repository's https address on GitHub, which a push as the confirmed account goes to. */
115
+ export declare const githubHttpsUrl: (owner: string, repo: string) => string;
116
+ /**
117
+ * Pushes `sha`, the commit the person confirmed, to `head` in `owner/repo`: the GitHub repository the
118
+ * confirm named (origin, checked), not wherever `remote.origin.pushurl` points, over https as the
119
+ * confirmed account (its token, never git's stored credentials or an ssh key). Never forced; never
120
+ * prompts. A branch without an upstream then tracks origin's.
121
+ */
122
+ export declare function pushBranch(git: GitRunner, repository: {
123
+ owner: string;
124
+ repo: string;
125
+ }, head: string, sha: string, token: string): Promise<void>;
126
+ /** git refused the push; nothing was opened on GitHub. */
127
+ export declare class PullRequestPushFailed extends PullRequestRefusal {
128
+ }
129
+ export interface PullRequestCreateRequest {
130
+ /** The login the person confirmed; `gh` must already run as it. */
131
+ as: string;
132
+ owner: string;
133
+ repo: string;
134
+ head: string;
135
+ headSha: string;
136
+ base: string;
137
+ title: string;
138
+ body?: string;
139
+ draft: boolean;
140
+ /** Attach the PR GitHub already has open for this branch instead of opening one. */
141
+ attach?: boolean;
142
+ /** Open it in the repository origin was forked from, rather than in origin. */
143
+ into?: {
144
+ owner: string;
145
+ repo: string;
146
+ };
147
+ }
148
+ /**
149
+ * Opens the pull request the person confirmed, through `gh` already pinned to their account. The folder
150
+ * must still be on `head` at `headSha` with origin at `owner/repo`; the branch is pushed first when GitHub
151
+ * lacks it or its newest commits (never forced); then the PR is opened. With `attach`, the open PR GitHub
152
+ * already has for the branch is returned instead, and nothing is written.
153
+ */
154
+ export declare function createFromFolder(gh: GhRunner, git: GitRunner, request: PullRequestCreateRequest): Promise<{
155
+ url: string;
156
+ number: number;
157
+ pushed: boolean;
158
+ attached?: true;
159
+ }>;
160
+ /** Opens the pull request (`POST /repos/{owner}/{repo}/pulls`), with the text on standard input. */
161
+ export declare function createPullRequest(gh: GhRunner, request: {
162
+ owner: string;
163
+ repo: string;
164
+ head: string;
165
+ base: string;
166
+ title: string;
167
+ body?: string;
168
+ draft: boolean;
169
+ }): Promise<{
170
+ url: string;
171
+ number: number;
172
+ }>;
173
+ export declare function branchName(value: unknown, name: string): string;
174
+ export declare function repositoryName(value: unknown, name: string): string;
175
+ export declare function pullRequestTitle(value: unknown): string;