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