1 import { spawnSync } from "child_process"
2 import fs from "fs"
3 import os from "os"
4 import path from "path"
5 import inquirer from "inquirer"
6 import logMessage from "./log-message.js"
7 import pkg from '@medusajs/telemetry';
8 const { Store, track } = pkg
9
10 const CLAUDE_DIR = path.join(os.homedir(), ".claude")
11 const INSTALLED_PLUGINS_FILE = path.join(
12 CLAUDE_DIR,
13 "plugins",
14 "installed_plugins.json"
15 )
16 const PLUGIN_ID = "medusa-dev@medusa"
17 const CONFIG_KEY = "claude-code-plugin.prompted"
18
19 function isClaudeCodePresent(): boolean {
20 return !!process.env.CLAUDE_CODE || fs.existsSync(CLAUDE_DIR)
21 }
22
23 function isNonInteractive(): boolean {
24 return process.env.CI === "true" || !process.stdout.isTTY
25 }
26
27 function isPluginInstalled(): boolean {
28 if (!fs.existsSync(INSTALLED_PLUGINS_FILE)) {
29 return false
30 }
31 try {
32 const data = JSON.parse(fs.readFileSync(INSTALLED_PLUGINS_FILE, "utf-8"))
33 return !!data?.plugins?.[PLUGIN_ID]
34 } catch {
35 return false
36 }
37 }
38
39 function runInstall(): boolean {
40 try {
41 const marketplace = spawnSync(
42 "claude",
43 ["plugin", "marketplace", "add", "medusajs/medusa-agent-skills"],
44 { stdio: "inherit" }
45 )
46 if (marketplace.error) {
47 return false
48 }
49
50 const install = spawnSync("claude", ["plugin", "install", PLUGIN_ID], {
51 stdio: "inherit",
52 })
53 return !install.error
54 } catch {
55 return false
56 }
57 }
58
59 export async function promptClaudeCodePlugin(): Promise<void> {
60 if (isNonInteractive() || !isClaudeCodePresent() || isPluginInstalled()) {
61 return
62 }
63
64 const configStore = new Store()
65 console.log(configStore.config_.path)
66 if (configStore.getConfig(CONFIG_KEY)) {
67 return
68 }
69
70 configStore.setConfig(CONFIG_KEY, true)
71
72 const { install } = await inquirer.prompt([
73 {
74 type: "confirm",
75 name: "install",
76 message:
77 "Working with Medusa is easier with the Medusa Plugin for Claude Code. Would you like to install it?",
78 default: true,
79 },
80 ])
81
82 track("CMA_CLAUDE_CODE_PLUGIN_PROMPT", {
83 install,
84 })
85
86 if (!install) {
87 return
88 }
89
90 const success = runInstall()
91 if (!success) {
92 logMessage({
93 message: `Could not auto-install. To install manually, open Claude Code in your project and run:\n\n /plugin marketplace add medusajs/medusa-agent-skills\n`,
94 })
95 }
96 }