Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
"source": {
"source": "github",
"repo": "cavi-ai/mlx-agent",
"ref": "v0.12.0",
"sha": "fc585f36abdd9d47614327afec4719fa9049d729"
"ref": "v0.13.0",
"sha": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec"
},
"description": "Discover, verify, and wire local MLX-optimized models on Apple Silicon."
},
Expand Down
5 changes: 3 additions & 2 deletions packages/codex/expected-integrity.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
{
"mlx-agent": {
"repository": "cavi-ai/mlx-agent",
"source_commit": "fc585f36abdd9d47614327afec4719fa9049d729",
"source_commit": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec",
"source_path": "providers/codex",
"tree": "b08974c6522c5e049f882f82bb3395fa91b6cf29669345a0b44c897f847dc73d",
"tree": "7317af0f4afada75a7f4b7a86310eb49ca2c431b81a9506ea5a3638dab81892a",
"skills": [
"mlx-adopt",
"mlx-bench",
"mlx-doctor",
"mlx-fleet",
"mlx-scout",
"mlx-task",
"mlx-watch",
"mlx-wire"
]
Expand Down
2 changes: 1 addition & 1 deletion packages/codex/mlx-agent/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mlx-agent",
"version": "0.12.0",
"version": "0.13.0",
"description": "Structured local MLX discovery, adoption, and wiring for Apple Silicon agents.",
"author": {
"name": "Sasan Sotoodehfar",
Expand Down
4 changes: 2 additions & 2 deletions packages/codex/mlx-agent/provenance.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"repository": "cavi-ai/mlx-agent",
"source_commit": "fc585f36abdd9d47614327afec4719fa9049d729",
"source_commit": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec",
"source_path": "providers/codex",
"included": [
".codex-plugin",
Expand All @@ -17,6 +17,6 @@
"exclusion_reason": "Codex skills use the packaged CLI entrypoint; MCP transport artifacts are not required or distributed by this catalog.",
"integrity": {
"algorithm": "sha256",
"tree": "b08974c6522c5e049f882f82bb3395fa91b6cf29669345a0b44c897f847dc73d"
"tree": "7317af0f4afada75a7f4b7a86310eb49ca2c431b81a9506ea5a3638dab81892a"
}
}
24 changes: 24 additions & 0 deletions packages/codex/mlx-agent/skills/mlx-task/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
name: "mlx-task"
description: "Run, track and collect durable local inference tasks."
---

Use `$mlx-agent:mlx-task` to invoke this installed Codex skill explicitly. Codex does not support custom `/mlx-*` slash commands.

# MLX Task

Resolve `<plugin-root>` as the absolute directory two levels above the directory containing this SKILL.md; it holds `scripts/` and `src/`. Never resolve the bundled executable from the shell working directory.

canonical capability ID: mlx-agent.task

List the supported inference kinds and their request contracts without loading a model:

`python3 <plugin-root>/scripts/mlx-agent task capabilities --json`

Add `--model-path <absolute-model-dir>` to read one local model's optional media settings. To run a task, write a `task-request` JSON file whose `kind`, `model_path` and `parameters` follow the returned contract, then start it with an absolute path:

`python3 <plugin-root>/scripts/mlx-agent task start --request <absolute-request.json> --json`

Follow it with `task status --id <task-id> --json`, collect verified output paths with `task result --id <task-id> --json`, and review recent runs with `task list --json`. `task cancel --id <task-id> --json` stops a running task; `task verify-model --id <task-id> --json` rechecks that the model still matches the one the task used.

Present the returned status, metrics and artifact paths as returned. Tasks use only an existing local model and its installed backend; they must not download model weights, install a runtime, or change configuration.
2 changes: 1 addition & 1 deletion packages/codex/mlx-agent/src/mlx_agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from .contracts import ResultEnvelope

__all__ = ["ResultEnvelope"]
__version__ = "0.12.0"
__version__ = "0.13.0"
9 changes: 9 additions & 0 deletions packages/codex/mlx-agent/src/mlx_agent/acestep_fsq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Create ACE-Step's quantizer constants outside Transformers' meta device."""
import torch
from vector_quantize_pytorch import ResidualFSQ as _ResidualFSQ


class ResidualFSQ(_ResidualFSQ):
def __init__(self, *args, **kwargs):
with torch.device("cpu"):
super().__init__(*args, **kwargs)
144 changes: 144 additions & 0 deletions packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""Run inside the isolated ACE-Step backend; write a new WAV and measured metrics.

ACE-Step copies its model code into the checkpoint folder it loads and keeps a progress cache in
its project root, so both live in a private folder of links to the checkpoint's weights and configs;
nothing is written into the model folder or the working directory.
The network is closed: every file comes from the folders beside the checkpoint.
"""

import argparse
import json
import os
from pathlib import Path
import socket
import tempfile
import time

SIBLINGS = ("vae", "Qwen3-Embedding-0.6B")


def offline(*args, **kwargs):
raise OSError("network access is disabled for music generation")


def link_folder(source, target):
"""Link every file of a checkpoint folder except Python code into a new folder."""
target.mkdir()
for entry in sorted(Path(source).iterdir()):
if entry.suffix == ".py" or entry.name == "__pycache__":
continue
(target / entry.name).symlink_to(entry.resolve())


def stage(model, planner, directory):
"""A checkpoints folder that holds links to the DiT, its VAE, text encoder and planner."""
checkpoints = Path(directory) / "checkpoints"
checkpoints.mkdir()
for name in (model.name, *SIBLINGS, *([planner] if planner else [])):
link_folder(model.parent / name, checkpoints / name)
return checkpoints


def adapt_quantizer(checkpoint):
"""Adapt the trusted model code copied into the private staging folder."""
files = list(Path(checkpoint).glob("modeling_acestep_v15_*.py"))
if len(files) != 1 or files[0].is_symlink():
raise RuntimeError("ACE-Step staged model code is missing or ambiguous")
path = files[0]
source = path.read_text(encoding="utf-8")
original = "from vector_quantize_pytorch import ResidualFSQ"
replacement = "from acestep_fsq import ResidualFSQ"
if source.count(original) != 1 or replacement in source:
raise RuntimeError("ACE-Step staged quantizer import is unexpected")
path.write_text(source.replace(original, replacement), encoding="utf-8")


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
for name in ("model", "caption", "lyrics", "out"):
parser.add_argument("--" + name, required=True)
parser.add_argument("--duration", type=float, required=True)
parser.add_argument("--steps", type=int, required=True)
parser.add_argument("--seed", type=int, required=True)
parser.add_argument("--shift", type=float, required=True)
parser.add_argument("--guidance", type=float, required=True)
parser.add_argument("--bpm", type=int)
parser.add_argument("--time-signature", type=int)
parser.add_argument("--reference")
parser.add_argument("--planner")
args = parser.parse_args(argv)
model, out = Path(args.model), Path(args.out)
from acestep.model_downloader import _CHECKPOINT_TO_VARIANT
if model.name not in _CHECKPOINT_TO_VARIANT:
print(json.dumps({"error": "unknown_checkpoint", "detail": model.name}), flush=True)
return 2
socket.socket.connect = offline
socket.create_connection = offline
os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_HUB_DISABLE_IMPLICIT_TOKEN="1")
import mlx.core as mx
import soundfile
from acestep.handler import AceStepHandler
from acestep.inference import GenerationConfig, GenerationParams, generate_music
from acestep.llm_inference import LLMHandler

class LocalHandler(AceStepHandler):
"""Never download: the staged folders hold every file the DiT, VAE and text encoder read."""

def _ensure_models_present(self, *, checkpoint_path, config_path, prefer_source, vae_variant=None):
return None

def _sync_model_code_if_needed(self, config_path, checkpoint_path):
super()._sync_model_code_if_needed(config_path, checkpoint_path)
adapt_quantizer(Path(checkpoint_path) / config_path)

instrumental = args.lyrics.strip().lower() == "[instrumental]"
# The take is written beside the output, so linking it to the output name stays on one volume.
with tempfile.TemporaryDirectory(prefix="mlx-agent-acestep-") as directory, \
tempfile.TemporaryDirectory(prefix=".acestep-", dir=out.parent) as scratch:
checkpoints = stage(model, args.planner, directory)
# ACE-Step keeps its progress cache under its project root, the working directory by default.
os.environ.update(ACESTEP_CHECKPOINTS_DIR=str(checkpoints), ACESTEP_PROJECT_ROOT=directory)
started = time.perf_counter()
handler = LocalHandler()
status, ok = handler.initialize_service(
project_root=directory, config_path=model.name, device="mps", use_flash_attention=False,
compile_model=False, offload_to_cpu=False, offload_dit_to_cpu=False, quantization=None, use_mlx_dit=True)
if not ok:
raise RuntimeError("ACE-Step did not load: {0}".format(status))
planner = None
if args.planner:
planner = LLMHandler()
status, ok = planner.initialize(checkpoint_dir=str(checkpoints), lm_model_path=args.planner,
backend="mlx", device="mps")
if not ok:
raise RuntimeError("The ACE-Step planner did not load: {0}".format(status))
load_seconds = time.perf_counter() - started
mx.reset_peak_memory()
params = GenerationParams(
task_type="text2music", caption=args.caption, lyrics="[Instrumental]" if instrumental else args.lyrics,
instrumental=instrumental, bpm=args.bpm,
timesignature=str(args.time_signature) if args.time_signature else "",
duration=args.duration, inference_steps=args.steps, guidance_scale=args.guidance, shift=args.shift,
seed=args.seed, thinking=planner is not None, use_cot_metas=planner is not None,
use_cot_caption=planner is not None, use_cot_language=planner is not None,
reference_audio=args.reference)
config = GenerationConfig(batch_size=1, use_random_seed=False, seeds=[args.seed], audio_format="wav")
started = time.perf_counter()
result = generate_music(dit_handler=handler, llm_handler=planner, params=params, config=config,
save_dir=scratch)
seconds = time.perf_counter() - started
if not result.success or not result.audios:
raise RuntimeError("ACE-Step generated nothing: {0}".format(result.error))
written = Path(result.audios[0]["path"])
info = soundfile.info(str(written))
# A hard link claims the new output name or fails, so an existing file is never replaced.
os.link(written, out)
audio_seconds = info.frames / info.samplerate
print(json.dumps({"path": str(out), "sample_rate": info.samplerate, "audio_seconds": audio_seconds,
"seconds": seconds, "load_seconds": load_seconds, "real_time_factor": seconds / audio_seconds,
"peak_memory_gb": mx.get_peak_memory() / 1e9}), flush=True)
return 0


if __name__ == "__main__":
raise SystemExit(main())
119 changes: 119 additions & 0 deletions packages/codex/mlx-agent/src/mlx_agent/allocator_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Optional free-buffer controls inside one admitted resident MLX worker."""
import importlib
import sys
import time

FIELDS = frozenset(('allocator_cache_limit_mib', 'cache_reclaim'))
MODES = ('off', 'idle', 'pressure')


class CacheUnavailable(ValueError):
pass


def policy(value=None):
value = {} if value is None else value
if not isinstance(value, dict) or set(value) - FIELDS:
raise ValueError('Unknown allocator cache policy fields.')
limit, mode = value.get('allocator_cache_limit_mib'), value.get('cache_reclaim', 'off')
if limit is not None and (type(limit) is not int or not 0 <= limit <= 1048576):
raise ValueError('Allocator cache limit must be null or an integer from 0 to 1048576 MiB.')
if mode not in MODES:
raise ValueError('Cache reclaim must be off, idle or pressure.')
return {'allocator_cache_limit_mib': limit, 'cache_reclaim': mode}


def from_memory(value):
return policy({key: value[key] for key in FIELDS if key in value})


def requested(value):
settings = from_memory(value)
return settings['allocator_cache_limit_mib'] is not None or settings['cache_reclaim'] != 'off'


def validate_state(value):
if not isinstance(value, dict) or set(value) != {'available', 'applied_policy', 'last_reclaim', 'error'}:
raise ValueError('Invalid allocator cache state.')
if type(value['available']) is not bool or value['error'] is not None and not isinstance(value['error'], str):
raise ValueError('Invalid allocator cache availability.')
if value['applied_policy'] is not None:
policy(value['applied_policy'])
last = value['last_reclaim']
if last is not None:
if not isinstance(last, dict) or set(last) != {'reason', 'before_cache_bytes', 'after_cache_bytes', 'released_cache_bytes', 'captured_at'}:
raise ValueError('Invalid allocator reclaim observation.')
if last['reason'] not in ('manual', 'idle', 'pressure', 'policy', 'limit'):
raise ValueError('Invalid allocator reclaim reason.')
if any(type(last[key]) is not int or last[key] < 0 for key in ('before_cache_bytes', 'after_cache_bytes', 'released_cache_bytes')):
raise ValueError('Invalid allocator reclaim size.')
if type(last['captured_at']) not in (int, float) or not 0 <= last['captured_at'] < float('inf'):
raise ValueError('Invalid allocator reclaim time.')
return value


class AllocatorCache:
def __init__(self):
self.desired = policy()
self.applied = None
self.default_limit = None
self.current_limit = None
self.last_reclaim = None
self.error = None

@staticmethod
def _core(required=False):
core = sys.modules.get('mlx.core')
if core is None and required:
try:
core = importlib.import_module('mlx.core')
except (ImportError, RuntimeError) as error:
raise CacheUnavailable('The worker MLX allocator is unavailable.') from error
if core is None or not all(callable(getattr(core, name, None)) for name in
('set_cache_limit', 'get_cache_memory', 'clear_cache', 'synchronize')):
if required:
raise CacheUnavailable('This backend does not expose MLX allocator cache controls.')
return None
return core

def configure(self, value):
self.desired = policy(value)

def apply_limit(self, enforce=True):
try:
limit = self.desired['allocator_cache_limit_mib']
core = self._core(requested(self.desired) or self.default_limit is not None)
if core is not None:
if limit is not None:
previous = core.set_cache_limit(limit * 1024**2)
if self.default_limit is None:
self.default_limit = previous
self.current_limit = limit
if enforce and core.get_cache_memory() > limit * 1024**2:
self.reclaim('limit')
elif self.current_limit is not None:
core.set_cache_limit(self.default_limit)
self.current_limit = None
self.applied = dict(self.desired)
self.error = None
except (ValueError, RuntimeError, NotImplementedError) as error:
self.error = str(error)
raise CacheUnavailable(str(error)) from error

def reclaim(self, reason):
try:
core = self._core(True)
core.synchronize()
before = core.get_cache_memory()
core.clear_cache()
after = core.get_cache_memory()
self.last_reclaim = {'reason': reason, 'before_cache_bytes': before, 'after_cache_bytes': after,
'released_cache_bytes': max(0, before - after), 'captured_at': time.time()}
self.error = None
except (ValueError, RuntimeError, NotImplementedError) as error:
self.error = str(error)
raise CacheUnavailable(str(error)) from error

def snapshot(self):
return validate_state({'available': self._core() is not None, 'applied_policy': self.applied,
'last_reclaim': self.last_reclaim, 'error': self.error})
7 changes: 7 additions & 0 deletions packages/codex/mlx-agent/src/mlx_agent/backend_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,13 @@ def plan_install(backend_id, manifests=None, root=None, python=None, version_inf
plan["build_lock_sha256"] = hashlib.sha256(build_lock.read_bytes()).hexdigest()
plan["argv"] += ["--build-lock", str(build_lock)]
plan["network"] += ["github.com", "release-assets.githubusercontent.com"]
elif backend_id == "ace-step":
build_lock = BACKENDS_DIR / "ace-step-build.lock"
if not build_lock.is_file():
raise BackendError("lock_missing", "The ACE-Step build lock is missing.", "Reinstall mlx-agent; the lock ships with it.")
plan["build_lock_sha256"] = hashlib.sha256(build_lock.read_bytes()).hexdigest()
plan["argv"] += ["--build-lock", str(build_lock)]
plan["network"] += ["github.com", "codeload.github.com"]
plan = _finalize(plan)
plan["argv"] = plan["argv"] + ["--preview-hash", plan["preview_hash"]]
return plan
Expand Down
14 changes: 14 additions & 0 deletions packages/codex/mlx-agent/src/mlx_agent/backend_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ def main(argv=None):
"--require-hashes", "--no-deps", "--only-binary=:all:", "-r", build_lock])
steps[2] += ["--no-binary=docopt", "--no-build-isolation"]
steps.append([venv_python, str(Path(__file__).with_name("kokoro_runtime.py"))])
elif arguments.id == "ace-step":
# ACE-Step installs from its pinned, hashed source archive, built with hashed
# hatchling and build isolation disabled; its dependencies stay binary-only.
build_lock = arguments.build_lock or str(Path(arguments.lock).with_name("ace-step-build.lock"))
steps.insert(1, [venv_python, "-m", "pip", "install", "--disable-pip-version-check", "--no-input",
"--require-hashes", "--no-deps", "--only-binary=:all:", "-r", build_lock])
steps[2] += ["--no-binary=ace-step", "--no-build-isolation"]
steps[3] = [venv_python, "-c", (
"import mlx.core; import soundfile; "
"from acestep.model_downloader import _CHECKPOINT_TO_VARIANT; "
"from acestep.handler import AceStepHandler; "
"from acestep.inference import GenerationConfig, GenerationParams, generate_music; "
"from acestep.llm_inference import LLMHandler"
)]
for step in steps:
print("$ " + " ".join(step), flush=True)
completed = subprocess.run(step, stdin=subprocess.DEVNULL, check=False)
Expand Down
Loading