Repository navigation
feat: create @mlx-node/cli package with unified mlx CLI - #25
Conversation
Migrate standalone scripts (download-model, convert-model, download-gsm8k) into a proper @mlx-node/cli subpackage with subcommand routing: mlx download model, mlx download dataset, mlx convert Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR replaces legacy yarn/oxnode scripts with a new MLX CLI package. It removes Changes
Sequence DiagramsequenceDiagram
participant User
participant CLI as "mlx\n(packages/cli/src/cli.ts)"
participant Cmd as "Command Handler\n(download-model / download-dataset / convert)"
participant Core as "@mlx-node/core"
participant HF as "HuggingFace API / File System"
User->>CLI: run "yarn mlx download model [args]"
CLI->>Cmd: route -> run(argv)
Cmd->>Cmd: parse args, validate, prepare cache/output
Cmd->>HF: list model files & metadata
HF-->>Cmd: file list & sizes
Cmd->>HF: download files to cache
HF-->>Cmd: downloaded blobs
Cmd->>HF: copy/write to output dir
Cmd->>Cmd: verify config.json and weights
Cmd-->>User: success / failure message
User->>CLI: run "yarn mlx convert [args]"
CLI->>Cmd: route -> run(argv)
Cmd->>Cmd: parse args, detect model-type
Cmd->>Core: invoke convertModel / convertForeignWeights
Core->>HF: read input weights
HF-->>Core: weight data
Core->>HF: write SafeTensors output
Cmd-->>User: conversion summary (tensors, params, duration)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
packages/cli/src/utils.ts (1)
10-19: Consider extracting units as a module-level constant.Per the codebase convention, module-level constants use UPPER_SNAKE_CASE.
♻️ Optional refactor
+const BYTE_UNITS = ['B', 'KB', 'MB', 'GB']; + export function formatBytes(bytes: number): string { - const units = ['B', 'KB', 'MB', 'GB']; let size = bytes; let unitIndex = 0; - while (size >= 1024 && unitIndex < units.length - 1) { + while (size >= 1024 && unitIndex < BYTE_UNITS.length - 1) { size /= 1024; unitIndex++; } - return `${size.toFixed(2)} ${units[unitIndex]}`; + return `${size.toFixed(2)} ${BYTE_UNITS[unitIndex]}`; }Based on learnings: "In TypeScript files within mlx-node/mlx-node, use camelCase for variables, functions, and methods, but UPPER_SNAKE_CASE is the preferred convention for module-level constants."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/utils.ts` around lines 10 - 19, Extract the units array from formatBytes into a module-level UPPER_SNAKE_CASE constant (e.g., BYTE_UNITS) and replace the inline units reference in the formatBytes(bytes: number) function with that constant; ensure the new constant is exported or kept file-scoped as appropriate and follows the existing naming convention for module-level constants.packages/cli/package.json (1)
1-20: Consider addingenginesfield for Node.js version requirement.The README states Node.js 18+ is required, and CI uses Node.js 24. Adding an
enginesfield would help users identify version requirements upfront.♻️ Suggested addition
"type": "module", + "engines": { + "node": ">=18" + }, "scripts": {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/package.json` around lines 1 - 20, Add a top-level "engines" field to the package.json for `@mlx-node/cli` to declare the Node.js requirement; update the JSON to include an "engines": { "node": ">=18" } (or ">=18 <25" if you want to explicitly cap to current CI Node 24) so users and tooling get clear version guidance; place this field at the top level of package.json near "type"/"version"/"scripts" and ensure package remains valid JSON.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli/src/commands/convert.ts`:
- Around line 78-89: The current checks only test for NaN; replace them with
strict validation: ensure args['q-bits'] and args['q-group-size'] are pure
integer strings (no "4abc") and parse to integers, then validate quantBits is
one of the allowed bit widths (e.g., supportedQuantBits array) and
quantGroupSize > 0 (positive integer), and validate quantMode is one of
supportedQuantModes; if any check fails, print a specific error and exit. Update
the validation around the quantBits/quantGroupSize/quantMode variables (symbols:
quantBits, quantGroupSize, quantMode, args['q-bits'], args['q-group-size'],
args['q-mode']) and apply the same hardened checks for the later validation
block referenced (the similar code at lines ~150-154).
In `@packages/cli/src/commands/download-model.ts`:
- Around line 205-215: The loop iterating over filesToDownload in
download-model.ts may call copyFile(join(outputDir, file.path)) before creating
any nested directories for file.path; update the loop (around where
downloadFileToCacheDir, stats, fileSizeStr are used) to ensure the destination
directory exists by creating the parent directory for join(outputDir, file.path)
(e.g., using mkdir/ensureDir) before calling copyFile, so nested paths are safe
when file.path contains subdirectories.
---
Nitpick comments:
In `@packages/cli/package.json`:
- Around line 1-20: Add a top-level "engines" field to the package.json for
`@mlx-node/cli` to declare the Node.js requirement; update the JSON to include an
"engines": { "node": ">=18" } (or ">=18 <25" if you want to explicitly cap to
current CI Node 24) so users and tooling get clear version guidance; place this
field at the top level of package.json near "type"/"version"/"scripts" and
ensure package remains valid JSON.
In `@packages/cli/src/utils.ts`:
- Around line 10-19: Extract the units array from formatBytes into a
module-level UPPER_SNAKE_CASE constant (e.g., BYTE_UNITS) and replace the inline
units reference in the formatBytes(bytes: number) function with that constant;
ensure the new constant is exported or kept file-scoped as appropriate and
follows the existing naming convention for module-level constants.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 54b65f96-3dcb-4554-8416-9d3054963b0e
⛔ Files ignored due to path filters (1)
yarn.lockis excluded by!**/yarn.lock,!**/*.lock
📒 Files selected for processing (14)
.github/workflows/ci.ymlREADME.mdexamples/vlm-inference.tspackage.jsonpackages/cli/package.jsonpackages/cli/src/cli.tspackages/cli/src/commands/convert.tspackages/cli/src/commands/download-dataset.tspackages/cli/src/commands/download-model.tspackages/cli/src/utils.tspackages/cli/tsconfig.jsonscripts/convert-model.tsscripts/download-model.tstsconfig.json
💤 Files with no reviewable changes (2)
- scripts/download-model.ts
- scripts/convert-model.ts
- Strict positive integer parsing for --q-bits/--q-group-size (rejects "4abc") - Validate --q-mode at CLI level (must be "affine" or "mxfp8") - Create subdirectories before copyFile for nested HuggingFace paths Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/cli/src/commands/download-model.ts (1)
158-158: Use camelCase for function-scoped variables.Line 158 uses
HUGGINGFACE_TOKENfor a local variable; this should behuggingfaceTokento match the TypeScript naming rule used in this repo.♻️ Proposed rename
- const HUGGINGFACE_TOKEN = await keyringEntry.getPassword(); + const huggingfaceToken = await keyringEntry.getPassword(); - if (!HUGGINGFACE_TOKEN) { + if (!huggingfaceToken) { @@ - accessToken: HUGGINGFACE_TOKEN, + accessToken: huggingfaceToken,As per coding guidelines:
**/*.{ts,tsx}: Use camelCase for all variable, function, and method names in TypeScript.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/download-model.ts` at line 158, The local variable HUGGINGFACE_TOKEN violates the repo's camelCase rule; rename it to huggingfaceToken wherever declared and used (the assignment from keyringEntry.getPassword() and any subsequent references) to maintain TypeScript naming conventions; update any occurrences in the downloadModel command logic (references to HUGGINGFACE_TOKEN, keyringEntry.getPassword()) so the new huggingfaceToken identifier is consistently used.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli/src/commands/download-model.ts`:
- Around line 73-76: getModelFiles currently always calls listFiles anonymously,
preventing access to gated/private repos; update the function signature
getModelFiles(modelName: string) to accept an optional accessToken?: string and
pass that token through to listFiles (e.g., listFiles({ repo: { type: 'model',
name: modelName }, accessToken })). Then update the caller that invokes
getModelFiles (the call site near the current download flow where
HUGGINGFACE_TOKEN is available) to forward process.env.HUGGINGFACE_TOKEN (or the
retrieved token variable) into getModelFiles so gated models can be listed.
---
Nitpick comments:
In `@packages/cli/src/commands/download-model.ts`:
- Line 158: The local variable HUGGINGFACE_TOKEN violates the repo's camelCase
rule; rename it to huggingfaceToken wherever declared and used (the assignment
from keyringEntry.getPassword() and any subsequent references) to maintain
TypeScript naming conventions; update any occurrences in the downloadModel
command logic (references to HUGGINGFACE_TOKEN, keyringEntry.getPassword()) so
the new huggingfaceToken identifier is consistently used.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7469ddde-8178-4130-b0c0-748eec025b3c
📒 Files selected for processing (2)
packages/cli/src/commands/convert.tspackages/cli/src/commands/download-model.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/cli/src/commands/convert.ts
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/cli/src/commands/download-model.ts (1)
158-161: Use camelCase for the function-scoped token variable.
HUGGINGFACE_TOKENis a local variable; this should be camelCase for consistency with TypeScript naming conventions in this repo.🧹 Proposed rename
- const HUGGINGFACE_TOKEN = (await keyringEntry.getPassword()) ?? undefined; + const huggingfaceToken = (await keyringEntry.getPassword()) ?? undefined; - if (!HUGGINGFACE_TOKEN) { + if (!huggingfaceToken) { console.warn('No HuggingFace token found, the model will download with anonymous access'); } @@ - const { totalSize, filesToDownload } = await getModelFiles(modelName, HUGGINGFACE_TOKEN); + const { totalSize, filesToDownload } = await getModelFiles(modelName, huggingfaceToken); @@ - accessToken: HUGGINGFACE_TOKEN, + accessToken: huggingfaceToken,As per coding guidelines "Use camelCase for all variable, function, and method names in TypeScript".
Also applies to: 198-210
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/download-model.ts` around lines 158 - 161, The local constant HUGGINGFACE_TOKEN should use camelCase; rename the function-scoped HUGGINGFACE_TOKEN to huggingfaceToken and update every reference within the same function (including the other occurrences around the later block referenced) to match; ensure you change the const declaration and all uses (e.g., pass to functions, checks like if (!huggingfaceToken), and any assignments) while leaving any true top-level or exported constants untouched.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli/src/commands/download-model.ts`:
- Around line 93-117: The verifyDownload function can incorrectly succeed when
weightFiles is empty; add a check in verifyDownload (function name) to treat an
empty weightFiles array as a verification failure: if weightFiles.length === 0,
log an error like " ✗ No weight files downloaded" (or similar) and set
allPresent = false (or return false immediately) before looping over weightFiles
so the function fails when no weights were downloaded.
- Line 7: The token prompt currently uses input(...) which echoes the
HuggingFace token; change to using the password prompt from `@inquirer/prompts` by
importing password instead of input and calling password(...) where input(...)
is used (e.g., the token variable/huggingfaceToken prompt in download-model.ts).
Ensure the prompt options mirror the current prompt (message, default/initial if
any) and that the returned value is assigned to the same variable so downstream
code (token usage) is unchanged.
---
Nitpick comments:
In `@packages/cli/src/commands/download-model.ts`:
- Around line 158-161: The local constant HUGGINGFACE_TOKEN should use
camelCase; rename the function-scoped HUGGINGFACE_TOKEN to huggingfaceToken and
update every reference within the same function (including the other occurrences
around the later block referenced) to match; ensure you change the const
declaration and all uses (e.g., pass to functions, checks like if
(!huggingfaceToken), and any assignments) while leaving any true top-level or
exported constants untouched.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 1a7a335e-99ba-4958-819a-166a9372d4a9
📒 Files selected for processing (2)
packages/cli/src/commands/convert.tspackages/cli/src/commands/download-model.ts
Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
packages/cli/src/commands/download-model.ts (1)
7-7:⚠️ Potential issue | 🟠 MajorMask HuggingFace token entry in prompt.
Line 35 uses
input(...), which echoes the token in plain text. This should usepassword(...)with masking.🔐 Proposed fix
-import { input } from '@inquirer/prompts'; +import { password } from '@inquirer/prompts'; @@ - const token = await input({ + const token = await password({ message: 'Enter your HuggingFace token:', required: true, + mask: true, theme: { validationFailureMode: 'clear', },`@inquirer/prompts` v8.2.1 documentation for password prompt options (including mask support) and recommended usage for secret inputAlso applies to: 35-37
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/download-model.ts` at line 7, The prompt currently uses the plain-text input prompt (imported as input) which echoes the HuggingFace token; change to use the masked password prompt by importing password from '@inquirer/prompts' and replace calls to input(...) that request the token with password(..., {mask: '*'} ) (or another mask char) so the token is not echoed; update all occurrences around the token prompt (references: input and the token prompt invocation in download-model.ts) to use password with an appropriate mask option.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli/src/commands/download-model.ts`:
- Around line 188-191: The current check treats presence of
model.safetensors.index.json (hasShardedModel) as sufficient even if shard files
are missing; update the logic so that when hasShardedModel is true you parse
model.safetensors.index.json (e.g., read and JSON.parse the file referenced by
the files list in the download-model command) and inspect the weight map (or
shard filename entries) and verify every shard filename appears in the files
array before deciding the model is already downloaded; if parsing fails or any
shard is missing, treat hasShardedModel as false so the command proceeds to
download; keep hasSingleModel and hasPaddleModel checks unchanged and log or
handle parse errors gracefully.
- Around line 160-161: The current default output dir computation uses only the
last segment (modelSlug derived from modelName.split('/').pop()) which causes
collisions for models with the same name under different namespaces; update the
logic that computes modelSlug (and thus outputDir) to incorporate the full
modelName namespace (e.g., replace path separators with a safe delimiter or
encode the entire modelName) and then normalize (lowercase) so orgA/model-x and
orgB/model-x produce distinct slugs; adjust references in this file to use the
new modelSlug derivation when computing outputDir (used with resolve and
args.output).
---
Duplicate comments:
In `@packages/cli/src/commands/download-model.ts`:
- Line 7: The prompt currently uses the plain-text input prompt (imported as
input) which echoes the HuggingFace token; change to use the masked password
prompt by importing password from '@inquirer/prompts' and replace calls to
input(...) that request the token with password(..., {mask: '*'} ) (or another
mask char) so the token is not echoed; update all occurrences around the token
prompt (references: input and the token prompt invocation in download-model.ts)
to use password with an appropriate mask option.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: a92d7a71-71c9-4a03-847e-155272dbe07e
📒 Files selected for processing (1)
packages/cli/src/commands/download-model.ts
Qwen/model-x and OtherOrg/model-x now map to different directories. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The org-prefixed slug (qwen--qwen3-0.6b) breaks CI and README references that expect .cache/models/qwen3-0.6b. Users needing disambiguation can use --output explicitly. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Migrate standalone scripts (download-model, convert-model, download-gsm8k) into a proper @mlx-node/cli subpackage with subcommand routing: mlx download model, mlx download dataset, mlx convert <!-- CURSOR_SUMMARY --> --- > [!NOTE] > <sup>[Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) is generating a summary for commit 5cfee84. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a unified mlx CLI with commands for downloading models, converting models, and downloading datasets. * **Documentation** * Updated README and runtime guidance, plus example messages, to use the new yarn mlx ... command syntax. * **Refactor** * Replaced legacy standalone scripts with a packaged, modular CLI and command implementations. * **Chores** * Introduced CLI package and script entry; removed older download/convert script files and updated TypeScript project references. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
Migrate standalone scripts (download-model, convert-model, download-gsm8k) into a proper @mlx-node/cli subpackage with subcommand routing:
mlx download model, mlx download dataset, mlx convert
Note
Cursor Bugbot is generating a summary for commit 5cfee84. Configure here.
Summary by CodeRabbit
New Features
Documentation
Refactor
Chores