@aviaratech/ai-delivery 0.3.34 → 0.3.36

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