Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

feat: add MiniMax provider support (chat + TTS)

Octopus9c78e9b07302
diff --git a/.gitignore b/.gitignore
index eb6375764..e1b286a08 100644
--- a/.gitignore
+++ b/.gitignore
@@ -65,6 +65,7 @@
!/dify-workflow/
!/adguardhome/
!/novita/
+!/minimax/
!/ollama/
!/browser/
!/seaclip/
@@ -214,6 +215,7 @@
!/dify-workflow/agent-harness/
!/adguardhome/agent-harness/
!/novita/agent-harness/
+!/minimax/agent-harness/
!/ollama/agent-harness/
!/browser/agent-harness/
!/seaclip/agent-harness/
diff --git a/minimax/agent-harness/cli_anything/minimax/README.md b/minimax/agent-harness/cli_anything/minimax/README.md
new file mode 100644
index 000000000..8e7a035d1
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/README.md
@@ -0,0 +1,95 @@
+# cli-anything-minimax
+
+CLI harness for **MiniMax AI** — chat and text-to-speech via the MiniMax API.
+
+## Installation
+
+```bash
+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=minimax/agent-harness
+```
+
+## Prerequisites
+
+- Python 3.10+
+- MiniMax API key from [platform.minimax.io](https://platform.minimax.io)
+
+## Quick Start
+
+```bash
+export MINIMAX_API_KEY="your-api-key"
+cli-anything-minimax chat --prompt "Hello!"
+cli-anything-minimax tts --text "Hello world" --output hello.mp3
+```
+
+## Usage
+
+### Chat
+
+```bash
+# Simple chat (default model: MiniMax-M2.7)
+cli-anything-minimax chat --prompt "Explain quantum computing"
+
+# High-speed model
+cli-anything-minimax chat --prompt "Quick answer please" --model MiniMax-M2.7-highspeed
+
+# Streaming output
+cli-anything-minimax stream --prompt "Write a haiku about AI"
+
+# JSON output for agents
+cli-anything-minimax --json chat --prompt "Hello"
+```
+
+### TTS
+
+```bash
+# Synthesize speech (default model: speech-2.8-hd, default voice: English_Graceful_Lady)
+cli-anything-minimax tts --text "Hello, world!" --output hello.mp3
+
+# Use turbo model
+cli-anything-minimax tts --text "Fast speech" --model speech-2.8-turbo --output fast.mp3
+
+# List available voices
+cli-anything-minimax voices
+```
+
+### Session & Config
+
+```bash
+# Session management
+cli-anything-minimax session status
+cli-anything-minimax session clear
+
+# Configuration
+cli-anything-minimax config set api_key "your-key"
+cli-anything-minimax config get
+
+# Test connectivity
+cli-anything-minimax test
+
+# List models
+cli-anything-minimax models
+cli-anything-minimax models --tts
+```
+
+## Models
+
+### Chat
+
+| Model | Description |
+|-------|-------------|
+| `MiniMax-M2.7` | Peak Performance. Ultimate Value. (default) |
+| `MiniMax-M2.7-highspeed` | Same performance, faster and more agile |
+
+### TTS
+
+| Model | Description |
+|-------|-------------|
+| `speech-2.8-hd` | High-definition TTS (default) |
+| `speech-2.8-turbo` | Fast TTS |
+
+## Environment Variables
+
+| Variable | Description |
+|----------|-------------|
+| `MINIMAX_API_KEY` | MiniMax API key (required) |
+| `MINIMAX_BASE_URL` | Override API base URL (optional) |
diff --git a/minimax/agent-harness/cli_anything/minimax/__init__.py b/minimax/agent-harness/cli_anything/minimax/__init__.py
new file mode 100644
index 000000000..1e82c396f
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/__init__.py
@@ -0,0 +1 @@
+"""cli_anything.minimax package."""
diff --git a/minimax/agent-harness/cli_anything/minimax/__main__.py b/minimax/agent-harness/cli_anything/minimax/__main__.py
new file mode 100644
index 000000000..49675a75f
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/__main__.py
@@ -0,0 +1,5 @@
+"""Entry point for python -m cli_anything.minimax."""
+from cli_anything.minimax.minimax_cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/minimax/agent-harness/cli_anything/minimax/core/__init__.py b/minimax/agent-harness/cli_anything/minimax/core/__init__.py
new file mode 100644
index 000000000..67ce27111
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/core/__init__.py
@@ -0,0 +1 @@
+"""cli_anything.minimax.core package."""
diff --git a/minimax/agent-harness/cli_anything/minimax/core/session.py b/minimax/agent-harness/cli_anything/minimax/core/session.py
new file mode 100644
index 000000000..7083eceb7
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/core/session.py
@@ -0,0 +1,98 @@
+"""Lightweight session for chat history management."""
+
+from __future__ import annotations
+
+import json
+import os
+from datetime import datetime
+from pathlib import Path
+
+
+def _locked_save_json(path, data, **dump_kwargs) -> None:
+ """Atomically write JSON with exclusive file locking."""
+ try:
+ f = open(path, "r+")
+ except FileNotFoundError:
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ f = open(path, "w")
+ with f:
+ _locked = False
+ try:
+ import fcntl
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
+ _locked = True
+ except (ImportError, OSError):
+ pass
+ try:
+ f.seek(0)
+ f.truncate()
+ json.dump(data, f, **dump_kwargs)
+ f.flush()
+ finally:
+ if _locked:
+ import fcntl
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
+
+
+class ChatSession:
+ """Lightweight session for chat history management."""
+
+ def __init__(self, session_file: str = None):
+ self.session_file = session_file or str(
+ Path.home() / ".cli-anything-minimax" / "session.json"
+ )
+ self.messages = []
+ self.history = []
+ self.max_history = 50
+ self.modified = False
+ if os.path.exists(self.session_file):
+ try:
+ with open(self.session_file, "r") as f:
+ data = json.load(f)
+ self.messages = data.get("messages", [])
+ self.history = data.get("history", [])
+ except (json.JSONDecodeError, IOError):
+ self.messages = []
+
+ def add_user_message(self, content: str):
+ self.messages.append({"role": "user", "content": content})
+ self.modified = True
+ self._save()
+
+ def add_assistant_message(self, content: str):
+ self.messages.append({"role": "assistant", "content": content})
+ self.modified = True
+ self._save()
+
+ def get_messages(self):
+ return self.messages.copy()
+
+ def clear(self):
+ self.messages = []
+ self.history = []
+ self.modified = True
+ self._save()
+
+ def status(self):
+ return {
+ "message_count": len(self.messages),
+ "history_count": len(self.history),
+ "modified": self.modified,
+ "session_file": self.session_file,
+ }
+
+ def _save(self):
+ _locked_save_json(
+ self.session_file,
+ {"messages": self.messages, "history": self.history},
+ indent=2,
+ )
+ self.modified = False
+
+ def save_history(self, command: str, result: dict):
+ self.history.append(
+ {"command": command, "result": result, "timestamp": str(datetime.now())}
+ )
+ if len(self.history) > self.max_history:
+ self.history = self.history[-self.max_history:]
+ self._save()
diff --git a/minimax/agent-harness/cli_anything/minimax/minimax_cli.py b/minimax/agent-harness/cli_anything/minimax/minimax_cli.py
new file mode 100644
index 000000000..2345fe965
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/minimax_cli.py
@@ -0,0 +1,489 @@
+#!/usr/bin/env python3
+"""MiniMax CLI — Chat and TTS client for MiniMax AI API.
+
+Usage:
+ # One-shot commands
+ cli-anything-minimax chat --prompt "Hello" --model MiniMax-M2.7
+ cli-anything-minimax stream --prompt "Tell me a story"
+ cli-anything-minimax tts --text "Hello world" --output hello.mp3
+
+ # Interactive REPL
+ cli-anything-minimax
+"""
+
+from __future__ import annotations
+
+import sys
+import os
+import json
+import click
+from pathlib import Path
+
+from cli_anything.minimax.core.session import ChatSession
+from cli_anything.minimax.utils.minimax_backend import (
+ get_api_key,
+ load_config,
+ save_config,
+ chat_completion,
+ chat_completion_stream,
+ tts_synthesize,
+ run_full_workflow,
+ CHAT_MODELS,
+ TTS_MODELS,
+ TTS_VOICES,
+ ENV_API_KEY,
+)
+
+_session = None
+_json_output = False
+_repl_mode = False
+
+
+def get_session():
+ global _session
+ if _session is None:
+ sf = str(Path.home() / ".cli-anything-minimax" / "session.json")
+ _session = ChatSession(session_file=sf)
+ return _session
+
+
+def output(data, message: str = ""):
+ if _json_output:
+ click.echo(json.dumps(data, indent=2, default=str))
+ else:
+ if message:
+ click.echo(message)
+ if isinstance(data, dict):
+ _print_dict(data)
+ else:
+ click.echo(str(data))
+
+
+def _print_dict(d: dict, indent: int = 0):
+ prefix = " " * indent
+ for k, v in d.items():
+ if isinstance(v, dict):
+ click.echo(f"{prefix}{k}:")
+ _print_dict(v, indent + 1)
+ elif isinstance(v, list):
+ click.echo(f"{prefix}{k}:")
+ _print_list(v, indent + 1)
+ else:
+ click.echo(f"{prefix}{k}: {v}")
+
+
+def _print_list(items: list, indent: int = 0):
+ prefix = " " * indent
+ for i, item in enumerate(items):
+ if isinstance(item, dict):
+ click.echo(f"{prefix}[{i}]")
+ _print_dict(item, indent + 1)
+ else:
+ click.echo(f"{prefix}- {item}")
+
+
+def handle_error(func):
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except (RuntimeError, ValueError) as e:
+ if _json_output:
+ click.echo(json.dumps({"error": str(e), "type": type(e).__name__}))
+ else:
+ click.echo(f"Error: {e}", err=True)
+ if not _repl_mode:
+ sys.exit(1)
+
+ wrapper.__name__ = func.__name__
+ wrapper.__doc__ = func.__doc__
+ return wrapper
+
+
[email protected](invoke_without_command=True)
[email protected]("--json", "use_json", is_flag=True, help="Output as JSON")
[email protected]("--api-key", "api_key_opt", type=str, default=None, help="MiniMax API key")
+ "--model",
+ "model_opt",
+ type=str,
+ default=None,
+ help="Model ID (default: MiniMax-M2.7)",
+)
+def cli(ctx, use_json, api_key_opt, model_opt):
+ """MiniMax CLI — Chat and TTS via MiniMax AI API."""
+ global _json_output
+ _json_output = use_json
+ ctx.ensure_object(dict)
+ ctx.obj["api_key"] = api_key_opt
+ ctx.obj["model"] = model_opt
+
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl)
+
+
[email protected]("--prompt", "-p", required=True, help="User prompt")
+ "--model",
+ "model_opt",
+ type=str,
+ default=None,
+ help="Model ID (default: MiniMax-M2.7)",
+)
+ "--temperature",
+ type=float,
+ default=None,
+ help="Temperature (0.0-1.0, default 1.0)",
+)
[email protected]("--max-tokens", type=int, default=None, help="Maximum tokens to generate")
+@handle_error
+def chat(ctx, prompt, model_opt=None, temperature=None, max_tokens=None):
+ """Chat with the MiniMax API."""
+ parent_key = ctx.obj.get("api_key") if ctx.obj else None
+ api_key = get_api_key(parent_key)
+ model = model_opt or (ctx.obj.get("model") if ctx.obj else None) or "MiniMax-M2.7"
+
+ session = get_session()
+ messages = []
+ messages.extend(session.get_messages())
+ messages.append({"role": "user", "content": prompt})
+
+ result = chat_completion(
+ api_key=api_key,
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ )
+
+ choices = result.get("choices", [])
+ content = choices[0].get("message", {}).get("content", "") if choices else ""
+
+ session.add_user_message(prompt)
+ session.add_assistant_message(content)
+
+ output_data = {"content": content}
+ usage = result.get("usage", {})
+ if usage:
+ output_data["usage"] = usage
+
+ output(output_data, f"✓ Response from {model}")
+
+
[email protected]("--prompt", "-p", required=True, help="User prompt")
+ "--model",
+ "model_opt",
+ type=str,
+ default=None,
+ help="Model ID (default: MiniMax-M2.7)",
+)
+ "--temperature",
+ type=float,
+ default=None,
+ help="Temperature (0.0-1.0, default 1.0)",
+)
[email protected]("--max-tokens", type=int, default=None, help="Maximum tokens to generate")
+@handle_error
+def stream(ctx, prompt, model_opt=None, temperature=None, max_tokens=None):
+ """Stream chat completion from MiniMax."""
+ parent_key = ctx.obj.get("api_key") if ctx.obj else None
+ api_key = get_api_key(parent_key)
+ model = model_opt or (ctx.obj.get("model") if ctx.obj else None) or "MiniMax-M2.7"
+
+ session = get_session()
+ messages = []
+ messages.extend(session.get_messages())
+ messages.append({"role": "user", "content": prompt})
+
+ full_response = ""
+
+ def on_chunk(chunk_content):
+ if chunk_content:
+ nonlocal full_response
+ full_response += chunk_content
+ if not _json_output:
+ click.echo(chunk_content, nl=False)
+
+ chat_completion_stream(
+ api_key=api_key,
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ on_chunk=on_chunk,
+ )
+
+ if not _json_output:
+ click.echo()
+
+ session.add_user_message(prompt)
+ session.add_assistant_message(full_response)
+
+ output({"content": full_response}, "✓ Stream completed")
+
+
[email protected]("--text", "-t", required=True, help="Text to synthesize")
+ "--model",
+ "model_opt",
+ type=str,
+ default="speech-2.8-hd",
+ show_default=True,
+ help="TTS model ID",
+)
+ "--voice",
+ type=str,
+ default="English_Graceful_Lady",
+ show_default=True,
+ help=f"Voice ID. Available: {', '.join(TTS_VOICES)}",
+)
+ "--output",
+ "-o",
+ type=click.Path(),
+ default="output.mp3",
+ show_default=True,
+ help="Output audio file path",
+)
+@handle_error
+def tts(ctx, text, model_opt, voice, output):
+ """Synthesize text to speech using MiniMax TTS."""
+ parent_key = ctx.obj.get("api_key") if ctx.obj else None
+ api_key = get_api_key(parent_key)
+
+ audio_data = tts_synthesize(
+ api_key=api_key,
+ text=text,
+ model=model_opt,
+ voice=voice,
+ output_path=output,
+ )
+
+ output_data = {
+ "output_file": output,
+ "size_bytes": len(audio_data),
+ "model": model_opt,
+ "voice": voice,
+ }
+ output(output_data, f"✓ Audio saved to {output} ({len(audio_data)} bytes)")
+
+
+def session():
+ """Session management commands."""
+ pass
+
+
+@handle_error
+def session_status():
+ """Show session status."""
+ s = get_session()
+ output(s.status(), "Session status")
+
+
+@handle_error
+def session_clear():
+ """Clear session history."""
+ s = get_session()
+ s.clear()
+ output({"cleared": True}, "Session cleared")
+
+
[email protected]("--limit", "-n", type=int, default=20, help="Maximum entries to show")
+@handle_error
+def session_history(limit):
+ """Show command history."""
+ s = get_session()
+ history = s.history[-limit:]
+ output(history, f"History ({len(history)} entries)")
+
+
+def config():
+ """Configuration management."""
+ pass
+
+
[email protected]("key", type=click.Choice(["api_key", "default_model"]))
+def config_set(key, value):
+ """Set a configuration value."""
+ cfg = load_config()
+ cfg[key] = value
+ save_config(cfg)
+ display = value[:10] + "..." if key == "api_key" and len(value) > 10 else value
+ output({"key": key, "value": display}, f"✓ Set {key} = {display}")
+
+
[email protected]("key", required=False)
+def config_get(key):
+ """Get a configuration value (or show all)."""
+ cfg = load_config()
+ if key:
+ val = cfg.get(key)
+ if val:
+ if key == "api_key" and len(val) > 10:
+ val = val[:10] + "..."
+ output({"key": key, "value": val}, f"{key} = {val}")
+ else:
+ output({"key": key, "value": None}, f"{key} is not set")
+ else:
+ if cfg:
+ masked = {}
+ for k, v in cfg.items():
+ masked[k] = v[:10] + "..." if k == "api_key" and len(v) > 10 else v
+ output(masked)
+ else:
+ output({}, "No configuration set")
+
+
+def config_delete(key):
+ """Delete a configuration value."""
+ cfg = load_config()
+ if key in cfg:
+ del cfg[key]
+ save_config(cfg)
+ output({"deleted": key}, f"✓ Deleted {key}")
+ else:
+ output({"error": f"{key} not found"}, f"{key} not found in config")
+
+
+def config_path():
+ """Show the config file path."""
+ from cli_anything.minimax.utils.minimax_backend import CONFIG_FILE
+
+ output({"path": str(CONFIG_FILE)}, f"Config file: {CONFIG_FILE}")
+
+
+ "--model",
+ "model_opt",
+ type=str,
+ default=None,
+ help="Chat model ID to test (default: MiniMax-M2.7)",
+)
+@handle_error
+def test(model_opt=None):
+ """Test MiniMax API connectivity."""
+ api_key = get_api_key()
+ model = model_opt or "MiniMax-M2.7"
+
+ result = chat_completion(
+ api_key=api_key,
+ model=model,
+ messages=[{"role": "user", "content": "Say 'ok'"}],
+ max_tokens=5,
+ )
+
+ choices = result.get("choices", [])
+ content = choices[0].get("message", {}).get("content", "") if choices else ""
+
+ output(
+ {"status": "ok", "model": model, "response": content},
+ "✓ MiniMax API test passed",
+ )
+
+
[email protected]("--tts", "show_tts", is_flag=True, help="Show TTS models instead of chat models")
+@handle_error
+def models(show_tts):
+ """List available MiniMax models."""
+ if show_tts:
+ for m in TTS_MODELS:
+ click.echo(f"{m['id']} — {m['description']}")
+ else:
+ for m in CHAT_MODELS:
+ click.echo(f"{m['id']} — {m['description']}")
+
+
+@handle_error
+def voices():
+ """List available TTS voice IDs."""
+ for v in TTS_VOICES:
+ click.echo(v)
+
+
[email protected]("repl", hidden=True)
+@handle_error
+def repl():
+ """Enter interactive REPL mode."""
+ global _repl_mode
+ _repl_mode = True
+
+ from cli_anything.minimax.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("minimax", version="1.0.0")
+ skin.print_banner()
+
+ pt_session = skin.create_prompt_session()
+
+ commands = {
+ "chat --prompt <text>": "Chat with MiniMax (MiniMax-M2.7)",
+ "stream --prompt <text>": "Stream chat completion",
+ "tts --text <text> --output out.mp3": "Text-to-speech synthesis",
+ "models": "List chat models",
+ "models --tts": "List TTS models",
+ "voices": "List TTS voice IDs",
+ "session status": "Show session status",
+ "session clear": "Clear session history",
+ "config set <key> <val>": "Set configuration",
+ "config get [key]": "Show configuration",
+ "test [--model <id>]": "Test API connectivity",
+ "help": "Show this help",
+ "quit / exit": "Exit REPL",
+ }
+
+ while True:
+ try:
+ line = skin.get_input(pt_session, context="minimax")
+ except (EOFError, KeyboardInterrupt):
+ skin.print_goodbye()
+ break
+
+ if not line:
+ continue
+ if line in ("quit", "exit", "q"):
+ skin.print_goodbye()
+ break
+ if line == "help":
+ skin.help(commands)
+ continue
+
+ parts = line.split()
+ try:
+ cli.main(parts, standalone_mode=False)
+ except SystemExit:
+ pass
+ except click.exceptions.UsageError as e:
+ skin.error(str(e))
+ except Exception as e:
+ skin.error(str(e))
+
+
+def main():
+ cli()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/minimax/agent-harness/cli_anything/minimax/skills/SKILL.md b/minimax/agent-harness/cli_anything/minimax/skills/SKILL.md
new file mode 100644
index 000000000..6dfc75629
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/skills/SKILL.md
@@ -0,0 +1,137 @@
+---
+name: >-
+ cli-anything-minimax
+description: >-
+ Command-line interface for MiniMax AI — chat (MiniMax-M2.7) and TTS (speech-2.8-hd) via the MiniMax API.
+---
+
+# cli-anything-minimax
+
+A CLI harness for **MiniMax AI** — providing chat completions and text-to-speech synthesis through the MiniMax API.
+
+## Installation
+
+```bash
+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=minimax/agent-harness
+```
+
+**Prerequisites:**
+- Python 3.10+
+- MiniMax API key from [platform.minimax.io](https://platform.minimax.io)
+
+## Usage
+
+### Basic Commands
+
+```bash
+# Show help
+cli-anything-minimax --help
+
+# Start interactive REPL
+cli-anything-minimax
+
+# Chat with MiniMax-M2.7
+cli-anything-minimax chat --prompt "What is AI?"
+
+# High-speed model
+cli-anything-minimax chat --prompt "Quick answer" --model MiniMax-M2.7-highspeed
+
+# Stream chat response
+cli-anything-minimax stream --prompt "Write a poem about code"
+
+# Synthesize speech
+cli-anything-minimax tts --text "Hello world" --output hello.mp3
+
+# JSON output for agents
+cli-anything-minimax --json chat --prompt "Hello"
+```
+
+## Command Groups
+
+### Chat
+
+| Command | Description |
+|---------|-------------|
+| `chat` | Chat with MiniMax LLM |
+| `stream` | Stream chat completion |
+
+### TTS
+
+| Command | Description |
+|---------|-------------|
+| `tts` | Synthesize text to speech (hex-decoded MP3 via SSE) |
+| `voices` | List available voice IDs |
+
+### Session
+
+| Command | Description |
+|---------|-------------|
+| `session status` | Show session status |
+| `session clear` | Clear session history |
+| `session history` | Show command history |
+
+### Config
+
+| Command | Description |
+|---------|-------------|
+| `config set` | Set a configuration value |
+| `config get` | Get a configuration value (or show all) |
+| `config delete` | Delete a configuration value |
+| `config path` | Show the config file path |
+
+### Utility
+
+| Command | Description |
+|---------|-------------|
+| `test` | Test API connectivity |
+| `models` | List chat models |
+| `models --tts` | List TTS models |
+
+## Examples
+
+### Configure API Key
+
+```bash
+export MINIMAX_API_KEY="your-api-key"
+# or
+cli-anything-minimax config set api_key "your-api-key"
+```
+
+### Chat
+
+```bash
+cli-anything-minimax chat --prompt "Explain quantum computing"
+cli-anything-minimax stream --prompt "Write a Python quicksort"
+```
+
+### TTS
+
+```bash
+cli-anything-minimax tts --text "Hello!" --output hello.mp3
+cli-anything-minimax tts --text "Fast" --model speech-2.8-turbo --voice English_Insightful_Speaker --output fast.mp3
+```
+
+## Chat Models
+
+| Model ID | Description |
+|----------|-------------|
+| `MiniMax-M2.7` | Peak Performance. Ultimate Value. (default) |
+| `MiniMax-M2.7-highspeed` | Same performance, faster and more agile |
+
+## TTS Models
+
+| Model ID | Description |
+|----------|-------------|
+| `speech-2.8-hd` | High-definition TTS (default) |
+| `speech-2.8-turbo` | Fast TTS |
+
+## For AI Agents
+
+1. **Always use `--json` flag** for parseable output
+2. **Check return codes** — 0 for success, non-zero for errors
+3. **Parse stderr** for error messages on failure
+4. **Use absolute paths** for TTS output files
+
+## Version
+
+1.0.0
diff --git a/minimax/agent-harness/cli_anything/minimax/tests/__init__.py b/minimax/agent-harness/cli_anything/minimax/tests/__init__.py
new file mode 100644
index 000000000..13f21a124
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/tests/__init__.py
@@ -0,0 +1 @@
+"""cli_anything.minimax.tests package."""
diff --git a/minimax/agent-harness/cli_anything/minimax/tests/test_core.py b/minimax/agent-harness/cli_anything/minimax/tests/test_core.py
new file mode 100644
index 000000000..056db2a24
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/tests/test_core.py
@@ -0,0 +1,290 @@
+"""Unit tests for MiniMax backend — no API key required (mock HTTP)."""
+
+import json
+import requests
+from unittest.mock import patch, MagicMock
+
+from cli_anything.minimax.utils.minimax_backend import (
+ get_api_key,
+ load_config,
+ save_config,
+ chat_completion,
+ chat_completion_stream,
+ tts_synthesize,
+ run_full_workflow,
+ CHAT_MODELS,
+ TTS_MODELS,
+ TTS_VOICES,
+)
+
+
+# ── API key resolution ─────────────────────────────────────────────────────────
+
+def test_get_api_key_priority():
+ """Test API key resolution order: CLI arg > env > config."""
+ with patch.dict("os.environ", {}, clear=True):
+ assert get_api_key(None) is None
+
+ # CLI arg takes priority
+ assert get_api_key("cli-key-123") == "cli-key-123"
+
+ with patch.dict("os.environ", {"MINIMAX_API_KEY": "env-key-456"}):
+ assert get_api_key(None) == "env-key-456"
+
+
+def test_get_api_key_no_env_no_config():
+ """No key available returns None."""
+ with patch.dict("os.environ", {}, clear=True):
+ with patch("cli_anything.minimax.utils.minimax_backend.load_config", return_value={}):
+ assert get_api_key(None) is None
+
+
+# ── Config persistence ─────────────────────────────────────────────────────────
+
+def test_save_and_load_config(tmp_path):
+ """Test config save/load."""
+ import tempfile
+ from pathlib import Path
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ config_file = Path(tmpdir) / "config.json"
+ import cli_anything.minimax.utils.minimax_backend as backend
+
+ original_file = backend.CONFIG_FILE
+ backend.CONFIG_FILE = config_file
+ try:
+ save_config({"api_key": "test-key-123", "default_model": "MiniMax-M2.7"})
+ loaded = load_config()
+ assert loaded["api_key"] == "test-key-123"
+ assert loaded["default_model"] == "MiniMax-M2.7"
+ finally:
+ backend.CONFIG_FILE = original_file
+
+
+# ── Chat models ────────────────────────────────────────────────────────────────
+
+def test_chat_models_list():
+ """MiniMax-M2.7 and MiniMax-M2.7-highspeed must be in the model list."""
+ model_ids = [m["id"] for m in CHAT_MODELS]
+ assert "MiniMax-M2.7" in model_ids
+ assert "MiniMax-M2.7-highspeed" in model_ids
+ assert len(CHAT_MODELS) == 2
+
+
+def test_tts_models_list():
+ """speech-2.8-hd must be the first (default) TTS model."""
+ assert TTS_MODELS[0]["id"] == "speech-2.8-hd"
+ assert any(m["id"] == "speech-2.8-turbo" for m in TTS_MODELS)
+
+
+def test_tts_voices_list():
+ """Verify TTS voices are populated."""
+ assert len(TTS_VOICES) > 0
+ assert "English_Graceful_Lady" in TTS_VOICES
+
+
+# ── Chat completion ────────────────────────────────────────────────────────────
+
+def test_chat_completion_success():
+ """Test chat completion with mock response."""
+ mock_response = {
+ "choices": [
+ {"message": {"role": "assistant", "content": "Hello! How can I help?"}}
+ ],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 12, "total_tokens": 22},
+ }
+
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = mock_response
+ mock_post.return_value = mock_resp
+
+ result = chat_completion(
+ api_key="fake-key",
+ model="MiniMax-M2.7",
+ messages=[{"role": "user", "content": "Hello"}],
+ )
+
+ assert result["choices"][0]["message"]["content"] == "Hello! How can I help?"
+ assert result["usage"]["total_tokens"] == 22
+
+
+def test_chat_completion_uses_minimax_base_url():
+ """Verify chat completion calls api.minimax.io/v1."""
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"choices": [{"message": {"content": "ok"}}]}
+ mock_post.return_value = mock_resp
+
+ chat_completion(api_key="key", model="MiniMax-M2.7", messages=[])
+
+ call_url = mock_post.call_args[0][0]
+ assert "minimax.io" in call_url
+ assert "/v1/chat/completions" in call_url
+
+
+def test_chat_completion_default_temperature():
+ """Temperature defaults to 1.0 (MiniMax requirement)."""
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"choices": [{"message": {"content": "ok"}}]}
+ mock_post.return_value = mock_resp
+
+ chat_completion(api_key="key", model="MiniMax-M2.7", messages=[])
+
+ body = mock_post.call_args[1]["json"]
+ assert body["temperature"] == 1.0
+
+
+def test_chat_completion_error():
+ """Test chat completion with error response."""
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 401
+ mock_resp.text = '{"error": "Invalid API key"}'
+ mock_resp.raise_for_status.side_effect = requests.HTTPError("HTTP 401")
+ mock_post.return_value = mock_resp
+
+ try:
+ chat_completion(api_key="invalid-key", messages=[])
+ assert False, "Should have raised RuntimeError"
+ except RuntimeError as e:
+ assert "MiniMax API error" in str(e)
+
+
+def test_chat_completion_missing_api_key():
+ """Missing API key raises RuntimeError."""
+ with patch.dict("os.environ", {}, clear=True):
+ with patch("cli_anything.minimax.utils.minimax_backend.load_config", return_value={}):
+ try:
+ chat_completion(api_key=None, messages=[])
+ assert False, "Should have raised RuntimeError"
+ except RuntimeError as e:
+ assert "API key" in str(e)
+
+
+# ── Streaming ─────────────────────────────────────────────────────────────────
+
+def test_chat_completion_stream_success():
+ """Test streaming with mock SSE response."""
+ mock_chunks = [
+ b'data: {"choices": [{"delta": {"content": "Hello"}}]}\n\n',
+ b'data: {"choices": [{"delta": {"content": " world"}}]}\n\n',
+ b"data: [DONE]\n\n",
+ ]
+
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.iter_lines.return_value = mock_chunks
+ mock_post.return_value = mock_resp
+
+ received = []
+
+ def on_chunk(c):
+ received.append(c)
+
+ result = chat_completion_stream(
+ api_key="fake-key",
+ model="MiniMax-M2.7",
+ messages=[{"role": "user", "content": "Hi"}],
+ on_chunk=on_chunk,
+ )
+
+ assert result == "Hello world"
+ assert received == ["Hello", " world"]
+
+
+# ── TTS ────────────────────────────────────────────────────────────────────────
+
+def test_tts_synthesize_hex_decoding(tmp_path):
+ """TTS audio is hex-encoded and must be decoded correctly."""
+ # 'Hello' in hex-encoded fake MP3 bytes
+ hex_audio = bytes([0xFF, 0xFB]).hex() # minimal fake MP3 header
+
+ sse_line = json.dumps(
+ {
+ "data": {"audio": hex_audio, "status": 2},
+ "base_resp": {"status_code": 0, "status_msg": "success"},
+ }
+ )
+
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.iter_content.return_value = [f"data:{sse_line}\n\n".encode()]
+ mock_post.return_value = mock_resp
+
+ out_file = str(tmp_path / "test.mp3")
+ audio = tts_synthesize(
+ api_key="fake-key",
+ text="Hello",
+ model="speech-2.8-hd",
+ voice="English_Graceful_Lady",
+ output_path=out_file,
+ )
+
+ assert len(audio) == 2
+ assert audio == bytes.fromhex(hex_audio)
+
+
+def test_tts_synthesize_uses_correct_endpoint():
+ """TTS must call /v1/t2a_v2."""
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.iter_content.return_value = []
+ mock_post.return_value = mock_resp
+
+ tts_synthesize(api_key="key", text="test")
+
+ call_url = mock_post.call_args[0][0]
+ assert "/v1/t2a_v2" in call_url
+
+
+def test_tts_synthesize_api_error():
+ """TTS raises RuntimeError on API-level error response."""
+ err_sse = json.dumps(
+ {"base_resp": {"status_code": 2013, "status_msg": "invalid voice"}}
+ )
+
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.iter_content.return_value = [f"data:{err_sse}\n\n".encode()]
+ mock_post.return_value = mock_resp
+
+ try:
+ tts_synthesize(api_key="key", text="test")
+ assert False, "Should have raised RuntimeError"
+ except RuntimeError as e:
+ assert "invalid voice" in str(e)
+
+
+# ── Full workflow ──────────────────────────────────────────────────────────────
+
+def test_run_full_workflow():
+ """Test full workflow with mock response."""
+ mock_response = {
+ "choices": [{"message": {"role": "assistant", "content": "Here is the response"}}],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25},
+ }
+
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = mock_response
+ mock_post.return_value = mock_resp
+
+ result = run_full_workflow(
+ api_key="fake-key",
+ prompt="Test prompt",
+ system_message="You are helpful",
+ )
+
+ assert result["content"] == "Here is the response"
+ assert result["prompt_tokens"] == 10
+ assert result["total_tokens"] == 25
diff --git a/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.py b/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.py
new file mode 100644
index 000000000..4ead4c685
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/tests/test_full_e2e.py
@@ -0,0 +1,158 @@
+"""E2E tests for MiniMax CLI — uses real API when MINIMAX_API_KEY is set."""
+
+import os
+import json
+from unittest.mock import patch, MagicMock
+
+from cli_anything.minimax.utils.minimax_backend import (
+ chat_completion,
+ chat_completion_stream,
+ tts_synthesize,
+)
+
+API_KEY = os.environ.get("MINIMAX_API_KEY")
+
+
+# ── Chat ───────────────────────────────────────────────────────────────────────
+
+def test_chat_completion_e2e():
+ """Test chat completion — real API if key present, otherwise mock."""
+ if not API_KEY:
+ mock_response = {
+ "choices": [{"message": {"role": "assistant", "content": "ok"}}],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
+ }
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = mock_response
+ mock_post.return_value = mock_resp
+
+ result = chat_completion(
+ api_key="sk-mock",
+ model="MiniMax-M2.7",
+ messages=[{"role": "user", "content": "Say ok"}],
+ )
+ assert result["choices"][0]["message"]["content"] == "ok"
+ return
+
+ result = chat_completion(
+ api_key=API_KEY,
+ model="MiniMax-M2.7",
+ messages=[{"role": "user", "content": "Say 'ok'"}],
+ max_tokens=10,
+ )
+ assert "choices" in result
+ assert result["choices"][0]["message"]["content"]
+
+
+def test_chat_completion_highspeed_model_e2e():
+ """Test MiniMax-M2.7-highspeed model."""
+ if not API_KEY:
+ mock_response = {
+ "choices": [{"message": {"role": "assistant", "content": "done"}}],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6},
+ }
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = mock_response
+ mock_post.return_value = mock_resp
+
+ result = chat_completion(
+ api_key="sk-mock",
+ model="MiniMax-M2.7-highspeed",
+ messages=[{"role": "user", "content": "Say done"}],
+ )
+ body = mock_post.call_args[1]["json"]
+ assert body["model"] == "MiniMax-M2.7-highspeed"
+ assert result["choices"][0]["message"]["content"] == "done"
+ return
+
+ result = chat_completion(
+ api_key=API_KEY,
+ model="MiniMax-M2.7-highspeed",
+ messages=[{"role": "user", "content": "Say 'done'"}],
+ max_tokens=10,
+ )
+ assert "choices" in result
+ assert result["choices"][0]["message"]["content"]
+
+
+def test_chat_stream_e2e():
+ """Test streaming chat."""
+ if not API_KEY:
+ mock_chunks = [
+ b'data: {"choices": [{"delta": {"content": "Hello"}}]}\n\n',
+ b'data: {"choices": [{"delta": {"content": "!"}}]}\n\n',
+ b"data: [DONE]\n\n",
+ ]
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.iter_lines.return_value = mock_chunks
+ mock_post.return_value = mock_resp
+
+ full = ""
+
+ def on_chunk(c):
+ nonlocal full
+ full += c
+
+ chat_completion_stream(
+ api_key="sk-mock",
+ model="MiniMax-M2.7",
+ messages=[{"role": "user", "content": "Hello"}],
+ on_chunk=on_chunk,
+ )
+ assert full == "Hello!"
+ return
+
+ # Real streaming test
+ received = []
+ chat_completion_stream(
+ api_key=API_KEY,
+ model="MiniMax-M2.7",
+ messages=[{"role": "user", "content": "Say 'ok' only"}],
+ max_tokens=5,
+ on_chunk=lambda c: received.append(c),
+ )
+ assert len(received) > 0
+
+
+# ── TTS ────────────────────────────────────────────────────────────────────────
+
+def test_tts_e2e(tmp_path):
+ """Test TTS synthesis."""
+ if not API_KEY:
+ hex_audio = bytes([0xFF, 0xFB, 0x00]).hex()
+ sse_line = json.dumps({
+ "data": {"audio": hex_audio, "status": 2},
+ "base_resp": {"status_code": 0, "status_msg": "success"},
+ })
+ with patch("requests.post") as mock_post:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.iter_content.return_value = [f"data:{sse_line}\n\n".encode()]
+ mock_post.return_value = mock_resp
+
+ out = str(tmp_path / "test.mp3")
+ audio = tts_synthesize(
+ api_key="sk-mock",
+ text="Hello world",
+ model="speech-2.8-hd",
+ voice="English_Graceful_Lady",
+ output_path=out,
+ )
+ assert len(audio) == 3
+ return
+
+ out = str(tmp_path / "real.mp3")
+ audio = tts_synthesize(
+ api_key=API_KEY,
+ text="Hello, this is a test.",
+ model="speech-2.8-hd",
+ voice="English_Graceful_Lady",
+ output_path=out,
+ )
+ assert len(audio) > 100, "Expected non-trivial audio output"
diff --git a/minimax/agent-harness/cli_anything/minimax/utils/__init__.py b/minimax/agent-harness/cli_anything/minimax/utils/__init__.py
new file mode 100644
index 000000000..1e4c45052
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/utils/__init__.py
@@ -0,0 +1 @@
+"""cli_anything.minimax.utils package."""
diff --git a/minimax/agent-harness/cli_anything/minimax/utils/minimax_backend.py b/minimax/agent-harness/cli_anything/minimax/utils/minimax_backend.py
new file mode 100644
index 000000000..8a5a42648
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/utils/minimax_backend.py
@@ -0,0 +1,291 @@
+"""MiniMax API backend — wraps the MiniMax OpenAI-compatible REST API and TTS API."""
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from typing import Optional, Callable
+
+try:
+ import requests
+except ImportError:
+ print("requests library not found. Install with: pip3 install requests", file=sys.stderr)
+ sys.exit(1)
+
+CHAT_API_BASE = os.environ.get("MINIMAX_BASE_URL", "https://api.minimax.io/v1").rstrip("/")
+TTS_API_BASE = os.environ.get("MINIMAX_BASE_URL", "https://api.minimax.io").rstrip("/")
+CONFIG_DIR = Path.home() / ".config" / "cli-anything-minimax"
+CONFIG_FILE = CONFIG_DIR / "config.json"
+ENV_API_KEY = "MINIMAX_API_KEY"
+
+CHAT_MODELS = [
+ {"id": "MiniMax-M2.7", "description": "Peak Performance. Ultimate Value. Master the Complex"},
+ {"id": "MiniMax-M2.7-highspeed", "description": "Same performance, faster and more agile"},
+]
+
+TTS_MODELS = [
+ {"id": "speech-2.8-hd", "description": "High-definition TTS (recommended default)"},
+ {"id": "speech-2.8-turbo", "description": "Fast TTS"},
+]
+
+TTS_VOICES = [
+ "English_Graceful_Lady",
+ "English_Insightful_Speaker",
+ "English_radiant_girl",
+ "English_Persuasive_Man",
+ "English_Lucky_Robot",
+ "English_expressive_narrator",
+]
+
+
+def get_config_dir() -> Path:
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+ return CONFIG_DIR
+
+
+def load_config() -> dict:
+ if not CONFIG_FILE.exists():
+ return {}
+ try:
+ with open(CONFIG_FILE, "r") as f:
+ return json.load(f)
+ except (json.JSONDecodeError, IOError):
+ return {}
+
+
+def save_config(config: dict) -> None:
+ get_config_dir()
+ with open(CONFIG_FILE, "w") as f:
+ json.dump(config, f, indent=2)
+ CONFIG_FILE.chmod(0o600)
+
+
+def get_api_key(cli_key: Optional[str] = None) -> Optional[str]:
+ if cli_key:
+ return cli_key
+ env_key = os.environ.get(ENV_API_KEY)
+ if env_key:
+ return env_key
+ return load_config().get("api_key")
+
+
+def _require_api_key(api_key: Optional[str]) -> str:
+ if not api_key:
+ raise RuntimeError(
+ "MiniMax API key not found. Provide one via:\n"
+ " 1. --api-key sk-xxx\n"
+ f" 2. export {ENV_API_KEY}=sk-xxx\n"
+ " 3. cli-anything-minimax config set api_key sk-xxx\n"
+ "Get a key at https://platform.minimax.io"
+ )
+ return api_key
+
+
+def _make_auth_headers(api_key: str) -> dict:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+
+
+def chat_completion(
+ api_key: Optional[str] = None,
+ model: str = "MiniMax-M2.7",
+ messages: Optional[list] = None,
+ temperature: Optional[float] = None,
+ max_tokens: Optional[int] = None,
+) -> dict:
+ api_key = _require_api_key(api_key)
+ if messages is None:
+ messages = []
+ body: dict = {"model": model, "messages": messages}
+ # MiniMax temperature range is (0.0, 1.0], default 1.0
+ body["temperature"] = temperature if temperature is not None else 1.0
+ if max_tokens is not None:
+ body["max_tokens"] = max_tokens
+ headers = _make_auth_headers(api_key)
+ resp = None
+ try:
+ resp = requests.post(
+ f"{CHAT_API_BASE}/chat/completions",
+ json=body,
+ headers=headers,
+ timeout=60,
+ )
+ resp.raise_for_status()
+ return resp.json()
+ except requests.RequestException:
+ detail = ""
+ if resp is not None:
+ detail = resp.text[:500]
+ raise RuntimeError(f"MiniMax API error: {detail}")
+
+
+def chat_completion_stream(
+ api_key: Optional[str] = None,
+ model: str = "MiniMax-M2.7",
+ messages: Optional[list] = None,
+ temperature: Optional[float] = None,
+ max_tokens: Optional[int] = None,
+ on_chunk: Optional[Callable[[str], None]] = None,
+) -> str:
+ api_key = _require_api_key(api_key)
+ if messages is None:
+ messages = []
+ body: dict = {
+ "model": model,
+ "messages": messages,
+ "stream": True,
+ "temperature": temperature if temperature is not None else 1.0,
+ }
+ if max_tokens is not None:
+ body["max_tokens"] = max_tokens
+ headers = _make_auth_headers(api_key)
+ full_response = ""
+ try:
+ resp = requests.post(
+ f"{CHAT_API_BASE}/chat/completions",
+ json=body,
+ headers=headers,
+ timeout=120,
+ stream=True,
+ )
+ resp.raise_for_status()
+ for line in resp.iter_lines():
+ if not line:
+ continue
+ line = line.decode("utf-8")
+ if line.startswith("data: "):
+ data_str = line[6:]
+ if data_str.strip() == "[DONE]":
+ break
+ try:
+ data = json.loads(data_str)
+ content = (
+ data.get("choices", [{}])[0].get("delta", {}).get("content", "")
+ )
+ if content:
+ full_response += content
+ if on_chunk:
+ on_chunk(content)
+ except json.JSONDecodeError:
+ continue
+ return full_response
+ except requests.RequestException as e:
+ raise RuntimeError(f"MiniMax streaming error: {e}")
+
+
+def tts_synthesize(
+ api_key: Optional[str] = None,
+ text: str = "",
+ model: str = "speech-2.8-hd",
+ voice: str = "English_Graceful_Lady",
+ output_path: Optional[str] = None,
+) -> bytes:
+ """Synthesize text to speech using MiniMax TTS API (SSE stream, hex-encoded audio)."""
+ api_key = _require_api_key(api_key)
+ headers = _make_auth_headers(api_key)
+ body = {
+ "model": model,
+ "text": text,
+ "stream": True,
+ "voice_setting": {
+ "voice_id": voice,
+ "speed": 1,
+ "vol": 1,
+ "pitch": 0,
+ },
+ "audio_setting": {
+ "sample_rate": 32000,
+ "bitrate": 128000,
+ "format": "mp3",
+ "channel": 1,
+ },
+ }
+ try:
+ resp = requests.post(
+ f"{TTS_API_BASE}/v1/t2a_v2",
+ json=body,
+ headers=headers,
+ timeout=120,
+ stream=True,
+ )
+ resp.raise_for_status()
+ except requests.RequestException as e:
+ raise RuntimeError(f"MiniMax TTS error: {e}")
+
+ # Parse SSE stream — collect hex-encoded audio chunks
+ audio_chunks: list[bytes] = []
+ buffer = ""
+ for raw in resp.iter_content(chunk_size=None):
+ buffer += raw.decode("utf-8", errors="replace")
+ lines = buffer.split("\n")
+ buffer = lines.pop()
+ for line in lines:
+ if not line.startswith("data:"):
+ continue
+ json_str = line[5:].strip()
+ if not json_str or json_str == "[DONE]":
+ continue
+ try:
+ event = json.loads(json_str)
+ # Check API-level errors
+ base_resp = event.get("base_resp", {})
+ if base_resp.get("status_code", 0) != 0:
+ raise RuntimeError(
+ f"MiniMax TTS API error: {base_resp.get('status_msg', 'unknown')}"
+ )
+ audio_hex = event.get("data", {}).get("audio", "")
+ if audio_hex:
+ audio_chunks.append(bytes.fromhex(audio_hex))
+ except (json.JSONDecodeError, ValueError):
+ continue
+
+ audio_data = b"".join(audio_chunks)
+ if output_path:
+ with open(output_path, "wb") as f:
+ f.write(audio_data)
+ return audio_data
+
+
+def run_full_workflow(
+ api_key: Optional[str] = None,
+ model: str = "MiniMax-M2.7",
+ prompt: str = "",
+ system_message: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_tokens: Optional[int] = None,
+ on_chunk: Optional[Callable[[str], None]] = None,
+) -> dict:
+ messages = []
+ if system_message:
+ messages.append({"role": "system", "content": system_message})
+ messages.append({"role": "user", "content": prompt})
+ if on_chunk:
+ response = chat_completion_stream(
+ api_key=api_key,
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ on_chunk=on_chunk,
+ )
+ return {"content": response}
+ else:
+ result = chat_completion(
+ api_key=api_key,
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ )
+ choices = result.get("choices", [])
+ if choices:
+ return {
+ "content": choices[0].get("message", {}).get("content", ""),
+ "prompt_tokens": result.get("usage", {}).get("prompt_tokens", 0),
+ "completion_tokens": result.get("usage", {}).get("completion_tokens", 0),
+ "total_tokens": result.get("usage", {}).get("total_tokens", 0),
+ }
+ return {"content": ""}
diff --git a/minimax/agent-harness/cli_anything/minimax/utils/repl_skin.py b/minimax/agent-harness/cli_anything/minimax/utils/repl_skin.py
new file mode 100644
index 000000000..68d5a179a
--- /dev/null
+++ b/minimax/agent-harness/cli_anything/minimax/utils/repl_skin.py
@@ -0,0 +1,518 @@
+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner()
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# ── ANSI color codes (no external deps for core styling) ──────────────
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors — each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+ "anygen": "\033[38;5;141m", # soft violet
+ "novita": "\033[38;5;81m", # vivid blue (for Novita AI)
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# ── Brand icon ────────────────────────────────────────────────────────
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"
+_ICON_SMALL = f"{_CYAN}▸{_RESET}"
+
+# ── Box drawing characters ────────────────────────────────────────────
+
+_H_LINE = "─"
+_V_LINE = "│"
+_TL = "╭"
+_TR = "╮"
+_BL = "╰"
+_BR = "╯"
+_T_DOWN = "┬"
+_T_UP = "┴"
+_T_RIGHT = "├"
+_T_LEFT = "┤"
+_CROSS = "┼"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(
+ self, software: str, version: str = "1.0.0", history_file: str | None = None
+ ):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # ── Banner ────────────────────────────────────────────────────────
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: ◆ cli-anything · Novita
+ icon = self._c(_CYAN + _BOLD, "◆")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "·")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # ── Prompt ────────────────────────────────────────────────────────
+
+ def prompt(
+ self, project_name: str = "", modified: bool = False, context: str = ""
+ ) -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}◆{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, "]"))
+
+ parts.append(self._c(_GRAY, " ❯ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(
+ self, project_name: str = "", modified: bool = False, context: str = ""
+ ):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "◆ "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " ❯ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict(
+ {
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ }
+ )
+
+ # ── Messages ──────────────────────────────────────────────────────
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "✓")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "✗")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "⚠")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "●")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # ── Status display ────────────────────────────────────────────────
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # ── Table display ─────────────────────────────────────────────────
+
+ def table(self, headers: list[str], rows: list[list[str]], max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i])) for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(
+ _DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}"
+ )
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # ── Help display ──────────────────────────────────────────────────
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # ── Goodbye ───────────────────────────────────────────────────────
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # ── Prompt toolkit session factory ────────────────────────────────
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(
+ self,
+ pt_session,
+ project_name: str = "",
+ modified: bool = False,
+ context: str = "",
+ ) -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # ── Toolbar builder ───────────────────────────────────────────────
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " │ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+
+ return toolbar
+
+
+# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;81m": "#5fd7ff", # novita vivid blue
+ "\033[38;5;141m": "#af87ff", # anygen soft violet
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/minimax/agent-harness/setup.py b/minimax/agent-harness/setup.py
new file mode 100644
index 000000000..1e52430df
--- /dev/null
+++ b/minimax/agent-harness/setup.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""
+setup.py for cli-anything-minimax
+
+Install with: pip install -e .
+"""
+
+from setuptools import setup, find_namespace_packages
+
+with open("cli_anything/minimax/README.md", "r", encoding="utf-8") as fh:
+ long_description = fh.read()
+
+setup(
+ name="cli-anything-minimax",
+ version="1.0.0",
+ author="cli-anything contributors",
+ author_email="",
+ description="CLI harness for MiniMax AI — chat (MiniMax-M2.7) and TTS via MiniMax API. Requires: MINIMAX_API_KEY",
+ long_description=long_description,
+ long_description_content_type="text/markdown",
+ url="https://github.com/HKUDS/CLI-Anything",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ classifiers=[
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Developers",
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ ],
+ python_requires=">=3.10",
+ install_requires=[
+ "click>=8.0.0",
+ "requests>=2.28.0",
+ "prompt-toolkit>=3.0.0",
+ ],
+ extras_require={
+ "dev": [
+ "pytest>=7.0.0",
+ "pytest-cov>=4.0.0",
+ ],
+ },
+ entry_points={
+ "console_scripts": [
+ "cli-anything-minimax=cli_anything.minimax.minimax_cli:main",
+ ],
+ },
+ package_data={
+ "cli_anything.minimax": ["skills/*.md"],
+ },
+ include_package_data=True,
+ zip_safe=False,
+)
diff --git a/registry.json b/registry.json
index b0833dc10..3fff2b661 100644
--- a/registry.json
+++ b/registry.json
@@ -1189,6 +1189,25 @@
"url": "https://github.com/Gituheart"
}
]
+ },
+ {
+ "name": "minimax",
+ "display_name": "MiniMax",
+ "version": "1.0.0",
+ "description": "Chat and TTS via MiniMax AI API — MiniMax-M2.7 chat models and speech-2.8-hd TTS",
+ "requires": "MINIMAX_API_KEY",
+ "homepage": "https://platform.minimax.io",
+ "source_url": null,
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=minimax/agent-harness",
+ "entry_point": "cli-anything-minimax",
+ "skill_md": "minimax/agent-harness/cli_anything/minimax/skills/SKILL.md",
+ "category": "ai",
+ "contributors": [
+ {
+ "name": "octo-patch",
+ "url": "https://github.com/octo-patch"
+ }
+ ]
}
]
}