@aviaratech/ai-delivery 0.3.35 → 0.3.37

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 +56 -554
  3. package/dist/agent.d.ts +1 -3
  4. package/dist/agent.js +74 -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 +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +91 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +389 -517
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  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 -479
  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.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +316 -354
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +63 -23
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.d.ts +0 -3
  95. package/dist/git.js +59 -76
  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 +42 -52
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +1 -0
  106. package/dist/github/discovery.js +197 -215
  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 +18 -2
  121. package/dist/github/projectDelivery.js +615 -557
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.js +433 -389
  124. package/dist/github/relationships.js.map +7 -1
  125. package/dist/github/repo.d.ts +1 -0
  126. package/dist/github/repo.js +123 -96
  127. package/dist/github/repo.js.map +7 -1
  128. package/dist/index.js +3 -3
  129. package/dist/index.js.map +7 -1
  130. package/dist/issue.d.ts +40 -9
  131. package/dist/issue.js +2102 -1742
  132. package/dist/issue.js.map +7 -1
  133. package/dist/issue63History.test.js +40 -42
  134. package/dist/issue63History.test.js.map +7 -1
  135. package/dist/issue63Routes.test.js +154 -143
  136. package/dist/issue63Routes.test.js.map +7 -1
  137. package/dist/issueBatchUpdate.test.js +989 -885
  138. package/dist/issueBatchUpdate.test.js.map +7 -1
  139. package/dist/issueBlockerGuard.test.js +262 -226
  140. package/dist/issueBlockerGuard.test.js.map +7 -1
  141. package/dist/issueContract.d.ts +23 -4
  142. package/dist/issueContract.js +416 -395
  143. package/dist/issueContract.js.map +7 -1
  144. package/dist/issueContract.test.d.ts +4 -3
  145. package/dist/issueContract.test.js +358 -321
  146. package/dist/issueContract.test.js.map +7 -1
  147. package/dist/issueDates.test.js +235 -233
  148. package/dist/issueDates.test.js.map +7 -1
  149. package/dist/issueInfoReadback.test.js +304 -190
  150. package/dist/issueInfoReadback.test.js.map +7 -1
  151. package/dist/issueIntake.test.js +1938 -1732
  152. package/dist/issueIntake.test.js.map +7 -1
  153. package/dist/issueJournal.d.ts +40 -19
  154. package/dist/issueJournal.js +229 -138
  155. package/dist/issueJournal.js.map +7 -1
  156. package/dist/issueJournal.test.js +605 -422
  157. package/dist/issueJournal.test.js.map +7 -1
  158. package/dist/issueRollup.test.d.ts +1 -0
  159. package/dist/issueRollup.test.js +476 -0
  160. package/dist/issueRollup.test.js.map +7 -0
  161. package/dist/issueTracking.test.js +1059 -989
  162. package/dist/issueTracking.test.js.map +7 -1
  163. package/dist/issueWriteRecovery.test.d.ts +1 -0
  164. package/dist/issueWriteRecovery.test.js +260 -0
  165. package/dist/issueWriteRecovery.test.js.map +7 -0
  166. package/dist/lifecycle.test.js +112 -441
  167. package/dist/lifecycle.test.js.map +7 -1
  168. package/dist/logger.js +80 -74
  169. package/dist/logger.js.map +7 -1
  170. package/dist/mcp/index.js +116 -94
  171. package/dist/mcp/index.js.map +7 -1
  172. package/dist/mcp/tools.d.ts +252 -310
  173. package/dist/mcp/tools.js +235 -342
  174. package/dist/mcp/tools.js.map +7 -1
  175. package/dist/pluginAuthProbe.js +63 -52
  176. package/dist/pluginAuthProbe.js.map +7 -1
  177. package/dist/pluginAuthProbe.test.js +85 -62
  178. package/dist/pluginAuthProbe.test.js.map +7 -1
  179. package/dist/pluginCredentials.test.js +282 -259
  180. package/dist/pluginCredentials.test.js.map +7 -1
  181. package/dist/pluginDoctor.test.js +653 -588
  182. package/dist/pluginDoctor.test.js.map +7 -1
  183. package/dist/pluginInstaller.d.ts +7 -5
  184. package/dist/pluginInstaller.js +1173 -1229
  185. package/dist/pluginInstaller.js.map +7 -1
  186. package/dist/pluginInstaller.test.js +1842 -1423
  187. package/dist/pluginInstaller.test.js.map +7 -1
  188. package/dist/pluginPackaging.test.js +417 -413
  189. package/dist/pluginPackaging.test.js.map +7 -1
  190. package/dist/pr.d.ts +114 -131
  191. package/dist/pr.js +1314 -1327
  192. package/dist/pr.js.map +7 -1
  193. package/dist/pr.test.js +967 -653
  194. package/dist/pr.test.js.map +7 -1
  195. package/dist/prAssociation.test.js +2419 -1788
  196. package/dist/prAssociation.test.js.map +7 -1
  197. package/dist/prDispatch.test.js +123 -89
  198. package/dist/prDispatch.test.js.map +7 -1
  199. package/dist/readView.d.ts +184 -0
  200. package/dist/readView.js +218 -0
  201. package/dist/readView.js.map +7 -0
  202. package/dist/readView.test.d.ts +1 -0
  203. package/dist/readView.test.js +146 -0
  204. package/dist/readView.test.js.map +7 -0
  205. package/dist/releaseReconciliation.test.js +267 -288
  206. package/dist/releaseReconciliation.test.js.map +7 -1
  207. package/dist/releaseWorkflow.test.js +2493 -422
  208. package/dist/releaseWorkflow.test.js.map +7 -1
  209. package/dist/review.d.ts +738 -2
  210. package/dist/review.js +601 -348
  211. package/dist/review.js.map +7 -1
  212. package/dist/review.test.js +1218 -812
  213. package/dist/review.test.js.map +7 -1
  214. package/dist/reviewSubmit.test.d.ts +1 -0
  215. package/dist/reviewSubmit.test.js +747 -0
  216. package/dist/reviewSubmit.test.js.map +7 -0
  217. package/dist/services/agentReadinessService.js +42 -37
  218. package/dist/services/agentReadinessService.js.map +7 -1
  219. package/dist/services/blockerGuardService.js +188 -188
  220. package/dist/services/blockerGuardService.js.map +7 -1
  221. package/dist/services/boardReconcileService.d.ts +125 -125
  222. package/dist/services/boardReconcileService.js +1295 -1421
  223. package/dist/services/boardReconcileService.js.map +7 -1
  224. package/dist/services/deliveryHealthService.js +197 -199
  225. package/dist/services/deliveryHealthService.js.map +7 -1
  226. package/dist/services/legacyIssueMigration.js +263 -277
  227. package/dist/services/legacyIssueMigration.js.map +7 -1
  228. package/dist/stagedChecks.test.js +396 -194
  229. package/dist/stagedChecks.test.js.map +7 -1
  230. package/dist/start.test.js +99 -95
  231. package/dist/start.test.js.map +7 -1
  232. package/dist/stdoutRegression.test.js +321 -358
  233. package/dist/stdoutRegression.test.js.map +7 -1
  234. package/dist/targetPolicyDiscovery.test.js +141 -143
  235. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  236. package/dist/targetPolicyEntrypoints.test.js +308 -269
  237. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  238. package/dist/targetPolicyLocal.test.js +580 -1051
  239. package/dist/targetPolicyLocal.test.js.map +7 -1
  240. package/dist/targetPolicyRoutes.test.js +274 -281
  241. package/dist/targetPolicyRoutes.test.js.map +7 -1
  242. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  243. package/dist/targetRepositoryExecution.test.js +451 -0
  244. package/dist/targetRepositoryExecution.test.js.map +7 -0
  245. package/dist/terminalMessages.js +41 -35
  246. package/dist/terminalMessages.js.map +7 -1
  247. package/dist/toolOutput.d.ts +2 -0
  248. package/dist/toolOutput.js +36 -0
  249. package/dist/toolOutput.js.map +7 -0
  250. package/dist/toolOutput.test.d.ts +1 -0
  251. package/dist/toolOutput.test.js +240 -0
  252. package/dist/toolOutput.test.js.map +7 -0
  253. package/dist/utils/atomicJson.d.ts +0 -2
  254. package/dist/utils/atomicJson.js +81 -77
  255. package/dist/utils/atomicJson.js.map +7 -1
  256. package/dist/utils/filesystem.d.ts +0 -8
  257. package/dist/utils/filesystem.js +5 -19
  258. package/dist/utils/filesystem.js.map +7 -1
  259. package/dist/utils/lockfile.js +68 -71
  260. package/dist/utils/lockfile.js.map +7 -1
  261. package/dist/verification.d.ts +1 -54
  262. package/dist/verification.js +976 -1941
  263. package/dist/verification.js.map +7 -1
  264. package/dist/verificationGate.test.js +127 -117
  265. package/dist/verificationGate.test.js.map +7 -1
  266. package/dist/version.js +45 -24
  267. package/dist/version.js.map +7 -1
  268. package/package.json +9 -8
  269. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  270. package/plugins/ai-delivery/README.md +47 -156
  271. package/plugins/ai-delivery/plugin.json +1 -1
  272. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  273. package/plugins/ai-delivery/runtime/dist/cli.js +351 -115
  274. package/plugins/ai-delivery/runtime/package.json +1 -1
  275. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  276. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  277. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  278. package/dist/investigationCompletion.test.js +0 -728
  279. package/dist/investigationCompletion.test.js.map +0 -1
  280. package/dist/services/deliveryAdmission.d.ts +0 -49
  281. package/dist/services/deliveryAdmission.js +0 -165
  282. package/dist/services/deliveryAdmission.js.map +0 -1
  283. package/dist/services/worktreeRegistry.d.ts +0 -434
  284. package/dist/services/worktreeRegistry.js +0 -1248
  285. package/dist/services/worktreeRegistry.js.map +0 -1
  286. package/dist/setup.d.ts +0 -60
  287. package/dist/setup.js +0 -585
  288. package/dist/setup.js.map +0 -1
  289. package/dist/setup.test.js +0 -3329
  290. package/dist/setup.test.js.map +0 -1
  291. package/dist/worktree.d.ts +0 -28
  292. package/dist/worktree.js +0 -188
  293. package/dist/worktree.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 → build.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,1320 +1,1264 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { existsSync, constants, fstatSync, closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
3
- import { homedir } from 'node:os';
4
- import { basename, dirname, join, resolve } from 'node:path';
5
- import { gunzipSync } from 'node:zlib';
6
- import { fileURLToPath } from 'node:url';
7
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
- import { DEFAULT_INHERITED_ENV_VARS, StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
9
- import { z } from 'zod';
10
- import { marketplaceDocuments, nativePluginArgs } from '@aviaratech/ai-plugin-tools';
11
- import { loadDeliverySettings, resolveDeliveryRoleCredentials } from './config/deliveryConfig.js';
12
- import { captureAuthenticationProbe } from './pluginAuthProbe.js';
13
- import { assertSupportedAuthorHost, machineAuthorEligible, MACHINE_AUTH_ENV_NAMES } from './github/machineAuth.js';
14
- import { ensurePrivateDirectoryDurably, writePrivateJsonFileAtomically } from './utils/atomicJson.js';
15
- import { withLock } from './utils/lockfile.js';
16
- import { confirmOwnedCleanup, processSnapshot, retainedWorktreeTransitionProducerDigest, runStageCommand, terminateOwnedProcesses, } from './verification.js';
17
- const Version = z
18
- .string()
19
- .max(128)
20
- .regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u);
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import {
3
+ existsSync,
4
+ constants,
5
+ fstatSync,
6
+ closeSync,
7
+ fsyncSync,
8
+ lstatSync,
9
+ mkdirSync,
10
+ openSync,
11
+ readFileSync,
12
+ readSync,
13
+ readdirSync,
14
+ realpathSync,
15
+ renameSync,
16
+ rmSync,
17
+ writeFileSync
18
+ } from "node:fs";
19
+ import { homedir } from "node:os";
20
+ import { basename, dirname, join, resolve } from "node:path";
21
+ import { gunzipSync } from "node:zlib";
22
+ import { fileURLToPath } from "node:url";
23
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
24
+ import { DEFAULT_INHERITED_ENV_VARS, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
25
+ import { z } from "zod";
26
+ import { marketplaceDocuments, nativePluginArgs } from "@aviaratech/ai-plugin-tools";
27
+ import {
28
+ credentialReferenceNames,
29
+ loadDeliverySettings,
30
+ resolveDeliveryRoleCredentials
31
+ } from "./config/deliveryConfig.js";
32
+ import { captureAuthenticationProbe } from "./pluginAuthProbe.js";
33
+ import { assertSupportedAuthorHost, machineAuthorEligible, MACHINE_AUTH_ENV_NAMES } from "./github/machineAuth.js";
34
+ import { ensurePrivateDirectoryDurably, writePrivateJsonFileAtomically } from "./utils/atomicJson.js";
35
+ import { withLock } from "./utils/lockfile.js";
36
+ import {
37
+ confirmOwnedCleanup,
38
+ processSnapshot,
39
+ retainedWorktreeTransitionProducerDigest,
40
+ runStageCommand,
41
+ terminateOwnedProcesses
42
+ } from "./verification.js";
43
+ const Version = z.string().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u);
21
44
  const InputSchema = z.strictObject({
22
- action: z.enum(['install', 'doctor', 'preview', 'update', 'rollback', 'remove']),
23
- host: z.enum(['codex', 'claude-code']),
24
- scope: z.enum(['user', 'project', 'local']),
25
- version: Version.optional(),
26
- dryRun: z.boolean().default(false),
27
- checkAuth: z.boolean().default(false),
28
- repo: z
29
- .string()
30
- .regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)
31
- .optional(),
32
- repoRoot: z.string().min(1),
45
+ action: z.enum(["install", "doctor", "preview", "update", "rollback", "remove"]),
46
+ host: z.enum(["codex", "claude-code"]),
47
+ scope: z.enum(["user", "project", "local"]),
48
+ version: Version.optional(),
49
+ dryRun: z.boolean().default(false),
50
+ checkAuth: z.boolean().default(false),
51
+ repo: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),
52
+ repoRoot: z.string().min(1)
33
53
  });
34
54
  const ProcessIdentity = z.strictObject({ pid: z.number().int().positive(), birth: z.string().min(1) });
35
55
  const Pending = z.strictObject({
36
- action: InputSchema.shape.action,
37
- targetVersion: Version.nullable(),
38
- owner: ProcessIdentity,
39
- producerDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
40
- staging: z
41
- .strictObject({
42
- path: z.string(),
43
- device: z.number().int().nonnegative().optional(),
44
- inode: z.number().int().nonnegative().optional(),
56
+ action: InputSchema.shape.action,
57
+ targetVersion: Version.nullable(),
58
+ owner: ProcessIdentity,
59
+ producerDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
60
+ staging: z.strictObject({
61
+ path: z.string(),
62
+ device: z.number().int().nonnegative().optional(),
63
+ inode: z.number().int().nonnegative().optional()
64
+ }).optional(),
65
+ command: z.discriminatedUnion("phase", [
66
+ z.strictObject({ phase: z.literal("idle") }),
67
+ z.strictObject({ phase: z.literal("starting") }),
68
+ z.strictObject({
69
+ phase: z.literal("running"),
70
+ process: ProcessIdentity,
71
+ tracked: z.array(ProcessIdentity.extend({ pgid: z.number().int().positive() })).max(256)
45
72
  })
46
- .optional(),
47
- command: z.discriminatedUnion('phase', [
48
- z.strictObject({ phase: z.literal('idle') }),
49
- z.strictObject({ phase: z.literal('starting') }),
50
- z.strictObject({
51
- phase: z.literal('running'),
52
- process: ProcessIdentity,
53
- tracked: z.array(ProcessIdentity.extend({ pgid: z.number().int().positive() })).max(256),
54
- }),
55
- ]),
73
+ ])
56
74
  });
57
75
  const StateSchema = z.strictObject({
58
- owner: z.literal('@aviaratech/ai-delivery.plugin@1'),
59
- host: InputSchema.shape.host,
60
- scope: InputSchema.shape.scope,
61
- projectRoot: z.string().nullable(),
62
- nativeHome: z.string().min(1),
63
- marketplace: z.string(),
64
- currentVersion: Version.nullable(),
65
- previousVersion: Version.nullable(),
66
- installedPath: z.string().nullable(),
67
- nativeVersion: z.string().optional(),
68
- pending: Pending.optional(),
76
+ owner: z.literal("@aviaratech/ai-delivery.plugin@1"),
77
+ host: InputSchema.shape.host,
78
+ scope: InputSchema.shape.scope,
79
+ projectRoot: z.string().nullable(),
80
+ nativeHome: z.string().min(1),
81
+ marketplace: z.string(),
82
+ currentVersion: Version.nullable(),
83
+ previousVersion: Version.nullable(),
84
+ installedPath: z.string().nullable(),
85
+ nativeVersion: z.string().optional(),
86
+ pending: Pending.optional()
69
87
  });
70
88
  const Unit = z.strictObject({
71
- owner: z.literal('@aviaratech/ai-delivery.plugin-version@1'),
72
- version: Version,
73
- archiveSha256: z.string().regex(/^[a-f0-9]{64}$/u),
74
- files: z.record(z.string(), z.string().regex(/^[a-f0-9]{64}$/u)),
89
+ owner: z.literal("@aviaratech/ai-delivery.plugin-version@1"),
90
+ version: Version,
91
+ archiveSha256: z.string().regex(/^[a-f0-9]{64}$/u),
92
+ files: z.record(z.string(), z.string().regex(/^[a-f0-9]{64}$/u))
75
93
  });
76
- const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
94
+ const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
77
95
  function sourceDiagnostics(input, target) {
78
- const report = {
79
- completeness: 'incomplete',
80
- registrations: [],
81
- nativeInventory: 'not_checked',
82
- plannedChanges: [],
83
- migration: 'refused',
84
- findings: ['native_session_scope_unverified', 'settings_preservation_unproved', 'native_writer_exclusion_unproved'],
85
- };
86
- const text = (path) => {
87
- let descriptor;
88
- try {
89
- assertCanonical(path);
90
- if (!existsSync(path))
91
- return undefined;
92
- const metadata = lstatSync(path);
93
- if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > 1024 * 1024)
94
- throw new Error('Unsafe configuration');
95
- // Nonblocking open also protects against replacement with a FIFO between
96
- // lstat and open; descriptor validation remains authoritative.
97
- descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
98
- const info = fstatSync(descriptor);
99
- if (!info.isFile() || info.nlink !== 1 || info.size > 1024 * 1024)
100
- throw new Error('Unsafe configuration');
101
- const bytes = Buffer.alloc(1024 * 1024 + 1);
102
- let size = 0;
103
- while (size < bytes.length) {
104
- const count = readSync(descriptor, bytes, size, bytes.length - size, null);
105
- if (count === 0)
106
- break;
107
- size += count;
108
- }
109
- if (size > 1024 * 1024)
110
- throw new Error('Configuration exceeded read limit');
111
- return bytes.subarray(0, size).toString('utf8');
112
- }
113
- catch {
114
- report.findings.push('configuration_unavailable');
115
- return undefined;
116
- }
117
- finally {
118
- if (descriptor !== undefined)
119
- closeSync(descriptor);
120
- }
121
- };
122
- const json = (path) => {
123
- const value = text(path);
124
- if (value === undefined)
125
- return undefined;
126
- try {
127
- const parsed = JSON.parse(value);
128
- return z.record(z.string(), z.unknown()).parse(parsed);
129
- }
130
- catch {
131
- report.findings.push('configuration_unavailable');
132
- return undefined;
133
- }
134
- };
135
- const observe = (scope, servers) => {
136
- if (typeof servers !== 'object' || servers === null || Array.isArray(servers)) {
137
- if (servers !== undefined)
138
- report.findings.push('configuration_unavailable');
139
- return;
140
- }
141
- // Names and launcher text identify candidates, never ownership. Nothing from
142
- // command arguments, URLs, environments or permission values reaches output.
143
- const candidate = Object.entries(servers).some(([name, value]) => {
144
- if (name === 'ai-delivery')
145
- return true;
146
- if (typeof value !== 'object' || value === null)
147
- return false;
148
- const entry = value;
149
- return (entry.command === 'ai-delivery' ||
150
- (Array.isArray(entry.args) &&
151
- entry.args.some((arg) => typeof arg === 'string' && arg.includes('@aviaratech/ai-delivery'))));
152
- });
153
- if (candidate)
154
- report.registrations.push({
155
- kind: 'standalone',
156
- scope,
157
- ownership: 'unknown',
158
- source: 'unknown',
159
- version: null,
160
- enabled: null,
161
- });
162
- };
163
- if (input.host === 'claude-code') {
164
- if (process.env.CLAUDE_CONFIG_DIR) {
165
- report.findings.push('custom_profile_configuration_unverified');
166
- }
167
- else {
168
- const user = json(join(realpathSync(homedir()), '.claude.json'));
169
- const projects = user?.projects;
170
- if (typeof projects === 'object' && projects !== null && !Array.isArray(projects)) {
171
- const local = projects[target.projectRoot];
172
- if (typeof local === 'object' && local !== null)
173
- observe('local', local.mcpServers);
174
- }
175
- observe('user', user?.mcpServers);
176
- }
177
- const project = json(join(target.projectRoot, '.mcp.json'))?.mcpServers;
178
- const userIndex = report.registrations.findIndex((entry) => entry.scope === 'user');
179
- observe('project', project);
180
- if (userIndex !== -1 && report.registrations.at(-1)?.scope === 'project') {
181
- const entry = report.registrations.pop();
182
- report.registrations.splice(userIndex, 0, entry);
183
- }
96
+ const report = {
97
+ completeness: "incomplete",
98
+ latestPublishedVersion: null,
99
+ registrations: [],
100
+ nativeInventory: "not_checked",
101
+ plannedChanges: [],
102
+ migration: "refused",
103
+ findings: ["native_session_scope_unverified", "settings_preservation_unproved", "native_writer_exclusion_unproved"]
104
+ };
105
+ const text = (path) => {
106
+ let descriptor;
107
+ try {
108
+ assertCanonical(path);
109
+ if (!existsSync(path)) return void 0;
110
+ const metadata = lstatSync(path);
111
+ if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > 1024 * 1024)
112
+ throw new Error("Unsafe configuration");
113
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
114
+ const info = fstatSync(descriptor);
115
+ if (!info.isFile() || info.nlink !== 1 || info.size > 1024 * 1024) throw new Error("Unsafe configuration");
116
+ const bytes = Buffer.alloc(1024 * 1024 + 1);
117
+ let size = 0;
118
+ while (size < bytes.length) {
119
+ const count = readSync(descriptor, bytes, size, bytes.length - size, null);
120
+ if (count === 0) break;
121
+ size += count;
122
+ }
123
+ if (size > 1024 * 1024) throw new Error("Configuration exceeded read limit");
124
+ return bytes.subarray(0, size).toString("utf8");
125
+ } catch {
126
+ report.findings.push("configuration_unavailable");
127
+ return void 0;
128
+ } finally {
129
+ if (descriptor !== void 0) closeSync(descriptor);
184
130
  }
185
- else {
186
- for (const [scope, path] of [
187
- ['project', join(target.projectRoot, '.codex/config.toml')],
188
- ['user', join(target.nativeHome, 'config.toml')],
189
- ]) {
190
- if (scope === 'project' && path === join(target.nativeHome, 'config.toml'))
191
- continue;
192
- const value = text(path);
193
- if (value === undefined)
194
- continue;
195
- // This is a conservative header observation, not a TOML resolver. Quoted
196
- // strings, profiles, managed and CLI overlays stay explicitly unverified.
197
- report.findings.push('codex_configuration_not_fully_resolved');
198
- if (/^\s*\[\s*mcp_servers\.(?:"ai-delivery"|'ai-delivery'|ai-delivery)\s*\]/mu.test(value))
199
- observe(scope, { 'ai-delivery': {} });
200
- }
131
+ };
132
+ const json = (path) => {
133
+ const value = text(path);
134
+ if (value === void 0) return void 0;
135
+ try {
136
+ const parsed = JSON.parse(value);
137
+ return z.record(z.string(), z.unknown()).parse(parsed);
138
+ } catch {
139
+ report.findings.push("configuration_unavailable");
140
+ return void 0;
141
+ }
142
+ };
143
+ const observe = (scope, servers) => {
144
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) {
145
+ if (servers !== void 0) report.findings.push("configuration_unavailable");
146
+ return;
147
+ }
148
+ const candidate = Object.entries(servers).some(([name, value]) => {
149
+ if (name === "ai-delivery") return true;
150
+ if (typeof value !== "object" || value === null) return false;
151
+ const entry = value;
152
+ return entry.command === "ai-delivery" || Array.isArray(entry.args) && entry.args.some((arg) => typeof arg === "string" && arg.includes("@aviaratech/ai-delivery"));
153
+ });
154
+ if (candidate)
155
+ report.registrations.push({
156
+ kind: "standalone",
157
+ scope,
158
+ ownership: "unknown",
159
+ source: "unknown",
160
+ version: null,
161
+ behind: null,
162
+ enabled: null
163
+ });
164
+ };
165
+ if (input.host === "claude-code") {
166
+ if (process.env.CLAUDE_CONFIG_DIR) {
167
+ report.findings.push("custom_profile_configuration_unverified");
168
+ } else {
169
+ const user = json(join(realpathSync(homedir()), ".claude.json"));
170
+ const projects = user?.projects;
171
+ if (typeof projects === "object" && projects !== null && !Array.isArray(projects)) {
172
+ const local = projects[target.projectRoot];
173
+ if (typeof local === "object" && local !== null)
174
+ observe("local", local.mcpServers);
175
+ }
176
+ observe("user", user?.mcpServers);
201
177
  }
202
- report.findings = [...new Set(report.findings)];
203
- return report;
178
+ const project = json(join(target.projectRoot, ".mcp.json"))?.mcpServers;
179
+ const userIndex = report.registrations.findIndex((entry) => entry.scope === "user");
180
+ observe("project", project);
181
+ if (userIndex !== -1 && report.registrations.at(-1)?.scope === "project") {
182
+ const entry = report.registrations.pop();
183
+ report.registrations.splice(userIndex, 0, entry);
184
+ }
185
+ } else {
186
+ for (const [scope, path] of [
187
+ ["project", join(target.projectRoot, ".codex/config.toml")],
188
+ ["user", join(target.nativeHome, "config.toml")]
189
+ ]) {
190
+ if (scope === "project" && path === join(target.nativeHome, "config.toml")) continue;
191
+ const value = text(path);
192
+ if (value === void 0) continue;
193
+ report.findings.push("codex_configuration_not_fully_resolved");
194
+ if (/^\s*\[\s*mcp_servers\.(?:"ai-delivery"|'ai-delivery'|ai-delivery)\s*\]/mu.test(value))
195
+ observe(scope, { "ai-delivery": {} });
196
+ }
197
+ }
198
+ report.findings = [...new Set(report.findings)];
199
+ return report;
204
200
  }
205
201
  function observeNativePlugins(result, input, target, entries, verifiedRegistration) {
206
- const report = result.diagnostics;
207
- report.nativeInventory = 'observed';
208
- let count = 0;
209
- for (const entry of entries) {
210
- const id = entry.pluginId ?? entry.id;
211
- if (!(entry.name === 'ai-delivery' || (typeof id === 'string' && id.startsWith('ai-delivery@'))))
212
- continue;
213
- if (input.host === 'codex' && entry.installed !== true)
214
- continue;
215
- if (input.host === 'claude-code' && (entry.scope === 'project' || entry.scope === 'local')) {
216
- if (typeof entry.projectPath === 'string' && entry.projectPath !== target.projectRoot)
217
- continue;
218
- if (typeof entry.projectPath !== 'string')
219
- report.findings.push('native_registration_project_unverified');
220
- }
221
- if (++count > 256) {
222
- report.findings.push('native_inventory_truncated');
223
- break;
224
- }
225
- const managed = result.sourceIntegrity === true && entry === verifiedRegistration;
226
- const version = Version.safeParse(entry.version);
227
- const scope = input.host === 'codex'
228
- ? 'user'
229
- : entry.scope === 'user' || entry.scope === 'project' || entry.scope === 'local'
230
- ? entry.scope
231
- : 'unknown';
232
- report.registrations.push({
233
- kind: 'plugin',
234
- scope,
235
- ownership: managed ? 'managed' : 'external',
236
- source: managed ? 'managed_archive' : 'unknown',
237
- version: version.success ? version.data : null,
238
- enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null,
239
- });
202
+ const report = result.diagnostics;
203
+ report.nativeInventory = "observed";
204
+ let count = 0;
205
+ for (const entry of entries) {
206
+ const id = entry.pluginId ?? entry.id;
207
+ if (!(entry.name === "ai-delivery" || typeof id === "string" && id.startsWith("ai-delivery@"))) continue;
208
+ if (input.host === "codex" && entry.installed !== true) continue;
209
+ if (input.host === "claude-code" && (entry.scope === "project" || entry.scope === "local")) {
210
+ if (typeof entry.projectPath === "string" && entry.projectPath !== target.projectRoot) continue;
211
+ if (typeof entry.projectPath !== "string") report.findings.push("native_registration_project_unverified");
240
212
  }
213
+ if (++count > 256) {
214
+ report.findings.push("native_inventory_truncated");
215
+ break;
216
+ }
217
+ const managed = result.sourceIntegrity === true && entry === verifiedRegistration;
218
+ const version = Version.safeParse(entry.version);
219
+ const scope = input.host === "codex" ? "user" : entry.scope === "user" || entry.scope === "project" || entry.scope === "local" ? entry.scope : "unknown";
220
+ report.registrations.push({
221
+ kind: "plugin",
222
+ scope,
223
+ ownership: managed ? "managed" : "external",
224
+ source: managed ? "managed_archive" : "unknown",
225
+ version: version.success ? version.data : null,
226
+ behind: null,
227
+ enabled: typeof entry.enabled === "boolean" ? entry.enabled : null
228
+ });
229
+ }
230
+ }
231
+ function versionBehind(installed, latest) {
232
+ const [installedCore, ...installedSuffix] = installed.split("+")[0].split("-");
233
+ const [latestCore, ...latestSuffix] = latest.split("+")[0].split("-");
234
+ for (let index = 0; index < 3; index++) {
235
+ const left2 = BigInt(installedCore.split(".")[index]);
236
+ const right2 = BigInt(latestCore.split(".")[index]);
237
+ if (left2 !== right2) return left2 < right2;
238
+ }
239
+ if (installedSuffix.length === 0 || latestSuffix.length === 0)
240
+ return installedSuffix.length > 0 && latestSuffix.length === 0;
241
+ const left = installedSuffix.join("-").split(".");
242
+ const right = latestSuffix.join("-").split(".");
243
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
244
+ const a = left[index], b = right[index];
245
+ if (a === b) continue;
246
+ if (a === void 0) return true;
247
+ if (b === void 0) return false;
248
+ const numericA = /^\d+$/u.test(a), numericB = /^\d+$/u.test(b);
249
+ if (numericA && numericB) return BigInt(a) < BigInt(b);
250
+ if (numericA !== numericB) return numericA;
251
+ return a < b;
252
+ }
253
+ return false;
254
+ }
255
+ async function publishedVersionDiagnostics(result) {
256
+ const report = result.diagnostics;
257
+ if (report.registrations.length === 0) return result;
258
+ try {
259
+ const response = await fetch("https://registry.npmjs.org/-/package/@aviaratech%2fai-delivery/dist-tags", {
260
+ signal: AbortSignal.timeout(5e3),
261
+ redirect: "error",
262
+ headers: { accept: "application/json" }
263
+ });
264
+ if (!response.ok || !response.body) {
265
+ await response.body?.cancel();
266
+ throw new Error("Published version unavailable.");
267
+ }
268
+ const reader = response.body.getReader(), chunks = [];
269
+ let bytes = 0;
270
+ try {
271
+ while (true) {
272
+ const chunk = await reader.read();
273
+ if (chunk.done) break;
274
+ if (!(chunk.value instanceof Uint8Array)) throw new Error("Invalid published version response.");
275
+ bytes += chunk.value.byteLength;
276
+ if (bytes > 8192) throw new Error("Published version response exceeded its limit.");
277
+ chunks.push(chunk.value);
278
+ }
279
+ } finally {
280
+ await reader.cancel();
281
+ }
282
+ const { latest } = z.object({ latest: Version }).parse(JSON.parse(Buffer.concat(chunks).toString("utf8")));
283
+ report.latestPublishedVersion = latest;
284
+ for (const entry of report.registrations)
285
+ entry.behind = entry.version === null ? null : versionBehind(entry.version, latest);
286
+ } catch {
287
+ report.findings.push("latest_published_version_unavailable");
288
+ }
289
+ return result;
241
290
  }
242
- // Native inventory and startup must not inherit the caller's credentials or
243
- // runtime injection flags. Install/update/recovery keep their existing owner.
244
291
  function doctorEnvironment() {
245
- const env = { PATH: process.env.PATH ?? '', DISABLE_AUTOUPDATER: '1' };
246
- for (const name of ['HOME', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR'])
247
- if (process.env[name] !== undefined)
248
- env[name] = process.env[name];
249
- return env;
292
+ const env = { PATH: process.env.PATH ?? "", DISABLE_AUTOUPDATER: "1" };
293
+ for (const name of ["HOME", "CODEX_HOME", "CLAUDE_CONFIG_DIR"])
294
+ if (process.env[name] !== void 0) env[name] = process.env[name];
295
+ return env;
250
296
  }
251
297
  const AuthReadback = z.object({
252
- routing: z.object({ repository: InputSchema.shape.repo.unwrap() }),
253
- reviewRoute: z.object({
254
- author: z.object({
255
- actorLogin: z
256
- .string()
257
- .regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u)
258
- .max(200),
259
- authSource: z.enum(['app', 'personal']),
260
- credentialSource: z.string().optional(),
261
- identity: z.string(),
262
- }),
263
- reviewer: z.object({
264
- actorLogin: z
265
- .string()
266
- .regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u)
267
- .max(200),
268
- identity: z.string(),
269
- repositoryAccess: z.literal('readable'),
270
- }),
271
- rules: z.object({
272
- visibility: z.enum(['complete', 'partial', 'unknown']),
273
- observedRequiredApprovals: z.number().int().nonnegative().nullable(),
274
- }),
275
- approvalEligibility: z.enum(['unknown', 'insufficient-permission']),
298
+ routing: z.object({ repository: InputSchema.shape.repo.unwrap() }),
299
+ reviewRoute: z.object({
300
+ author: z.object({
301
+ actorLogin: z.string().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),
302
+ authSource: z.enum(["app", "personal"]),
303
+ credentialSource: z.string().optional(),
304
+ identity: z.string()
305
+ }),
306
+ reviewer: z.object({
307
+ actorLogin: z.string().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),
308
+ identity: z.string(),
309
+ repositoryAccess: z.literal("readable")
276
310
  }),
311
+ rules: z.object({
312
+ visibility: z.enum(["complete", "partial", "unknown"]),
313
+ observedRequiredApprovals: z.number().int().nonnegative().nullable()
314
+ }),
315
+ approvalEligibility: z.enum(["unknown", "insufficient-permission"])
316
+ })
277
317
  });
278
318
  async function checkAuthentication(input, root, probe) {
279
- let settings;
280
- try {
281
- settings = await loadDeliverySettings();
282
- probe.settings = 'valid';
283
- }
284
- catch {
285
- probe.settings = 'unavailable_or_invalid';
286
- probe.outcome = 'blocked';
287
- probe.reason = 'settings_unavailable_or_invalid';
288
- return;
289
- }
290
- const names = Object.values(settings.roles).flatMap((role) => Object.values(role.credentialEnv));
291
- const author = settings.roles.author;
292
- const machineSession = author.authSource === 'personal' && machineAuthorEligible(author.credentialEnv.token, process.env);
293
- const requiredNames = machineSession ? names.filter((name) => name !== 'GH_TOKEN') : names;
294
- probe.processReferences.requiredNames = requiredNames;
295
- const missing = requiredNames.filter((name) => !process.env[name]?.trim());
296
- probe.processReferences.missingNames = missing;
297
- if (missing.length > 0) {
298
- probe.processReferences.status = 'missing';
299
- probe.outcome = 'blocked';
300
- probe.reason = 'missing_references';
301
- return;
302
- }
303
- // A credential reference cannot also change the selected Node/configuration
304
- // boundary. No legacy personal override or ambient fallback is forwarded.
305
- if (names.some((name) => /^(?:NODE_|NPM_|GIT_)/u.test(name) ||
306
- [
307
- ...MACHINE_AUTH_ENV_NAMES,
308
- 'PATH',
309
- 'HOME',
310
- 'CODEX_HOME',
311
- 'CLAUDE_CONFIG_DIR',
312
- 'AI_DELIVERY_CONFIG',
313
- 'AI_DELIVERY_IDENTITY',
314
- 'DISABLE_AUTOUPDATER',
315
- ].includes(name))) {
316
- probe.processReferences.status = 'invalid';
317
- probe.outcome = 'blocked';
318
- probe.reason = 'invalid_references';
319
- return;
320
- }
321
- const env = {
322
- PATH: process.env.PATH ?? '',
323
- AI_DELIVERY_CONFIG: settings.configPath,
324
- NODE_OPTIONS: '--max-old-space-size=512 --v8-pool-size=1',
325
- DISABLE_AUTOUPDATER: '1',
319
+ let settings;
320
+ try {
321
+ settings = await loadDeliverySettings();
322
+ probe.settings = "valid";
323
+ } catch {
324
+ probe.settings = "unavailable_or_invalid";
325
+ probe.outcome = "blocked";
326
+ probe.reason = "settings_unavailable_or_invalid";
327
+ return;
328
+ }
329
+ const names = Object.values(settings.roles).flatMap(credentialReferenceNames);
330
+ const author = settings.roles.author;
331
+ const machineSession = author.authSource === "personal" && machineAuthorEligible(author.credentialEnv.token, process.env);
332
+ const requiredNames = machineSession ? names.filter((name) => name !== "GH_TOKEN") : names;
333
+ probe.processReferences.requiredNames = requiredNames;
334
+ const missing = requiredNames.filter((name) => !process.env[name]?.trim());
335
+ probe.processReferences.missingNames = missing;
336
+ if (missing.length > 0) {
337
+ probe.processReferences.status = "missing";
338
+ probe.outcome = "blocked";
339
+ probe.reason = "missing_references";
340
+ return;
341
+ }
342
+ if (names.some(
343
+ (name) => /^(?:NODE_|NPM_|GIT_)/u.test(name) || [
344
+ ...MACHINE_AUTH_ENV_NAMES,
345
+ "PATH",
346
+ "HOME",
347
+ "CODEX_HOME",
348
+ "CLAUDE_CONFIG_DIR",
349
+ "AI_DELIVERY_CONFIG",
350
+ "AI_DELIVERY_IDENTITY",
351
+ "DISABLE_AUTOUPDATER"
352
+ ].includes(name)
353
+ )) {
354
+ probe.processReferences.status = "invalid";
355
+ probe.outcome = "blocked";
356
+ probe.reason = "invalid_references";
357
+ return;
358
+ }
359
+ const env = {
360
+ PATH: process.env.PATH ?? "",
361
+ AI_DELIVERY_CONFIG: settings.configPath,
362
+ NODE_OPTIONS: "--max-old-space-size=512 --v8-pool-size=1",
363
+ DISABLE_AUTOUPDATER: "1"
364
+ };
365
+ for (const name of names) if (process.env[name] !== void 0) env[name] = process.env[name].trim();
366
+ if (machineSession) {
367
+ for (const name of MACHINE_AUTH_ENV_NAMES) if (process.env[name] !== void 0) env[name] = process.env[name];
368
+ }
369
+ try {
370
+ if (author.authSource === "personal") assertSupportedAuthorHost(process.env);
371
+ for (const role of ["author", "reviewer"])
372
+ if (settings.roles[role].authSource !== "personal")
373
+ resolveDeliveryRoleCredentials({ config: settings, role, env });
374
+ } catch {
375
+ probe.processReferences.status = "invalid";
376
+ probe.outcome = "blocked";
377
+ probe.reason = "invalid_references";
378
+ return;
379
+ }
380
+ probe.processReferences.status = "complete";
381
+ const captured = await captureAuthenticationProbe(
382
+ input.repoRoot,
383
+ [process.execPath, join(root, "runtime/dist/cli.js"), "--repo", input.repo, "config:resolve"],
384
+ env
385
+ );
386
+ if (!captured.cleanupConfirmed) {
387
+ probe.outcome = "failed";
388
+ probe.authentication.status = "unverified";
389
+ probe.repositoryAccess.status = "unverified";
390
+ probe.reason = "probe_cleanup_unverified";
391
+ return;
392
+ }
393
+ if (captured.failed) {
394
+ probe.outcome = "failed";
395
+ probe.authentication.status = "unverified";
396
+ probe.repositoryAccess.status = "unverified";
397
+ const diagnostic = captured.diagnostic;
398
+ if (diagnostic === "ai-delivery: Configured personal author token is invalid or expired; refresh the selected token." || diagnostic === "ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.") {
399
+ probe.authentication.status = "failed";
400
+ probe.reason = "authentication_failed";
401
+ } else if ([
402
+ "ai-delivery: Author cannot read the selected GitHub repository; verify configured access.",
403
+ "ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access."
404
+ ].includes(diagnostic ?? "")) {
405
+ probe.repositoryAccess.status = "denied";
406
+ probe.reason = "repository_denied";
407
+ } else probe.reason = "probe_failed";
408
+ return;
409
+ }
410
+ try {
411
+ const data = AuthReadback.parse(JSON.parse(captured.stdout));
412
+ const route = data.reviewRoute;
413
+ if (data.routing.repository.toLowerCase() !== input.repo.toLowerCase() || route.author.authSource !== (settings.roles.author.authSource ?? "app") || route.author.identity !== settings.roles.author.identity || route.reviewer.identity !== settings.roles.reviewer.identity || route.author.actorLogin.toLowerCase() === route.reviewer.actorLogin.toLowerCase())
414
+ throw new Error("Inconsistent readback");
415
+ const projected = {
416
+ author: {
417
+ actorLogin: route.author.actorLogin,
418
+ authSource: route.author.authSource,
419
+ ...machineSession && route.author.credentialSource !== void 0 ? { credentialSource: route.author.credentialSource } : {}
420
+ },
421
+ reviewer: { actorLogin: route.reviewer.actorLogin, authSource: "app" }
326
422
  };
327
- for (const name of names)
328
- if (process.env[name] !== undefined)
329
- env[name] = process.env[name].trim();
330
- if (machineSession)
331
- for (const name of MACHINE_AUTH_ENV_NAMES)
332
- if (process.env[name] !== undefined)
333
- env[name] = process.env[name];
334
- try {
335
- if (author.authSource === 'personal')
336
- assertSupportedAuthorHost(process.env);
337
- for (const role of ['author', 'reviewer'])
338
- if (settings.roles[role].authSource !== 'personal')
339
- resolveDeliveryRoleCredentials({ config: settings, role, env });
340
- }
341
- catch {
342
- probe.processReferences.status = 'invalid';
343
- probe.outcome = 'blocked';
344
- probe.reason = 'invalid_references';
345
- return;
346
- }
347
- probe.processReferences.status = 'complete';
348
- // Supervise the selected CLI and its descendants with the existing owned
349
- // process runner. Timeout and host cancellation await identity-checked
350
- // cleanup; authentication output stays in bounded memory, never a stage log.
351
- const captured = await captureAuthenticationProbe(input.repoRoot, [process.execPath, join(root, 'runtime/dist/cli.js'), '--repo', input.repo, 'config:resolve'], env);
352
- if (!captured.cleanupConfirmed) {
353
- probe.outcome = 'failed';
354
- probe.authentication.status = 'unverified';
355
- probe.repositoryAccess.status = 'unverified';
356
- probe.reason = 'probe_cleanup_unverified';
357
- return;
358
- }
359
- if (captured.failed) {
360
- probe.outcome = 'failed';
361
- probe.authentication.status = 'unverified';
362
- probe.repositoryAccess.status = 'unverified';
363
- // REST request logging can precede the CLI-owned final diagnostic. Classify
364
- // only that exact final line; all surrounding opaque output stays withheld.
365
- const diagnostic = captured.diagnostic;
366
- if (diagnostic ===
367
- 'ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.' ||
368
- diagnostic ===
369
- 'ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.') {
370
- probe.authentication.status = 'failed';
371
- probe.reason = 'authentication_failed';
372
- }
373
- else if ([
374
- 'ai-delivery: Author cannot read the selected GitHub repository; verify configured access.',
375
- 'ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.',
376
- ].includes(diagnostic ?? '')) {
377
- probe.repositoryAccess.status = 'denied';
378
- probe.reason = 'repository_denied';
379
- }
380
- else
381
- probe.reason = 'probe_failed';
382
- return;
383
- }
384
- try {
385
- const data = AuthReadback.parse(JSON.parse(captured.stdout));
386
- const route = data.reviewRoute;
387
- if (data.routing.repository.toLowerCase() !== input.repo.toLowerCase() ||
388
- route.author.authSource !== (settings.roles.author.authSource ?? 'app') ||
389
- route.author.identity !== settings.roles.author.identity ||
390
- route.reviewer.identity !== settings.roles.reviewer.identity ||
391
- route.author.actorLogin.toLowerCase() === route.reviewer.actorLogin.toLowerCase())
392
- throw new Error('Inconsistent readback');
393
- const projected = {
394
- author: {
395
- actorLogin: route.author.actorLogin,
396
- authSource: route.author.authSource,
397
- ...(machineSession && route.author.credentialSource !== undefined
398
- ? { credentialSource: route.author.credentialSource }
399
- : {}),
400
- },
401
- reviewer: { actorLogin: route.reviewer.actorLogin, authSource: 'app' },
402
- };
403
- // Even a syntactically valid actor must not reproduce a supplied credential.
404
- if (machineSession && !route.author.credentialSource?.startsWith('gh:github.com:'))
405
- throw new Error('Missing session route');
406
- if (names.some((name) => env[name] !== undefined && JSON.stringify(projected).includes(env[name])))
407
- throw new Error('Unsafe readback');
408
- probe.authentication = { status: 'verified', ...projected };
409
- probe.repositoryAccess.status = 'verified';
410
- probe.reviewRules = { ...route.rules, approvalEligibility: route.approvalEligibility };
411
- probe.outcome = 'readback_complete';
412
- }
413
- catch {
414
- probe.authentication.status = 'unverified';
415
- probe.repositoryAccess.status = 'unverified';
416
- probe.outcome = 'failed';
417
- probe.reason = 'invalid_readback';
418
- }
423
+ if (machineSession && !route.author.credentialSource?.startsWith("gh:github.com:"))
424
+ throw new Error("Missing session route");
425
+ if (names.some((name) => env[name] !== void 0 && JSON.stringify(projected).includes(env[name])))
426
+ throw new Error("Unsafe readback");
427
+ probe.authentication = { status: "verified", ...projected };
428
+ probe.repositoryAccess.status = "verified";
429
+ probe.reviewRules = { ...route.rules, approvalEligibility: route.approvalEligibility };
430
+ probe.outcome = "readback_complete";
431
+ } catch {
432
+ probe.authentication.status = "unverified";
433
+ probe.repositoryAccess.status = "unverified";
434
+ probe.outcome = "failed";
435
+ probe.reason = "invalid_readback";
436
+ }
419
437
  }
420
438
  function assertCanonical(path) {
421
- let cursor = resolve(path);
422
- while (true) {
423
- if (existsSync(cursor) && lstatSync(cursor).isSymbolicLink())
424
- throw new Error('Managed plugin paths must not use symlinks.');
425
- const parent = dirname(cursor);
426
- if (parent === cursor)
427
- break;
428
- cursor = parent;
429
- }
439
+ let cursor = resolve(path);
440
+ while (true) {
441
+ if (existsSync(cursor) && lstatSync(cursor).isSymbolicLink())
442
+ throw new Error("Managed plugin paths must not use symlinks.");
443
+ const parent = dirname(cursor);
444
+ if (parent === cursor) break;
445
+ cursor = parent;
446
+ }
430
447
  }
431
448
  function targetFor(input) {
432
- const projectRoot = realpathSync(resolve(input.repoRoot));
433
- const nativeProfile = resolve(projectRoot, (input.host === 'codex' ? process.env.CODEX_HOME : process.env.CLAUDE_CONFIG_DIR) ??
434
- join(homedir(), input.host === 'codex' ? '.codex' : '.claude'));
435
- let ancestor = nativeProfile;
436
- const missing = [];
437
- while (!existsSync(ancestor)) {
438
- missing.unshift(basename(ancestor));
439
- ancestor = dirname(ancestor);
440
- }
441
- const nativeHome = join(realpathSync(ancestor), ...missing);
442
- const scopeKey = input.scope === 'user'
443
- ? 'user'
444
- : `${input.scope}-${createHash('sha256').update(projectRoot).digest('hex').slice(0, 16)}`;
445
- const directory = join(homedir(), '.cache', 'ai-delivery', 'plugins', input.host, scopeKey);
446
- assertCanonical(directory);
447
- if (existsSync(directory) && (!lstatSync(directory).isDirectory() || (lstatSync(directory).mode & 0o077) !== 0))
448
- throw new Error('Managed plugin directory is not private.');
449
- return {
450
- directory,
451
- projectRoot,
452
- nativeHome,
453
- marketplace: `ai-delivery-${scopeKey}`,
454
- catalog: join(directory, 'marketplace'),
455
- statePath: join(directory, 'state.json'),
456
- tool: input.host === 'codex' ? 'codex' : 'claude',
457
- };
449
+ const projectRoot = realpathSync(resolve(input.repoRoot));
450
+ const nativeProfile = resolve(
451
+ projectRoot,
452
+ (input.host === "codex" ? process.env.CODEX_HOME : process.env.CLAUDE_CONFIG_DIR) ?? join(homedir(), input.host === "codex" ? ".codex" : ".claude")
453
+ );
454
+ let ancestor = nativeProfile;
455
+ const missing = [];
456
+ while (!existsSync(ancestor)) {
457
+ missing.unshift(basename(ancestor));
458
+ ancestor = dirname(ancestor);
459
+ }
460
+ const nativeHome = join(realpathSync(ancestor), ...missing);
461
+ const scopeKey = input.scope === "user" ? "user" : `${input.scope}-${createHash("sha256").update(projectRoot).digest("hex").slice(0, 16)}`;
462
+ const directory = join(homedir(), ".cache", "ai-delivery", "plugins", input.host, scopeKey);
463
+ assertCanonical(directory);
464
+ if (existsSync(directory) && (!lstatSync(directory).isDirectory() || (lstatSync(directory).mode & 63) !== 0))
465
+ throw new Error("Managed plugin directory is not private.");
466
+ return {
467
+ directory,
468
+ projectRoot,
469
+ nativeHome,
470
+ marketplace: `ai-delivery-${scopeKey}`,
471
+ catalog: join(directory, "marketplace"),
472
+ statePath: join(directory, "state.json"),
473
+ tool: input.host === "codex" ? "codex" : "claude"
474
+ };
458
475
  }
459
476
  function readState(input, target) {
460
- if (!existsSync(target.statePath))
461
- return undefined;
462
- const metadata = lstatSync(target.statePath);
463
- if (!metadata.isFile() || metadata.nlink !== 1 || (metadata.mode & 0o077) !== 0 || metadata.size > 65536)
464
- throw new Error('Managed plugin state is unsafe.');
465
- const state = StateSchema.parse(JSON.parse(readFileSync(target.statePath, 'utf8')));
466
- if (state.nativeHome !== target.nativeHome)
467
- throw new Error('Managed plugin state belongs to a different native profile.');
468
- if (state.host !== input.host ||
469
- state.scope !== input.scope ||
470
- state.marketplace !== target.marketplace ||
471
- state.projectRoot !== (input.scope === 'user' ? null : target.projectRoot))
472
- throw new Error('Managed plugin state belongs to a different target.');
473
- return state;
477
+ if (!existsSync(target.statePath)) return void 0;
478
+ const metadata = lstatSync(target.statePath);
479
+ if (!metadata.isFile() || metadata.nlink !== 1 || (metadata.mode & 63) !== 0 || metadata.size > 65536)
480
+ throw new Error("Managed plugin state is unsafe.");
481
+ const state = StateSchema.parse(JSON.parse(readFileSync(target.statePath, "utf8")));
482
+ if (state.nativeHome !== target.nativeHome)
483
+ throw new Error("Managed plugin state belongs to a different native profile.");
484
+ if (state.host !== input.host || state.scope !== input.scope || state.marketplace !== target.marketplace || state.projectRoot !== (input.scope === "user" ? null : target.projectRoot))
485
+ throw new Error("Managed plugin state belongs to a different target.");
486
+ return state;
474
487
  }
475
488
  function identity(pid) {
476
- const member = processSnapshot().get(pid);
477
- return member && !member.status.startsWith('Z') ? member.identity : undefined;
489
+ const member = processSnapshot().get(pid);
490
+ return member && !member.status.startsWith("Z") ? member.identity : void 0;
478
491
  }
479
492
  async function recover(pending) {
480
- if (identity(pending.owner.pid) === pending.owner.birth)
481
- throw new Error('A live plugin installer still owns this target.');
482
- if (pending.command.phase === 'starting')
483
- throw new Error('Interrupted installer command ownership is unknown; preserve its state before recovery.');
484
- if (pending.command.phase !== 'running')
485
- return;
486
- const owned = {
487
- rootPid: pending.command.process.pid,
488
- rootIdentity: pending.command.process.birth,
489
- sampled: true,
490
- tracked: new Map(pending.command.tracked.map(({ pid, birth, pgid }) => [
491
- pid,
492
- { pid, identity: birth, pgid, ppid: 0, rssBytes: 0, status: '' },
493
- ])),
494
- };
495
- terminateOwnedProcesses(owned);
496
- await confirmOwnedCleanup(owned);
493
+ if (identity(pending.owner.pid) === pending.owner.birth)
494
+ throw new Error("A live plugin installer still owns this target.");
495
+ if (pending.command.phase === "starting")
496
+ throw new Error("Interrupted installer command ownership is unknown; preserve its state before recovery.");
497
+ if (pending.command.phase !== "running") return;
498
+ const owned = {
499
+ rootPid: pending.command.process.pid,
500
+ rootIdentity: pending.command.process.birth,
501
+ sampled: true,
502
+ tracked: new Map(
503
+ pending.command.tracked.map(({ pid, birth, pgid }) => [
504
+ pid,
505
+ { pid, identity: birth, pgid, ppid: 0, rssBytes: 0, status: "" }
506
+ ])
507
+ )
508
+ };
509
+ terminateOwnedProcesses(owned);
510
+ await confirmOwnedCleanup(owned);
497
511
  }
498
512
  async function command(binary, args, cwd, signal, publish, credentialFreeDoctor = false) {
499
- const output = await runStageCommand(cwd, [binary, ...args], signal, undefined, { maxAggregateRssBytes: 1024 ** 3, minFreeDiskBytes: 256 * 1024 ** 2, maxNewOutputBytes: 512 * 1024 ** 2 }, undefined, undefined, {
500
- starting: () => publish?.({ phase: 'starting' }),
501
- observed: (owned) => publish?.({
502
- phase: 'running',
503
- process: { pid: owned.rootPid, birth: owned.rootIdentity },
504
- tracked: [...owned.tracked.values()].map(({ pid, identity: birth, pgid }) => ({ pid, birth, pgid })),
505
- }),
506
- idle: () => publish?.({ phase: 'idle' }),
507
- assertQuiescent: () => { },
508
- }, {
509
- environment: credentialFreeDoctor ? doctorEnvironment() : { ...process.env, DISABLE_AUTOUPDATER: '1' },
510
- cwd,
511
- maxCapturedOutputBytes: 1024 * 1024,
512
- stdoutOnly: true,
513
- failedOutput: (bytes) => credentialFreeDoctor
514
- ? ' Native inventory failed; raw output withheld.'
515
- : ` Native command output: ${bytes.toString('utf8').slice(-2000)}`,
516
- });
517
- return output.toString('utf8');
513
+ const output = await runStageCommand(
514
+ cwd,
515
+ [binary, ...args],
516
+ signal,
517
+ void 0,
518
+ { maxAggregateRssBytes: 1024 ** 3, minFreeDiskBytes: 256 * 1024 ** 2, maxNewOutputBytes: 512 * 1024 ** 2 },
519
+ void 0,
520
+ void 0,
521
+ {
522
+ starting: () => publish?.({ phase: "starting" }),
523
+ observed: (owned) => publish?.({
524
+ phase: "running",
525
+ process: { pid: owned.rootPid, birth: owned.rootIdentity },
526
+ tracked: [...owned.tracked.values()].map(({ pid, identity: birth, pgid }) => ({ pid, birth, pgid }))
527
+ }),
528
+ idle: () => publish?.({ phase: "idle" }),
529
+ assertQuiescent: () => {
530
+ }
531
+ },
532
+ {
533
+ environment: credentialFreeDoctor ? doctorEnvironment() : { ...process.env, DISABLE_AUTOUPDATER: "1" },
534
+ cwd,
535
+ maxCapturedOutputBytes: 1024 * 1024,
536
+ stdoutOnly: true,
537
+ failedOutput: (bytes) => credentialFreeDoctor ? " Native inventory failed; raw output withheld." : ` Native command output: ${bytes.toString("utf8").slice(-2e3)}`
538
+ }
539
+ );
540
+ return output.toString("utf8");
518
541
  }
519
542
  function sync(path) {
520
- const fd = openSync(path, 'r');
521
- try {
522
- fsyncSync(fd);
523
- }
524
- finally {
525
- closeSync(fd);
526
- }
543
+ const fd = openSync(path, "r");
544
+ try {
545
+ fsyncSync(fd);
546
+ } finally {
547
+ closeSync(fd);
548
+ }
527
549
  }
528
550
  function pluginRoot(target, version) {
529
- return join(target.catalog, 'versions', version, 'plugins', 'ai-delivery');
551
+ return join(target.catalog, "versions", version, "plugins", "ai-delivery");
530
552
  }
531
553
  function unitDirectory(target, version) {
532
- return join(target.catalog, 'versions', version);
554
+ return join(target.catalog, "versions", version);
533
555
  }
534
556
  function tree(root) {
535
- const files = {};
536
- let entries = 0;
537
- const visit = (directory, prefix, depth) => {
538
- if (depth > 16)
539
- throw new Error('Plugin tree exceeds the depth bound.');
540
- for (const name of readdirSync(directory).sort()) {
541
- if (++entries > 4096)
542
- throw new Error('Plugin tree exceeds the entry bound.');
543
- const path = join(directory, name), relative = `${prefix}${name}`, metadata = lstatSync(path);
544
- if (metadata.isSymbolicLink() || (!metadata.isDirectory() && (!metadata.isFile() || metadata.nlink !== 1)))
545
- throw new Error('Plugin tree contains links or special files.');
546
- if (metadata.isDirectory())
547
- visit(path, `${relative}/`, depth + 1);
548
- else {
549
- if (metadata.size > 32 * 1024 ** 2)
550
- throw new Error('Plugin file exceeds the size bound.');
551
- files[relative] = sha(readFileSync(path));
552
- }
553
- }
554
- };
555
- visit(root, '', 0);
556
- return files;
557
+ const files = {};
558
+ let entries = 0;
559
+ const visit = (directory, prefix, depth) => {
560
+ if (depth > 16) throw new Error("Plugin tree exceeds the depth bound.");
561
+ for (const name of readdirSync(directory).sort()) {
562
+ if (++entries > 4096) throw new Error("Plugin tree exceeds the entry bound.");
563
+ const path = join(directory, name), relative = `${prefix}${name}`, metadata = lstatSync(path);
564
+ if (metadata.isSymbolicLink() || !metadata.isDirectory() && (!metadata.isFile() || metadata.nlink !== 1))
565
+ throw new Error("Plugin tree contains links or special files.");
566
+ if (metadata.isDirectory()) visit(path, `${relative}/`, depth + 1);
567
+ else {
568
+ if (metadata.size > 32 * 1024 ** 2) throw new Error("Plugin file exceeds the size bound.");
569
+ files[relative] = sha(readFileSync(path));
570
+ }
571
+ }
572
+ };
573
+ visit(root, "", 0);
574
+ return files;
557
575
  }
558
576
  function verifiedUnit(target, version) {
559
- const directory = unitDirectory(target, version);
560
- assertCanonical(directory);
561
- const path = join(directory, 'version.json');
562
- if (!existsSync(path))
563
- throw new Error(`No completed immutable plugin unit for ${version}.`);
564
- const metadata = lstatSync(path), archive = join(directory, 'archive.tgz'), archiveMetadata = lstatSync(archive);
565
- if (!metadata.isFile() ||
566
- metadata.nlink !== 1 ||
567
- metadata.size > 1024 * 1024 ||
568
- !archiveMetadata.isFile() ||
569
- archiveMetadata.nlink !== 1 ||
570
- archiveMetadata.size > 32 * 1024 ** 2)
571
- throw new Error('Immutable plugin unit metadata is unsafe.');
572
- const unit = Unit.parse(JSON.parse(readFileSync(path, 'utf8')));
573
- if (unit.version !== version ||
574
- JSON.stringify(tree(pluginRoot(target, version))) !== JSON.stringify(unit.files) ||
575
- sha(readFileSync(archive)) !== unit.archiveSha256)
576
- throw new Error('Immutable plugin unit integrity changed.');
577
- return unit;
577
+ const directory = unitDirectory(target, version);
578
+ assertCanonical(directory);
579
+ const path = join(directory, "version.json");
580
+ if (!existsSync(path)) throw new Error(`No completed immutable plugin unit for ${version}.`);
581
+ const metadata = lstatSync(path), archive = join(directory, "archive.tgz"), archiveMetadata = lstatSync(archive);
582
+ if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > 1024 * 1024 || !archiveMetadata.isFile() || archiveMetadata.nlink !== 1 || archiveMetadata.size > 32 * 1024 ** 2)
583
+ throw new Error("Immutable plugin unit metadata is unsafe.");
584
+ const unit = Unit.parse(JSON.parse(readFileSync(path, "utf8")));
585
+ if (unit.version !== version || JSON.stringify(tree(pluginRoot(target, version))) !== JSON.stringify(unit.files) || sha(readFileSync(archive)) !== unit.archiveSha256)
586
+ throw new Error("Immutable plugin unit integrity changed.");
587
+ return unit;
578
588
  }
579
589
  function unpack(bytes) {
580
- if (bytes.length > 32 * 1024 ** 2)
581
- throw new Error('Plugin archive exceeds 32 MiB.');
582
- const tar = gunzipSync(bytes, { maxOutputLength: 128 * 1024 ** 2 });
583
- const files = new Map();
584
- for (let offset = 0; offset + 512 <= tar.length;) {
585
- const header = tar.subarray(offset, offset + 512);
586
- if (header.every((byte) => byte === 0))
587
- break;
588
- const text = (start, length) => header
589
- .subarray(start, start + length)
590
- .toString()
591
- .replace(/\0.*$/su, '')
592
- .trim();
593
- const octal = (start, length) => {
594
- const value = text(start, length);
595
- if (!/^[0-7]+$/u.test(value))
596
- throw new Error('Unsupported tar numeric header.');
597
- return Number.parseInt(value, 8);
598
- };
599
- const checksum = [...header].reduce((sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte), 0);
600
- if (checksum !== octal(148, 8))
601
- throw new Error('Plugin archive header checksum mismatch.');
602
- const name = `${text(345, 155) ? `${text(345, 155)}/` : ''}${text(0, 100)}`, size = octal(124, 12), kind = text(156, 1);
603
- if (!/^package\/[A-Za-z0-9_./-]+$/u.test(name) ||
604
- name.split('/').some((part) => part === '..' || part === '.') ||
605
- name.split('/').length > 16 ||
606
- !['', '0', '5'].includes(kind) ||
607
- offset + 512 + size > tar.length ||
608
- files.has(name) ||
609
- files.size >= 4096)
610
- throw new Error('Unsafe or unsupported plugin archive member.');
611
- if (kind !== '5')
612
- files.set(name, tar.subarray(offset + 512, offset + 512 + size));
613
- offset += 512 + Math.ceil(size / 512) * 512;
614
- }
615
- return files;
590
+ if (bytes.length > 32 * 1024 ** 2) throw new Error("Plugin archive exceeds 32 MiB.");
591
+ const tar = gunzipSync(bytes, { maxOutputLength: 128 * 1024 ** 2 });
592
+ const files = /* @__PURE__ */ new Map();
593
+ for (let offset = 0; offset + 512 <= tar.length; ) {
594
+ const header = tar.subarray(offset, offset + 512);
595
+ if (header.every((byte) => byte === 0)) break;
596
+ const text = (start, length) => header.subarray(start, start + length).toString().replace(/\0.*$/su, "").trim();
597
+ const octal = (start, length) => {
598
+ const value = text(start, length);
599
+ if (!/^[0-7]+$/u.test(value)) throw new Error("Unsupported tar numeric header.");
600
+ return Number.parseInt(value, 8);
601
+ };
602
+ const checksum = [...header].reduce((sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte), 0);
603
+ if (checksum !== octal(148, 8)) throw new Error("Plugin archive header checksum mismatch.");
604
+ const name = `${text(345, 155) ? `${text(345, 155)}/` : ""}${text(0, 100)}`, size = octal(124, 12), kind = text(156, 1);
605
+ if (!/^package\/[A-Za-z0-9_./-]+$/u.test(name) || name.split("/").some((part) => part === ".." || part === ".") || name.split("/").length > 16 || !["", "0", "5"].includes(kind) || offset + 512 + size > tar.length || files.has(name) || files.size >= 4096)
606
+ throw new Error("Unsafe or unsupported plugin archive member.");
607
+ if (kind !== "5") files.set(name, tar.subarray(offset + 512, offset + 512 + size));
608
+ offset += 512 + Math.ceil(size / 512) * 512;
609
+ }
610
+ return files;
616
611
  }
617
612
  async function stageVersion(target, version, signal, publish, staging) {
618
- const unit = unitDirectory(target, version);
619
- if (existsSync(unit)) {
620
- verifiedUnit(target, version);
621
- return;
622
- }
623
- const parent = dirname(unit);
624
- ensurePrivateDirectoryDurably(parent);
625
- const temporary = join(parent, `.stage-${randomUUID()}`);
626
- staging({ path: temporary });
627
- mkdirSync(temporary, { mode: 0o700 });
628
- const allocation = lstatSync(temporary);
613
+ const unit = unitDirectory(target, version);
614
+ if (existsSync(unit)) {
615
+ verifiedUnit(target, version);
616
+ return;
617
+ }
618
+ const parent = dirname(unit);
619
+ ensurePrivateDirectoryDurably(parent);
620
+ const temporary = join(parent, `.stage-${randomUUID()}`);
621
+ staging({ path: temporary });
622
+ mkdirSync(temporary, { mode: 448 });
623
+ const allocation = lstatSync(temporary);
624
+ sync(parent);
625
+ staging({ path: temporary, device: allocation.dev, inode: allocation.ino });
626
+ let quiescent = true;
627
+ let failed = false;
628
+ let failure;
629
+ const unitPublish = (value) => {
630
+ quiescent = value.phase === "idle";
631
+ publish(value);
632
+ };
633
+ try {
634
+ const packed = JSON.parse(
635
+ await command(
636
+ "npm",
637
+ [
638
+ "pack",
639
+ `@aviaratech/ai-delivery@${version}`,
640
+ "--ignore-scripts",
641
+ "--json",
642
+ "--logs-max",
643
+ "0",
644
+ "--cache",
645
+ join(target.directory, "npm-cache"),
646
+ "--pack-destination",
647
+ temporary
648
+ ],
649
+ temporary,
650
+ signal,
651
+ unitPublish
652
+ )
653
+ );
654
+ const filename = packed[0]?.filename;
655
+ if (typeof filename !== "string" || !/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(filename))
656
+ throw new Error("npm returned an unsafe archive path.");
657
+ const bytes = readFileSync(join(temporary, filename)), files = unpack(bytes);
658
+ const packageInfo = JSON.parse(files.get("package/package.json")?.toString() ?? "null");
659
+ if (packageInfo?.name !== "@aviaratech/ai-delivery" || packageInfo.version !== version)
660
+ throw new Error("Archive package identity does not match the explicit version.");
661
+ const prefix = "package/plugins/ai-delivery/";
662
+ const destination = join(temporary, "plugins", "ai-delivery");
663
+ for (const [name, content] of files)
664
+ if (name.startsWith(prefix)) {
665
+ const path = join(destination, name.slice(prefix.length));
666
+ ensurePrivateDirectoryDurably(dirname(path));
667
+ writeFileSync(path, content, { mode: 384, flag: "wx" });
668
+ sync(path);
669
+ }
670
+ const portable = JSON.parse(readFileSync(join(destination, "plugin.json"), "utf8"));
671
+ const native = JSON.parse(readFileSync(join(destination, ".claude-plugin/plugin.json"), "utf8"));
672
+ const runtime = JSON.parse(readFileSync(join(destination, "runtime/package.json"), "utf8"));
673
+ if (portable.name !== "ai-delivery" || portable.version !== version || native.name !== portable.name || native.version !== version || native.packageVersion !== version || native.deliveryCapabilityVersion !== 2 || runtime.name !== packageInfo.name || runtime.version !== version)
674
+ throw new Error("Archive does not contain a coherent self-contained native plugin.");
675
+ if ((await command(
676
+ process.execPath,
677
+ [join(destination, "runtime/dist/cli.js"), "--version"],
678
+ temporary,
679
+ signal,
680
+ unitPublish
681
+ )).trim() !== version)
682
+ throw new Error("Built native CLI version does not match its archive.");
683
+ renameSync(join(temporary, filename), join(temporary, "archive.tgz"));
684
+ sync(join(temporary, "archive.tgz"));
685
+ writePrivateJsonFileAtomically(join(temporary, "version.json"), {
686
+ owner: "@aviaratech/ai-delivery.plugin-version@1",
687
+ version,
688
+ archiveSha256: sha(bytes),
689
+ files: tree(destination)
690
+ });
691
+ renameSync(temporary, unit);
629
692
  sync(parent);
630
- staging({ path: temporary, device: allocation.dev, inode: allocation.ino });
631
- let quiescent = true;
632
- let failed = false;
633
- let failure;
634
- const unitPublish = (value) => {
635
- quiescent = value.phase === 'idle';
636
- publish(value);
637
- };
638
- try {
639
- const packed = JSON.parse(await command('npm', [
640
- 'pack',
641
- `@aviaratech/ai-delivery@${version}`,
642
- '--ignore-scripts',
643
- '--json',
644
- '--logs-max',
645
- '0',
646
- '--cache',
647
- join(target.directory, 'npm-cache'),
648
- '--pack-destination',
649
- temporary,
650
- ], temporary, signal, unitPublish));
651
- const filename = packed[0]?.filename;
652
- if (typeof filename !== 'string' || !/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(filename))
653
- throw new Error('npm returned an unsafe archive path.');
654
- const bytes = readFileSync(join(temporary, filename)), files = unpack(bytes);
655
- const packageInfo = JSON.parse(files.get('package/package.json')?.toString() ?? 'null');
656
- if (packageInfo?.name !== '@aviaratech/ai-delivery' || packageInfo.version !== version)
657
- throw new Error('Archive package identity does not match the explicit version.');
658
- const prefix = 'package/plugins/ai-delivery/';
659
- const destination = join(temporary, 'plugins', 'ai-delivery');
660
- for (const [name, content] of files)
661
- if (name.startsWith(prefix)) {
662
- const path = join(destination, name.slice(prefix.length));
663
- ensurePrivateDirectoryDurably(dirname(path));
664
- writeFileSync(path, content, { mode: 0o600, flag: 'wx' });
665
- sync(path);
666
- }
667
- const portable = JSON.parse(readFileSync(join(destination, 'plugin.json'), 'utf8'));
668
- const native = JSON.parse(readFileSync(join(destination, '.claude-plugin/plugin.json'), 'utf8'));
669
- const runtime = JSON.parse(readFileSync(join(destination, 'runtime/package.json'), 'utf8'));
670
- if (portable.name !== 'ai-delivery' ||
671
- portable.version !== version ||
672
- native.name !== portable.name ||
673
- native.version !== version ||
674
- native.packageVersion !== version ||
675
- native.deliveryCapabilityVersion !== 2 ||
676
- runtime.name !== packageInfo.name ||
677
- runtime.version !== version)
678
- throw new Error('Archive does not contain a coherent self-contained native plugin.');
679
- if ((await command(process.execPath, [join(destination, 'runtime/dist/cli.js'), '--version'], temporary, signal, unitPublish)).trim() !== version)
680
- throw new Error('Built native CLI version does not match its archive.');
681
- renameSync(join(temporary, filename), join(temporary, 'archive.tgz'));
682
- sync(join(temporary, 'archive.tgz'));
683
- writePrivateJsonFileAtomically(join(temporary, 'version.json'), {
684
- owner: '@aviaratech/ai-delivery.plugin-version@1',
685
- version,
686
- archiveSha256: sha(bytes),
687
- files: tree(destination),
688
- });
689
- renameSync(temporary, unit);
690
- sync(parent);
691
- staging(undefined);
692
- verifiedUnit(target, version);
693
- }
694
- catch (error) {
695
- failed = true;
696
- failure = error;
697
- }
698
- try {
699
- if (quiescent && existsSync(temporary)) {
700
- const current = lstatSync(temporary);
701
- if (current.dev !== allocation.dev ||
702
- current.ino !== allocation.ino ||
703
- !current.isDirectory() ||
704
- current.isSymbolicLink())
705
- throw new Error('Owned staging directory identity changed.');
706
- rmSync(temporary, { recursive: true });
707
- sync(parent);
708
- }
709
- if (quiescent)
710
- staging(undefined);
711
- }
712
- catch (error) {
713
- failure = failed
714
- ? new AggregateError([failure, error], 'Plugin preparation failed and staging cleanup also failed.')
715
- : error;
716
- failed = true;
693
+ staging(void 0);
694
+ verifiedUnit(target, version);
695
+ } catch (error) {
696
+ failed = true;
697
+ failure = error;
698
+ }
699
+ try {
700
+ if (quiescent && existsSync(temporary)) {
701
+ const current = lstatSync(temporary);
702
+ if (current.dev !== allocation.dev || current.ino !== allocation.ino || !current.isDirectory() || current.isSymbolicLink())
703
+ throw new Error("Owned staging directory identity changed.");
704
+ rmSync(temporary, { recursive: true });
705
+ sync(parent);
717
706
  }
718
- if (failed)
719
- throw failure;
707
+ if (quiescent) staging(void 0);
708
+ } catch (error) {
709
+ failure = failed ? new AggregateError([failure, error], "Plugin preparation failed and staging cleanup also failed.") : error;
710
+ failed = true;
711
+ }
712
+ if (failed) throw failure;
720
713
  }
721
714
  function catalogDocuments(target, version) {
722
- const source = `./versions/${version}/plugins/ai-delivery`;
723
- const { codexDocument, claudeDocument } = marketplaceDocuments({
724
- marketplaceName: target.marketplace,
725
- pluginName: 'ai-delivery',
726
- relativeSource: source,
727
- version,
728
- ownerName: 'AviaraTech',
729
- metadata: {
730
- kind: 'interface-policy',
731
- displayName: 'ai-delivery',
732
- policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' },
733
- category: 'Productivity',
734
- },
735
- });
736
- return [
737
- {
738
- path: join(target.catalog, '.agents/plugins/marketplace.json'),
739
- value: codexDocument,
740
- },
741
- {
742
- path: join(target.catalog, '.claude-plugin/marketplace.json'),
743
- value: claudeDocument,
744
- },
745
- ];
715
+ const source = `./versions/${version}/plugins/ai-delivery`;
716
+ const { codexDocument, claudeDocument } = marketplaceDocuments({
717
+ marketplaceName: target.marketplace,
718
+ pluginName: "ai-delivery",
719
+ relativeSource: source,
720
+ version,
721
+ ownerName: "AviaraTech",
722
+ metadata: {
723
+ kind: "interface-policy",
724
+ displayName: "ai-delivery",
725
+ policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
726
+ category: "Productivity"
727
+ }
728
+ });
729
+ return [
730
+ {
731
+ path: join(target.catalog, ".agents/plugins/marketplace.json"),
732
+ value: codexDocument
733
+ },
734
+ {
735
+ path: join(target.catalog, ".claude-plugin/marketplace.json"),
736
+ value: claudeDocument
737
+ }
738
+ ];
746
739
  }
747
740
  function readCatalog(target, version) {
748
- return catalogDocuments(target, version).map(({ path }) => {
749
- assertCanonical(path);
750
- const metadata = lstatSync(path);
751
- if (!metadata.isFile() || metadata.nlink !== 1 || (metadata.mode & 0o777) !== 0o600 || metadata.size > 1024 ** 2)
752
- throw new Error('Managed catalog is unsafe.');
753
- return { path, bytes: readFileSync(path), device: metadata.dev, inode: metadata.ino };
754
- });
741
+ return catalogDocuments(target, version).map(({ path }) => {
742
+ assertCanonical(path);
743
+ const metadata = lstatSync(path);
744
+ if (!metadata.isFile() || metadata.nlink !== 1 || (metadata.mode & 511) !== 384 || metadata.size > 1024 ** 2)
745
+ throw new Error("Managed catalog is unsafe.");
746
+ return { path, bytes: readFileSync(path), device: metadata.dev, inode: metadata.ino };
747
+ });
755
748
  }
756
749
  function catalogMatches(snapshot, target, version) {
757
- return catalogDocuments(target, version).map(({ value }, index) => JSON.stringify(JSON.parse(snapshot[index].bytes.toString())) === JSON.stringify(value));
750
+ return catalogDocuments(target, version).map(
751
+ ({ value }, index) => JSON.stringify(JSON.parse(snapshot[index].bytes.toString())) === JSON.stringify(value)
752
+ );
758
753
  }
759
754
  function assertCatalogUnchanged(entry) {
760
- assertCanonical(entry.path);
761
- const current = lstatSync(entry.path);
762
- if (!current.isFile() ||
763
- current.nlink !== 1 ||
764
- (current.mode & 0o777) !== 0o600 ||
765
- current.size !== entry.bytes.length ||
766
- current.dev !== entry.device ||
767
- current.ino !== entry.inode ||
768
- !readFileSync(entry.path).equals(entry.bytes))
769
- throw new Error('Managed catalog changed during this operation.');
755
+ assertCanonical(entry.path);
756
+ const current = lstatSync(entry.path);
757
+ if (!current.isFile() || current.nlink !== 1 || (current.mode & 511) !== 384 || current.size !== entry.bytes.length || current.dev !== entry.device || current.ino !== entry.inode || !readFileSync(entry.path).equals(entry.bytes))
758
+ throw new Error("Managed catalog changed during this operation.");
770
759
  }
771
760
  function catalog(target, version, expected) {
772
- verifiedUnit(target, version);
773
- for (const [index, document] of catalogDocuments(target, version).entries()) {
774
- if (expected)
775
- assertCatalogUnchanged(expected[index]);
776
- writePrivateJsonFileAtomically(document.path, document.value);
777
- }
761
+ verifiedUnit(target, version);
762
+ for (const [index, document] of catalogDocuments(target, version).entries()) {
763
+ if (expected) assertCatalogUnchanged(expected[index]);
764
+ writePrivateJsonFileAtomically(document.path, document.value);
765
+ }
778
766
  }
779
767
  async function inventory(input, target, signal, publish, allPlugins = false) {
780
- const value = JSON.parse(await command(target.tool, [
781
- 'plugin',
782
- 'list',
783
- ...(input.host === 'codex' && !allPlugins ? ['--marketplace', target.marketplace, '--available'] : []),
784
- '--json',
785
- ], target.projectRoot, signal, publish, input.action === 'doctor'));
786
- if (input.host === 'claude-code')
787
- return z.array(z.record(z.string(), z.unknown())).parse(value);
788
- const all = z
789
- .object({
790
- installed: z.array(z.record(z.string(), z.unknown())),
791
- available: z.array(z.record(z.string(), z.unknown())),
792
- })
793
- .parse(value);
794
- return [
795
- ...all.installed.map((entry) => ({ ...entry, installed: true })),
796
- ...all.available.map((entry) => ({ ...entry, installed: false })),
797
- ];
768
+ const value = JSON.parse(
769
+ await command(
770
+ target.tool,
771
+ [
772
+ "plugin",
773
+ "list",
774
+ ...input.host === "codex" && !allPlugins ? ["--marketplace", target.marketplace, "--available"] : [],
775
+ "--json"
776
+ ],
777
+ target.projectRoot,
778
+ signal,
779
+ publish,
780
+ input.action === "doctor"
781
+ )
782
+ );
783
+ if (input.host === "claude-code") return z.array(z.record(z.string(), z.unknown())).parse(value);
784
+ const all = z.object({
785
+ installed: z.array(z.record(z.string(), z.unknown())),
786
+ available: z.array(z.record(z.string(), z.unknown()))
787
+ }).parse(value);
788
+ return [
789
+ ...all.installed.map((entry) => ({ ...entry, installed: true })),
790
+ ...all.available.map((entry) => ({ ...entry, installed: false }))
791
+ ];
798
792
  }
799
793
  function registration(input, target, entries) {
800
- if (input.host === 'claude-code') {
801
- const path = join(target.nativeHome, 'plugins/known_marketplaces.json');
802
- if (!existsSync(path))
803
- return false;
804
- if (!lstatSync(path).isFile() || lstatSync(path).size > 1024 * 1024)
805
- throw new Error('Native marketplace registry is unsafe.');
806
- const markets = z.record(z.string(), z.unknown()).parse(JSON.parse(readFileSync(path, 'utf8')));
807
- if (markets[target.marketplace] === undefined)
808
- return false;
809
- const selected = z
810
- .object({ source: z.object({ source: z.literal('directory'), path: z.string() }), installLocation: z.string() })
811
- .parse(markets[target.marketplace]);
812
- if (resolve(selected.source.path) !== target.catalog || resolve(selected.installLocation) !== target.catalog)
813
- throw new Error('Native marketplace name belongs to an unmanaged source.');
814
- return true;
815
- }
816
- const selected = entries.filter((entry) => entry.marketplaceName === target.marketplace);
817
- for (const entry of selected) {
818
- const source = z.object({ sourceType: z.literal('local'), source: z.string() }).parse(entry.marketplaceSource);
819
- if (resolve(source.source) !== target.catalog)
820
- throw new Error('Native marketplace name belongs to an unmanaged source.');
821
- }
822
- return selected.length > 0;
794
+ if (input.host === "claude-code") {
795
+ const path = join(target.nativeHome, "plugins/known_marketplaces.json");
796
+ if (!existsSync(path)) return false;
797
+ if (!lstatSync(path).isFile() || lstatSync(path).size > 1024 * 1024)
798
+ throw new Error("Native marketplace registry is unsafe.");
799
+ const markets = z.record(z.string(), z.unknown()).parse(JSON.parse(readFileSync(path, "utf8")));
800
+ if (markets[target.marketplace] === void 0) return false;
801
+ const selected2 = z.object({ source: z.object({ source: z.literal("directory"), path: z.string() }), installLocation: z.string() }).parse(markets[target.marketplace]);
802
+ if (resolve(selected2.source.path) !== target.catalog || resolve(selected2.installLocation) !== target.catalog)
803
+ throw new Error("Native marketplace name belongs to an unmanaged source.");
804
+ return true;
805
+ }
806
+ const selected = entries.filter((entry) => entry.marketplaceName === target.marketplace);
807
+ for (const entry of selected) {
808
+ const source = z.object({ sourceType: z.literal("local"), source: z.string() }).parse(entry.marketplaceSource);
809
+ if (resolve(source.source) !== target.catalog)
810
+ throw new Error("Native marketplace name belongs to an unmanaged source.");
811
+ }
812
+ return selected.length > 0;
823
813
  }
824
814
  function nativeEntry(input, target, entries) {
825
- const matches = entries.filter((entry) => (entry.pluginId ?? entry.id) === `ai-delivery@${target.marketplace}` &&
826
- (input.host === 'codex' ? entry.installed === true : entry.scope === input.scope) &&
827
- (input.scope === 'user' || entry.projectPath === target.projectRoot));
828
- if (matches.length > 1)
829
- throw new Error('Native plugin readback is ambiguous.');
830
- const entry = matches[0];
831
- if (!entry)
832
- return undefined;
833
- const sourceRoot = input.host === 'codex'
834
- ? z.object({ source: z.literal('local'), path: z.string() }).parse(entry.source).path
835
- : undefined;
836
- return {
837
- registration: entry,
838
- version: Version.parse(entry.version),
839
- enabled: z.boolean().parse(entry.enabled),
840
- ...(typeof entry.installPath === 'string' ? { installedPath: entry.installPath } : {}),
841
- ...(sourceRoot ? { sourceRoot } : {}),
842
- ...(entry.mcpServers ? { mcpServers: z.record(z.string(), z.unknown()).parse(entry.mcpServers) } : {}),
843
- };
815
+ const matches = entries.filter(
816
+ (entry2) => (entry2.pluginId ?? entry2.id) === `ai-delivery@${target.marketplace}` && (input.host === "codex" ? entry2.installed === true : entry2.scope === input.scope) && (input.scope === "user" || entry2.projectPath === target.projectRoot)
817
+ );
818
+ if (matches.length > 1) throw new Error("Native plugin readback is ambiguous.");
819
+ const entry = matches[0];
820
+ if (!entry) return void 0;
821
+ const sourceRoot = input.host === "codex" ? z.object({ source: z.literal("local"), path: z.string() }).parse(entry.source).path : void 0;
822
+ return {
823
+ registration: entry,
824
+ version: Version.parse(entry.version),
825
+ enabled: z.boolean().parse(entry.enabled),
826
+ ...typeof entry.installPath === "string" ? { installedPath: entry.installPath } : {},
827
+ ...sourceRoot ? { sourceRoot } : {},
828
+ ...entry.mcpServers ? { mcpServers: z.record(z.string(), z.unknown()).parse(entry.mcpServers) } : {}
829
+ };
844
830
  }
845
831
  function claudeCatalogSelection(target) {
846
- const path = join(target.catalog, '.claude-plugin/marketplace.json');
847
- assertCanonical(path);
848
- if (!lstatSync(path).isFile() || lstatSync(path).size > 1024 * 1024)
849
- throw new Error('Managed Claude catalog is unsafe.');
850
- const catalog = z
851
- .object({
852
- name: z.literal(target.marketplace),
853
- plugins: z.array(z.object({ name: z.string(), version: Version, source: z.string() })),
854
- })
855
- .parse(JSON.parse(readFileSync(path, 'utf8')));
856
- const entries = catalog.plugins.filter((entry) => entry.name === 'ai-delivery');
857
- if (entries.length !== 1)
858
- throw new Error('Managed Claude catalog selection is ambiguous.');
859
- const entry = entries[0];
860
- if (!entry.source.startsWith('./') || resolve(target.catalog, entry.source) !== pluginRoot(target, entry.version))
861
- throw new Error('Claude catalog source differs from the immutable managed unit.');
862
- return entry;
832
+ const path = join(target.catalog, ".claude-plugin/marketplace.json");
833
+ assertCanonical(path);
834
+ if (!lstatSync(path).isFile() || lstatSync(path).size > 1024 * 1024)
835
+ throw new Error("Managed Claude catalog is unsafe.");
836
+ const catalog2 = z.object({
837
+ name: z.literal(target.marketplace),
838
+ plugins: z.array(z.object({ name: z.string(), version: Version, source: z.string() }))
839
+ }).parse(JSON.parse(readFileSync(path, "utf8")));
840
+ const entries = catalog2.plugins.filter((entry2) => entry2.name === "ai-delivery");
841
+ if (entries.length !== 1) throw new Error("Managed Claude catalog selection is ambiguous.");
842
+ const entry = entries[0];
843
+ if (!entry.source.startsWith("./") || resolve(target.catalog, entry.source) !== pluginRoot(target, entry.version))
844
+ throw new Error("Claude catalog source differs from the immutable managed unit.");
845
+ return entry;
863
846
  }
864
847
  function selectedRoot(input, target, entry, cachePath, sourceVersion = entry.version) {
865
- const unit = verifiedUnit(target, entry.version), source = pluginRoot(target, sourceVersion);
866
- if (sourceVersion !== entry.version)
867
- verifiedUnit(target, sourceVersion);
868
- if (input.host === 'claude-code' && claudeCatalogSelection(target).version !== sourceVersion)
869
- throw new Error('Claude catalog version differs from its native selection.');
870
- if (input.host === 'codex' && resolve(entry.sourceRoot) !== source)
871
- throw new Error('Native plugin source differs from the managed version.');
872
- const root = cachePath;
873
- if (!root)
874
- throw new Error('Native cache path is missing.');
875
- if (input.host === 'claude-code' &&
876
- (entry.installedPath === undefined || resolve(entry.installedPath) !== resolve(root)))
877
- throw new Error('Native cache path differs from the managed native selection.');
878
- if (resolve(root) !== join(target.nativeHome, 'plugins/cache', target.marketplace, 'ai-delivery', entry.version))
879
- throw new Error('Native cache path is outside the managed native selection.');
880
- assertCanonical(root);
881
- if (JSON.stringify(tree(root)) !== JSON.stringify(unit.files))
882
- throw new Error('Selected native plugin bytes differ from the verified archive.');
883
- if (input.host === 'claude-code') {
884
- const server = z
885
- .object({ command: z.literal('node'), args: z.tuple([z.literal('${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js')]) })
886
- .parse(entry.mcpServers?.['ai-delivery']);
887
- if (!server)
888
- throw new Error('Native MCP binding is missing.');
889
- }
890
- return root;
848
+ const unit = verifiedUnit(target, entry.version), source = pluginRoot(target, sourceVersion);
849
+ if (sourceVersion !== entry.version) verifiedUnit(target, sourceVersion);
850
+ if (input.host === "claude-code" && claudeCatalogSelection(target).version !== sourceVersion)
851
+ throw new Error("Claude catalog version differs from its native selection.");
852
+ if (input.host === "codex" && resolve(entry.sourceRoot) !== source)
853
+ throw new Error("Native plugin source differs from the managed version.");
854
+ const root = cachePath;
855
+ if (!root) throw new Error("Native cache path is missing.");
856
+ if (input.host === "claude-code" && (entry.installedPath === void 0 || resolve(entry.installedPath) !== resolve(root)))
857
+ throw new Error("Native cache path differs from the managed native selection.");
858
+ if (resolve(root) !== join(target.nativeHome, "plugins/cache", target.marketplace, "ai-delivery", entry.version))
859
+ throw new Error("Native cache path is outside the managed native selection.");
860
+ assertCanonical(root);
861
+ if (JSON.stringify(tree(root)) !== JSON.stringify(unit.files))
862
+ throw new Error("Selected native plugin bytes differ from the verified archive.");
863
+ if (input.host === "claude-code") {
864
+ const server = z.object({ command: z.literal("node"), args: z.tuple([z.literal("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")]) }).parse(entry.mcpServers?.["ai-delivery"]);
865
+ if (!server) throw new Error("Native MCP binding is missing.");
866
+ }
867
+ return root;
891
868
  }
892
869
  async function startup(root, version, cwd) {
893
- const transport = new StdioClientTransport({
894
- command: process.execPath,
895
- args: [join(root, 'dist/mcp-launcher.js')],
896
- cwd,
897
- // The SDK merges its default inherited names even when env is supplied.
898
- // Explicitly mask every one; startup needs no caller environment values.
899
- env: {
900
- ...Object.fromEntries(DEFAULT_INHERITED_ENV_VARS.map((name) => [name, ''])),
901
- NODE_OPTIONS: '--max-old-space-size=1024',
902
- },
903
- stderr: 'pipe',
904
- maxBufferSize: 1024 * 1024,
905
- });
906
- const client = new Client({ name: 'ai-delivery-plugin-doctor', version: '1.0.0' });
870
+ const transport = new StdioClientTransport({
871
+ command: process.execPath,
872
+ args: [join(root, "dist/mcp-launcher.js")],
873
+ cwd,
874
+ // The SDK merges its default inherited names even when env is supplied.
875
+ // Explicitly mask every one; startup needs no caller environment values.
876
+ env: {
877
+ ...Object.fromEntries(DEFAULT_INHERITED_ENV_VARS.map((name) => [name, ""])),
878
+ NODE_OPTIONS: "--max-old-space-size=1024"
879
+ },
880
+ stderr: "pipe",
881
+ maxBufferSize: 1024 * 1024
882
+ });
883
+ const client = new Client({ name: "ai-delivery-plugin-doctor", version: "1.0.0" });
884
+ try {
885
+ await client.connect(transport, { timeout: 3e4 });
886
+ if (client.getServerVersion()?.version !== version)
887
+ throw new Error("MCP server version differs from the selected archive.");
888
+ await client.listTools({}, { timeout: 3e4 });
889
+ return { configuration: "native_manifest_present", startup: "ready", version };
890
+ } catch {
891
+ return {
892
+ configuration: "native_manifest_present",
893
+ startup: "failed",
894
+ error: "Bundled MCP startup failed; raw output withheld."
895
+ };
896
+ } finally {
897
+ await client.close();
898
+ await transport.close();
899
+ }
900
+ }
901
+ async function managePlugin(value) {
902
+ const input = InputSchema.parse(value);
903
+ if (input.checkAuth && input.action !== "doctor") throw new Error("--check-auth is supported only for doctor.");
904
+ if (input.checkAuth && input.repo === void 0)
905
+ throw new Error("doctor --check-auth requires explicit --repo owner/name.");
906
+ if (input.host === "codex" && input.scope !== "user")
907
+ throw new Error("Codex currently supports user plugin installation; select --scope user.");
908
+ if ((input.action === "install" || input.action === "update") && input.version === void 0)
909
+ throw new Error("An explicit --version is required for install and update.");
910
+ if (input.version !== void 0 && input.action !== "install" && input.action !== "update")
911
+ throw new Error(
912
+ "--version is supported only for install and update; rollback selects the recorded previous version."
913
+ );
914
+ if (!["darwin", "linux"].includes(process.platform))
915
+ throw new Error("Plugin management requires the supported POSIX runtime environment.");
916
+ const target = targetFor(input);
917
+ let state = readState(input, target);
918
+ const result = {
919
+ action: input.action,
920
+ host: input.host,
921
+ scope: input.scope,
922
+ version: input.action === "remove" ? null : input.version ?? (input.action === "rollback" ? state?.previousVersion : state?.currentVersion) ?? null,
923
+ changed: false,
924
+ dryRun: input.dryRun,
925
+ installed: false,
926
+ marketplace: target.marketplace,
927
+ managedDirectory: target.directory,
928
+ repositoryAdmission: "explicit_stage_and_admit_required"
929
+ };
930
+ if (input.checkAuth)
931
+ result.authProbe = {
932
+ invocationContext: "selected_runtime_cli",
933
+ nativeGuiPropagation: "unverified",
934
+ settings: "not_checked",
935
+ processReferences: { status: "not_checked", requiredNames: [], missingNames: [] },
936
+ authentication: { status: "not_checked" },
937
+ repositoryAccess: { repository: input.repo, status: "not_checked" },
938
+ outcome: input.dryRun ? "not_checked" : "blocked",
939
+ reason: input.dryRun ? "dry_run" : "native_plugin_not_ready"
940
+ };
941
+ if (input.dryRun) return result;
942
+ result.diagnostics = sourceDiagnostics(input, target);
943
+ result.activation = { installedVersion: null, startupVersion: null, loadedVersion: null };
944
+ if (input.action === "preview") return result;
945
+ if (input.action === "doctor") {
946
+ if (state) result.recoveryRequired = state.pending !== void 0;
947
+ if (state?.pending) return result;
948
+ if (!state?.currentVersion) {
949
+ try {
950
+ observeNativePlugins(
951
+ result,
952
+ input,
953
+ target,
954
+ await inventory(input, target, new AbortController().signal, void 0, true)
955
+ );
956
+ } catch {
957
+ result.diagnostics.nativeInventory = "unavailable";
958
+ result.diagnostics.findings.push("native_inventory_unavailable");
959
+ }
960
+ return publishedVersionDiagnostics(result);
961
+ }
907
962
  try {
908
- await client.connect(transport, { timeout: 30000 });
909
- if (client.getServerVersion()?.version !== version)
910
- throw new Error('MCP server version differs from the selected archive.');
911
- await client.listTools({}, { timeout: 30000 });
912
- return { configuration: 'native_manifest_present', startup: 'ready', version };
963
+ verifiedUnit(target, state.currentVersion);
964
+ } catch {
965
+ result.sourceIntegrity = false;
966
+ result.mcp = { configuration: "unverified", startup: "not_checked", error: "Managed archive integrity failed." };
967
+ return result;
913
968
  }
914
- catch {
915
- return {
916
- configuration: 'native_manifest_present',
917
- startup: 'failed',
918
- error: 'Bundled MCP startup failed; raw output withheld.',
919
- };
969
+ const entries = await inventory(input, target, new AbortController().signal);
970
+ const registered = registration(input, target, entries), entry = nativeEntry(input, target, entries);
971
+ result.installed = entry?.version === state.currentVersion;
972
+ result.enabled = entry?.enabled ?? false;
973
+ if (state.installedPath) result.nativeCachePath = state.installedPath;
974
+ if (state.nativeVersion) result.nativeVersion = state.nativeVersion;
975
+ if (!registered || !result.installed) {
976
+ result.mcp = { configuration: "missing", startup: "not_checked" };
977
+ try {
978
+ observeNativePlugins(
979
+ result,
980
+ input,
981
+ target,
982
+ await inventory(input, target, new AbortController().signal, void 0, true)
983
+ );
984
+ } catch {
985
+ result.diagnostics.nativeInventory = "unavailable";
986
+ result.diagnostics.findings.push("native_inventory_unavailable");
987
+ }
988
+ return publishedVersionDiagnostics(result);
920
989
  }
921
- finally {
922
- await client.close();
923
- await transport.close();
990
+ result.activation.installedVersion = state.currentVersion;
991
+ try {
992
+ result.nativePluginRoot = selectedRoot(input, target, entry, state.installedPath);
993
+ result.sourceIntegrity = true;
994
+ result.skills = readdirSync(join(result.nativePluginRoot, "skills")).sort();
995
+ result.mcp = entry.enabled ? await startup(result.nativePluginRoot, state.currentVersion, target.projectRoot) : { configuration: "disabled", startup: "not_checked" };
996
+ } catch (error) {
997
+ result.sourceIntegrity = false;
998
+ result.mcp = {
999
+ configuration: "unverified",
1000
+ startup: "not_checked",
1001
+ error: input.checkAuth ? "Selected native plugin integrity failed; raw output withheld." : (error instanceof Error ? error.message : String(error)).slice(0, 2e3)
1002
+ };
924
1003
  }
925
- }
926
- export async function managePlugin(value) {
927
- const input = InputSchema.parse(value);
928
- if (input.checkAuth && input.action !== 'doctor')
929
- throw new Error('--check-auth is supported only for doctor.');
930
- if (input.checkAuth && input.repo === undefined)
931
- throw new Error('doctor --check-auth requires explicit --repo owner/name.');
932
- if (input.host === 'codex' && input.scope !== 'user')
933
- throw new Error('Codex currently supports user plugin installation; select --scope user.');
934
- if ((input.action === 'install' || input.action === 'update') && input.version === undefined)
935
- throw new Error('An explicit --version is required for install and update.');
936
- if (input.version !== undefined && input.action !== 'install' && input.action !== 'update')
937
- throw new Error('--version is supported only for install and update; rollback selects the recorded previous version.');
938
- if (!['darwin', 'linux'].includes(process.platform))
939
- throw new Error('Plugin management requires the supported POSIX runtime environment.');
940
- const target = targetFor(input);
941
- let state = readState(input, target);
942
- const result = {
943
- action: input.action,
1004
+ observeNativePlugins(result, input, target, entries, entry.registration);
1005
+ if (input.host === "codex") {
1006
+ try {
1007
+ const global = await inventory(input, target, new AbortController().signal, void 0, true);
1008
+ const selectedIds = new Set(
1009
+ entries.flatMap((entry2) => typeof entry2.pluginId === "string" ? [entry2.pluginId] : [])
1010
+ );
1011
+ observeNativePlugins(
1012
+ result,
1013
+ input,
1014
+ target,
1015
+ global.filter((entry2) => typeof entry2.pluginId !== "string" || !selectedIds.has(entry2.pluginId))
1016
+ );
1017
+ } catch {
1018
+ result.diagnostics.nativeInventory = "unavailable";
1019
+ result.diagnostics.findings.push("native_inventory_unavailable");
1020
+ }
1021
+ }
1022
+ if (result.mcp?.startup === "ready") result.activation.startupVersion = result.mcp.version ?? null;
1023
+ if (result.authProbe && result.sourceIntegrity && result.enabled && result.mcp?.startup === "ready") {
1024
+ delete result.authProbe.reason;
1025
+ await checkAuthentication(input, result.nativePluginRoot, result.authProbe);
1026
+ }
1027
+ return publishedVersionDiagnostics(result);
1028
+ }
1029
+ if (!state && input.action === "remove") return result;
1030
+ if (!state && existsSync(target.directory) && readdirSync(target.directory).length > 0)
1031
+ throw new Error("Managed plugin directory contains unrecognized content.");
1032
+ ensurePrivateDirectoryDurably(target.directory);
1033
+ return withLock(target.statePath, {
1034
+ projectRoot: target.directory,
1035
+ timeout: 200,
1036
+ onReleaseError: (error) => {
1037
+ throw error;
1038
+ },
1039
+ operation: async () => {
1040
+ state = readState(input, target);
1041
+ if (input.action === "rollback") {
1042
+ if (!state?.currentVersion)
1043
+ throw new Error(
1044
+ "Preserving rollback requires a current managed selection; it cannot reinstall a removed plugin."
1045
+ );
1046
+ if (state.previousVersion !== result.version)
1047
+ throw new Error("Managed rollback target changed before acquiring its ownership lock.");
1048
+ }
1049
+ let expectedState = existsSync(target.statePath) ? { bytes: readFileSync(target.statePath), metadata: lstatSync(target.statePath) } : void 0;
1050
+ const persist = () => {
1051
+ assertCanonical(target.statePath);
1052
+ if (expectedState) {
1053
+ readState(input, target);
1054
+ const current = lstatSync(target.statePath);
1055
+ if (current.dev !== expectedState.metadata.dev || current.ino !== expectedState.metadata.ino || (current.mode & 511) !== 384 || current.mode !== expectedState.metadata.mode || !readFileSync(target.statePath).equals(expectedState.bytes))
1056
+ throw new Error("Managed state changed during this operation.");
1057
+ } else if (existsSync(target.statePath)) {
1058
+ throw new Error("Managed state appeared during this operation.");
1059
+ }
1060
+ writePrivateJsonFileAtomically(target.statePath, state);
1061
+ expectedState = { bytes: readFileSync(target.statePath), metadata: lstatSync(target.statePath) };
1062
+ };
1063
+ const resuming = state?.pending !== void 0;
1064
+ if (state?.pending) {
1065
+ await recover(state.pending);
1066
+ if (state.pending.producerDigest !== retainedWorktreeTransitionProducerDigest(dirname(fileURLToPath(import.meta.url))))
1067
+ throw new Error(
1068
+ "Interrupted plugin operation belongs to a different controller; resume with its original version."
1069
+ );
1070
+ const allocation = state.pending.staging;
1071
+ if (allocation && existsSync(allocation.path)) {
1072
+ const parent = dirname(unitDirectory(target, state.pending.targetVersion));
1073
+ if (dirname(allocation.path) !== parent || !/^\.stage-[a-f0-9-]{36}$/u.test(allocation.path.slice(parent.length + 1)))
1074
+ throw new Error("Recorded staging path is outside this version target.");
1075
+ assertCanonical(allocation.path);
1076
+ const current = lstatSync(allocation.path);
1077
+ if (!current.isDirectory() || (allocation.device === void 0 ? readdirSync(allocation.path).length !== 0 : current.dev !== allocation.device || current.ino !== allocation.inode))
1078
+ throw new Error("Interrupted staging directory ownership is unresolved.");
1079
+ rmSync(allocation.path, { recursive: true });
1080
+ sync(parent);
1081
+ }
1082
+ if (state.pending.action !== input.action || state.pending.targetVersion !== result.version)
1083
+ throw new Error("Resume the interrupted original plugin command before selecting a different operation.");
1084
+ }
1085
+ if (input.action === "update" && !state?.currentVersion)
1086
+ throw new Error("Install a managed plugin before updating or rolling it back.");
1087
+ const version = input.action === "remove" ? null : result.version;
1088
+ if (version === null && input.action !== "remove")
1089
+ throw new Error("No previous managed plugin version is available.");
1090
+ const prior = state?.currentVersion ?? null;
1091
+ state ??= {
1092
+ owner: "@aviaratech/ai-delivery.plugin@1",
944
1093
  host: input.host,
945
1094
  scope: input.scope,
946
- version: input.action === 'remove'
947
- ? null
948
- : (input.version ?? (input.action === 'rollback' ? state?.previousVersion : state?.currentVersion) ?? null),
949
- changed: false,
950
- dryRun: input.dryRun,
951
- installed: false,
1095
+ projectRoot: input.scope === "user" ? null : target.projectRoot,
1096
+ nativeHome: target.nativeHome,
952
1097
  marketplace: target.marketplace,
953
- managedDirectory: target.directory,
954
- repositoryAdmission: 'explicit_stage_and_admit_required',
955
- };
956
- if (input.checkAuth)
957
- result.authProbe = {
958
- invocationContext: 'selected_runtime_cli',
959
- nativeGuiPropagation: 'unverified',
960
- settings: 'not_checked',
961
- processReferences: { status: 'not_checked', requiredNames: [], missingNames: [] },
962
- authentication: { status: 'not_checked' },
963
- repositoryAccess: { repository: input.repo, status: 'not_checked' },
964
- outcome: input.dryRun ? 'not_checked' : 'blocked',
965
- reason: input.dryRun ? 'dry_run' : 'native_plugin_not_ready',
966
- };
967
- if (input.dryRun)
968
- return result;
969
- result.diagnostics = sourceDiagnostics(input, target);
970
- result.activation = { installedVersion: null, startupVersion: null, loadedVersion: null };
971
- if (input.action === 'preview')
972
- return result;
973
- if (input.action === 'doctor') {
974
- if (state)
975
- result.recoveryRequired = state.pending !== undefined;
976
- if (state?.pending)
977
- return result;
978
- if (!state?.currentVersion) {
979
- try {
980
- observeNativePlugins(result, input, target, await inventory(input, target, new AbortController().signal, undefined, true));
981
- }
982
- catch {
983
- result.diagnostics.nativeInventory = 'unavailable';
984
- result.diagnostics.findings.push('native_inventory_unavailable');
985
- }
986
- return result;
987
- }
988
- try {
989
- verifiedUnit(target, state.currentVersion);
1098
+ currentVersion: null,
1099
+ previousVersion: null,
1100
+ installedPath: null
1101
+ };
1102
+ const birth = identity(process.pid);
1103
+ if (!birth) throw new Error("Installer owner identity is unknown.");
1104
+ state.pending = {
1105
+ action: input.action,
1106
+ targetVersion: version,
1107
+ owner: { pid: process.pid, birth },
1108
+ producerDigest: retainedWorktreeTransitionProducerDigest(dirname(fileURLToPath(import.meta.url))),
1109
+ command: { phase: "idle" }
1110
+ };
1111
+ persist();
1112
+ const controller = new AbortController();
1113
+ const cancel = () => controller.abort();
1114
+ process.once("SIGINT", cancel);
1115
+ process.once("SIGTERM", cancel);
1116
+ const publish = (command2) => {
1117
+ state.pending.command = command2;
1118
+ persist();
1119
+ };
1120
+ const native = (args) => command(target.tool, args, target.projectRoot, controller.signal, publish);
1121
+ const selector = `ai-delivery@${target.marketplace}`;
1122
+ const nativeTarget = input.host === "codex" ? { host: input.host, scope: "user", pluginId: selector } : { host: input.host, scope: input.scope, pluginId: selector };
1123
+ const removeArgs = nativePluginArgs({ ...nativeTarget, action: "remove" });
1124
+ const installArgs = nativePluginArgs({ ...nativeTarget, action: prior ? "update" : "install" });
1125
+ let selectionStarted = false;
1126
+ try {
1127
+ state.nativeVersion = (await native(["--version"])).trim();
1128
+ if (prior && version) {
1129
+ if (input.host === "claude-code") {
1130
+ const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;
1131
+ if (state.nativeVersion !== "2.1.296 (Claude Code)" || input.scope !== "user" || !stable.test(prior) || !stable.test(version) || (version.split(".").map(BigInt).map((part, index) => part - BigInt(prior.split(".")[index])).find((part) => part !== 0n) ?? 0n) < 0n)
1132
+ throw new Error(
1133
+ "Claude preserving replacement is unqualified; no catalog or native selection was changed."
1134
+ );
1135
+ }
1136
+ if (input.host === "codex" && state.nativeVersion !== "codex-cli 0.162.1")
1137
+ throw new Error("This native version has no qualified preserving replacement route.");
990
1138
  }
991
- catch {
992
- result.sourceIntegrity = false;
993
- result.mcp = { configuration: 'unverified', startup: 'not_checked', error: 'Managed archive integrity failed.' };
994
- return result;
1139
+ if (input.host === "claude-code" && !(await native(["plugin", "uninstall", "--help"])).includes("--keep-data"))
1140
+ throw new Error("This Claude Code version cannot preserve plugin data; upgrade the native tool first.");
1141
+ process.stderr.write(
1142
+ `ai-delivery.plugin ${JSON.stringify({ action: input.action, host: input.host, scope: input.scope, stage: version ? "prepare_version" : "native_remove", version })}
1143
+ `
1144
+ );
1145
+ const before = await inventory(input, target, controller.signal, publish);
1146
+ const registered = registration(input, target, before), current = nativeEntry(input, target, before);
1147
+ if (current && !prior && !(resuming && current.version === version))
1148
+ throw new Error("Existing native plugin is not owned by managed state.");
1149
+ let recoverySourceVersion = current?.version;
1150
+ if (current && resuming && input.host === "claude-code") {
1151
+ recoverySourceVersion = claudeCatalogSelection(target).version;
1152
+ if (recoverySourceVersion !== prior && recoverySourceVersion !== version)
1153
+ throw new Error("Interrupted native selection has an incompatible catalog version.");
995
1154
  }
996
- const entries = await inventory(input, target, new AbortController().signal);
997
- const registered = registration(input, target, entries), entry = nativeEntry(input, target, entries);
998
- result.installed = entry?.version === state.currentVersion;
999
- result.enabled = entry?.enabled ?? false;
1000
- if (state.installedPath)
1001
- result.nativeCachePath = state.installedPath;
1002
- if (state.nativeVersion)
1003
- result.nativeVersion = state.nativeVersion;
1004
- if (!registered || !result.installed) {
1005
- result.mcp = { configuration: 'missing', startup: 'not_checked' };
1006
- try {
1007
- observeNativePlugins(result, input, target, await inventory(input, target, new AbortController().signal, undefined, true));
1008
- }
1009
- catch {
1010
- result.diagnostics.nativeInventory = 'unavailable';
1011
- result.diagnostics.findings.push('native_inventory_unavailable');
1012
- }
1013
- return result;
1155
+ if (current && version && !current.enabled)
1156
+ throw new Error("Native plugin selection is disabled; preserving replacement cannot enable it.");
1157
+ let catalogBefore;
1158
+ let reuseSelection = false;
1159
+ if (prior && version) {
1160
+ if (!registered || !current || current.version !== prior && !(resuming && current.version === version))
1161
+ throw new Error("Managed native selection changed; replacement ownership is unresolved.");
1162
+ catalogBefore = readCatalog(target, prior);
1163
+ const priorMatches = catalogMatches(catalogBefore, target, prior);
1164
+ const targetMatches = catalogMatches(catalogBefore, target, version);
1165
+ const priorCatalog = priorMatches.every(Boolean), targetCatalog = targetMatches.every(Boolean);
1166
+ const partialCatalog = resuming && targetMatches[0] && priorMatches[1];
1167
+ if (!priorCatalog && !targetCatalog && !partialCatalog)
1168
+ throw new Error("Managed catalog differs from the owned prior or target publication.");
1169
+ recoverySourceVersion = targetMatches[input.host === "codex" ? 0 : 1] ? version : prior;
1170
+ if (current.version === version) {
1171
+ if (!targetCatalog) throw new Error("Selected target has an incompatible managed catalog.");
1172
+ reuseSelection = true;
1173
+ } else if (targetCatalog) {
1174
+ throw new Error("Interrupted replacement is ambiguous; native selection will not be repeated.");
1175
+ }
1176
+ } else if (version && current && resuming) {
1177
+ catalogBefore = readCatalog(target, version);
1178
+ if (!catalogMatches(catalogBefore, target, version).every(Boolean))
1179
+ throw new Error("Selected target has an incompatible managed catalog.");
1180
+ reuseSelection = current.version === version;
1014
1181
  }
1015
- result.activation.installedVersion = state.currentVersion;
1016
- try {
1017
- result.nativePluginRoot = selectedRoot(input, target, entry, state.installedPath);
1018
- result.sourceIntegrity = true;
1019
- result.skills = readdirSync(join(result.nativePluginRoot, 'skills')).sort();
1020
- result.mcp = entry.enabled
1021
- ? await startup(result.nativePluginRoot, state.currentVersion, target.projectRoot)
1022
- : { configuration: 'disabled', startup: 'not_checked' };
1182
+ let observedRoot;
1183
+ if (current)
1184
+ observedRoot = selectedRoot(
1185
+ input,
1186
+ target,
1187
+ current,
1188
+ current.installedPath ?? (current.version === prior ? state.installedPath : join(target.nativeHome, "plugins/cache", target.marketplace, "ai-delivery", current.version)),
1189
+ recoverySourceVersion
1190
+ );
1191
+ if (version) {
1192
+ await stageVersion(target, version, controller.signal, publish, (allocation) => {
1193
+ if (allocation) state.pending.staging = allocation;
1194
+ else delete state.pending.staging;
1195
+ persist();
1196
+ });
1197
+ if (!reuseSelection) {
1198
+ selectionStarted = true;
1199
+ catalog(target, version, catalogBefore);
1200
+ }
1201
+ if (!registered && !reuseSelection)
1202
+ await native([
1203
+ "plugin",
1204
+ "marketplace",
1205
+ "add",
1206
+ target.catalog,
1207
+ ...input.host === "codex" ? ["--json"] : ["--scope", input.scope]
1208
+ ]);
1023
1209
  }
1024
- catch (error) {
1025
- result.sourceIntegrity = false;
1026
- result.mcp = {
1027
- configuration: 'unverified',
1028
- startup: 'not_checked',
1029
- error: input.checkAuth
1030
- ? 'Selected native plugin integrity failed; raw output withheld.'
1031
- : (error instanceof Error ? error.message : String(error)).slice(0, 2000),
1032
- };
1210
+ if (current && input.action === "remove") {
1211
+ selectionStarted = true;
1212
+ await native(removeArgs);
1033
1213
  }
1034
- observeNativePlugins(result, input, target, entries, entry.registration);
1035
- if (input.host === 'codex') {
1036
- try {
1037
- const global = await inventory(input, target, new AbortController().signal, undefined, true);
1038
- const selectedIds = new Set(entries.flatMap((entry) => (typeof entry.pluginId === 'string' ? [entry.pluginId] : [])));
1039
- observeNativePlugins(result, input, target, global.filter((entry) => typeof entry.pluginId !== 'string' || !selectedIds.has(entry.pluginId)));
1040
- }
1041
- catch {
1042
- result.diagnostics.nativeInventory = 'unavailable';
1043
- result.diagnostics.findings.push('native_inventory_unavailable');
1044
- }
1214
+ let installedPath = reuseSelection ? current?.installedPath ?? observedRoot ?? state.installedPath : state.installedPath;
1215
+ if (version && !reuseSelection) {
1216
+ const installed = await native(installArgs);
1217
+ if (input.host === "codex")
1218
+ installedPath = z.object({ installedPath: z.string() }).parse(JSON.parse(installed)).installedPath;
1045
1219
  }
1046
- if (result.mcp?.startup === 'ready')
1047
- result.activation.startupVersion = result.mcp.version ?? null;
1048
- if (result.authProbe && result.sourceIntegrity && result.enabled && result.mcp?.startup === 'ready') {
1049
- delete result.authProbe.reason;
1050
- await checkAuthentication(input, result.nativePluginRoot, result.authProbe);
1220
+ const after = await inventory(input, target, controller.signal, publish);
1221
+ if (!registration(input, target, after) && version)
1222
+ throw new Error("Native marketplace registration is missing.");
1223
+ const readback = nativeEntry(input, target, after);
1224
+ if (version ? readback?.version !== version : readback !== void 0)
1225
+ throw new Error("Native installation readback does not match the selected version.");
1226
+ if (version) {
1227
+ selectedRoot(input, target, readback, readback?.installedPath ?? installedPath);
1228
+ if (!readback.enabled) throw new Error("Native plugin selection is disabled.");
1051
1229
  }
1230
+ state.currentVersion = version;
1231
+ if (prior !== version) state.previousVersion = prior;
1232
+ state.installedPath = version ? readback?.installedPath ?? installedPath : null;
1233
+ delete state.pending;
1234
+ persist();
1235
+ result.version = version;
1236
+ result.changed = prior !== version;
1237
+ result.installed = version !== null;
1238
+ result.activation = { installedVersion: version, startupVersion: null, loadedVersion: null };
1239
+ if (version) result.nativePluginRoot = state.installedPath ?? pluginRoot(target, version);
1052
1240
  return result;
1053
- }
1054
- if (!state && input.action === 'remove')
1055
- return result;
1056
- if (!state && existsSync(target.directory) && readdirSync(target.directory).length > 0)
1057
- throw new Error('Managed plugin directory contains unrecognized content.');
1058
- ensurePrivateDirectoryDurably(target.directory);
1059
- return withLock(target.statePath, {
1060
- projectRoot: target.directory,
1061
- timeout: 200,
1062
- onReleaseError: (error) => {
1063
- throw error;
1064
- },
1065
- operation: async () => {
1066
- state = readState(input, target);
1067
- if (input.action === 'rollback') {
1068
- if (!state?.currentVersion)
1069
- throw new Error('Preserving rollback requires a current managed selection; it cannot reinstall a removed plugin.');
1070
- if (state.previousVersion !== result.version)
1071
- throw new Error('Managed rollback target changed before acquiring its ownership lock.');
1072
- }
1073
- let expectedState = existsSync(target.statePath)
1074
- ? { bytes: readFileSync(target.statePath), metadata: lstatSync(target.statePath) }
1075
- : undefined;
1076
- // Guard the cooperative owned record; this is not a native-settings CAS.
1077
- const persist = () => {
1078
- assertCanonical(target.statePath);
1079
- if (expectedState) {
1080
- readState(input, target);
1081
- const current = lstatSync(target.statePath);
1082
- if (current.dev !== expectedState.metadata.dev ||
1083
- current.ino !== expectedState.metadata.ino ||
1084
- (current.mode & 0o777) !== 0o600 ||
1085
- current.mode !== expectedState.metadata.mode ||
1086
- !readFileSync(target.statePath).equals(expectedState.bytes))
1087
- throw new Error('Managed state changed during this operation.');
1088
- }
1089
- else if (existsSync(target.statePath)) {
1090
- throw new Error('Managed state appeared during this operation.');
1091
- }
1092
- writePrivateJsonFileAtomically(target.statePath, state);
1093
- expectedState = { bytes: readFileSync(target.statePath), metadata: lstatSync(target.statePath) };
1094
- };
1095
- const resuming = state?.pending !== undefined;
1096
- if (state?.pending) {
1097
- await recover(state.pending);
1098
- if (state.pending.producerDigest !==
1099
- retainedWorktreeTransitionProducerDigest(dirname(fileURLToPath(import.meta.url))))
1100
- throw new Error('Interrupted plugin operation belongs to a different controller; resume with its original version.');
1101
- const allocation = state.pending.staging;
1102
- if (allocation && existsSync(allocation.path)) {
1103
- const parent = dirname(unitDirectory(target, state.pending.targetVersion));
1104
- if (dirname(allocation.path) !== parent ||
1105
- !/^\.stage-[a-f0-9-]{36}$/u.test(allocation.path.slice(parent.length + 1)))
1106
- throw new Error('Recorded staging path is outside this version target.');
1107
- assertCanonical(allocation.path);
1108
- const current = lstatSync(allocation.path);
1109
- if (!current.isDirectory() ||
1110
- (allocation.device === undefined
1111
- ? readdirSync(allocation.path).length !== 0
1112
- : current.dev !== allocation.device || current.ino !== allocation.inode))
1113
- throw new Error('Interrupted staging directory ownership is unresolved.');
1114
- rmSync(allocation.path, { recursive: true });
1115
- sync(parent);
1116
- }
1117
- if (state.pending.action !== input.action || state.pending.targetVersion !== result.version)
1118
- throw new Error('Resume the interrupted original plugin command before selecting a different operation.');
1119
- }
1120
- if (input.action === 'update' && !state?.currentVersion)
1121
- throw new Error('Install a managed plugin before updating or rolling it back.');
1122
- const version = input.action === 'remove' ? null : result.version;
1123
- if (version === null && input.action !== 'remove')
1124
- throw new Error('No previous managed plugin version is available.');
1125
- const prior = state?.currentVersion ?? null;
1126
- state ??= {
1127
- owner: '@aviaratech/ai-delivery.plugin@1',
1128
- host: input.host,
1129
- scope: input.scope,
1130
- projectRoot: input.scope === 'user' ? null : target.projectRoot,
1131
- nativeHome: target.nativeHome,
1132
- marketplace: target.marketplace,
1133
- currentVersion: null,
1134
- previousVersion: null,
1135
- installedPath: null,
1136
- };
1137
- const birth = identity(process.pid);
1138
- if (!birth)
1139
- throw new Error('Installer owner identity is unknown.');
1140
- state.pending = {
1141
- action: input.action,
1142
- targetVersion: version,
1143
- owner: { pid: process.pid, birth },
1144
- producerDigest: retainedWorktreeTransitionProducerDigest(dirname(fileURLToPath(import.meta.url))),
1145
- command: { phase: 'idle' },
1146
- };
1241
+ } catch (error) {
1242
+ if (!resuming && !controller.signal.aborted && !selectionStarted && state.pending?.command.phase === "idle" && state.pending.staging === void 0) {
1243
+ delete state.pending;
1244
+ try {
1147
1245
  persist();
1148
- const controller = new AbortController();
1149
- const cancel = () => controller.abort();
1150
- process.once('SIGINT', cancel);
1151
- process.once('SIGTERM', cancel);
1152
- const publish = (command) => {
1153
- state.pending.command = command;
1154
- persist();
1155
- };
1156
- const native = (args) => command(target.tool, args, target.projectRoot, controller.signal, publish);
1157
- const selector = `ai-delivery@${target.marketplace}`;
1158
- const nativeTarget = input.host === 'codex'
1159
- ? { host: input.host, scope: 'user', pluginId: selector }
1160
- : { host: input.host, scope: input.scope, pluginId: selector };
1161
- const removeArgs = nativePluginArgs({ ...nativeTarget, action: 'remove' });
1162
- const installArgs = nativePluginArgs({ ...nativeTarget, action: prior ? 'update' : 'install' });
1163
- let selectionStarted = false;
1164
- try {
1165
- state.nativeVersion = (await native(['--version'])).trim();
1166
- if (prior && version) {
1167
- if (input.host === 'claude-code') {
1168
- // Qualified against this native binary in an isolated USER profile,
1169
- // including unknown settings, unrelated selections and a catalog path change.
1170
- const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;
1171
- if (state.nativeVersion !== '2.1.296 (Claude Code)' ||
1172
- input.scope !== 'user' ||
1173
- !stable.test(prior) ||
1174
- !stable.test(version) ||
1175
- (version
1176
- .split('.')
1177
- .map(BigInt)
1178
- .map((part, index) => part - BigInt(prior.split('.')[index]))
1179
- .find((part) => part !== 0n) ?? 0n) < 0n)
1180
- throw new Error('Claude preserving replacement is unqualified; no catalog or native selection was changed.');
1181
- }
1182
- // Only this pinned native source has a qualified preserving-add footprint.
1183
- // This does not establish exclusion of concurrent, unrelated native writers.
1184
- if (input.host === 'codex' && state.nativeVersion !== 'codex-cli 0.162.1')
1185
- throw new Error('This native version has no qualified preserving replacement route.');
1186
- }
1187
- if (input.host === 'claude-code' && !(await native(['plugin', 'uninstall', '--help'])).includes('--keep-data'))
1188
- throw new Error('This Claude Code version cannot preserve plugin data; upgrade the native tool first.');
1189
- process.stderr.write(`ai-delivery.plugin ${JSON.stringify({ action: input.action, host: input.host, scope: input.scope, stage: version ? 'prepare_version' : 'native_remove', version })}\n`);
1190
- const before = await inventory(input, target, controller.signal, publish);
1191
- const registered = registration(input, target, before), current = nativeEntry(input, target, before);
1192
- if (current && !prior && !(resuming && current.version === version))
1193
- throw new Error('Existing native plugin is not owned by managed state.');
1194
- let recoverySourceVersion = current?.version;
1195
- if (current && resuming && input.host === 'claude-code') {
1196
- recoverySourceVersion = claudeCatalogSelection(target).version;
1197
- if (recoverySourceVersion !== prior && recoverySourceVersion !== version)
1198
- throw new Error('Interrupted native selection has an incompatible catalog version.');
1199
- }
1200
- if (current && version && !current.enabled)
1201
- throw new Error('Native plugin selection is disabled; preserving replacement cannot enable it.');
1202
- let catalogBefore;
1203
- let reuseSelection = false;
1204
- if (prior && version) {
1205
- if (!registered || !current || (current.version !== prior && !(resuming && current.version === version)))
1206
- throw new Error('Managed native selection changed; replacement ownership is unresolved.');
1207
- catalogBefore = readCatalog(target, prior);
1208
- const priorMatches = catalogMatches(catalogBefore, target, prior);
1209
- const targetMatches = catalogMatches(catalogBefore, target, version);
1210
- const priorCatalog = priorMatches.every(Boolean), targetCatalog = targetMatches.every(Boolean);
1211
- const partialCatalog = resuming && targetMatches[0] && priorMatches[1];
1212
- if (!priorCatalog && !targetCatalog && !partialCatalog)
1213
- throw new Error('Managed catalog differs from the owned prior or target publication.');
1214
- // The installed cache and the host-specific catalog source are separate observations.
1215
- recoverySourceVersion = targetMatches[input.host === 'codex' ? 0 : 1] ? version : prior;
1216
- if (current.version === version) {
1217
- if (!targetCatalog)
1218
- throw new Error('Selected target has an incompatible managed catalog.');
1219
- reuseSelection = true;
1220
- }
1221
- else if (targetCatalog) {
1222
- throw new Error('Interrupted replacement is ambiguous; native selection will not be repeated.');
1223
- }
1224
- }
1225
- else if (version && current && resuming) {
1226
- catalogBefore = readCatalog(target, version);
1227
- if (!catalogMatches(catalogBefore, target, version).every(Boolean))
1228
- throw new Error('Selected target has an incompatible managed catalog.');
1229
- reuseSelection = current.version === version;
1230
- }
1231
- let observedRoot;
1232
- if (current)
1233
- observedRoot = selectedRoot(input, target, current, current.installedPath ??
1234
- (current.version === prior
1235
- ? state.installedPath
1236
- : join(target.nativeHome, 'plugins/cache', target.marketplace, 'ai-delivery', current.version)), recoverySourceVersion);
1237
- if (version) {
1238
- await stageVersion(target, version, controller.signal, publish, (allocation) => {
1239
- if (allocation)
1240
- state.pending.staging = allocation;
1241
- else
1242
- delete state.pending.staging;
1243
- persist();
1244
- });
1245
- if (!reuseSelection) {
1246
- selectionStarted = true;
1247
- catalog(target, version, catalogBefore);
1248
- }
1249
- if (!registered && !reuseSelection)
1250
- await native([
1251
- 'plugin',
1252
- 'marketplace',
1253
- 'add',
1254
- target.catalog,
1255
- ...(input.host === 'codex' ? ['--json'] : ['--scope', input.scope]),
1256
- ]);
1257
- }
1258
- if (current && input.action === 'remove') {
1259
- selectionStarted = true;
1260
- await native(removeArgs);
1261
- }
1262
- let installedPath = reuseSelection
1263
- ? (current?.installedPath ?? observedRoot ?? state.installedPath)
1264
- : state.installedPath;
1265
- if (version && !reuseSelection) {
1266
- const installed = await native(installArgs);
1267
- if (input.host === 'codex')
1268
- installedPath = z.object({ installedPath: z.string() }).parse(JSON.parse(installed)).installedPath;
1269
- }
1270
- const after = await inventory(input, target, controller.signal, publish);
1271
- if (!registration(input, target, after) && version)
1272
- throw new Error('Native marketplace registration is missing.');
1273
- const readback = nativeEntry(input, target, after);
1274
- if (version ? readback?.version !== version : readback !== undefined)
1275
- throw new Error('Native installation readback does not match the selected version.');
1276
- if (version) {
1277
- selectedRoot(input, target, readback, readback?.installedPath ?? installedPath);
1278
- if (!readback.enabled)
1279
- throw new Error('Native plugin selection is disabled.');
1280
- }
1281
- state.currentVersion = version;
1282
- if (prior !== version)
1283
- state.previousVersion = prior;
1284
- state.installedPath = version ? (readback?.installedPath ?? installedPath) : null;
1285
- delete state.pending;
1286
- persist();
1287
- result.version = version;
1288
- result.changed = prior !== version;
1289
- result.installed = version !== null;
1290
- result.activation = { installedVersion: version, startupVersion: null, loadedVersion: null };
1291
- if (version)
1292
- result.nativePluginRoot = state.installedPath ?? pluginRoot(target, version);
1293
- return result;
1294
- }
1295
- catch (error) {
1296
- if (!resuming &&
1297
- !controller.signal.aborted &&
1298
- !selectionStarted &&
1299
- state.pending?.command.phase === 'idle' &&
1300
- state.pending.staging === undefined) {
1301
- delete state.pending;
1302
- try {
1303
- persist();
1304
- }
1305
- catch (recoveryError) {
1306
- throw new AggregateError([error, recoveryError], 'Plugin preparation failed and pending-state cleanup also failed.');
1307
- }
1308
- }
1309
- // A failed acknowledgement may follow a successful selection. Retain the
1310
- // catalog and pending intent for exact postimage reconciliation, not rollback.
1311
- throw error;
1312
- }
1313
- finally {
1314
- process.removeListener('SIGINT', cancel);
1315
- process.removeListener('SIGTERM', cancel);
1316
- }
1317
- },
1318
- });
1246
+ } catch (recoveryError) {
1247
+ throw new AggregateError(
1248
+ [error, recoveryError],
1249
+ "Plugin preparation failed and pending-state cleanup also failed."
1250
+ );
1251
+ }
1252
+ }
1253
+ throw error;
1254
+ } finally {
1255
+ process.removeListener("SIGINT", cancel);
1256
+ process.removeListener("SIGTERM", cancel);
1257
+ }
1258
+ }
1259
+ });
1319
1260
  }
1320
- //# sourceMappingURL=pluginInstaller.js.map
1261
+ export {
1262
+ managePlugin
1263
+ };
1264
+ //# sourceMappingURL=pluginInstaller.js.map