@aviaratech/ai-delivery 0.3.34 → 0.3.36

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 (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -477
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,420 +1,525 @@
1
- import { createAppAuth } from '@octokit/auth-app';
2
- import { graphql } from '@octokit/graphql';
3
- import { Octokit } from '@octokit/rest';
4
- import { readFileSync } from 'node:fs';
5
- import { types } from 'node:util';
6
- import { resolveDeliveryRoleCredentials } from '../config/deliveryConfig.js';
7
- import { DeliveryError, setMachineRequestDiagnostics, getRateLimitDiagnostics, } from '../errors.js';
8
- import { assertSupportedAuthorHost, machineAuthorEligible, withMachineAuthorCredential, MACHINE_AUTH_ENV_NAMES, } from './machineAuth.js';
9
- const authorGitTokens = new WeakMap();
10
- const machineClients = new WeakSet();
11
- const machineProtectionAbsence = new WeakMap();
12
- const machineAuthorSelections = new WeakMap();
13
- const resolvedMachineAuthors = new WeakMap();
14
- /** Keep repository discovery and command execution on one resolved account. */
15
- export function retainMachineAuthorForConfiguration(config, clients, signal) {
16
- const selection = machineAuthorSelections.get(clients);
17
- if (selection !== undefined) {
18
- if (selection.signal !== signal)
19
- throw new DeliveryError('Machine GitHub session command context changed; resolve the command again.');
20
- resolvedMachineAuthors.set(config.roles, { clients, ...selection });
21
- }
1
+ import { createAppAuth } from "@octokit/auth-app";
2
+ import { graphql } from "@octokit/graphql";
3
+ import { Octokit } from "@octokit/rest";
4
+ import { closeSync, constants, fstatSync, openSync, readFileSync, readSync } from "node:fs";
5
+ import { createPrivateKey } from "node:crypto";
6
+ import { homedir } from "node:os";
7
+ import { types } from "node:util";
8
+ import {
9
+ appCredentialSource,
10
+ privateKeyVariable,
11
+ resolveDeliveryRoleCredentials
12
+ } from "../config/deliveryConfig.js";
13
+ import { runStageCommand } from "../verification.js";
14
+ import {
15
+ DeliveryError,
16
+ setMachineRequestDiagnostics,
17
+ getRateLimitDiagnostics
18
+ } from "../errors.js";
19
+ import {
20
+ assertSupportedAuthorHost,
21
+ machineAuthorEligible,
22
+ withMachineAuthorCredential,
23
+ MACHINE_AUTH_ENV_NAMES
24
+ } from "./machineAuth.js";
25
+ const authorGitTokens = /* @__PURE__ */ new WeakMap();
26
+ const machineClients = /* @__PURE__ */ new WeakSet();
27
+ const machineProtectionAbsence = /* @__PURE__ */ new WeakMap();
28
+ const machineAuthorSelections = /* @__PURE__ */ new WeakMap();
29
+ const resolvedMachineAuthors = /* @__PURE__ */ new WeakMap();
30
+ function retainMachineAuthorForConfiguration(config, clients, signal) {
31
+ const selection = machineAuthorSelections.get(clients);
32
+ if (selection !== void 0) {
33
+ if (selection.signal !== signal)
34
+ throw new DeliveryError("Machine GitHub session command context changed; resolve the command again.");
35
+ resolvedMachineAuthors.set(config.roles, { clients, ...selection });
36
+ }
22
37
  }
23
38
  function sessionSelectors(env) {
24
- return JSON.stringify(MACHINE_AUTH_ENV_NAMES.map((name) => [name, env[name]]));
39
+ return JSON.stringify(MACHINE_AUTH_ENV_NAMES.map((name) => [name, env[name]]));
25
40
  }
26
- /** Pass the selected author token only to the operation that needs Git HTTP auth. */
27
- export async function withAuthorGitToken(clients, callback) {
28
- const token = clients.role === 'author' ? authorGitTokens.get(clients) : undefined;
29
- if (!token)
30
- throw new DeliveryError('Git push requires the selected author credential token.');
31
- return callback(token);
41
+ async function withAuthorGitToken(clients, callback) {
42
+ const token = clients.role === "author" ? authorGitTokens.get(clients) : void 0;
43
+ if (!token) throw new DeliveryError("Git push requires the selected author credential token.");
44
+ return callback(token);
32
45
  }
33
- export function assertDeliveryRolePermissions(input) {
34
- if (typeof input.permissions !== 'object' || input.permissions === null || Array.isArray(input.permissions)) {
35
- throw new DeliveryError(`GitHub App ${input.role} role did not return installation permissions.`);
36
- }
37
- const permissions = input.permissions;
38
- const required = input.role === 'author'
39
- ? { contents: 'write', issues: 'write', organization_projects: 'write', pull_requests: 'write' }
40
- : { contents: 'read', pull_requests: 'write' };
41
- for (const [name, level] of [...Object.entries(required), ...Object.entries(input.additional ?? {})]) {
42
- const actual = permissions[name];
43
- if (actual !== 'admin' && actual !== 'write' && (level === 'write' || actual !== 'read')) {
44
- throw new DeliveryError(`GitHub App ${input.role} role lacks required ${name}:${level} permission.`);
45
- }
46
+ function assertDeliveryRolePermissions(input) {
47
+ if (typeof input.permissions !== "object" || input.permissions === null || Array.isArray(input.permissions)) {
48
+ throw new DeliveryError(`GitHub App ${input.role} role did not return installation permissions.`);
49
+ }
50
+ const permissions = input.permissions;
51
+ const required = input.role === "author" ? { contents: "write", issues: "write", organization_projects: "write", pull_requests: "write" } : { contents: "read", pull_requests: "write" };
52
+ for (const [name, level] of [...Object.entries(required), ...Object.entries(input.additional ?? {})]) {
53
+ const actual = permissions[name];
54
+ if (actual !== "admin" && actual !== "write" && (level === "write" || actual !== "read")) {
55
+ throw new DeliveryError(`GitHub App ${input.role} role lacks required ${name}:${level} permission.`);
46
56
  }
57
+ }
47
58
  }
48
- /** The author role may use a personal token only after an explicit operator opt-in. */
49
- export async function createDeliveryGitHubClients(input) {
50
- input.signal?.throwIfAborted();
51
- const env = input.env ?? process.env;
52
- const selected = input.config.roles[input.role];
53
- const retained = input.role === 'author' ? resolvedMachineAuthors.get(input.config.roles) : undefined;
54
- if (retained !== undefined) {
55
- // A command that discovered its repository as account A must not acquire
56
- // a newly supplied token/profile and then operate as account B.
57
- if (selected.authSource !== 'personal' ||
58
- input.identity.trim().toLowerCase() !== selected.identity.toLowerCase() ||
59
- !machineAuthorEligible(selected.credentialEnv.token, env) ||
60
- retained.env !== env ||
61
- retained.signal !== input.signal ||
62
- retained.selectors !== sessionSelectors(env))
63
- throw new DeliveryError('Machine GitHub session environment changed after repository selection; resolve the command again.');
64
- assertSupportedAuthorHost(env);
65
- return retained.clients;
59
+ async function createDeliveryGitHubClients(input) {
60
+ input.signal?.throwIfAborted();
61
+ const env = input.env ?? process.env;
62
+ const selected = input.config.roles[input.role];
63
+ const retained = input.role === "author" ? resolvedMachineAuthors.get(input.config.roles) : void 0;
64
+ if (retained !== void 0) {
65
+ if (selected.authSource !== "personal" || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase() || !machineAuthorEligible(selected.credentialEnv.token, env) || retained.env !== env || retained.signal !== input.signal || retained.selectors !== sessionSelectors(env))
66
+ throw new DeliveryError(
67
+ "Machine GitHub session environment changed after repository selection; resolve the command again."
68
+ );
69
+ assertSupportedAuthorHost(env);
70
+ return retained.clients;
71
+ }
72
+ if (selected.authSource === "personal") {
73
+ if (input.role !== "author" || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
74
+ throw new DeliveryError("Personal author operation requires the configured author identity.");
66
75
  }
67
- if (selected.authSource === 'personal') {
68
- if (input.role !== 'author' || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
69
- throw new DeliveryError('Personal author operation requires the configured author identity.');
70
- }
71
- assertSupportedAuthorHost(env);
72
- if (machineAuthorEligible(selected.credentialEnv.token, env)) {
73
- const selection = { env, signal: input.signal, selectors: sessionSelectors(env) };
74
- return withMachineAuthorCredential(env, input.signal, async (token, session) => {
75
- const clients = personalClients(token, `gh:github.com:${session.executable}`, input.signal, session.login);
76
- await clients.authenticatedAuthor(input.signal);
77
- machineAuthorSelections.set(clients, selection);
78
- return clients;
79
- });
80
- }
81
- const token = env[selected.credentialEnv.token]?.trim();
82
- if (!token) {
83
- throw new DeliveryError(`Missing personal author token in ${selected.credentialEnv.token}.`);
84
- }
85
- return personalClients(token, `env:${selected.credentialEnv.token}`, input.signal);
76
+ assertSupportedAuthorHost(env);
77
+ if (machineAuthorEligible(selected.credentialEnv.token, env)) {
78
+ const selection = { env, signal: input.signal, selectors: sessionSelectors(env) };
79
+ return withMachineAuthorCredential(env, input.signal, async (token2, session) => {
80
+ const clients = personalClients(token2, `gh:github.com:${session.executable}`, input.signal, session.login);
81
+ await clients.authenticatedAuthor(input.signal);
82
+ machineAuthorSelections.set(clients, selection);
83
+ return clients;
84
+ });
86
85
  }
87
- if (input.personalAuth !== undefined) {
88
- if (input.personalAuth.enabled !== true ||
89
- input.role !== 'author' ||
90
- input.identity.trim().toLowerCase() !== 'personal') {
91
- throw new DeliveryError('Personal-token auth requires the explicit personal author identity.');
92
- }
93
- assertSupportedAuthorHost(env);
94
- const token = (input.personalAuth.token ?? env.GH_TOKEN ?? env.GITHUB_TOKEN)?.trim();
95
- if (!token)
96
- throw new DeliveryError('Explicit personal-token auth requested but no token was supplied.');
97
- const source = input.personalAuth.token !== undefined
98
- ? 'explicit-personal-token'
99
- : env.GH_TOKEN !== undefined
100
- ? 'env:GH_TOKEN'
101
- : 'env:GITHUB_TOKEN';
102
- return personalClients(token, source, input.signal);
86
+ const token = env[selected.credentialEnv.token]?.trim();
87
+ if (!token) {
88
+ throw new DeliveryError(`Missing personal author token in ${selected.credentialEnv.token}.`);
103
89
  }
104
- if (input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
105
- throw new DeliveryError(`GitHub ${input.role} operation requires the configured ${input.role} identity.`);
90
+ return personalClients(token, `env:${selected.credentialEnv.token}`, input.signal);
91
+ }
92
+ if (input.personalAuth !== void 0) {
93
+ if (input.personalAuth.enabled !== true || input.role !== "author" || input.identity.trim().toLowerCase() !== "personal") {
94
+ throw new DeliveryError("Personal-token auth requires the explicit personal author identity.");
106
95
  }
107
- const credentials = resolveDeliveryRoleCredentials({ config: input.config, env, role: input.role });
108
- const otherRole = input.role === 'author' ? 'reviewer' : 'author';
109
- const personalAuthorSelected = input.role === 'reviewer' &&
110
- input.selectedAuthor?.role === 'author' &&
111
- input.selectedAuthor.authSource === 'personal';
112
- if (!personalAuthorSelected && input.config.roles[otherRole].authSource !== 'personal') {
113
- const other = resolveDeliveryRoleCredentials({ config: input.config, env, role: otherRole });
114
- if (credentials.appId === other.appId ||
115
- credentials.installationId === other.installationId ||
116
- credentials.privateKeyPath === other.privateKeyPath) {
117
- throw new DeliveryError('Author and reviewer must use distinct GitHub App credentials.');
118
- }
96
+ assertSupportedAuthorHost(env);
97
+ const token = (input.personalAuth.token ?? env.GH_TOKEN ?? env.GITHUB_TOKEN)?.trim();
98
+ if (!token) throw new DeliveryError("Explicit personal-token auth requested but no token was supplied.");
99
+ const source = input.personalAuth.token !== void 0 ? "explicit-personal-token" : env.GH_TOKEN !== void 0 ? "env:GH_TOKEN" : "env:GITHUB_TOKEN";
100
+ return personalClients(token, source, input.signal);
101
+ }
102
+ if (input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
103
+ throw new DeliveryError(`GitHub ${input.role} operation requires the configured ${input.role} identity.`);
104
+ }
105
+ const credentials = resolveDeliveryRoleCredentials({ config: input.config, env, role: input.role });
106
+ const otherRole = input.role === "author" ? "reviewer" : "author";
107
+ const personalAuthorSelected = input.role === "reviewer" && input.selectedAuthor?.role === "author" && input.selectedAuthor.authSource === "personal";
108
+ if (!personalAuthorSelected && input.config.roles[otherRole].authSource !== "personal") {
109
+ const otherRoleConfig = input.config.roles[otherRole];
110
+ const other = credentials.profile === void 0 ? resolveDeliveryRoleCredentials({ config: input.config, env, role: otherRole }) : "appId" in otherRoleConfig ? {
111
+ appId: String(otherRoleConfig.appId),
112
+ installationId: otherRoleConfig.installationId,
113
+ privateKeyPath: void 0
114
+ } : {
115
+ appId: env[otherRoleConfig.credentialEnv.appId]?.trim(),
116
+ installationId: Number(env[otherRoleConfig.credentialEnv.installationId]),
117
+ privateKeyPath: void 0
118
+ };
119
+ if (credentials.appId === other.appId || credentials.installationId === other.installationId || credentials.privateKeyPath !== void 0 && credentials.privateKeyPath === other.privateKeyPath) {
120
+ throw new DeliveryError("Author and reviewer must use distinct GitHub App credentials.");
119
121
  }
120
- let privateKey;
122
+ }
123
+ let privateKey;
124
+ if (credentials.profile !== void 0) {
125
+ privateKey = await selectedPrivateKey(credentials.profile, env, input.config, input.signal);
126
+ } else {
121
127
  try {
122
- privateKey = readFileSync(credentials.privateKeyPath, 'utf8');
128
+ privateKey = readFileSync(credentials.privateKeyPath, "utf8");
129
+ } catch {
130
+ throw new DeliveryError(`GitHub App private key for ${input.role} role is unavailable.`);
123
131
  }
124
- catch {
125
- throw new DeliveryError(`GitHub App private key for ${input.role} role is unavailable.`);
132
+ }
133
+ try {
134
+ const auth = createAppAuth({
135
+ appId: credentials.appId,
136
+ privateKey,
137
+ ...input.signal === void 0 ? {} : { request: new Octokit({ request: { signal: input.signal } }).request }
138
+ });
139
+ const result = await auth({ installationId: credentials.installationId, type: "installation" });
140
+ if (typeof result.token !== "string" || !result.token.startsWith("ghs_")) {
141
+ throw new DeliveryError(`GitHub ${input.role} role did not receive an App installation token.`);
126
142
  }
127
- try {
128
- const auth = createAppAuth({
129
- appId: credentials.appId,
130
- privateKey,
131
- ...(input.signal === undefined ? {} : { request: new Octokit({ request: { signal: input.signal } }).request }),
132
- });
133
- const result = await auth({ installationId: credentials.installationId, type: 'installation' });
134
- if (typeof result.token !== 'string' || !result.token.startsWith('ghs_')) {
135
- throw new DeliveryError(`GitHub ${input.role} role did not receive an App installation token.`);
143
+ assertDeliveryRolePermissions({
144
+ ...input.additionalPermissions === void 0 ? {} : { additional: input.additionalPermissions },
145
+ permissions: result.permissions,
146
+ role: input.role
147
+ });
148
+ const appActorLogin = input.role === "reviewer" ? async (signal) => {
149
+ const requestSignal = signal ?? input.signal;
150
+ try {
151
+ const app = await new Octokit({
152
+ auth: (await auth({ type: "app" })).token,
153
+ ...requestSignal === void 0 ? {} : { request: { signal: requestSignal } }
154
+ }).rest.apps.getAuthenticated();
155
+ if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
156
+ throw new DeliveryError("Reviewer GitHub App identity did not match its configured App ID.");
136
157
  }
137
- assertDeliveryRolePermissions({
138
- ...(input.additionalPermissions === undefined ? {} : { additional: input.additionalPermissions }),
139
- permissions: result.permissions,
140
- role: input.role,
141
- });
142
- const appActorLogin = input.role === 'reviewer'
143
- ? async (signal) => {
144
- const requestSignal = signal ?? input.signal;
145
- try {
146
- const app = await new Octokit({
147
- auth: (await auth({ type: 'app' })).token,
148
- ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),
149
- }).rest.apps.getAuthenticated();
150
- if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
151
- throw new DeliveryError('Reviewer GitHub App identity did not match its configured App ID.');
152
- }
153
- return `${app.data.slug}[bot]`;
154
- }
155
- catch (error) {
156
- if (error instanceof DeliveryError)
157
- throw error;
158
- throw new DeliveryError('Reviewer GitHub App actor lookup failed.');
159
- }
160
- }
161
- : undefined;
162
- const authenticatedAuthor = input.role === 'author'
163
- ? async (signal) => {
164
- const requestSignal = signal ?? input.signal;
165
- try {
166
- const app = await new Octokit({
167
- auth: (await auth({ type: 'app' })).token,
168
- ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),
169
- }).rest.apps.getAuthenticated();
170
- if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
171
- throw new DeliveryError('Author GitHub App identity did not match its configured App ID.');
172
- }
173
- return {
174
- actorLogin: `${app.data.slug}[bot]`,
175
- credentialIdentity: `app:${String(app.data.id)}:installation:${credentials.installationId}`,
176
- };
177
- }
178
- catch (error) {
179
- if (error instanceof DeliveryError)
180
- throw error;
181
- throw new DeliveryError('Author GitHub App actor lookup failed.');
182
- }
158
+ const actor = `${app.data.slug}[bot]`;
159
+ if (credentials.profile !== void 0 && actor !== credentials.profile.actorLogin)
160
+ throw new DeliveryError("Reviewer GitHub App actor did not match its configured actorLogin.");
161
+ return actor;
162
+ } catch (error) {
163
+ if (error instanceof DeliveryError) throw error;
164
+ throw new DeliveryError("Reviewer GitHub App actor lookup failed.");
165
+ }
166
+ } : void 0;
167
+ const authenticatedAuthor = input.role === "author" ? async (signal) => {
168
+ const requestSignal = signal ?? input.signal;
169
+ try {
170
+ const app = await new Octokit({
171
+ auth: (await auth({ type: "app" })).token,
172
+ ...requestSignal === void 0 ? {} : { request: { signal: requestSignal } }
173
+ }).rest.apps.getAuthenticated();
174
+ if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
175
+ throw new DeliveryError("Author GitHub App identity did not match its configured App ID.");
176
+ }
177
+ return {
178
+ actorLogin: `${app.data.slug}[bot]`,
179
+ credentialIdentity: `app:${String(app.data.id)}:installation:${credentials.installationId}`
180
+ };
181
+ } catch (error) {
182
+ if (error instanceof DeliveryError) throw error;
183
+ throw new DeliveryError("Author GitHub App actor lookup failed.");
184
+ }
185
+ } : void 0;
186
+ return buildClients(
187
+ result.token,
188
+ "app",
189
+ input.role,
190
+ `app:${credentials.appId}:installation:${credentials.installationId}`,
191
+ appActorLogin,
192
+ authenticatedAuthor,
193
+ result.permissions.contents,
194
+ input.signal
195
+ );
196
+ } catch (error) {
197
+ input.signal?.throwIfAborted();
198
+ if (error instanceof DeliveryError) throw error;
199
+ throw new DeliveryError(`GitHub App authentication failed for ${input.role} role.`);
200
+ }
201
+ }
202
+ async function selectedPrivateKey(profile, env, config, signal) {
203
+ const source = appCredentialSource(profile);
204
+ const failure = (reason) => new DeliveryError(`Reviewer ${profile.identity} credential source ${source.type}: ${reason}`);
205
+ let bytes;
206
+ try {
207
+ signal?.throwIfAborted();
208
+ if (source.type === "env") {
209
+ const value = env[privateKeyVariable(profile)];
210
+ if (!value) throw failure("selected variable is missing or empty; configure this identity.");
211
+ if (Buffer.byteLength(value) > 64 * 1024) throw failure("response exceeds 64 KiB.");
212
+ bytes = Buffer.from(value);
213
+ } else if (source.type === "file") {
214
+ const fd = openSync(source.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
215
+ try {
216
+ const stat = fstatSync(fd);
217
+ if (!stat.isFile() || (stat.mode & 4095) !== 384 || stat.nlink !== 1 || process.getuid !== void 0 && stat.uid !== process.getuid())
218
+ throw failure("key file must be a regular, owned, single-link file with mode 0600.");
219
+ const buffer = Buffer.alloc(64 * 1024 + 1);
220
+ let size = 0;
221
+ for (; ; ) {
222
+ const read = readSync(fd, buffer, size, buffer.length - size, null);
223
+ if (read === 0) break;
224
+ size += read;
225
+ if (size === buffer.length) throw failure("response exceeds 64 KiB.");
226
+ }
227
+ bytes = buffer.subarray(0, size);
228
+ } finally {
229
+ closeSync(fd);
230
+ }
231
+ } else {
232
+ if (process.platform === "win32")
233
+ throw failure("command sources currently require a POSIX process supervisor; use env on Windows.");
234
+ const commandEnv = {};
235
+ const forbidden = /* @__PURE__ */ new Set([
236
+ ...config.credentialKeyReferences ?? [],
237
+ ...Object.values(config.roles).flatMap(
238
+ (role) => "credentialEnv" in role ? Object.values(role.credentialEnv) : appCredentialSource(role).type === "env" ? [privateKeyVariable(role)] : []
239
+ )
240
+ ]);
241
+ for (const name of [
242
+ "HOME",
243
+ "USER",
244
+ "LOGNAME",
245
+ "PATH",
246
+ "LANG",
247
+ "LC_ALL",
248
+ "TMPDIR",
249
+ "TEMP",
250
+ "TMP",
251
+ "SystemRoot",
252
+ "USERPROFILE",
253
+ "APPDATA",
254
+ "LOCALAPPDATA"
255
+ ]) {
256
+ if (forbidden.has(name)) throw failure("credential reference conflicts with an implicit OS selector.");
257
+ if (env[name] !== void 0) commandEnv[name] = env[name];
258
+ }
259
+ for (const name of source.env ?? []) {
260
+ if (forbidden.has(name) || /^(?:NODE_|NPM_|DYLD_|LD_|BASH_|GIT_|GH_PRIVATE_KEY)/u.test(name) || ["ENV", "SHELLOPTS", "CDPATH"].includes(name))
261
+ throw failure("helper environment reference conflicts with author/key or execution selectors.");
262
+ if (env[name] === void 0) throw failure("a configured helper environment reference is missing.");
263
+ commandEnv[name] = env[name];
264
+ }
265
+ const timeout = new AbortController();
266
+ const timer = setTimeout(() => timeout.abort(), 3e4);
267
+ let cleanupFailed = false;
268
+ try {
269
+ bytes = await runStageCommand(
270
+ env.HOME ?? homedir(),
271
+ source.argv,
272
+ signal === void 0 ? timeout.signal : AbortSignal.any([signal, timeout.signal]),
273
+ void 0,
274
+ void 0,
275
+ void 0,
276
+ void 0,
277
+ void 0,
278
+ {
279
+ environment: commandEnv,
280
+ cwd: env.HOME ?? homedir(),
281
+ maxCapturedOutputBytes: 64 * 1024,
282
+ stdoutOnly: true,
283
+ failedOutput: () => "",
284
+ onCleanupFailure: () => {
285
+ cleanupFailed = true;
183
286
  }
184
- : undefined;
185
- return buildClients(result.token, 'app', input.role, `app:${credentials.appId}:installation:${credentials.installationId}`, appActorLogin, authenticatedAuthor, result.permissions.contents, input.signal);
287
+ }
288
+ );
289
+ } catch {
290
+ throw failure(
291
+ cleanupFailed ? "helper failed and owned process cleanup is unverified; reconcile before retrying." : timeout.signal.aborted ? "helper response timed out; verify the selected command." : signal?.aborted ? "helper request cancelled." : "helper failed; verify its executable, access and bounded output."
292
+ );
293
+ } finally {
294
+ clearTimeout(timer);
295
+ }
186
296
  }
187
- catch (error) {
188
- if (error instanceof DeliveryError)
189
- throw error;
190
- throw new DeliveryError(`GitHub App authentication failed for ${input.role} role.`);
297
+ if (bytes.length === 0 || bytes.length > 64 * 1024) throw failure("response is empty or exceeds 64 KiB.");
298
+ let pem = bytes.toString("utf8");
299
+ if (!Buffer.from(pem).equals(bytes)) throw failure("response must be valid UTF-8.");
300
+ if (source.type !== "file" && source.encoding === "base64") {
301
+ const encoded = pem.trim();
302
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded))
303
+ throw failure("response must be canonical base64.");
304
+ const decoded = Buffer.from(encoded, "base64");
305
+ if (decoded.toString("base64") !== encoded) throw failure("response must be canonical base64.");
306
+ pem = decoded.toString("utf8");
307
+ if (!Buffer.from(pem).equals(decoded)) throw failure("decoded response must be UTF-8 PEM.");
191
308
  }
309
+ if (!/^-----BEGIN (?:RSA )?PRIVATE KEY-----\r?\n[\s\S]+\r?\n-----END (?:RSA )?PRIVATE KEY-----\s*$/u.test(pem) || createPrivateKey(pem).asymmetricKeyType !== "rsa")
310
+ throw failure("response must be an unencrypted RSA private key in PEM format.");
311
+ signal?.throwIfAborted();
312
+ return pem;
313
+ } catch (error) {
314
+ if (error instanceof DeliveryError) throw error;
315
+ throw failure("selected key is unavailable or malformed; verify this source.");
316
+ }
192
317
  }
193
318
  function personalClients(token, credentialSource, signal, machineLogin) {
194
- if (!/^[A-Za-z0-9_-]{1,4096}$/u.test(token))
195
- throw new DeliveryError('Selected personal author token is malformed; verify the explicit credential.');
196
- if (machineLogin !== undefined && (credentialSource.includes(token) || machineLogin.includes(token)))
197
- throw new DeliveryError('Machine GitHub session readback is unsafe.');
198
- return buildClients(token, 'personal', 'author', credentialSource, undefined, async (requestSignal) => {
199
- const selectedSignal = requestSignal ?? signal;
200
- try {
201
- const user = (await new Octokit({
202
- auth: token,
203
- ...(machineLogin === undefined ? {} : { log: { debug() { }, info() { }, warn() { }, error() { } } }),
204
- ...(selectedSignal === undefined ? {} : { request: { signal: selectedSignal } }),
205
- }).rest.users.getAuthenticated()).data;
206
- if (!Number.isSafeInteger(user.id) || user.id <= 0 || !user.login) {
207
- throw new DeliveryError('Personal author identity readback is incomplete.');
208
- }
209
- if (machineLogin !== undefined &&
210
- (user.type !== 'User' ||
211
- user.login.toLowerCase() !== machineLogin.toLowerCase() ||
212
- !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u.test(user.login) ||
213
- user.login.includes(token)))
214
- throw new DeliveryError('Machine GitHub session identity does not match the selected active account.');
215
- return { actorLogin: user.login, credentialIdentity: `user:${String(user.id)}` };
319
+ if (!/^[A-Za-z0-9_-]{1,4096}$/u.test(token))
320
+ throw new DeliveryError("Selected personal author token is malformed; verify the explicit credential.");
321
+ if (machineLogin !== void 0 && (credentialSource.includes(token) || machineLogin.includes(token)))
322
+ throw new DeliveryError("Machine GitHub session readback is unsafe.");
323
+ return buildClients(
324
+ token,
325
+ "personal",
326
+ "author",
327
+ credentialSource,
328
+ void 0,
329
+ async (requestSignal) => {
330
+ const selectedSignal = requestSignal ?? signal;
331
+ try {
332
+ const user = (await new Octokit({
333
+ auth: token,
334
+ ...machineLogin === void 0 ? {} : { log: { debug() {
335
+ }, info() {
336
+ }, warn() {
337
+ }, error() {
338
+ } } },
339
+ ...selectedSignal === void 0 ? {} : { request: { signal: selectedSignal } }
340
+ }).rest.users.getAuthenticated()).data;
341
+ if (!Number.isSafeInteger(user.id) || user.id <= 0 || !user.login) {
342
+ throw new DeliveryError("Personal author identity readback is incomplete.");
216
343
  }
217
- catch (error) {
218
- if (error instanceof DeliveryError)
219
- throw error;
220
- if (error.status === 401) {
221
- throw new DeliveryError(machineLogin === undefined
222
- ? 'Configured personal author token is invalid or expired; refresh the selected token.'
223
- : 'Machine GitHub session is invalid or expired; verify the selected github.com account.');
224
- }
225
- throw new DeliveryError('Personal author identity readback failed.');
344
+ if (machineLogin !== void 0 && (user.type !== "User" || user.login.toLowerCase() !== machineLogin.toLowerCase() || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u.test(user.login) || user.login.includes(token)))
345
+ throw new DeliveryError("Machine GitHub session identity does not match the selected active account.");
346
+ return { actorLogin: user.login, credentialIdentity: `user:${String(user.id)}` };
347
+ } catch (error) {
348
+ if (error instanceof DeliveryError) throw error;
349
+ if (error.status === 401) {
350
+ throw new DeliveryError(
351
+ machineLogin === void 0 ? "Configured personal author token is invalid or expired; refresh the selected token." : "Machine GitHub session is invalid or expired; verify the selected github.com account."
352
+ );
226
353
  }
227
- }, undefined, signal, machineLogin !== undefined);
354
+ throw new DeliveryError("Personal author identity readback failed.");
355
+ }
356
+ },
357
+ void 0,
358
+ signal,
359
+ machineLogin !== void 0
360
+ );
228
361
  }
229
362
  function buildClients(token, authSource, role, credentialSource, appActorLogin, authenticatedAuthor, effectiveContentsPermission, signal, machineSession = false) {
230
- const rest = new Octokit({
231
- auth: token,
232
- ...(machineSession ? { log: { debug() { }, info() { }, warn() { }, error() { } } } : {}),
233
- ...(signal === undefined ? {} : { request: { signal } }),
234
- });
235
- const rawGraphql = graphql.defaults({
236
- headers: { authorization: `token ${token}` },
237
- ...(signal === undefined ? {} : { request: { signal } }),
238
- });
239
- let observedRateLimit;
240
- const observeRateLimit = (error, graphqlFailure = false) => {
241
- observedRateLimit = getRateLimitDiagnostics(error, graphqlFailure) ?? observedRateLimit;
242
- };
243
- rest.hook.error('request', (error) => {
244
- observeRateLimit(error);
245
- throw error;
363
+ const rest = new Octokit({
364
+ auth: token,
365
+ ...machineSession ? { log: { debug() {
366
+ }, info() {
367
+ }, warn() {
368
+ }, error() {
369
+ } } } : {},
370
+ ...signal === void 0 ? {} : { request: { signal } }
371
+ });
372
+ const rawGraphql = graphql.defaults({
373
+ headers: { authorization: `token ${token}` },
374
+ ...signal === void 0 ? {} : { request: { signal } }
375
+ });
376
+ let observedRateLimit;
377
+ const observeRateLimit = (error, graphqlFailure = false) => {
378
+ observedRateLimit = getRateLimitDiagnostics(error, graphqlFailure) ?? observedRateLimit;
379
+ };
380
+ rest.hook.error("request", (error) => {
381
+ observeRateLimit(error);
382
+ throw error;
383
+ });
384
+ if (machineSession)
385
+ rest.hook.error("request", (error, options) => {
386
+ const safe = safeMachineRequestError(error, "rest.request", restMachineEndpoint(options));
387
+ const target = branchProtectionTarget(options);
388
+ const responseTarget = branchProtectionTarget({ method: "GET", url: ownData(ownData(error, "response"), "url") });
389
+ if (target && responseTarget && target.owner.toLowerCase() === responseTarget.owner.toLowerCase() && target.repo.toLowerCase() === responseTarget.repo.toLowerCase() && target.branch === responseTarget.branch && exactBranchProtectionAbsence(error))
390
+ machineProtectionAbsence.set(safe, { clients, ...target });
391
+ throw safe;
246
392
  });
247
- if (machineSession)
248
- rest.hook.error('request', (error, options) => {
249
- const safe = safeMachineRequestError(error, 'rest.request', restMachineEndpoint(options));
250
- const target = branchProtectionTarget(options);
251
- const responseTarget = branchProtectionTarget({ method: 'GET', url: ownData(ownData(error, 'response'), 'url') });
252
- if (target &&
253
- responseTarget &&
254
- target.owner.toLowerCase() === responseTarget.owner.toLowerCase() &&
255
- target.repo.toLowerCase() === responseTarget.repo.toLowerCase() &&
256
- target.branch === responseTarget.branch &&
257
- exactBranchProtectionAbsence(error))
258
- machineProtectionAbsence.set(safe, { clients, ...target });
259
- throw safe;
393
+ const clients = {
394
+ authSource,
395
+ credentialSource,
396
+ ...effectiveContentsPermission ? { effectiveContentsPermission } : {},
397
+ role,
398
+ ...appActorLogin ? { appActorLogin } : {},
399
+ ...authenticatedAuthor ? { authenticatedAuthor } : {},
400
+ graphql: new Proxy(rawGraphql, {
401
+ apply(target, receiver, args) {
402
+ return Reflect.apply(target, receiver, args).catch((error) => {
403
+ observeRateLimit(error, true);
404
+ throw machineSession ? safeMachineRequestError(error, "graphql.request", "graphql") : error;
260
405
  });
261
- const clients = {
262
- authSource,
263
- credentialSource,
264
- ...(effectiveContentsPermission ? { effectiveContentsPermission } : {}),
265
- role,
266
- ...(appActorLogin ? { appActorLogin } : {}),
267
- ...(authenticatedAuthor ? { authenticatedAuthor } : {}),
268
- graphql: new Proxy(rawGraphql, {
269
- apply(target, receiver, args) {
270
- return Reflect.apply(target, receiver, args).catch((error) => {
271
- observeRateLimit(error, true);
272
- throw machineSession ? safeMachineRequestError(error, 'graphql.request', 'graphql') : error;
273
- });
274
- },
275
- }),
276
- rest,
277
- rateLimitObservation: () => observedRateLimit,
278
- };
279
- if (machineSession)
280
- machineClients.add(clients);
281
- if (role === 'author')
282
- authorGitTokens.set(clients, token);
283
- return clients;
406
+ }
407
+ }),
408
+ rest,
409
+ rateLimitObservation: () => observedRateLimit
410
+ };
411
+ if (machineSession) machineClients.add(clients);
412
+ if (role === "author") authorGitTokens.set(clients, token);
413
+ return clients;
284
414
  }
285
415
  function ownData(value, name) {
286
- if (typeof value !== 'object' || value === null || types.isProxy(value) || Array.isArray(value))
287
- return undefined;
288
- const descriptor = Object.getOwnPropertyDescriptor(value, name);
289
- return descriptor && 'value' in descriptor ? descriptor.value : undefined;
416
+ if (typeof value !== "object" || value === null || types.isProxy(value) || Array.isArray(value)) return void 0;
417
+ const descriptor = Object.getOwnPropertyDescriptor(value, name);
418
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
290
419
  }
291
420
  function exactBranchProtectionAbsence(error) {
292
- const response = ownData(error, 'response');
293
- return (ownData(error, 'status') === 404 &&
294
- ownData(response, 'status') === 404 &&
295
- ownData(ownData(response, 'data'), 'message') === 'Branch not protected');
421
+ const response = ownData(error, "response");
422
+ return ownData(error, "status") === 404 && ownData(response, "status") === 404 && ownData(ownData(response, "data"), "message") === "Branch not protected";
296
423
  }
297
424
  function branchProtectionTarget(options) {
298
- const url = ownData(options, 'url');
299
- if (ownData(options, 'method') !== 'GET' || typeof url !== 'string' || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
300
- return undefined;
301
- let path;
302
- if (url.startsWith('/')) {
303
- if (ownData(options, 'baseUrl') !== 'https://api.github.com' || /[?#]/u.test(url))
304
- return undefined;
305
- path = url;
306
- }
307
- else {
308
- try {
309
- const parsed = new URL(url);
310
- if (parsed.origin !== 'https://api.github.com' ||
311
- parsed.username ||
312
- parsed.password ||
313
- parsed.search ||
314
- parsed.hash)
315
- return undefined;
316
- path = parsed.pathname;
317
- }
318
- catch {
319
- return undefined;
320
- }
321
- }
322
- let owner, repo, branch;
323
- if (path === '/repos/{owner}/{repo}/branches/{branch}/protection') {
324
- owner = ownData(options, 'owner');
325
- repo = ownData(options, 'repo');
326
- branch = ownData(options, 'branch');
425
+ const url = ownData(options, "url");
426
+ if (ownData(options, "method") !== "GET" || typeof url !== "string" || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
427
+ return void 0;
428
+ let path;
429
+ if (url.startsWith("/")) {
430
+ if (ownData(options, "baseUrl") !== "https://api.github.com" || /[?#]/u.test(url)) return void 0;
431
+ path = url;
432
+ } else {
433
+ try {
434
+ const parsed = new URL(url);
435
+ if (parsed.origin !== "https://api.github.com" || parsed.username || parsed.password || parsed.search || parsed.hash)
436
+ return void 0;
437
+ path = parsed.pathname;
438
+ } catch {
439
+ return void 0;
327
440
  }
328
- else {
329
- const match = /^\/repos\/([^/]+)\/([^/]+)\/branches\/(.+)\/protection$/u.exec(path);
330
- if (!match)
331
- return undefined;
332
- try {
333
- [owner, repo, branch] = match.slice(1).map((part) => decodeURIComponent(part));
334
- }
335
- catch {
336
- return undefined;
337
- }
441
+ }
442
+ let owner, repo, branch;
443
+ if (path === "/repos/{owner}/{repo}/branches/{branch}/protection") {
444
+ owner = ownData(options, "owner");
445
+ repo = ownData(options, "repo");
446
+ branch = ownData(options, "branch");
447
+ } else {
448
+ const match = /^\/repos\/([^/]+)\/([^/]+)\/branches\/(.+)\/protection$/u.exec(path);
449
+ if (!match) return void 0;
450
+ try {
451
+ [owner, repo, branch] = match.slice(1).map((part) => decodeURIComponent(part));
452
+ } catch {
453
+ return void 0;
338
454
  }
339
- if (typeof owner !== 'string' ||
340
- !/^[A-Za-z0-9_-]{1,100}$/u.test(owner) ||
341
- typeof repo !== 'string' ||
342
- !/^[A-Za-z0-9_.-]{1,100}$/u.test(repo) ||
343
- typeof branch !== 'string' ||
344
- !branch.length ||
345
- branch.length > 1024 ||
346
- /[^\x21-\x7e]/u.test(branch))
347
- return undefined;
348
- return { owner, repo, branch };
455
+ }
456
+ if (typeof owner !== "string" || !/^[A-Za-z0-9_-]{1,100}$/u.test(owner) || typeof repo !== "string" || !/^[A-Za-z0-9_.-]{1,100}$/u.test(repo) || typeof branch !== "string" || !branch.length || branch.length > 1024 || /[^\x21-\x7e]/u.test(branch))
457
+ return void 0;
458
+ return { owner, repo, branch };
349
459
  }
350
- /** Internal read-only predicate: machine absence never comes from copied error fields. */
351
- export function hasBranchProtectionAbsence(error, clients, repository, branch) {
352
- if (!machineClients.has(clients))
353
- return exactBranchProtectionAbsence(error);
354
- if (typeof error !== 'object' || error === null || types.isProxy(error))
355
- return false;
356
- const target = machineProtectionAbsence.get(error);
357
- return (target?.clients === clients &&
358
- target.owner.toLowerCase() === repository.owner.toLowerCase() &&
359
- target.repo.toLowerCase() === repository.repo.toLowerCase() &&
360
- target.branch === branch);
460
+ function hasBranchProtectionAbsence(error, clients, repository, branch) {
461
+ if (!machineClients.has(clients)) return exactBranchProtectionAbsence(error);
462
+ if (typeof error !== "object" || error === null || types.isProxy(error)) return false;
463
+ const target = machineProtectionAbsence.get(error);
464
+ return target?.clients === clients && target.owner.toLowerCase() === repository.owner.toLowerCase() && target.repo.toLowerCase() === repository.repo.toLowerCase() && target.branch === branch;
361
465
  }
362
466
  function restMachineEndpoint(options) {
363
- const method = ownData(options, 'method'), url = ownData(options, 'url');
364
- if (typeof method !== 'string' || typeof url !== 'string' || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
365
- return 'UNKNOWN';
366
- let path;
367
- if (url.startsWith('/')) {
368
- const base = ownData(options, 'baseUrl');
369
- if (base !== 'https://api.github.com')
370
- return 'UNKNOWN';
371
- path = url.split(/[?#]/u)[0];
372
- }
373
- else {
374
- try {
375
- const parsed = new URL(url);
376
- if (parsed.origin !== 'https://api.github.com' || parsed.username || parsed.password)
377
- return 'UNKNOWN';
378
- path = parsed.pathname;
379
- }
380
- catch {
381
- return 'UNKNOWN';
382
- }
467
+ const method = ownData(options, "method"), url = ownData(options, "url");
468
+ if (typeof method !== "string" || typeof url !== "string" || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
469
+ return "UNKNOWN";
470
+ let path;
471
+ if (url.startsWith("/")) {
472
+ const base = ownData(options, "baseUrl");
473
+ if (base !== "https://api.github.com") return "UNKNOWN";
474
+ path = url.split(/[?#]/u)[0];
475
+ } else {
476
+ try {
477
+ const parsed = new URL(url);
478
+ if (parsed.origin !== "https://api.github.com" || parsed.username || parsed.password) return "UNKNOWN";
479
+ path = parsed.pathname;
480
+ } catch {
481
+ return "UNKNOWN";
383
482
  }
384
- const prefix = '/repos/[^/]{1,100}/[^/]{1,100}';
385
- const number = '(?:[0-9]{1,20}|\\{pull_number\\})';
386
- const routes = [
387
- ['PUT', new RegExp(`^${prefix}/pulls/${number}/merge$`, 'u'), 'pulls.merge'],
388
- ['GET', new RegExp(`^${prefix}/pulls/${number}$`, 'u'), 'pulls.get'],
389
- ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews$`, 'u'), 'pulls.listReviews'],
390
- ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews/(?:[0-9]{1,20}|\\{review_id\\})$`, 'u'), 'pulls.getReview'],
391
- ['GET', new RegExp(`^${prefix}/git/commits/[^/]{1,100}$`, 'u'), 'git.getCommit'],
392
- ['GET', new RegExp(`^${prefix}/git/ref/.{1,300}$`, 'u'), 'git.getRef'],
393
- ['GET', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, 'u'), 'issues.get'],
394
- ['PATCH', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, 'u'), 'issues.update'],
395
- ];
396
- return routes.find(([verb, pattern]) => verb === method && pattern.test(path))?.[2] ?? 'UNKNOWN';
483
+ }
484
+ const prefix = "/repos/[^/]{1,100}/[^/]{1,100}";
485
+ const number = "(?:[0-9]{1,20}|\\{pull_number\\})";
486
+ const routes = [
487
+ ["PUT", new RegExp(`^${prefix}/pulls/${number}/merge$`, "u"), "pulls.merge"],
488
+ ["GET", new RegExp(`^${prefix}/pulls/${number}$`, "u"), "pulls.get"],
489
+ ["GET", new RegExp(`^${prefix}/pulls/${number}/reviews$`, "u"), "pulls.listReviews"],
490
+ ["GET", new RegExp(`^${prefix}/pulls/${number}/reviews/(?:[0-9]{1,20}|\\{review_id\\})$`, "u"), "pulls.getReview"],
491
+ ["GET", new RegExp(`^${prefix}/git/commits/[^/]{1,100}$`, "u"), "git.getCommit"],
492
+ ["GET", new RegExp(`^${prefix}/git/ref/.{1,300}$`, "u"), "git.getRef"],
493
+ ["GET", new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, "u"), "issues.get"],
494
+ ["PATCH", new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, "u"), "issues.update"]
495
+ ];
496
+ return routes.find(([verb, pattern]) => verb === method && pattern.test(path))?.[2] ?? "UNKNOWN";
397
497
  }
398
498
  function safeMachineRequestError(error, phase, endpoint) {
399
- const status = ownData(error, 'status');
400
- const safe = new DeliveryError(status === 401
401
- ? 'Machine GitHub session is invalid or expired; verify the selected github.com account.'
402
- : status === 403 || status === 404
403
- ? 'Machine GitHub session cannot access the selected repository or operation; verify its existing permissions.'
404
- : 'Machine GitHub request failed; verify the selected account and repository access.');
405
- if (typeof status === 'number' && Number.isSafeInteger(status) && status >= 400 && status <= 599)
406
- Object.assign(safe, { status });
407
- const headers = ownData(error, 'headers') ?? ownData(ownData(error, 'response'), 'headers');
408
- setMachineRequestDiagnostics(safe, {
409
- phase,
410
- endpoint,
411
- status,
412
- code: ownData(error, 'code'),
413
- requestId: ownData(headers, 'x-github-request-id'),
414
- retryAfter: ownData(headers, 'retry-after'),
415
- resetAt: ownData(headers, 'x-ratelimit-reset'),
416
- remaining: ownData(headers, 'x-ratelimit-remaining'),
417
- });
418
- return safe;
499
+ const status = ownData(error, "status");
500
+ const safe = new DeliveryError(
501
+ status === 401 ? "Machine GitHub session is invalid or expired; verify the selected github.com account." : status === 403 || status === 404 ? "Machine GitHub session cannot access the selected repository or operation; verify its existing permissions." : "Machine GitHub request failed; verify the selected account and repository access."
502
+ );
503
+ if (typeof status === "number" && Number.isSafeInteger(status) && status >= 400 && status <= 599)
504
+ Object.assign(safe, { status });
505
+ const headers = ownData(error, "headers") ?? ownData(ownData(error, "response"), "headers");
506
+ setMachineRequestDiagnostics(safe, {
507
+ phase,
508
+ endpoint,
509
+ status,
510
+ code: ownData(error, "code"),
511
+ requestId: ownData(headers, "x-github-request-id"),
512
+ retryAfter: ownData(headers, "retry-after"),
513
+ resetAt: ownData(headers, "x-ratelimit-reset"),
514
+ remaining: ownData(headers, "x-ratelimit-remaining")
515
+ });
516
+ return safe;
419
517
  }
420
- //# sourceMappingURL=client.js.map
518
+ export {
519
+ assertDeliveryRolePermissions,
520
+ createDeliveryGitHubClients,
521
+ hasBranchProtectionAbsence,
522
+ retainMachineAuthorForConfiguration,
523
+ withAuthorGitToken
524
+ };
525
+ //# sourceMappingURL=client.js.map