@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,320 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { GITHUB_OWNER, GITHUB_REPO } from '../github-names.js';
3
+ import { runAsAccount } from '../pull-request-details.js';
4
+ import { COMMENT_BODY_LIMIT } from '../pull-request-review.js';
5
+ import { BOT_BODY_BYTES } from './client.js';
6
+ import { escapeWriteBody } from './review-text.js';
7
+ /** A thread the agent named that is not on its session's PR: refused before anything was written. */
8
+ export class ThreadElsewhere extends Error {
9
+ }
10
+ /**
11
+ * The person's own pending review on the PR: GitHub files a reply made through gh into it, where nobody sees it
12
+ * until the person submits the review. Refused before anything is written.
13
+ */
14
+ export class PendingReview extends Error {
15
+ }
16
+ export const AGENT_WRITE_ACTIONS = ['reply', 'resolve', 'comment'];
17
+ const THREAD_ID = /^PRRT_[A-Za-z0-9_-]{1,120}$/;
18
+ const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
19
+ /** A ULID: 48 bits of milliseconds, then 80 random bits, in Crockford's base 32. */
20
+ export function newRequestId(now = Date.now(), random = randomBytes(10)) {
21
+ if (random.length !== 10)
22
+ throw new Error('a request id takes 10 random bytes');
23
+ const value = (BigInt(Math.max(0, Math.floor(now))) & ((1n << 48n) - 1n)) << 80n | BigInt(`0x${Buffer.from(random).toString('hex')}`);
24
+ let id = '';
25
+ for (let shift = 125n; shift >= 0n; shift -= 5n)
26
+ id += CROCKFORD[Number((value >> shift) & 31n)];
27
+ return id;
28
+ }
29
+ function threadIdOf(value) {
30
+ if (value === undefined)
31
+ throw new Error('threadId is required: the review thread\'s id (PRRT_…), from gh\'s reviewThreads query');
32
+ if (typeof value !== 'string' || !THREAD_ID.test(value))
33
+ throw new Error('threadId must be a review thread id (PRRT_…), as gh\'s reviewThreads query gives it');
34
+ return value;
35
+ }
36
+ function bodyOf(value) {
37
+ if (value === undefined)
38
+ throw new Error('body is required');
39
+ if (typeof value !== 'string')
40
+ throw new Error('body must be text');
41
+ if (value.trim() === '')
42
+ throw new Error('body is empty');
43
+ // No hidden HTML comment, and never the review marker's opening, which only the service writes (R16).
44
+ const body = escapeWriteBody(value);
45
+ if (body.length > COMMENT_BODY_LIMIT)
46
+ throw new Error(`body is longer than GitHub's ${COMMENT_BODY_LIMIT} characters`);
47
+ return body;
48
+ }
49
+ /** The write the pull_request tool's `reply`, `resolve` or `comment` asks for, checked before anything is approved or sent. */
50
+ export function agentWriteFromArgs(args) {
51
+ const unexpected = (names) => {
52
+ for (const name of names)
53
+ if (args[name] !== undefined)
54
+ throw new Error(`${name} does not apply to ${String(args.action)}`);
55
+ };
56
+ switch (args.action) {
57
+ case 'reply':
58
+ unexpected(['resolved', 'url', 'autoFix', 'mergeWhenReady', 'draft', 'review', 'reviewRounds', 'reviewInstruction', 'reviewModel', 'timeoutMinutes']);
59
+ return { action: 'reply', threadId: threadIdOf(args.threadId), body: bodyOf(args.body) };
60
+ case 'resolve':
61
+ unexpected(['body', 'url', 'autoFix', 'mergeWhenReady', 'draft', 'review', 'reviewRounds', 'reviewInstruction', 'reviewModel', 'timeoutMinutes']);
62
+ if (args.resolved !== undefined && typeof args.resolved !== 'boolean')
63
+ throw new Error('resolved must be a boolean');
64
+ return { action: 'resolve', threadId: threadIdOf(args.threadId), resolved: args.resolved !== false };
65
+ case 'comment':
66
+ unexpected(['threadId', 'resolved', 'url', 'autoFix', 'mergeWhenReady', 'draft', 'review', 'reviewRounds', 'reviewInstruction', 'reviewModel', 'timeoutMinutes']);
67
+ return { action: 'comment', body: bodyOf(args.body) };
68
+ default: throw new Error('action must be reply, resolve or comment');
69
+ }
70
+ }
71
+ export const botAction = (write) => write.action === 'resolve' ? (write.resolved ? 'resolve' : 'unresolve') : write.action;
72
+ const repository = (pullRequest) => `${pullRequest.owner}/${pullRequest.repo}`;
73
+ /** Why a write went through gh without asking the service: the PR's coverage, or the person's setting. */
74
+ export function coverageReason(coverage, pullRequest) {
75
+ switch (coverage) {
76
+ case 'signed-out': return 'this engine is not signed in to Andorra';
77
+ case 'not-connected': return 'your GitHub account is not connected to Andorra';
78
+ case 'suspended': return `Andorra Code's installation for ${pullRequest.owner} is suspended`;
79
+ case 'disabled': return 'the Andorra Code GitHub App is turned off';
80
+ case 'unavailable': return 'Andorra\'s service was unavailable';
81
+ default: return `this pull request is not covered by Andorra Code (${repository(pullRequest)})`;
82
+ }
83
+ }
84
+ /** Why the service wrote nothing, in the words the tool result uses. */
85
+ export function fallbackReason(reason, pullRequest) {
86
+ switch (reason) {
87
+ case 'signed-out': return 'this engine is not signed in to Andorra';
88
+ case 'unauthorized': return 'Andorra\'s service did not accept this engine\'s sign-in';
89
+ case 'disabled': return 'the Andorra Code GitHub App is turned off on Andorra\'s service';
90
+ case 'not-allowed': return 'this Andorra account cannot use the Andorra Code GitHub App yet';
91
+ case 'not-covered': return `this pull request is not covered by Andorra Code (${repository(pullRequest)})`;
92
+ case 'forbidden': return 'Andorra\'s service refused the bot\'s write';
93
+ case 'rate-limited': return 'the bot reached its write limit for now';
94
+ case 'late': return 'Andorra\'s service could not start the bot\'s write in time';
95
+ case 'github-refused': return 'GitHub refused the bot\'s write';
96
+ case 'no-route': return 'Andorra\'s service does not offer bot replies here';
97
+ case 'unavailable': return 'Andorra\'s service was unavailable';
98
+ }
99
+ }
100
+ export const AS_ME_REASON = 'agent replies on pull requests are set to post as you';
101
+ export const CHANGED_WHILE_APPROVING = 'The pull request or reply setting changed while awaiting approval; retry.';
102
+ /**
103
+ * What the approval says the write does and who it posts as: the bot first and the PR record's account if the
104
+ * bot cannot, or the account alone. One approval covers both, so a fallback is never asked about again.
105
+ */
106
+ export function approvalDetail(write, pullRequest, bot, botName) {
107
+ const what = write.action === 'reply' ? 'Posts a reply' : write.action === 'comment' ? 'Posts a comment' : write.resolved ? 'Resolves a review thread' : 'Reopens a review thread';
108
+ const account = pullRequest.ghUser ?? 'your gh account';
109
+ const name = botName !== undefined && /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\[bot\]$/.test(botName) ? botName : 'the Andorra Code bot';
110
+ return bot ? `${what} on ${pullRequest.url} as ${name}; as ${account} if the bot can't.` : `${what} on ${pullRequest.url} as ${account}.`;
111
+ }
112
+ /**
113
+ * Whether an agent write goes to the service first: agent writes set to the bot, and the PR covered (or
114
+ * `permissions-pending`, where the service decides per action). The Auto-fix prompt uses the same rule, so
115
+ * the prompt and the tool agree on who the replies post as.
116
+ */
117
+ export const asksBot = (setting, coverage) => setting === 'bot' && (coverage === 'covered' || coverage === 'permissions-pending');
118
+ const noun = (action) => action === 'comment' ? 'comment' : action === 'reply' ? 'reply' : action === 'resolve' ? 'resolve' : 'unresolve';
119
+ function botText(action, as, url) {
120
+ const verb = action === 'reply' ? 'Replied' : action === 'comment' ? 'Commented' : action === 'resolve' ? 'Resolved the thread' : 'Unresolved the thread';
121
+ return `${verb} as ${as}.${url === undefined ? '' : ` ${url}`}`;
122
+ }
123
+ function ghText(action, login, reason, url) {
124
+ const verb = action === 'resolve' ? 'Resolved the thread' : action === 'unresolve' ? 'Unresolved the thread' : 'Posted';
125
+ return `${verb} as ${login}: ${reason}.${url === undefined ? '' : ` ${url}`}`;
126
+ }
127
+ /** The tracked PR's owner and name are safe to put in a REST path: GitHub's name characters, and not `.` or `..`. */
128
+ function checkRepository(pullRequest) {
129
+ if (!GITHUB_OWNER.test(pullRequest.owner) || !GITHUB_REPO.test(pullRequest.repo)
130
+ || !Number.isSafeInteger(pullRequest.number) || pullRequest.number < 1) {
131
+ throw new Error(`The tracked pull request ${pullRequest.url} does not name a GitHub repository this tool can write to; nothing was posted.`);
132
+ }
133
+ }
134
+ /**
135
+ * Carries out one agent write on the session's tracked PR. Throws for a write that must not fall back (the
136
+ * service refused it as malformed, or the thread is not on this PR), for one the person's pending review would
137
+ * swallow, and for a gh write that certainly failed; answers the tool result otherwise.
138
+ */
139
+ export async function performAgentWrite(options) {
140
+ const { pullRequest, write, signal } = options;
141
+ const action = botAction(write);
142
+ checkRepository(pullRequest);
143
+ const bot = asksBot(options.setting, options.coverage);
144
+ if (bot && write.action !== 'resolve' && Buffer.byteLength(write.body, 'utf8') > BOT_BODY_BYTES) {
145
+ throw new Error(`body is longer than the ${BOT_BODY_BYTES / 1024} KiB a bot ${noun(action)} may carry; shorten it. Nothing was posted.`);
146
+ }
147
+ // Everything the write will be refused for locally is checked: now the person is asked, before anything is sent.
148
+ await options.approve(approvalDetail(write, pullRequest, bot, options.botName));
149
+ if (options.current) {
150
+ // As edit_file re-reads its file: what was approved must still be what would be written.
151
+ const now = await options.current();
152
+ if (now === undefined || now.pullRequest.url !== pullRequest.url || (now.pullRequest.ghUser ?? null) !== (pullRequest.ghUser ?? null)
153
+ || asksBot(now.setting, now.coverage) !== bot)
154
+ throw new Error(CHANGED_WHILE_APPROVING);
155
+ }
156
+ let reason = options.setting === 'me' ? AS_ME_REASON : coverageReason(options.coverage, pullRequest);
157
+ if (bot) {
158
+ const requestId = (options.requestId ?? (() => newRequestId()))();
159
+ const outcome = await options.client.write({
160
+ requestId, owner: pullRequest.owner, repo: pullRequest.repo, number: pullRequest.number, action,
161
+ ...(write.action === 'comment' ? {} : { threadId: write.threadId }), ...(write.action === 'resolve' ? {} : { body: write.body }),
162
+ }, signal);
163
+ switch (outcome.kind) {
164
+ case 'written': return { text: botText(action, outcome.as, outcome.url), by: 'bot', as: outcome.as, ...(outcome.url === undefined ? {} : { url: outcome.url }), requestId };
165
+ case 'refused':
166
+ if (outcome.reason === 'not-found') {
167
+ throw new ThreadElsewhere(write.action === 'comment' ? `Andorra's service did not find ${pullRequest.url}; nothing was posted.` : `Thread ${write.threadId} is not on ${pullRequest.url}; nothing was posted.`);
168
+ }
169
+ throw new Error(`Andorra's service refused the ${noun(action)} as malformed (${outcome.field ?? 'request'}); nothing was posted.`);
170
+ case 'unknown':
171
+ return { text: `The bot's ${noun(action)} may not have ${write.action === 'resolve' ? 'gone through' : 'posted'}; check the PR before trying again. (${outcome.detail}.)`, by: 'unknown', requestId };
172
+ case 'not-written':
173
+ reason = fallbackReason(outcome.reason, pullRequest);
174
+ break;
175
+ }
176
+ }
177
+ signal?.throwIfAborted();
178
+ // gh as the record's account (or, with none recorded, the account gh answers as now), never another one.
179
+ const login = pullRequest.ghUser ?? await viewerLogin(options.gh);
180
+ let outcome;
181
+ try {
182
+ outcome = await runAsAccount(options.gh, login, gh => ghWrite(gh, pullRequest, write, login));
183
+ }
184
+ catch (error) {
185
+ if (error instanceof ThreadElsewhere || error instanceof PendingReview)
186
+ throw error;
187
+ throw new Error(`Could not ${write.action === 'resolve' ? (write.resolved ? 'resolve the thread' : 'reopen the thread') : 'post'} as ${login} (${reason}): ${error instanceof Error ? error.message : String(error)}`, { cause: error });
188
+ }
189
+ if (outcome.kind === 'unknown') {
190
+ return { text: `The ${noun(action)} as ${login} may have ${write.action === 'resolve' ? 'gone through' : 'posted'}; check the PR before trying again. (${outcome.detail}.)`, by: 'unknown', as: login, reason };
191
+ }
192
+ if (outcome.kind === 'pending') {
193
+ return {
194
+ text: `Filed as ${login} into ${login}'s pending review on ${pullRequest.url}, not posted: GitHub shows it to no one until they submit that review, so the thread is not answered yet. Do not resolve it; tell the user.`,
195
+ by: 'pending', as: login, ...(outcome.url === undefined ? {} : { url: outcome.url }), ...(outcome.nodeId === undefined ? {} : { nodeId: outcome.nodeId }), reason,
196
+ };
197
+ }
198
+ return { text: ghText(action, login, reason, outcome.url), by: 'gh', as: login, ...(outcome.url === undefined ? {} : { url: outcome.url }), ...(outcome.nodeId === undefined ? {} : { nodeId: outcome.nodeId }), reason };
199
+ }
200
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
201
+ const githubUrl = (value) => typeof value === 'string' && /^https:\/\/github\.com\/\S*$/.test(value) && value.length <= 2048 ? value : undefined;
202
+ /** A GraphQL read with its variables in a JSON body on gh's standard input, so no text passes through an argument. */
203
+ async function graphql(gh, query, variables) {
204
+ const raw = await gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], { input: JSON.stringify({ query, variables }) });
205
+ const value = record(JSON.parse(raw));
206
+ const errors = (Array.isArray(value.errors) ? value.errors : []).map(entry => record(entry).message).filter((message) => typeof message === 'string');
207
+ if (errors.length > 0)
208
+ throw new Error(`GraphQL: ${errors.join('; ')}`);
209
+ return record(value.data);
210
+ }
211
+ async function viewerLogin(gh) {
212
+ const login = record((await graphql(gh, 'query { viewer { login } }', {})).viewer).login;
213
+ if (typeof login !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,38})$/.test(login))
214
+ throw new Error('gh did not say which GitHub account it uses.');
215
+ return login;
216
+ }
217
+ /** GraphQL error types that mean GitHub refused the operation, so nothing was written (as the service reads them). */
218
+ const REFUSALS = new Set(['FORBIDDEN', 'INSUFFICIENT_SCOPES', 'NOT_FOUND', 'RATE_LIMITED', 'UNPROCESSABLE']);
219
+ /** What gh printed for a write, read as GitHub's answer: the result when it is there, a refusal, or neither. */
220
+ function answerOf(raw, field) {
221
+ let value;
222
+ try {
223
+ value = record(JSON.parse(raw));
224
+ }
225
+ catch {
226
+ return { unknown: 'gh answered something that is not JSON' };
227
+ }
228
+ if (field === undefined)
229
+ return githubUrl(value.html_url) === undefined ? { unknown: 'GitHub\'s answer named no comment' } : { result: value };
230
+ // A mutation's result that is there is the answer, errors or not: the write was made.
231
+ const result = record(value.data)[field];
232
+ if (typeof result === 'object' && result !== null)
233
+ return { result: record(result) };
234
+ const errors = Array.isArray(value.errors) ? value.errors.map(record) : [];
235
+ if (errors.length > 0 && errors.every(error => typeof error.type === 'string' && REFUSALS.has(error.type))) {
236
+ return { refused: `GraphQL: ${errors.map(error => String(error.message ?? error.type)).join('; ')}` };
237
+ }
238
+ return { unknown: errors.length > 0 ? `GitHub answered errors without the ${field} result` : `GitHub's answer had no ${field} result` };
239
+ }
240
+ /**
241
+ * One write through gh, read so that only a write GitHub certainly refused reads as failed (thrown): a result
242
+ * GitHub gave is a success even beside errors, and a gh stopped by its timeout, an answer that is not JSON, or
243
+ * one with neither a result nor a typed refusal is of unknown fate. A failure before anything was sent (the
244
+ * account's token lookup, gh missing, no connection) is thrown as it is.
245
+ */
246
+ async function ghMutation(run, field) {
247
+ let raw;
248
+ try {
249
+ raw = await run();
250
+ }
251
+ catch (error) {
252
+ const failure = error;
253
+ const text = failure instanceof Error ? failure.message : String(error);
254
+ if (/^gh auth |^gh user must not be empty|returned no token for|ENOENT|error connecting to|dial tcp|no such host|connection refused/i.test(text))
255
+ throw error;
256
+ if (failure.killed === true)
257
+ return { unknown: 'gh was stopped before GitHub\'s answer arrived' };
258
+ if (typeof failure.stdout === 'string') {
259
+ const answer = answerOf(failure.stdout, field);
260
+ if ('result' in answer)
261
+ return answer;
262
+ if ('refused' in answer)
263
+ throw new Error(answer.refused, { cause: error });
264
+ // A refusal gh names by its 4xx prints GitHub's error body, with no result: nothing was written.
265
+ if (/\bHTTP 4\d\d\b/.test(text))
266
+ throw error;
267
+ return answer;
268
+ }
269
+ if (/\bHTTP 4\d\d\b/.test(text))
270
+ throw error;
271
+ return { unknown: `gh failed without GitHub's answer (${text.replace(/\s+/g, ' ').slice(0, 200)})` };
272
+ }
273
+ const answer = answerOf(raw, field);
274
+ if ('refused' in answer)
275
+ throw new Error(answer.refused);
276
+ return answer;
277
+ }
278
+ const THREAD_QUERY = 'query($id: ID!, $owner: String!, $name: String!, $number: Int!) { node(id: $id) { ... on PullRequestReviewThread { pullRequest { number repository { databaseId } } comments(first: 1) { nodes { url } } } } repository(owner: $owner, name: $name) { databaseId pullRequest(number: $number) { reviews(states: [PENDING], first: 1) { totalCount } } } }';
279
+ const REPLY = 'mutation($thread: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body }) { comment { id url state } } }';
280
+ const resolveMutation = (resolved) => `mutation($thread: ID!) { ${resolved ? 'resolveReviewThread' : 'unresolveReviewThread'}(input: { threadId: $thread }) { thread { id isResolved } } }`;
281
+ /**
282
+ * The write itself, through gh. A reply or resolve first reads the thread and the tracked PR in one query, and
283
+ * refuses a thread on another PR by repository id and number (so a renamed or transferred repository still
284
+ * matches), as the service does; a reply is also refused while the account has a pending review on the PR,
285
+ * which GitHub would file it into. Answers the new comment's URL (the thread's first comment's for a resolve).
286
+ */
287
+ async function ghWrite(gh, pullRequest, write, login) {
288
+ const stdin = (input) => ({ input: JSON.stringify(input) });
289
+ if (write.action === 'comment') {
290
+ const answer = await ghMutation(() => gh(['api', '--hostname', 'github.com', '-X', 'POST', `repos/${pullRequest.owner}/${pullRequest.repo}/issues/${pullRequest.number}/comments`, '--input', '-'], stdin({ body: write.body })), undefined);
291
+ return 'unknown' in answer ? { kind: 'unknown', detail: answer.unknown } : { kind: 'written', ...urlOf(answer.result.html_url), ...nodeIdOf(answer.result.node_id) };
292
+ }
293
+ const data = await graphql(gh, THREAD_QUERY, { id: write.threadId, owner: pullRequest.owner, name: pullRequest.repo, number: pullRequest.number });
294
+ const node = record(data.node);
295
+ const pull = record(node.pullRequest);
296
+ const tracked = record(data.repository);
297
+ const repositoryId = tracked.databaseId;
298
+ if (pull.number !== pullRequest.number || typeof repositoryId !== 'number' || record(pull.repository).databaseId !== repositoryId) {
299
+ throw new ThreadElsewhere(`Thread ${write.threadId} is not on ${pullRequest.url}; nothing was posted.`);
300
+ }
301
+ const first = githubUrl(record((Array.isArray(record(node.comments).nodes) ? record(node.comments).nodes : [])[0]).url);
302
+ if (write.action === 'resolve') {
303
+ const field = write.resolved ? 'resolveReviewThread' : 'unresolveReviewThread';
304
+ const answer = await ghMutation(() => gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], stdin({ query: resolveMutation(write.resolved), variables: { thread: write.threadId } })), field);
305
+ return 'unknown' in answer ? { kind: 'unknown', detail: answer.unknown } : { kind: 'written', ...urlOf(first) };
306
+ }
307
+ const pending = record(record(record(tracked.pullRequest).reviews)).totalCount;
308
+ if (typeof pending === 'number' && pending > 0) {
309
+ throw new PendingReview(`Nothing was posted: ${login} has a pending review on ${pullRequest.url}, and GitHub would file this reply into it, where nobody sees it until they submit that review. Leave the thread unresolved and tell the user, who can submit or discard that review; then reply again.`);
310
+ }
311
+ const answer = await ghMutation(() => gh(['api', 'graphql', '--hostname', 'github.com', '--input', '-'], stdin({ query: REPLY, variables: { thread: write.threadId, body: write.body } })), 'addPullRequestReviewThreadReply');
312
+ if ('unknown' in answer)
313
+ return { kind: 'unknown', detail: answer.unknown };
314
+ const comment = record(answer.result.comment);
315
+ // A pending review started between the check and the reply still takes it: say so rather than "posted".
316
+ return { kind: comment.state === 'PENDING' ? 'pending' : 'written', ...urlOf(comment.url), ...nodeIdOf(comment.id) };
317
+ }
318
+ const urlOf = (value) => { const url = githubUrl(value); return url === undefined ? {} : { url }; };
319
+ /** A comment's GraphQL node id (an issue comment's `IC_…`, a review comment's `PRRC_…`), as GitHub named it. */
320
+ const nodeIdOf = (value) => typeof value === 'string' && /^[A-Za-z0-9_=+/-]{4,200}$/.test(value) ? { nodeId: value } : {};
@@ -0,0 +1,349 @@
1
+ /**
2
+ * The engine's client for the account API's GitHub App routes (`design/specs/github-app.md`): the
3
+ * connection status, connecting and disconnecting, the engine's subscriptions, the inbox pull, and the
4
+ * agent's bot writes (which the service makes with an installation token it never hands out). Every call
5
+ * carries the Andorra sign-in's access token, as `src/membership.ts` and `src/bug-report.ts` do.
6
+ */
7
+ export declare const GITHUB_COVERAGE_STATES: readonly ["covered", "signed-out", "not-connected", "not-installed", "not-covered", "suspended", "permissions-pending", "limit", "pending", "disabled", "unavailable"];
8
+ export type GitHubCoverage = typeof GITHUB_COVERAGE_STATES[number];
9
+ export declare const NOTICE_KINDS: readonly ["state", "head", "review", "comment", "thread", "checks", "coverage", "request"];
10
+ export type GitHubNoticeKind = typeof NOTICE_KINDS[number];
11
+ /** Where a `request` notice's comment is: the PR's conversation, a review thread, or a review's own text. */
12
+ export declare const MENTION_COMMENT_KINDS: readonly ["issue", "review_comment", "review"];
13
+ export type MentionCommentKind = typeof MENTION_COMMENT_KINDS[number];
14
+ export interface GitHubNotice {
15
+ id: string;
16
+ kind: GitHubNoticeKind;
17
+ action?: string;
18
+ owner?: string;
19
+ repo?: string;
20
+ repoId?: number;
21
+ number?: number;
22
+ actor?: string;
23
+ actorType?: string;
24
+ headSha?: string;
25
+ at?: string;
26
+ /** `request` only: the comment's GraphQL node id, never its text. */
27
+ commentId?: string;
28
+ commentKind?: MentionCommentKind;
29
+ /** `request` only: the comment's page on github.com, on the notice's own PR. */
30
+ commentUrl?: string;
31
+ /** `request` only, when the receiver sends it: when the comment was written (ISO). */
32
+ commentAt?: string;
33
+ }
34
+ /** A `request` notice as `parseNotice` accepts it: every field the receiver writes, checked, and no other. */
35
+ export type MentionNotice = GitHubNotice & {
36
+ kind: 'request';
37
+ owner: string;
38
+ repo: string;
39
+ repoId: number;
40
+ number: number;
41
+ actor: string;
42
+ actorType: 'User';
43
+ commentId: string;
44
+ commentKind: MentionCommentKind;
45
+ commentUrl: string;
46
+ };
47
+ export interface GitHubInstallation {
48
+ id: number;
49
+ account: string;
50
+ type: string;
51
+ selection: 'all' | 'selected';
52
+ suspended: boolean;
53
+ permissionsPending: boolean;
54
+ manageUrl?: string;
55
+ }
56
+ export interface GitHubConnection {
57
+ login: string;
58
+ githubUserId: number;
59
+ linkedAt?: string;
60
+ }
61
+ export interface GitHubAppStatus {
62
+ enabled: boolean;
63
+ allowed: boolean;
64
+ bot?: string;
65
+ installUrl?: string;
66
+ connection: GitHubConnection | null;
67
+ installations: GitHubInstallation[];
68
+ }
69
+ export interface SubscriptionRequest {
70
+ owner: string;
71
+ repo: string;
72
+ number: number;
73
+ headSha?: string;
74
+ }
75
+ export interface SubscriptionCoverage {
76
+ owner: string;
77
+ repo: string;
78
+ number: number;
79
+ covered: boolean;
80
+ reason?: GitHubCoverage;
81
+ repoId?: number;
82
+ }
83
+ export type SubscriptionAnswer = {
84
+ enabled: false;
85
+ } | {
86
+ enabled: true;
87
+ coverage: SubscriptionCoverage[];
88
+ renewBy?: string;
89
+ };
90
+ export type EventsAnswer = {
91
+ enabled: false;
92
+ } | {
93
+ enabled: true;
94
+ events: GitHubNotice[];
95
+ cursor?: string;
96
+ more: boolean;
97
+ reset: boolean;
98
+ };
99
+ export type GitHubAppFailure =
100
+ /** No Andorra sign-in on this installation. */
101
+ 'signed-out'
102
+ /** The service refused the token, and a fresh read of the sign-in did not change that. */
103
+ | 'unauthorized'
104
+ /** `403 not_allowed`: the account is outside the App's allowed group. */
105
+ | 'not-allowed' | 'forbidden' | 'rate-limited' | 'not-found' | 'invalid-request'
106
+ /** The service could not be reached, did not answer in time, or failed (5xx). */
107
+ | 'unavailable'
108
+ /** The service answered something this client does not understand. */
109
+ | 'invalid-answer';
110
+ export declare class GitHubAppError extends Error {
111
+ readonly code: GitHubAppFailure;
112
+ readonly retryAfterMs?: number | undefined;
113
+ constructor(code: GitHubAppFailure, message: string, retryAfterMs?: number | undefined);
114
+ }
115
+ /**
116
+ * The writes the service makes as the App's bot (`POST /v1/github/writes`). `react` is the 👀 on a comment that
117
+ * mentioned the bot (phase 3): the engine asks for it, never the agent.
118
+ */
119
+ export type BotWriteAction = 'reply' | 'resolve' | 'unresolve' | 'comment' | 'react';
120
+ export interface BotWriteRequest {
121
+ /** A ULID made for this write, sent again unchanged on every retry, so the service replays rather than posts twice. */
122
+ requestId: string;
123
+ owner: string;
124
+ repo: string;
125
+ number: number;
126
+ action: BotWriteAction;
127
+ threadId?: string;
128
+ body?: string;
129
+ /** `react` only: the comment's node id, from the `request` notice. */
130
+ commentId?: string;
131
+ }
132
+ /** Why the service wrote nothing, so the write may go through gh as the person instead. */
133
+ export type BotWriteFallback =
134
+ /** No Andorra sign-in to send. */
135
+ 'signed-out'
136
+ /** The token was refused, and a fresh read of the sign-in did not change that. */
137
+ | 'unauthorized'
138
+ /** `200 {"enabled": false}`: the App is off on the service. */
139
+ | 'disabled'
140
+ /** `403 not_allowed`: the account is outside the App's allowed group. */
141
+ | 'not-allowed'
142
+ /** `403 not_covered`: the bot may not write on this PR. */
143
+ | 'not-covered'
144
+ /** Any other 403 (`account_unavailable`): refused before anything was looked at. */
145
+ | 'forbidden'
146
+ /** `429`, the service's or API Gateway's own. */
147
+ | 'rate-limited'
148
+ /** `503 late`: the service did not start the write in time. */
149
+ | 'late'
150
+ /** `502 github` that GitHub refused (`written: false`, or GitHub's status 403, 404 or 422). */
151
+ | 'github-refused'
152
+ /** Not reachable before anything was sent (refused connection, DNS), or `written: false` with the service failing. */
153
+ | 'unavailable'
154
+ /** An account API without the writes route (API Gateway's own 404). */
155
+ | 'no-route';
156
+ export type BotWriteOutcome = {
157
+ kind: 'written';
158
+ as: string;
159
+ url?: string;
160
+ } | {
161
+ kind: 'not-written';
162
+ reason: BotWriteFallback;
163
+ }
164
+ /** The request itself was wrong (`400`, naming the field) or the thread is not on this PR (`404 not_found`): no fallback. */
165
+ | {
166
+ kind: 'refused';
167
+ reason: 'bad-request';
168
+ field?: string;
169
+ } | {
170
+ kind: 'refused';
171
+ reason: 'not-found';
172
+ }
173
+ /** It may have been written: never repeated through gh. */
174
+ | {
175
+ kind: 'unknown';
176
+ detail: string;
177
+ };
178
+ /** One inline comment of a review, in the service's shape (design/specs/andorra-review-loop.md, "The review write"). */
179
+ export interface ReviewWriteComment {
180
+ path: string;
181
+ line: number;
182
+ side: 'LEFT' | 'RIGHT';
183
+ startLine?: number;
184
+ startSide?: 'LEFT' | 'RIGHT';
185
+ body: string;
186
+ }
187
+ /** `review-check`: the checks a review would get, before any model runs. Its `requestId` is never one a `review` uses. */
188
+ export interface ReviewCheckRequest {
189
+ requestId: string;
190
+ owner: string;
191
+ repo: string;
192
+ number: number;
193
+ }
194
+ /** `review`: one comment-only review as the App's bot. The service writes the header and the marker, and fixes the event. */
195
+ export interface ReviewWriteRequest extends ReviewCheckRequest {
196
+ commitId: string;
197
+ loop: string;
198
+ round: number;
199
+ rounds: number;
200
+ body: string;
201
+ comments: ReviewWriteComment[];
202
+ }
203
+ /**
204
+ * What one answer to `review` or `review-check` means (the spec's "Answers, and what the engine does with each").
205
+ * The client asks once; the loop decides what to retry and with which `requestId`.
206
+ */
207
+ export type ReviewAnswer =
208
+ /** `review-check` passed. */
209
+ {
210
+ kind: 'ok';
211
+ }
212
+ /** Posted: only an answer that names the review's node id counts. */
213
+ | {
214
+ kind: 'posted';
215
+ reviewId: string;
216
+ as: string;
217
+ url?: string;
218
+ comments?: number;
219
+ } | {
220
+ kind: 'stale-head';
221
+ head?: string;
222
+ } | {
223
+ kind: 'closed';
224
+ merged: boolean;
225
+ } | {
226
+ kind: 'loop-taken';
227
+ }
228
+ /** GitHub refused the review and nothing was posted: 422 (a line outside the diff), or 403/404 (locked, gone, withdrawn). */
229
+ | {
230
+ kind: 'github-refused';
231
+ status: number;
232
+ }
233
+ /** The service's own limit (`429 rate_limited`), with its wait. */
234
+ | {
235
+ kind: 'rate-limited';
236
+ retryAfterMs?: number;
237
+ }
238
+ /** Nothing posted: `503 late`, `503 unavailable`, a GitHub 5xx or 401 with `written: false`, API Gateway's own 429, or no connection. */
239
+ | {
240
+ kind: 'unavailable';
241
+ detail: string;
242
+ }
243
+ /** An earlier attempt with this `requestId` is still running. */
244
+ | {
245
+ kind: 'in-progress';
246
+ }
247
+ /** `200 {"enabled": false}`: reviews are off on the service. */
248
+ | {
249
+ kind: 'service-off';
250
+ }
251
+ /** `403 not_covered`, `not_allowed` or any other refusal before GitHub: the bot may not post here. */
252
+ | {
253
+ kind: 'not-covered';
254
+ error: string;
255
+ } | {
256
+ kind: 'plan';
257
+ } | {
258
+ kind: 'signed-out';
259
+ } | {
260
+ kind: 'bad-request';
261
+ field?: string;
262
+ } | {
263
+ kind: 'not-found';
264
+ }
265
+ /** It may have posted. */
266
+ | {
267
+ kind: 'unknown';
268
+ detail: string;
269
+ };
270
+ export interface GitHubAppClient {
271
+ status(signal?: AbortSignal): Promise<GitHubAppStatus>;
272
+ connect(mode: 'install' | 'authorize', signal?: AbortSignal): Promise<{
273
+ enabled: false;
274
+ } | {
275
+ enabled: true;
276
+ url: string;
277
+ }>;
278
+ disconnect(signal?: AbortSignal): Promise<{
279
+ enabled: boolean;
280
+ }>;
281
+ subscribe(engine: string, pullRequests: SubscriptionRequest[], signal?: AbortSignal): Promise<SubscriptionAnswer>;
282
+ events(engine: string, after: string | undefined, signal?: AbortSignal): Promise<EventsAnswer>;
283
+ /**
284
+ * Asks the service to make one write as the App's bot. Never throws for an answer: it says whether the
285
+ * write was made, certainly not made (the caller may fall back to gh), refused, or of unknown fate. Only a
286
+ * cancelled `signal` throws. The answer is read for `ok`, `as`, `url`, `enabled`, `error`, `field`, `status`
287
+ * and `written` alone: no installation token is ever asked for, read or kept.
288
+ */
289
+ write(request: BotWriteRequest, signal?: AbortSignal): Promise<BotWriteOutcome>;
290
+ /** One `review-check` request. Never throws for an answer; only a cancelled `signal` throws. */
291
+ reviewCheck(request: ReviewCheckRequest, signal?: AbortSignal): Promise<ReviewAnswer>;
292
+ /** One `review` request, asked once with its `requestId`. Never throws for an answer; only a cancelled `signal` throws. */
293
+ review(request: ReviewWriteRequest, signal?: AbortSignal): Promise<ReviewAnswer>;
294
+ }
295
+ export interface GitHubAppClientDependencies {
296
+ accessToken(signal?: AbortSignal): Promise<string | undefined>;
297
+ apiBaseUrl(): string;
298
+ fetch: typeof globalThis.fetch;
299
+ /** Loopback `http:` is allowed only for the test-mode override below; everything else must be `https:`. */
300
+ allowLoopbackHttp?: boolean;
301
+ /** How long a bot write may wait for its answer, retries included (tests shorten it). */
302
+ writeBudgetMs?: number;
303
+ /** The pause between a bot write's attempts (tests skip it). */
304
+ sleep?(ms: number, signal?: AbortSignal): Promise<void>;
305
+ }
306
+ /** A bot write with no answer in this long is of unknown fate (the service's Lambda stops at 20 seconds). */
307
+ export declare const WRITE_BUDGET_MS = 25000;
308
+ /** At most this many requests for one write, all with its one `requestId`; a 401's refreshed token is one more. */
309
+ export declare const WRITE_ATTEMPTS = 3;
310
+ /**
311
+ * The kind of comment a node id names, as the service reads it (`comment_kind` in `github_app.py`): the current
312
+ * form by its prefix (`IC_`, `PRRC_`, `PRR_`), or a legacy id, base64 of `<length>:<Type><number>`. Undefined
313
+ * for any other node, or anything else.
314
+ */
315
+ export declare function commentKindOf(id: unknown): MentionCommentKind | undefined;
316
+ /** Any comment a `react` may name: a node id of one of the three kinds. */
317
+ export declare const isMentionCommentId: (value: unknown) => value is string;
318
+ export declare const isEngineId: (value: unknown) => value is string;
319
+ export declare const isCursor: (value: unknown) => value is string;
320
+ /**
321
+ * Where the account API is, and which token to send. Production always uses the stamped API and the
322
+ * signed-in account's token. Only with `ANDORRA_TEST_MODE=1`, and only with both `ANDORRA_TEST_ACCOUNT_API`
323
+ * (a staging stack over `https:`, or a fake on a loopback `http:` origin) and `ANDORRA_TEST_ACCOUNT_TOKEN`,
324
+ * do the GitHub App routes go elsewhere, and then always with the test token: the signed-in account's token
325
+ * is never sent anywhere but the production API, and a test token never to it. Either variable alone is
326
+ * ignored.
327
+ */
328
+ export declare function accountApiTarget(env?: NodeJS.ProcessEnv): {
329
+ baseUrl: string;
330
+ token?: string;
331
+ loopback: boolean;
332
+ };
333
+ export declare function parseNotice(value: unknown): GitHubNotice | undefined;
334
+ /** A notice `parseNotice` read as a `request`, with every field it requires. */
335
+ export declare const isMentionNotice: (notice: GitHubNotice) => notice is MentionNotice;
336
+ /** The service's own limit on a bot write's body. */
337
+ export declare const BOT_BODY_BYTES = 16384;
338
+ /** The first field of a bot write the service would refuse (`400 bad_request`), checked as it checks them; undefined when none. */
339
+ export declare function botWriteProblem(request: BotWriteRequest): string | undefined;
340
+ export declare function failedBeforeSending(error: unknown): boolean;
341
+ /** The opening of the review marker that only the service writes; it is refused in every body (R1). */
342
+ export declare const REVIEW_MARKER_OPENING: RegExp;
343
+ /** The first field of a `review-check` or `review` the service would refuse (`400 bad_request`), checked as it checks them. */
344
+ export declare function reviewWriteProblem(request: ReviewCheckRequest | ReviewWriteRequest, action: 'review-check' | 'review'): string | undefined;
345
+ /** What one answer of `POST /v1/github/writes` means for `review` and `review-check`. */
346
+ export declare function reviewVerdict(action: 'review-check' | 'review', status: number, answer: Record<string, unknown> | undefined, retryAfter?: number): ReviewAnswer;
347
+ export declare function createGitHubAppClient(deps: GitHubAppClientDependencies): GitHubAppClient;
348
+ /** The shipped client: the stamped account API and the signed-in account, or the test-mode override (see accountApiTarget). */
349
+ export declare function defaultGitHubAppClient(env?: NodeJS.ProcessEnv): GitHubAppClient;