@andorra-labs/code 0.1.15 → 0.1.17

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 (242) hide show
  1. package/dist/src/acp-agent.d.ts +6 -0
  2. package/dist/src/acp-agent.js +15 -4
  3. package/dist/src/agent-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +15 -10
  5. package/dist/src/agent-mcp-catalog.js +1 -0
  6. package/dist/src/agent-mcp.d.ts +4 -1
  7. package/dist/src/agent-mcp.js +46 -10
  8. package/dist/src/andorra/entry.d.ts +10 -0
  9. package/dist/src/andorra/entry.js +18 -4
  10. package/dist/src/andorra/hosted.d.ts +2 -1
  11. package/dist/src/andorra/hosted.js +2 -1
  12. package/dist/src/andorra/notices.d.ts +5 -0
  13. package/dist/src/andorra/notices.js +7 -0
  14. package/dist/src/andorra/state.d.ts +3 -2
  15. package/dist/src/andorra/state.js +4 -4
  16. package/dist/src/andorra/terminal.js +7 -2
  17. package/dist/src/anthropic-credentials.js +2 -0
  18. package/dist/src/app-server/error.d.ts +5 -0
  19. package/dist/src/app-server/error.js +7 -0
  20. package/dist/src/app-server/protocol.d.ts +22 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +89 -0
  23. package/dist/src/app-server/workspace.js +457 -11
  24. package/dist/src/app-server.d.ts +465 -32
  25. package/dist/src/app-server.js +3308 -517
  26. package/dist/src/auth/deployment.js +2 -2
  27. package/dist/src/bridge/cloud.d.ts +27 -0
  28. package/dist/src/bridge/cloud.js +187 -0
  29. package/dist/src/bridge/command.d.ts +30 -0
  30. package/dist/src/bridge/command.js +347 -0
  31. package/dist/src/bridge/control.d.ts +68 -0
  32. package/dist/src/bridge/control.js +233 -0
  33. package/dist/src/bridge/engines.d.ts +90 -0
  34. package/dist/src/bridge/engines.js +601 -0
  35. package/dist/src/bridge/host-ops.d.ts +9 -0
  36. package/dist/src/bridge/host-ops.js +129 -0
  37. package/dist/src/bridge/host.d.ts +47 -0
  38. package/dist/src/bridge/host.js +540 -0
  39. package/dist/src/bridge/link.d.ts +38 -0
  40. package/dist/src/bridge/link.js +508 -0
  41. package/dist/src/bridge/login-link.d.ts +29 -0
  42. package/dist/src/bridge/login-link.js +54 -0
  43. package/dist/src/bridge/protocol.d.ts +136 -0
  44. package/dist/src/bridge/protocol.js +11 -0
  45. package/dist/src/bridge/store.d.ts +12 -0
  46. package/dist/src/bridge/store.js +61 -0
  47. package/dist/src/bridge/wording.d.ts +6 -0
  48. package/dist/src/bridge/wording.js +10 -0
  49. package/dist/src/browser-runner.js +1 -0
  50. package/dist/src/browser-server.js +7 -1
  51. package/dist/src/browser-ui/style.css +3 -3
  52. package/dist/src/browser-ui/tokens.css +28 -17
  53. package/dist/src/change-authors.d.ts +41 -0
  54. package/dist/src/change-authors.js +146 -0
  55. package/dist/src/claude-provider.js +3 -1
  56. package/dist/src/cli.js +202 -38
  57. package/dist/src/codex-errors.js +4 -1
  58. package/dist/src/coding-tools.js +15 -15
  59. package/dist/src/command-screens.d.ts +6 -0
  60. package/dist/src/command-screens.js +19 -14
  61. package/dist/src/commands.d.ts +14 -1
  62. package/dist/src/compaction-phrases.d.ts +4 -0
  63. package/dist/src/compaction-phrases.js +20 -0
  64. package/dist/src/completion.js +82 -5
  65. package/dist/src/config.d.ts +71 -3
  66. package/dist/src/config.js +202 -77
  67. package/dist/src/context-compaction.js +2 -1
  68. package/dist/src/deadline.js +13 -1
  69. package/dist/src/decision/DecisionManager.js +3 -2
  70. package/dist/src/decision/checks.js +1 -1
  71. package/dist/src/decision/requestPhrases.d.ts +4 -0
  72. package/dist/src/decision/requestPhrases.js +22 -0
  73. package/dist/src/default-graph.js +1 -1
  74. package/dist/src/file-diff.d.ts +4 -0
  75. package/dist/src/file-diff.js +2 -1
  76. package/dist/src/github-app/agent-writes.d.ts +102 -0
  77. package/dist/src/github-app/agent-writes.js +320 -0
  78. package/dist/src/github-app/client.d.ts +349 -0
  79. package/dist/src/github-app/client.js +810 -0
  80. package/dist/src/github-app/event-source.d.ts +208 -0
  81. package/dist/src/github-app/event-source.js +684 -0
  82. package/dist/src/github-app/metrics.d.ts +32 -0
  83. package/dist/src/github-app/metrics.js +49 -0
  84. package/dist/src/github-app/review-loop.d.ts +274 -0
  85. package/dist/src/github-app/review-loop.js +1177 -0
  86. package/dist/src/github-app/review-node.d.ts +81 -0
  87. package/dist/src/github-app/review-node.js +205 -0
  88. package/dist/src/github-app/review-post.d.ts +73 -0
  89. package/dist/src/github-app/review-post.js +139 -0
  90. package/dist/src/github-app/review-text.d.ts +107 -0
  91. package/dist/src/github-app/review-text.js +1133 -0
  92. package/dist/src/github-app/review-threads.d.ts +47 -0
  93. package/dist/src/github-app/review-threads.js +107 -0
  94. package/dist/src/github-app/reviewer.d.ts +121 -0
  95. package/dist/src/github-app/reviewer.js +598 -0
  96. package/dist/src/github-app/store.d.ts +59 -0
  97. package/dist/src/github-app/store.js +148 -0
  98. package/dist/src/github-app/triggers.d.ts +141 -0
  99. package/dist/src/github-app/triggers.js +441 -0
  100. package/dist/src/github-inbox.d.ts +55 -0
  101. package/dist/src/github-inbox.js +153 -0
  102. package/dist/src/github-names.d.ts +8 -0
  103. package/dist/src/github-names.js +8 -0
  104. package/dist/src/glob-search.d.ts +61 -0
  105. package/dist/src/glob-search.js +180 -0
  106. package/dist/src/graph-health.js +13 -4
  107. package/dist/src/graph-manager-chat.js +1 -1
  108. package/dist/src/graph-preview.d.ts +46 -0
  109. package/dist/src/graph-preview.js +55 -0
  110. package/dist/src/graph-provider-portability.js +34 -11
  111. package/dist/src/graph-quota.d.ts +29 -2
  112. package/dist/src/graph-quota.js +68 -10
  113. package/dist/src/graph-runner.js +88 -10
  114. package/dist/src/graph-server.d.ts +1 -1
  115. package/dist/src/graph-server.js +11 -9
  116. package/dist/src/graph-sync.js +3 -3
  117. package/dist/src/graph-ui/app.js +201 -40
  118. package/dist/src/graph-ui/controls.css +1 -0
  119. package/dist/src/graph-ui/embed.js +2 -2
  120. package/dist/src/graph-ui/icons.js +3 -1
  121. package/dist/src/graph-ui/index.html +1 -1
  122. package/dist/src/graph-ui/manager.css +1 -1
  123. package/dist/src/graph-ui/manager.js +2 -2
  124. package/dist/src/graph-ui/sidebar.js +30 -0
  125. package/dist/src/graph-ui/studio-canvas.js +26 -13
  126. package/dist/src/graph-ui/studio.css +15 -7
  127. package/dist/src/graph-ui/studio.js +26 -5
  128. package/dist/src/graph-ui/style.css +77 -45
  129. package/dist/src/graph-ui/theme.js +3 -36
  130. package/dist/src/graph-ui/tokens.css +28 -20
  131. package/dist/src/graphs.d.ts +34 -1
  132. package/dist/src/graphs.js +162 -17
  133. package/dist/src/image-input.d.ts +16 -0
  134. package/dist/src/image-input.js +41 -0
  135. package/dist/src/membership.d.ts +30 -1
  136. package/dist/src/membership.js +48 -8
  137. package/dist/src/model-health-cache.js +1 -1
  138. package/dist/src/model-metadata.d.ts +7 -1
  139. package/dist/src/model-metadata.js +39 -17
  140. package/dist/src/model-relay/local.d.ts +116 -0
  141. package/dist/src/model-relay/local.js +468 -0
  142. package/dist/src/model-relay/remote.d.ts +129 -0
  143. package/dist/src/model-relay/remote.js +252 -0
  144. package/dist/src/model-relay/runs.d.ts +34 -0
  145. package/dist/src/model-relay/runs.js +146 -0
  146. package/dist/src/model-relay/wire.d.ts +5 -0
  147. package/dist/src/model-relay/wire.js +5 -0
  148. package/dist/src/plan-pass.d.ts +59 -0
  149. package/dist/src/plan-pass.js +165 -0
  150. package/dist/src/project-registry.d.ts +21 -0
  151. package/dist/src/project-registry.js +74 -0
  152. package/dist/src/provider-engine.js +3 -0
  153. package/dist/src/provider-import.d.ts +0 -12
  154. package/dist/src/provider-import.js +7 -195
  155. package/dist/src/providers.d.ts +40 -2
  156. package/dist/src/providers.js +93 -23
  157. package/dist/src/pull-request-checks.d.ts +26 -0
  158. package/dist/src/pull-request-checks.js +56 -0
  159. package/dist/src/pull-request-conversation.d.ts +134 -0
  160. package/dist/src/pull-request-conversation.js +221 -0
  161. package/dist/src/pull-request-create.d.ts +175 -0
  162. package/dist/src/pull-request-create.js +392 -0
  163. package/dist/src/pull-request-details.d.ts +242 -0
  164. package/dist/src/pull-request-details.js +614 -0
  165. package/dist/src/pull-request-edit.d.ts +23 -0
  166. package/dist/src/pull-request-edit.js +91 -0
  167. package/dist/src/pull-request-logs.d.ts +87 -0
  168. package/dist/src/pull-request-logs.js +183 -0
  169. package/dist/src/pull-request-merge.d.ts +112 -0
  170. package/dist/src/pull-request-merge.js +258 -0
  171. package/dist/src/pull-request-review.d.ts +137 -0
  172. package/dist/src/pull-request-review.js +401 -0
  173. package/dist/src/pull-requests.d.ts +369 -8
  174. package/dist/src/pull-requests.js +524 -55
  175. package/dist/src/react-runtime.js +38 -5
  176. package/dist/src/remote/engine-pool.d.ts +88 -4
  177. package/dist/src/remote/engine-pool.js +379 -90
  178. package/dist/src/remote/roots.d.ts +19 -0
  179. package/dist/src/remote/roots.js +45 -7
  180. package/dist/src/remote/types.d.ts +0 -44
  181. package/dist/src/run-control.d.ts +17 -0
  182. package/dist/src/run-control.js +47 -0
  183. package/dist/src/run-progress.d.ts +10 -0
  184. package/dist/src/run-progress.js +122 -0
  185. package/dist/src/run-records.d.ts +7 -2
  186. package/dist/src/run-records.js +71 -6
  187. package/dist/src/runtime.d.ts +9 -1
  188. package/dist/src/runtime.js +24 -4
  189. package/dist/src/session-changes.d.ts +35 -0
  190. package/dist/src/session-changes.js +194 -6
  191. package/dist/src/session-monitor.js +2 -1
  192. package/dist/src/session-reaper.d.ts +1 -1
  193. package/dist/src/session-reaper.js +6 -1
  194. package/dist/src/session-summary.d.ts +2 -1
  195. package/dist/src/session-summary.js +2 -1
  196. package/dist/src/sessions.d.ts +11 -1
  197. package/dist/src/sessions.js +17 -4
  198. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  199. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  200. package/dist/src/skills/bundled/provenance.json +2 -2
  201. package/dist/src/skills/runtime-skills.js +1 -1
  202. package/dist/src/subagent-run.js +1 -0
  203. package/dist/src/telemetry/capture-core.d.ts +17 -0
  204. package/dist/src/telemetry/capture-core.js +59 -1
  205. package/dist/src/telemetry/classify.d.ts +3 -1
  206. package/dist/src/telemetry/classify.js +37 -0
  207. package/dist/src/telemetry/emitter.d.ts +17 -0
  208. package/dist/src/telemetry/emitter.js +76 -5
  209. package/dist/src/telemetry/schema.d.ts +47 -2
  210. package/dist/src/telemetry/schema.js +120 -5
  211. package/dist/src/telemetry/surface.d.ts +3 -1
  212. package/dist/src/telemetry/surface.js +4 -1
  213. package/dist/src/telemetry/uploader.d.ts +6 -1
  214. package/dist/src/telemetry/uploader.js +22 -3
  215. package/dist/src/terminal-ui.d.ts +1 -0
  216. package/dist/src/terminal-ui.js +10 -3
  217. package/dist/src/test-edit-guard.d.ts +7 -0
  218. package/dist/src/test-edit-guard.js +49 -1
  219. package/dist/src/timers.d.ts +2 -0
  220. package/dist/src/tools.js +59 -9
  221. package/dist/src/transcript.js +8 -2
  222. package/dist/src/types.d.ts +7 -0
  223. package/dist/src/usage-analytics.js +18 -10
  224. package/package.json +6 -1
  225. package/dist/src/remote/cert.d.ts +0 -11
  226. package/dist/src/remote/cert.js +0 -87
  227. package/dist/src/remote/client.d.ts +0 -119
  228. package/dist/src/remote/client.js +0 -544
  229. package/dist/src/remote/command.d.ts +0 -4
  230. package/dist/src/remote/command.js +0 -194
  231. package/dist/src/remote/errors.d.ts +0 -11
  232. package/dist/src/remote/errors.js +0 -14
  233. package/dist/src/remote/network.d.ts +0 -22
  234. package/dist/src/remote/network.js +0 -102
  235. package/dist/src/remote/pairing.d.ts +0 -63
  236. package/dist/src/remote/pairing.js +0 -299
  237. package/dist/src/remote/pem.d.ts +0 -2
  238. package/dist/src/remote/pem.js +0 -7
  239. package/dist/src/remote/serve.d.ts +0 -68
  240. package/dist/src/remote/serve.js +0 -244
  241. package/dist/src/remote/server.d.ts +0 -21
  242. package/dist/src/remote/server.js +0 -406
@@ -0,0 +1,614 @@
1
+ import { parseCheck } from './pull-request-checks.js';
2
+ export { checksRollup, isChecksRollup, parseCheck, sameChecksRollup } from './pull-request-checks.js';
3
+ import { ghAccounts, ghFor, isGhAccessError, isGhListingUnsupported, readPullRequestAsAnyAccount } from './pull-requests.js';
4
+ import { readPullRequestReview, readRepositoryTeams } from './pull-request-review.js';
5
+ import { readPullRequestMergeContext } from './pull-request-merge.js';
6
+ import { readCheckLog } from './pull-request-logs.js';
7
+ const DETAIL_FIELDS = [
8
+ 'number', 'url', 'title', 'state', 'isDraft', 'headRefName', 'headRefOid', 'baseRefName', 'isCrossRepository', 'headRepositoryOwner',
9
+ 'author', 'createdAt', 'updatedAt', 'mergedAt', 'closedAt', 'mergedBy', 'mergeable', 'mergeStateStatus', 'reviewDecision',
10
+ 'body', 'additions', 'deletions', 'changedFiles', 'commits', 'statusCheckRollup', 'reviews',
11
+ ].join(',');
12
+ const text = (value) => typeof value === 'string' && value !== '' ? value : undefined;
13
+ const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0;
14
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
15
+ const list = (value) => Array.isArray(value) ? value : [];
16
+ // gh names a GitHub App's bot account "app/<name>"; the tab shows the name, as github.com does.
17
+ const login = (value) => text(record(value).login)?.replace(/^app\//, '');
18
+ export function pullRequestStateOf(value) {
19
+ return value.state === 'MERGED' ? 'merged' : value.state === 'CLOSED' ? 'closed' : value.isDraft === true ? 'draft' : 'open';
20
+ }
21
+ const REVIEW_STATES = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', COMMENTED: 'commented', DISMISSED: 'dismissed', PENDING: 'pending' };
22
+ const MERGE_STATES = { CLEAN: 'clean', BLOCKED: 'blocked', BEHIND: 'behind', DIRTY: 'dirty', UNSTABLE: 'unstable', DRAFT: 'draft', HAS_HOOKS: 'has-hooks' };
23
+ const DECISIONS = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', REVIEW_REQUIRED: 'review-required' };
24
+ /** The answer of `gh pr view --json <DETAIL_FIELDS>`, checked field by field. */
25
+ export function parsePullRequestDetails(raw, fallbackUrl) {
26
+ const value = record(raw);
27
+ const author = record(value.author);
28
+ const authorLogin = login(author);
29
+ const commits = list(value.commits).map(record).flatMap((commit) => {
30
+ const oid = text(commit.oid);
31
+ if (oid === undefined)
32
+ return [];
33
+ const authors = list(commit.authors).map(record).map(entry => text(entry.login) ?? text(entry.name)).filter((name) => name !== undefined);
34
+ return [{ oid, headline: text(commit.messageHeadline) ?? oid.slice(0, 7), authors, ...optional({ body: text(commit.messageBody), committedAt: text(commit.committedDate) ?? text(commit.authoredDate) }) }];
35
+ });
36
+ const reviews = list(value.reviews).map(record).flatMap((review) => {
37
+ const state = typeof review.state === 'string' ? REVIEW_STATES[review.state] : undefined;
38
+ if (state === undefined)
39
+ return [];
40
+ return [{ author: login(review.author) ?? 'ghost', state, ...optional({ submittedAt: text(review.submittedAt), body: text(review.body) }) }];
41
+ });
42
+ const owner = login(value.headRepositoryOwner);
43
+ return {
44
+ url: text(value.url) ?? fallbackUrl,
45
+ number: count(value.number),
46
+ title: text(value.title) ?? '',
47
+ state: pullRequestStateOf(value),
48
+ headRefName: text(value.headRefName) ?? '',
49
+ baseRefName: text(value.baseRefName) ?? '',
50
+ ...optional({
51
+ headSha: text(value.headRefOid),
52
+ headOwner: value.isCrossRepository === true ? owner : undefined,
53
+ createdAt: text(value.createdAt), updatedAt: text(value.updatedAt), mergedAt: text(value.mergedAt), closedAt: text(value.closedAt),
54
+ mergedBy: login(value.mergedBy),
55
+ reviewDecision: typeof value.reviewDecision === 'string' ? DECISIONS[value.reviewDecision] : undefined,
56
+ }),
57
+ ...(authorLogin === undefined ? {} : { author: { login: authorLogin, ...(author.is_bot === true ? { bot: true } : {}) } }),
58
+ mergeable: value.mergeable === 'MERGEABLE' ? 'mergeable' : value.mergeable === 'CONFLICTING' ? 'conflicting' : 'unknown',
59
+ mergeState: typeof value.mergeStateStatus === 'string' ? MERGE_STATES[value.mergeStateStatus] ?? 'unknown' : 'unknown',
60
+ body: typeof value.body === 'string' ? value.body : '',
61
+ additions: count(value.additions),
62
+ deletions: count(value.deletions),
63
+ changedFiles: count(value.changedFiles),
64
+ commits,
65
+ checks: list(value.statusCheckRollup).map(parseCheck).filter((check) => check !== undefined),
66
+ reviews,
67
+ };
68
+ }
69
+ export async function readPullRequestDetails(gh, url) {
70
+ const raw = await gh(['pr', 'view', url, '--json', DETAIL_FIELDS], { maxBuffer: 16 * 1024 * 1024 });
71
+ return parsePullRequestDetails(JSON.parse(raw), url);
72
+ }
73
+ /** Per-file and whole-PR caps on the lines sent to the desktop; past them a file is listed without its diff. */
74
+ export const FILE_DIFF_LINE_LIMIT = 3_000;
75
+ export const PULL_REQUEST_DIFF_LINE_LIMIT = 30_000;
76
+ const LINE_CHARS = 2_000;
77
+ const FILES_PER_PAGE = 100;
78
+ // GitHub lists at most 3000 files of a pull request.
79
+ const MAX_FILE_PAGES = 30;
80
+ const HUNK_HEAD = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
81
+ /** GitHub's `patch` for one file (hunks without the ---/+++ header) as the desktop's diff hunks. */
82
+ export function parsePatch(patch, maxLines = FILE_DIFF_LINE_LIMIT) {
83
+ const hunks = [];
84
+ let hunk;
85
+ let oldLine = 0;
86
+ let newLine = 0;
87
+ let shown = 0;
88
+ let hidden = 0;
89
+ let lastHidden = false;
90
+ for (const raw of patch.split('\n')) {
91
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
92
+ const head = HUNK_HEAD.exec(line);
93
+ if (head) {
94
+ oldLine = Number(head[1]);
95
+ newLine = Number(head[3]);
96
+ hunk = { oldStart: oldLine, oldLines: head[2] === undefined ? 1 : Number(head[2]), newStart: newLine, newLines: head[4] === undefined ? 1 : Number(head[4]), lines: [] };
97
+ hunks.push(hunk);
98
+ continue;
99
+ }
100
+ if (hunk === undefined)
101
+ continue;
102
+ if (line.startsWith('\\')) {
103
+ // The marker belongs to the line before it, which may be one past the cap.
104
+ const last = hunk.lines.at(-1);
105
+ if (last && !lastHidden)
106
+ last.noNewline = true;
107
+ continue;
108
+ }
109
+ const mark = line[0];
110
+ if (mark !== '+' && mark !== '-' && mark !== ' ' && line !== '')
111
+ continue;
112
+ const kind = mark === '+' ? 'add' : mark === '-' ? 'del' : 'context';
113
+ const numbers = kind === 'add' ? { newLine: newLine++ } : kind === 'del' ? { oldLine: oldLine++ } : { oldLine: oldLine++, newLine: newLine++ };
114
+ if (shown >= maxLines) {
115
+ hidden++;
116
+ lastHidden = true;
117
+ continue;
118
+ }
119
+ lastHidden = false;
120
+ shown++;
121
+ const body = line.slice(1);
122
+ hunk.lines.push({ kind, text: body.length > LINE_CHARS ? body.slice(0, LINE_CHARS) : body, ...numbers, ...(body.length > LINE_CHARS ? { clipped: true } : {}) });
123
+ }
124
+ return { hunks: hunks.filter(entry => entry.lines.length > 0), hiddenLines: hidden };
125
+ }
126
+ const FILE_STATUS = { added: 'added', removed: 'deleted', modified: 'modified', renamed: 'renamed', copied: 'copied', changed: 'modified', unchanged: 'modified' };
127
+ /** The diff text sent for one PR, so the answer stays well inside a paired machine's 12 MiB relay limit. */
128
+ export const PULL_REQUEST_DIFF_CHAR_LIMIT = 4_000_000;
129
+ const BINARY_PATH = /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|icns|tiff?|heic|psd|pdf|zip|gz|tgz|bz2|xz|7z|rar|jar|war|class|wasm|exe|dll|so|dylib|a|o|bin|dat|db|sqlite3?|woff2?|ttf|otf|eot|mp3|mp4|m4a|mov|avi|mkv|webm|wav|flac|ogg|node|pyc)$/i;
130
+ /**
131
+ * GitHub's files list as the tab shows it. A file with no `patch` is binary when its path says so, too
132
+ * large to diff when it has changed lines, and otherwise has no lines to show (an empty file, a pure
133
+ * rename, a mode change). Past the line or character budget a file is listed without its diff.
134
+ */
135
+ export function parsePullRequestFiles(pages, budget = PULL_REQUEST_DIFF_LINE_LIMIT, chars = PULL_REQUEST_DIFF_CHAR_LIMIT) {
136
+ let left = budget;
137
+ let charsLeft = chars;
138
+ return pages.flatMap(list).map(record).flatMap((entry) => {
139
+ const path = text(entry.filename);
140
+ if (path === undefined)
141
+ return [];
142
+ const status = FILE_STATUS[typeof entry.status === 'string' ? entry.status : ''] ?? 'modified';
143
+ const additions = count(entry.additions);
144
+ const deletions = count(entry.deletions);
145
+ const base = { path, status, additions, deletions, ...optional({ previousPath: text(entry.previous_filename) }) };
146
+ const patch = typeof entry.patch === 'string' ? entry.patch : undefined;
147
+ if (patch === undefined) {
148
+ if (BINARY_PATH.test(path))
149
+ return [{ ...base, diff: null, binary: true }];
150
+ return [{ ...base, diff: null, ...(additions + deletions > 0 ? { tooLarge: true } : {}) }];
151
+ }
152
+ if (left <= 0 || charsLeft <= 0 || patch.length > charsLeft)
153
+ return [{ ...base, diff: null, tooLarge: true }];
154
+ const diff = parsePatch(patch, Math.min(FILE_DIFF_LINE_LIMIT, left));
155
+ left -= diff.hunks.reduce((sum, hunk) => sum + hunk.lines.length, 0);
156
+ charsLeft -= diff.hunks.reduce((sum, hunk) => sum + hunk.lines.reduce((total, line) => total + line.text.length, 0), 0);
157
+ return [{ ...base, diff }];
158
+ });
159
+ }
160
+ export async function readPullRequestFiles(gh, pullRequest) {
161
+ const pages = [];
162
+ let truncated = false;
163
+ for (let page = 1;; page++) {
164
+ const raw = await gh(['api', '--hostname', 'github.com', `repos/${pullRequest.owner}/${pullRequest.repo}/pulls/${pullRequest.number}/files?per_page=${FILES_PER_PAGE}&page=${page}`], { maxBuffer: 32 * 1024 * 1024 });
165
+ const entries = JSON.parse(raw);
166
+ if (!Array.isArray(entries))
167
+ throw new Error('gh api returned no file list for this pull request');
168
+ pages.push(entries);
169
+ if (entries.length < FILES_PER_PAGE)
170
+ break;
171
+ if (page >= MAX_FILE_PAGES) {
172
+ truncated = true;
173
+ break;
174
+ }
175
+ }
176
+ return { files: parsePullRequestFiles(pages), truncated };
177
+ }
178
+ /** What went wrong reading a PR, in the tab's terms. The text of the original error is kept as the message. */
179
+ export function classifyGhError(error) {
180
+ const message = (error instanceof Error ? error.message : String(error)).trim();
181
+ if (/\bENOENT\b|command not found|is not recognized as an internal or external command/i.test(message))
182
+ return { kind: 'gh-missing', message };
183
+ if (/rate limit|HTTP 429\b|abuse detection/i.test(message))
184
+ return { kind: 'rate-limited', message };
185
+ if (/not logged in|gh auth login|Bad credentials|HTTP 401\b|no (?:oauth )?token (?:found )?for|authentication required/i.test(message))
186
+ return { kind: 'signed-out', message };
187
+ if (isGhAccessError(error) || /SAML|Resource not accessible/i.test(message))
188
+ return { kind: 'no-access', message };
189
+ return { kind: 'failed', message };
190
+ }
191
+ /** A write the engine itself turns down before asking GitHub, in words for the person. */
192
+ export class PullRequestRefusal extends Error {
193
+ }
194
+ /** The account that would write is not the one the person confirmed. */
195
+ export class PullRequestAccountChanged extends Error {
196
+ }
197
+ /** GitHub's own words from a gh failure: without "gh <cmd> failed:", "gh:", "GraphQL:" and the trailing "(HTTP 4xx)", "(path)" or API URL. */
198
+ function githubReason(message) {
199
+ return message
200
+ .replace(/^gh [^:]*? failed:\s*/, '')
201
+ .replace(/^(?:gh|GraphQL):\s*/, '')
202
+ .replace(/^HTTP \d{3}:?\s*/, '')
203
+ .replace(/\s*\((?:HTTP \d{3}|https:\/\/api\.github\.com\/[^)]*|[A-Za-z.]+)\)\s*$/, '')
204
+ .trim();
205
+ }
206
+ const REST_CODE_WORDS = { invalid: 'is not valid', missing: 'does not exist', missing_field: 'is missing', already_exists: 'already exists', unprocessable: 'cannot be used' };
207
+ /**
208
+ * GitHub's reasons from a refused REST call's body, which gh prints on stdout: an error's own message
209
+ * ("A pull request already exists for o:b."), or its field and code ("head is not valid.").
210
+ */
211
+ function restErrors(error) {
212
+ const stdout = error?.stdout;
213
+ if (typeof stdout !== 'string')
214
+ return [];
215
+ try {
216
+ const body = record(JSON.parse(stdout));
217
+ return list(body.errors).map(entry => {
218
+ if (typeof entry === 'string')
219
+ return entry;
220
+ const fields = record(entry);
221
+ const field = text(fields.field);
222
+ const code = text(fields.code);
223
+ return text(fields.message) ?? (field !== undefined && code !== undefined ? `${field} ${REST_CODE_WORDS[code] ?? code.replace(/_/g, ' ')}.` : undefined);
224
+ }).filter((reason) => reason !== undefined).slice(0, 5);
225
+ }
226
+ catch {
227
+ return [];
228
+ }
229
+ }
230
+ /**
231
+ * What went wrong with a write: the read's kinds, plus GitHub refusing it. gh prints a refused
232
+ * GraphQL mutation as "gh: <reason>" (older gh and the GUI stub as "GraphQL: <reason>") and a refused
233
+ * REST call as "gh: <reason> (HTTP 422)" or "HTTP 422: <reason>".
234
+ */
235
+ export function classifyWriteError(error) {
236
+ const sent = typeof error?.sentComments === 'number' ? error.sentComments : 0;
237
+ const joinedValue = error?.joinedComments;
238
+ const joined = Array.isArray(joinedValue) ? joinedValue.filter((index) => Number.isSafeInteger(index) && index >= 0) : [];
239
+ // `joined` is only said when it is more than the first `sent` in a row.
240
+ const scattered = joined.length > sent;
241
+ const posted = error?.commentPosted === true;
242
+ const withSent = (failure) => ({ ...failure, ...(sent > 0 ? { sent } : {}), ...(scattered ? { joined } : {}), ...(posted ? { commentPosted: true } : {}) });
243
+ if (error instanceof PullRequestRefusal)
244
+ return withSent({ kind: 'refused', message: error.message });
245
+ if (error instanceof PullRequestAccountChanged)
246
+ return withSent({ kind: 'account-changed', message: error.message });
247
+ const failure = classifyGhError(error);
248
+ if (failure.kind === 'gh-missing' || failure.kind === 'rate-limited' || failure.kind === 'signed-out')
249
+ return withSent(failure);
250
+ if (/^gh api graphql failed:|GraphQL: /.test(failure.message) || /\bHTTP 422\b/.test(failure.message)) {
251
+ const reason = githubReason(failure.message) || 'GitHub refused the change.';
252
+ const details = restErrors(error);
253
+ // Only a REST refusal (gh names its HTTP status) keeps GitHub's reasons in the body alone; a GraphQL one already says them.
254
+ return withSent({ kind: 'refused', message: details.length > 0 && /\bHTTP 4\d\d\b/.test(failure.message) ? `${reason.replace(/\.$/, '')}: ${details.join(' ')}` : reason });
255
+ }
256
+ if (failure.kind === 'no-access')
257
+ return withSent({ kind: 'no-access', message: githubReason(failure.message) });
258
+ return withSent(failure);
259
+ }
260
+ /** gh cannot hand out a named account's own token: it signs in with GH_TOKEN, or is too old for --user. */
261
+ function noAccountToken(error) {
262
+ return /no (?:oauth )?token (?:found )?for|returned no token for|unknown flag: --user/i.test(error instanceof Error ? error.message : String(error));
263
+ }
264
+ /** The login gh's default account answers as, read just before a write that cannot be pinned to an account. */
265
+ async function defaultViewer(gh) {
266
+ const value = JSON.parse(await gh(['api', 'graphql', '--hostname', 'github.com', '-f', 'query=query { viewer { login } }']));
267
+ return typeof value.data?.viewer?.login === 'string' ? value.data.viewer.login : undefined;
268
+ }
269
+ /**
270
+ * Runs a write as `login` and nobody else: with that account's own token (`gh auth token --user`), never
271
+ * whichever account gh has active. Where gh cannot give one (GH_TOKEN, an old gh), it first checks that
272
+ * gh's default account answers as that login, and refuses otherwise. A write is never retried as
273
+ * another account.
274
+ */
275
+ export async function runAsAccount(gh, login, run) {
276
+ try {
277
+ return await run(ghFor(gh, { ghUser: login }));
278
+ }
279
+ catch (error) {
280
+ // The token lookup comes before each gh call, so a refusal here means nothing was written. A refusal
281
+ // of the engine's own (a failed git push, whose credential helper may word a missing token alike) is not one.
282
+ if (error instanceof PullRequestRefusal || !noAccountToken(error))
283
+ throw error;
284
+ const now = await defaultViewer(gh);
285
+ if (now === undefined || now.toLowerCase() !== login.toLowerCase()) {
286
+ throw new PullRequestAccountChanged(`GitHub now answers as ${now ?? 'another account'}, not ${login}. Check the account and try again.`);
287
+ }
288
+ return run(gh);
289
+ }
290
+ }
291
+ /**
292
+ * Reads through the account the record names; when that account can no longer read the PR, tries the
293
+ * other signed-in accounts once and remembers the one that can. Signed-out and not-installed errors
294
+ * from that search are what the caller sees, so the tab can say which it is.
295
+ */
296
+ async function asReadableAccount(gh, pullRequest, user, read) {
297
+ const account = user ?? pullRequest.ghUser;
298
+ try {
299
+ return { value: await read(ghFor(gh, { ghUser: account })), ...optional({ user: account }) };
300
+ }
301
+ catch (error) {
302
+ if (!isGhAccessError(error))
303
+ throw error;
304
+ const again = await readPullRequestAsAnyAccount(gh, pullRequest.url);
305
+ if ('failed' in again && again.failed !== undefined)
306
+ throw again.failed;
307
+ if (!again.seen || again.ghUser === account) {
308
+ if (await signedOut(gh))
309
+ throw new Error(`gh is not logged in to github.com. Run gh auth login. (${error instanceof Error ? error.message : String(error)})`);
310
+ throw error;
311
+ }
312
+ return { value: await read(ghFor(gh, { ghUser: again.ghUser })), ...optional({ user: again.ghUser }) };
313
+ }
314
+ }
315
+ async function signedOut(gh) {
316
+ try {
317
+ return (await ghAccounts(gh)).length === 0;
318
+ }
319
+ catch (error) {
320
+ return !isGhListingUnsupported(error) && /not logged in|gh auth login/i.test(error instanceof Error ? error.message : String(error));
321
+ }
322
+ }
323
+ /** A request inside this window after the last read is answered from the cache, so polls from several windows cost one read. */
324
+ export const DETAILS_FRESH_MS = 15_000;
325
+ /** An explicit refresh still waits this long after the last read. */
326
+ export const REFRESH_FLOOR_MS = 2_000;
327
+ const FILES_FRESH_MS = 120_000;
328
+ const TEAMS_FRESH_MS = 10 * 60_000;
329
+ const BACKOFF_FIRST_MS = 60_000;
330
+ const BACKOFF_MAX_MS = 15 * 60_000;
331
+ const DETAIL_ENTRIES = 64;
332
+ const LOG_FRESH_MS = 10 * 60_000;
333
+ const LOG_ENTRIES = 40;
334
+ const FILE_ENTRIES = 12;
335
+ export class PullRequestReader {
336
+ gh;
337
+ now;
338
+ onDetails;
339
+ details = new Map();
340
+ files = new Map();
341
+ reviews = new Map();
342
+ merges = new Map();
343
+ teams = new Map();
344
+ /**
345
+ * `onDetails` hears each details read GitHub actually answered, never a cached or failed one, so what
346
+ * it records (the sidebar's checks rollup) is never older than what is already stored.
347
+ */
348
+ constructor(gh, now = Date.now, onDetails) {
349
+ this.gh = gh;
350
+ this.now = now;
351
+ this.onDetails = onDetails;
352
+ }
353
+ async readDetails(sessionId, pullRequest, options = {}) {
354
+ const entry = this.entry(this.details, DETAIL_ENTRIES, sessionId, pullRequest.url);
355
+ await this.load(entry, options.refresh === true ? REFRESH_FLOOR_MS : DETAILS_FRESH_MS, async () => {
356
+ const read = await asReadableAccount(this.gh, pullRequest, entry.user, runner => readPullRequestDetails(runner, pullRequest.url));
357
+ entry.user = read.user;
358
+ this.onDetails?.(sessionId, pullRequest, read.value);
359
+ return read.value;
360
+ });
361
+ return { details: entry.value ?? null, ...this.stamps(entry) };
362
+ }
363
+ async readFiles(sessionId, pullRequest, options = {}) {
364
+ const entry = this.entry(this.files, FILE_ENTRIES, sessionId, pullRequest.url);
365
+ const moved = options.headSha !== undefined && entry.head !== undefined && entry.head !== options.headSha;
366
+ const user = this.details.get(sessionId)?.url === pullRequest.url ? this.details.get(sessionId)?.user : undefined;
367
+ await this.load(entry, moved || options.refresh === true ? REFRESH_FLOOR_MS : FILES_FRESH_MS, async () => {
368
+ const read = await asReadableAccount(this.gh, pullRequest, entry.user ?? user, runner => readPullRequestFiles(runner, pullRequest));
369
+ entry.user = read.user;
370
+ entry.head = options.headSha;
371
+ return read.value;
372
+ });
373
+ return {
374
+ files: entry.value?.files ?? null,
375
+ ...optional({ headSha: entry.head }),
376
+ ...(entry.value?.truncated ? { truncated: true } : {}),
377
+ ...this.stamps(entry),
378
+ };
379
+ }
380
+ /**
381
+ * The PR's review state (threads, viewed files, reviewers) through the account that reads its details.
382
+ * `force` reads GitHub again at once, after a write, once any read already under way has finished.
383
+ */
384
+ async readReview(sessionId, pullRequest, options = {}) {
385
+ const entry = this.entry(this.reviews, DETAIL_ENTRIES, sessionId, pullRequest.url);
386
+ if (options.force === true) {
387
+ if (entry.inflight)
388
+ await entry.inflight;
389
+ delete entry.attemptedAt;
390
+ }
391
+ const user = entry.user ?? this.knownUser(sessionId, pullRequest.url);
392
+ await this.load(entry, options.refresh === true ? REFRESH_FLOOR_MS : DETAILS_FRESH_MS, async () => {
393
+ const read = await asReadableAccount(this.gh, pullRequest, user, runner => readPullRequestReview(runner, pullRequest));
394
+ entry.user = read.user;
395
+ const teams = read.value.organization ? await this.repositoryTeams(pullRequest, read.user) : undefined;
396
+ return teams === undefined ? read.value : { ...read.value, teams };
397
+ });
398
+ return { review: entry.value ?? null, ...this.stamps(entry) };
399
+ }
400
+ /**
401
+ * Runs a write as the account that read the review the person saw, and only when that account is
402
+ * still `as`, the login they confirmed: a write never goes out under another name. The write uses
403
+ * that account's own token (`gh auth token --user`), never whichever account gh has active; where
404
+ * gh cannot give one (GH_TOKEN, an old gh), it first checks that gh's default account answers as
405
+ * that login. A write is never retried as another account. Afterwards the next read of the review
406
+ * (and of the details, for writes that change them) goes to GitHub.
407
+ */
408
+ async write(sessionId, pullRequest, as, run, options = {}) {
409
+ let entry = this.reviews.get(sessionId);
410
+ if (entry?.url !== pullRequest.url || entry.value === undefined) {
411
+ await this.readReview(sessionId, pullRequest);
412
+ entry = this.reviews.get(sessionId);
413
+ }
414
+ const state = entry?.url === pullRequest.url ? entry.value : undefined;
415
+ if (entry === undefined || state === undefined)
416
+ return { ok: false, error: entry?.error ? { ...entry.error } : { kind: 'failed', message: 'GitHub did not answer.' } };
417
+ if (state.viewer.toLowerCase() !== as.toLowerCase()) {
418
+ return { ok: false, error: { kind: 'account-changed', message: `GitHub now answers as ${state.viewer}, not ${as}. Check the account and try again.` } };
419
+ }
420
+ const held = this.details.get(sessionId);
421
+ const details = held?.url === pullRequest.url ? held.value : undefined;
422
+ const login = entry.user ?? state.viewer;
423
+ try {
424
+ const value = await runAsAccount(this.gh, login, gh => run(gh, state, details));
425
+ // GitHub just answered, so a rate-limit back-off from earlier no longer holds the next reads.
426
+ settle(entry);
427
+ if (options.details === true && held?.url === pullRequest.url)
428
+ settle(held);
429
+ return { ok: true, value };
430
+ }
431
+ catch (error) {
432
+ return { ok: false, error: classifyWriteError(error) };
433
+ }
434
+ }
435
+ /**
436
+ * What merging needs: the methods the repository allows, GitHub's own commit message, why it is
437
+ * blocked, and whether the branch can be updated. Read when the Merge panel opens, through the
438
+ * account that reads the PR's details, cached and backed off like them.
439
+ */
440
+ async readMerge(sessionId, pullRequest, options = {}) {
441
+ const entry = this.entry(this.merges, DETAIL_ENTRIES, sessionId, pullRequest.url);
442
+ if (options.force === true) {
443
+ if (entry.inflight)
444
+ await entry.inflight;
445
+ delete entry.attemptedAt;
446
+ }
447
+ const user = entry.user ?? this.knownUser(sessionId, pullRequest.url);
448
+ await this.load(entry, options.refresh === true ? REFRESH_FLOOR_MS : DETAILS_FRESH_MS, async () => {
449
+ const read = await asReadableAccount(this.gh, pullRequest, user, runner => readPullRequestMergeContext(runner, pullRequest));
450
+ entry.user = read.user;
451
+ return read.value;
452
+ });
453
+ return { merge: entry.value ?? null, ...this.stamps(entry) };
454
+ }
455
+ /**
456
+ * A merge-side write (merge, update the branch, ready for review): like `write`, but checked against
457
+ * the merge read the person saw, and the details, review and merge reads all go to GitHub next.
458
+ */
459
+ async writeMerge(sessionId, pullRequest, as, run) {
460
+ // A merge acts on what GitHub says now, never on a cached read: the write reads first, and does not
461
+ // go ahead when that read fails.
462
+ await this.readMerge(sessionId, pullRequest, { force: true });
463
+ const entry = this.merges.get(sessionId);
464
+ const state = entry?.url === pullRequest.url && entry.error === undefined ? entry.value : undefined;
465
+ if (entry === undefined || state === undefined)
466
+ return { ok: false, error: entry?.error ? { ...entry.error } : { kind: 'failed', message: 'GitHub did not answer.' } };
467
+ if (state.viewer.toLowerCase() !== as.toLowerCase()) {
468
+ return { ok: false, error: { kind: 'account-changed', message: `GitHub now answers as ${state.viewer}, not ${as}. Check the account and try again.` } };
469
+ }
470
+ try {
471
+ const value = await runAsAccount(this.gh, entry.user ?? state.viewer, gh => run(gh, state));
472
+ for (const map of [this.merges, this.details, this.reviews]) {
473
+ const held = map.get(sessionId);
474
+ if (held?.url === pullRequest.url)
475
+ settle(held);
476
+ }
477
+ return { ok: true, value };
478
+ }
479
+ catch (error) {
480
+ const failure = classifyWriteError(error);
481
+ // What the person saw may be why it failed (a push since, a check that finished): the next read goes to GitHub.
482
+ if (failure.kind !== 'rate-limited')
483
+ delete entry.attemptedAt;
484
+ return { ok: false, error: failure };
485
+ }
486
+ }
487
+ /**
488
+ * The teams that can be asked to review, kept for 10 minutes per repository and account: teams change
489
+ * rarely, and the review is read every minute. A failed read leaves the picker without teams.
490
+ */
491
+ async repositoryTeams(pullRequest, user) {
492
+ const key = `${user ?? ''}\n${pullRequest.owner}/${pullRequest.repo}`.toLowerCase();
493
+ const held = this.teams.get(key);
494
+ if (held !== undefined && this.now() - held.at < TEAMS_FRESH_MS)
495
+ return held.teams;
496
+ let teams;
497
+ // A viewer who cannot list the teams is not asked again for ten minutes either.
498
+ try {
499
+ teams = await readRepositoryTeams(ghFor(this.gh, { ghUser: user }), pullRequest);
500
+ }
501
+ catch {
502
+ teams = held?.teams;
503
+ }
504
+ this.teams.delete(key);
505
+ this.teams.set(key, { teams, at: this.now() });
506
+ while (this.teams.size > DETAIL_ENTRIES)
507
+ this.teams.delete(this.teams.keys().next().value);
508
+ return teams;
509
+ }
510
+ /** The account a read of this PR last succeeded as, from whichever read knows it. */
511
+ knownUser(sessionId, url) {
512
+ for (const map of [this.details, this.files]) {
513
+ const entry = map.get(sessionId);
514
+ if (entry?.url === url && entry.user !== undefined)
515
+ return entry.user;
516
+ }
517
+ return undefined;
518
+ }
519
+ logs = new Map();
520
+ /**
521
+ * A failed job's log excerpt, through the account that reads the PR. A finished job's log does not
522
+ * change, so it is kept for ten minutes; a running one is asked again after 15 seconds.
523
+ */
524
+ async readCheckLog(sessionId, pullRequest, jobId) {
525
+ const key = `${pullRequest.url}\n${jobId}`;
526
+ const held = this.logs.get(key);
527
+ if (held !== undefined && this.now() - held.at < (held.value.running ? DETAILS_FRESH_MS : LOG_FRESH_MS))
528
+ return { log: held.value };
529
+ try {
530
+ const read = await asReadableAccount(this.gh, pullRequest, this.knownUser(sessionId, pullRequest.url), runner => readCheckLog(runner, pullRequest, jobId).catch(error => {
531
+ if (/maxBuffer/i.test(error instanceof Error ? error.message : String(error)))
532
+ throw new Error('The log is larger than the tab reads (32 MB). Read it on GitHub.');
533
+ throw error;
534
+ }));
535
+ this.logs.delete(key);
536
+ this.logs.set(key, { value: read.value, at: this.now() });
537
+ while (this.logs.size > LOG_ENTRIES)
538
+ this.logs.delete(this.logs.keys().next().value);
539
+ return { log: read.value };
540
+ }
541
+ catch (error) {
542
+ return { log: held?.value ?? null, error: classifyGhError(error) };
543
+ }
544
+ }
545
+ forget(sessionId) {
546
+ this.details.delete(sessionId);
547
+ this.files.delete(sessionId);
548
+ this.reviews.delete(sessionId);
549
+ this.merges.delete(sessionId);
550
+ }
551
+ entry(map, limit, sessionId, url) {
552
+ let entry = map.get(sessionId);
553
+ if (entry?.url !== url)
554
+ entry = { url, failures: 0 };
555
+ map.delete(sessionId);
556
+ map.set(sessionId, entry);
557
+ while (map.size > limit)
558
+ map.delete(map.keys().next().value);
559
+ return entry;
560
+ }
561
+ async load(entry, freshMs, read) {
562
+ if (entry.inflight)
563
+ return entry.inflight;
564
+ const now = this.now();
565
+ if (entry.retryAt !== undefined && now < entry.retryAt)
566
+ return;
567
+ if (entry.attemptedAt !== undefined && now - entry.attemptedAt < freshMs)
568
+ return;
569
+ entry.attemptedAt = now;
570
+ entry.inflight = (async () => {
571
+ try {
572
+ entry.value = await read();
573
+ entry.fetchedAt = this.now();
574
+ entry.failures = 0;
575
+ delete entry.error;
576
+ delete entry.retryAt;
577
+ }
578
+ catch (error) {
579
+ const failure = classifyGhError(error);
580
+ if (failure.kind === 'rate-limited') {
581
+ entry.failures++;
582
+ entry.retryAt = this.now() + Math.min(BACKOFF_MAX_MS, BACKOFF_FIRST_MS * 2 ** (entry.failures - 1));
583
+ failure.retryAt = new Date(entry.retryAt).toISOString();
584
+ }
585
+ else
586
+ entry.failures = 0;
587
+ entry.error = failure;
588
+ }
589
+ finally {
590
+ entry.inflight = undefined;
591
+ }
592
+ })();
593
+ return entry.inflight;
594
+ }
595
+ stamps(entry) {
596
+ return {
597
+ ...(entry.fetchedAt === undefined ? {} : { fetchedAt: new Date(entry.fetchedAt).toISOString() }),
598
+ ...(entry.error === undefined ? {} : { error: { ...entry.error } }),
599
+ };
600
+ }
601
+ }
602
+ /** Lets the next read of an entry go to GitHub at once: it is stale and no back-off holds it. */
603
+ function settle(entry) {
604
+ delete entry.attemptedAt;
605
+ delete entry.retryAt;
606
+ entry.failures = 0;
607
+ }
608
+ function optional(values) {
609
+ const kept = {};
610
+ for (const [key, value] of Object.entries(values))
611
+ if (value !== undefined)
612
+ kept[key] = value;
613
+ return kept;
614
+ }
@@ -0,0 +1,23 @@
1
+ import type { GhRunner } from './pull-requests.js';
2
+ /** The title and body GitHub holds now, read just before an edit so one made elsewhere is not overwritten. */
3
+ export declare function currentText(gh: GhRunner, pullRequestId: string): Promise<{
4
+ title: string;
5
+ body: string;
6
+ }>;
7
+ export declare function updateText(gh: GhRunner, pullRequestId: string, change: {
8
+ title?: string;
9
+ body?: string;
10
+ }): Promise<void>;
11
+ export declare function changeLabels(gh: GhRunner, pullRequestId: string, change: {
12
+ add: readonly string[];
13
+ remove: readonly string[];
14
+ }): Promise<void>;
15
+ export declare function changeAssignees(gh: GhRunner, pullRequestId: string, change: {
16
+ add: readonly string[];
17
+ remove: readonly string[];
18
+ }): Promise<void>;
19
+ /** Closes the PR (its branch stays), or reopens a closed one. */
20
+ export declare function setOpen(gh: GhRunner, pullRequestId: string, open: boolean): Promise<void>;
21
+ export declare function editTitle(value: unknown): string | undefined;
22
+ export declare function editBody(value: unknown, name?: string): string | undefined;
23
+ export declare function nodeIds(value: unknown, name: string): string[];