@302ai/media-studio-cli-cn
v0.1.10
Published
CLI for AI Media Studio — let external agents drive the core media-studio features
Maintainers
Readme
@302ai/media-studio-cli-cn@latest
This production package is bound to https://media.302ai.cn.
It installs both msc and media-studio-cli; there is no region selector.
Install or switch to this package
Requires Node.js >= 22. Ask permission before changing a global installation.
Both package names own the same executables: uninstall the old package before
switching sites or channels. Each package and channel keeps its own config
directory; after installing or upgrading, sign in again with msc login.
Earlier CLI versions left credentials this version does not read.
npm uninstall -g @302ai/media-studio-cli # if installed
npm uninstall -g @302ai/media-studio-cli-cn # if changing channel
npm install -g @302ai/media-studio-cli-cn@latest
msc --version
msc login --jsonOpen the returned authorization link at https://media.302ai.cn/cli/authorize and follow
the one-time-code instructions below; use msc whoami to verify the account.
For personal-terminal use, pass the code with msc login --with-code <code> --json.
Updates and Agent Skill
After user approval, update this same package and channel and its matching Skill:
npm install -g @302ai/media-studio-cli-cn@latest
npx -y skills add 302ai/msc-skill --skill msc-skill -g -y
msc --version
msc guideStop if either installation fails; do not switch sites or channels silently.
Complete guide
Usage
msc login # open the authorization link and enter a one-time code
msc guide # the full agent-facing manual
msc whoami # show current auth status
msc doctor # check version, PATH and npm prefix; no login
msc chat "hi" # one chat turn (multi-turn by default)
msc sessions # list sessions from the server
msc skills # list the skill catalog you can reference
msc logout # clear stored credentialsmedia-studio-cli is the long alias for msc — the same program, both
installed. The docs, the help output, and every error message use the short
name:
msc chat "画一只猫" -r # -r/--show-reasoning = 展示模型推理过程
msc chat "hi" --json # machine-readable output
msc chat "hi" --session <id> # 切换到已有会话(先校验存在)并设为默认
msc chat "hi" --new # 新建会话并设为默认(id 不复用)
msc sessions # 列出所有会话(标记当前默认 `(current)`)
msc sessions --json # 机器可读的原始 JSON 数组
msc sessions use <id> # 校验存在后切换默认会话
msc sessions use --new # 新建会话并设为默认
msc skills # 列出技能库(--plaza 浏览技能广场)
msc skills add <slug> # 从广场安装技能(如 brainstorming,见 --plaza --json 的 slug)
msc skills rm <command> # 从技能库移除(-y/--yes 跳过确认)
msc skills enable <command> # 启用 / disable 停用
msc --help # all flagsSession deletion is not available in the CLI. To delete a session, open the corresponding session page in the Media Studio web app and delete it manually.
msc --help carries an agent-oriented quickstart — the auth prerequisite, the
three canonical calls, and the --json contract. msc guide prints the full
manual: every command, both JSON schemas, the nextStep values, exit codes,
stream discipline, and skill semantics. Point an agent at those two instead of
duplicating them here.
CLI compatibility and updates
Online CLI requests carry X-Agent-Cli-Version: <package version> and X-Agent-Cli-Package: <package name>. The BFF applies CMS CliVersionPolicy (cli-version-policy) to whoami, chat, sessions, skills and attachments. enabled defaults true; enabled=false is the emergency disable. Blank minSupportedVersion uses the server's default floor (currently 0.1.4); a custom stable SemVer can raise or lower it. Clearing the minimum restores that default rather than disabling enforcement. Staging admits a prerelease of the same base version as the stable floor; older base versions remain rejected. Headerless Bearer requests are legacy CLI and normally receive 426 (prewarm exception below); headerless browser-cookie/anonymous requests are unaffected. These headers are not an authentication boundary. Local help, version, guide, logout and the login link remain available.
A below-floor request receives HTTP 426, CLI_UPGRADE_REQUIRED (10010) and nextStep: "upgrade_cli" before its upstream work or stream begins. This is an application convention, not an HTTP transport upgrade. CMS read failure uses a valid available cached policy or returns 503, not an upgrade refusal; do not interpret every whoami exit 1 as expired credentials. Policy caching uses save-triggered tag invalidation and periodic revalidation, not simultaneous cross-instance activation.
Older clients may not decode upgrade_cli; the server message still gives permission-first recovery guidance. Publishing a CLI does not deploy the BFF or change its default floor. See the operator activation procedure below.
The sole transport exception is an upgrade refusal for headerless Bearer POST /api/sessions/prewarm: HTTP 200 SSE event:error carries flat { err_code: 10010, message: <full permission-first guidance> }, with no session_ready or upstream work. The old CLI exits 1 and exposes errCode: 10010 and the message, but no httpStatus. Stamped clients and all other interfaces retain 426; CMS failure remains 503 and is not converted to SSE.
Optional npm discovery checks the installed package and channel using a best-effort 24-hour cache and short timeout; discovery failures never fail a media task or change its exit status. Chat success/incomplete JSON may contain updateAvailable: { current, latest, upgradeCommand, skillUpgradeCommand } for the current channel; successful whoami may append a notice. These emissions are deduplicated per target version across both commands after output, not acknowledgment. Interactive terminal commands may also report beta updates for beta builds; those notices are not deduplicated. Skills/sessions arrays and single-document JSON stdout stay unchanged. Agents finish the task before telling the user about an optional update, and never install silently.
Local notification deduplication is best-effort, not exactly-once: simultaneous processes or an unwritable cache can repeat notices.
Required upgrade recovery needs permission for both global installs. Use the
current package and channel shown by msc guide; never switch sites or channels
silently. Follow its package and Skill upgrade commands. The server uses a
validated package header for recovery and selects beta only on staging. For
legacy or unknown package headers in production, it directs the user to copy the
install command from their current website rather than guessing a package.
Staging safely defaults to the global beta package.
Stop if either install fails and report completed steps; do not claim success or automatically roll back the other installation. Skill installation may not reload a running Agent's cached context, so read the guide before resuming. Retry only definitely unaccepted generation. A refusal covers only that request: earlier stages may already have effects. Reuse an error's sessionId with --session, not --new; inspect the existing session/artifacts when acceptance is uncertain. Policy changes must not terminate accepted work or established SSE streams.
Operators: see CLI minimum-version activation before changing the floor.
Website authorization
Use a CLI build that supports the authorization-link flow and --with-code;
check msc login --help. The unchanged package version alone, including
previously published 0.1.5, does not establish that an npm build has it.
Run
msc loginin a terminal. It prints this build's single authorization link; an Agent can runmsc login --jsonto receive it without keeping a process open. In a terminal, paste the code at the masked prompt.Open that site and sign in if needed. 302 sign-in stays in the same tab and returns to the standalone code page. Check the account and site, then copy the one-time code to the terminal or a trusted Agent. Each code works once within five minutes; generating a new code does not invalidate earlier codes.
In a personal terminal, pass the code directly and run
msc whoamito verify the resulting session (whoamihas no--jsonflag):msc login --with-code <code> --json
Each code works once within five minutes. A used code cannot be redeemed again, but its CLI session does not expire with the code.
msc login --with-code <code> [--json] needs no browser, display, or loopback
listener on the CLI machine. It validates the argument before HTTP. The code
contains no site; it is exchanged only at this build's site.
Exchange is one version-stamped POST with a 30-second timeout, no retries and
no redirects. A lost response may mean the code was consumed: generate a new
one rather than automatically replaying it. The resulting CLI session is
independent of the browser session. Existing credentials remain intact on
input, exchange, response-validation or save failure. The temporary credential
file starts at mode 0600 on POSIX and atomically replaces the old file;
success is reported only after saving. Login does not read or trust an existing
credential, so a legacy or unreadable file never blocks it and is replaced only
after a successful save.
msc login --json without a code exits 2 with one pending document; this
is not a successful login and does not change saved credentials. An Agent with
an interactive browser tool opens the authorization URL in a new tab; otherwise
it gives the URL to the user. The example origin below represents the installed
package's site:
{"status":"authorization_required","nextStep":"open_authorization_url","guidance":"If an interactive browser tool is available, open the authorizationUrl in a new tab; otherwise give the user the URL to open. The user signs in if needed and provides the one-time code.","sites":[{"authorizationUrl":"https://your-site.example/cli/authorize"}]}After --with-code succeeds, it exits 0 and emits one document such as:
{"status":"success","apiUrl":"https://your-site.example","uid":"user-id","username":"Alice"}username is optional. Failures exit 1 with the existing structured error
fields (message, optional errCode, httpStatus, nextStep, guidance,
transportCode). JSON stdout never contains the code or token.
Multi-turn conversation
chat is multi-turn by default — no flag needed. The CLI keeps a single
lastSessionId pointer in config.json (under the config dir):
- First-ever chat provisions a session via the same prewarm flow the web
app uses (source
cli), printing stage progress (creating / sandbox / skills / finishing), then chats. The pointer is written the moment the session is durably persisted upstream — an interrupted provision never loses a live session. - Later chats continue that session — upstream remembers the conversation by session id, so no history is resent.
- If the current session is gone before a turn produces any output, the CLI transparently provisions a fresh one and re-runs the turn — a first-turn failure never strands you.
- Once a turn has started producing output, a session failure is reported instead: the partial result stands, nothing is re-run, and no replacement session is created (a retry would replay output and re-dispatch tool calls or generation tasks the first attempt may already have started).
--session <id>switches to an existing session (including web-created ones) and makes it the default. The id is verified upstream first: a missing id fails with a hint, it never provisions a different session behind your back.--newcreates a fresh session with a newly generated id and makes it the default for later runs. Ids are never reused or adopted: the CLI either uses the id it generated or reports the refusal.
Manual proof of continuity:
msc chat "记住数字42"
msc chat "刚才的数字是几?" # answers 42Use the package bound to your website; the CLI has no production region flag.
Configuration and storage
The CLI stores credentials and local settings in a directory chosen by the installed package and channel — there is no path override:
- Global latest:
~/.config/media-studio-cli/ - CN latest:
~/.config/media-studio-cli-cn/ - Beta:
~/.config/media-studio-cli-beta/(global package only) - Local:
~/.config/media-studio-cli-dev/ - XDG standard:
$XDG_CONFIG_HOME/<directory>/
Key files:
auth.json: this version's active platform credential and user session metadata (permissions0600on POSIX)config.json: stores CLI client settings, includinglastSessionIdpointer and optionaloutputDir
Generated chat media is downloaded automatically to
~/Downloads/media-studio-cli/ (the native equivalent on Windows). Manage the
directory with:
msc config get output-dir --json
msc config set output-dir <path> --json
msc config unset output-dir --jsonThe default is computed without writing config or creating a directory. set
expands a leading ~ and stores an absolute path; unset restores the default
without moving or deleting existing files. With --json all three print
{ "outputDir": "...", "source": "default" | "configured" }. Only results on
Media Studio storage are downloaded; any other host stays a remote link.
Successful chat JSON adds
localPath and fileUrl to each media item. Agents should display localPath
through local-file/media attachments and must keep resultUrl unchanged for
later editing. Human output displays fileUrl. A failed download reports
downloadError and preserves the remote URLs; partial media from an
incomplete turn is downloaded too.
The credential format is versioned. Credentials written by an earlier CLI
version are treated as not logged in and are never reused or migrated; run
msc login again. A successful login atomically replaces auth.json, and
msc logout deletes it.
In --json mode, an expired or invalid session carries
"nextStep": "relogin"; a missing or legacy credential reports status and
message only.
Skills
Discover what your account can reference, then reference it — the reference must name a skill that exists in your catalog:
msc skills # list your library
msc skills --json # raw catalog array (see fields below)
msc skills --plaza # browse the Skill Plaza with your library
# state merged in (built-ins excluded)
msc skills --plaza --json
msc skills add <slug> # install a plaza entry by slug
msc skills rm <command> # remove a library skill by command
msc skills enable <command> # flip a library skill's enabled flag
msc skills disable <command>add takes the entry's plaza slug (brainstorming, shown in
msc skills --plaza --json as slug); the library mutations take the
command string (brainstorming and /brainstorming are the same entry) —
the same string the prompt uses to reference the skill.
--json is the intended output for agents: the catalog is the input to a
decision the calling program makes itself. Both descriptionEn/descriptionZh
are passed through untouched — upstream does not guarantee the En slot is
English, so the CLI picks nothing. The human rendering lists names only (the
command string is available in --json) with the full descriptionEn on a
second line, and marks [on] enabled / [off] disabled / [-] not installed
in the plaza view.
Shared API endpoints: mutations use the exact same endpoints as the web app
(POST /api/skills for installs, DELETE /api/skills/:id for removal,
PUT /api/skills/:id with a multipart enabled field for enable/disable).
The CLI resolves the slug/command to the entry/id before calling the endpoint.
rm requires --yes outside a terminal. Built-in entries are rejected (422):
they sync into your library from the backend. Managing skills (upload, cover)
stays in the Media Studio web app.
Then reference a skill in the prompt and the CLI installs it into the session sandbox on demand:
msc chat "/always-hello 不管我说什么" # leading slash command
msc chat "%%/always-hello%%不管我说什么" # web composer marker, paste-compatibleBoth spellings resolve to the same thing. The upstream installs a skill only
from the turn's skill_urls field, so the CLI looks the reference up in your
catalog (GET /api/skills) and sends the matching package URL — prompt text
alone triggers nothing.
- A bare
/commandcounts only at the start of the prompt, so mid-sentence slashes stay prose (check /etc/hostsis not a skill reference). The%%…%%marker is also recognized anywhere — a web prompt pasted verbatim keeps its token — but the skill activates upstream only when the marker leads the message, so lead the prompt with it. The leading token can be any bare slug, single-segment included —/tmp what is thisresolves/tmp— and a reference that matches nothing fails the turn with the catalog listed, so a typo never silently degrades to a skill-less answer. - The catalog is fetched only when the prompt references a skill; skill-free turns cost no extra request.
- Unknown skills fail the turn with a non-zero exit before any session is
provisioned. A disabled skill is auto-enabled first — the same ADR-0001
behavior as the web's "Use in Chat" — because the upstream treats
enabledas a hard precondition for invocation and would otherwise download the package and silently never run it. The enable flips the skill'senabledflag on your account (a persistent change), is reported asAuto-enabled for this turn: …, and a failed enable aborts the turn.
Agent Skill (302ai/msc-skill)
To teach an external AI agent (Claude Code, Cursor, Codex, OpenCode, Gemini CLI,
etc.) how and when to invoke msc, install the public Agent Skill matching the
CLI channel using the command in msc guide. Production and beta use different
Skill channels. Ask permission before changing either global installation;
uninstall the old package before installing a different package, without
deleting configuration. The public beta branch is created by the first
successful beta sync.
- Source of truth: The canonical skill source lives in this repository under
msc-skill/. A verified CLI Release synchronizes its matching channel to 302ai/msc-skill; compatible Skill-only changes and retries use manual dispatch. - Contract co-evolution: When modifying CLI commands,
--jsonpayloads, exit codes, error structures (nextStep), authentication behavior, or file attachment syntax inmedia-studio-cli, always updatemsc-skill/skills/msc-skill/SKILL.mdin the same commit.
Attachments
Attach local files to a chat turn using @path anywhere in the prompt:
msc chat "看看 @cover.png 这张图" # bare path (ends at whitespace)
msc chat "总结 @/abs/path/notes.pdf" # absolute path
msc chat '对比 @"my docs/report.docx" 内容' # quoted path with spacesThe CLI mirrors the web composer's upload flow:
- Validates each referenced file locally (exists, readable, supported extension, under 50 MB) before any network call.
- Uploads each file via the web app's
POST /api/chat/attachmentsendpoint with a terminal spinner (Uploading attachment 1/2: cover.png). - Rewrites the prompt to inline the remote URL using the web's
&&<url>&&marker, which the upstream model and web session history natively understand. - Up to 10 unique attachments per turn (same as the web composer); referencing the same file twice uploads it once.
- An unattachable reference (missing file, unsupported format) fails the turn before any session is provisioned.
- Prose mentions (
@team 辛苦了, email addresses) stay literal text — only tokens with a file extension or path slash are treated as attachments. @pathis local-filesystem-only:@https://example.com/a.pngfails withno such file. There is no@urlform — remote URLs are not attachments.
In --json mode the uploaded attachments are surfaced under the attachments array:
[{ name, type, size, remoteUrl }].
Staging server
The test-only beta packages target https://media.tool302.com. Production
packages target their own site and do not select staging via login.
The beta CLI disables certificate verification because the test site's certificate is invalid. It writes a warning to stderr on first use. Production builds keep normal verification. Proxy environment settings still apply.
TLS-intercepting proxies
If browser SSO login works but every API call fails with fetch failed, a
TLS-intercepting proxy (Clash/FlClash TUN mode, corporate MITM) is breaking
certificate verification (unable to verify the first certificate).
Node/Bun do not use the OS keychain, so a proxy CA trusted by your browser
is not trusted by the CLI. Either trust the proxy CA explicitly:
export NODE_EXTRA_CA_CERTS=/path/to/proxy-ca.crtThe CLI has no switch that disables certificate verification for other hosts. Node's process-wide NODE_TLS_REJECT_UNAUTHORIZED=0 is not a supported workaround.
Proxies
msc follows the usual CLI convention (git, gh, curl): the environment
owns the proxy, the CLI only reads it. No OS-level "system proxy" detection, no
--proxy flag, and nothing printed.
export HTTPS_PROXY=http://127.0.0.1:7890
export NO_PROXY=localhost,127.0.0.1,::1 # appended automatically when absentHTTP_PROXY / HTTPS_PROXY / NO_PROXY and their lowercase spellings are
accepted. ALL_PROXY is not, matching gh. Loopback is never proxied, so
local development endpoints remain reachable when the proxy list is empty.
Node reads proxy settings only while it builds the global dispatcher, before
any CLI code runs, so a set proxy variable makes msc re-run itself once with
--use-env-proxy (one extra process start; nothing at all when no proxy
variable is set). Setting NODE_USE_ENV_PROXY=1 in the environment skips that
restart. NO_PROXY entries are host names, .suffix or host:port; CIDR
ranges are not matched. The Bun dev run (bun run dev) and the standalone
binary ignore the proxy variables — Node's flag does not exist there.
A proxied browser is not evidence that the CLI can reach the host: if SSO login
works but every command fails with fetch failed, check what the hostname
resolves to before blaming certificates.
Development
# from packages/media-studio-cli
bun run dev # run TS source, targeting localhost
bun run build # dist/packages: latest/{global,cn}, beta/global
bun run build:binary # global standalone binary -> bin/; beta for prerelease versionsThe source package is private; pack the generated package directories, not the source directory.
Testing (before shipping any change)
Test layers from fast to faithful. Minimum bar: layer 2 passes; before an actual publish also run layer 4.
1. Dev iteration (fastest)
bun run dev -- chat "hi" # runs TS source directly, no packaging2. Automated external-consumer check (required)
# from repo root
bun run package:cli:checkBuilds, type-checks, packs and checks the three generated variants as external consumer artifacts, catching packaging-only breakage that in-repo runs miss.
3. Manual user-install simulation
cd packages/media-studio-cli
bun run build
mkdir -p /tmp/cli-test
npm pack ./dist/packages/latest/global --pack-destination /tmp/cli-test
# Select latest/cn or beta/global instead to pack another variant.Install the resulting tarball in a disposable consumer to inspect it. Avoid overwriting an existing global installation or deleting its configuration.
4. End-to-end against a real server
# terminal 1, from the repository root: start the local gateway
bun run dev
# terminal 2, from packages/media-studio-cli: use the local source build
bun run dev -- login
bun run dev -- whoami
bun run dev -- chat "画一只猫" -r
bun run dev -- chat "hi" --json
# Multi-turn continuity acceptance recipe:
bun run dev -- chat "记住数字42"
bun run dev -- chat "刚才的数字是几?"
# Session management verification:
bun run dev -- sessions
bun run dev -- chat "hi" --session <id>
bun run dev -- chat "hi" --new
bun run dev -- sessions use <id>
bun run dev -- sessions use --newThe source command targets localhost; use the appropriate published package to work against a production site.
Notes learned the hard way
- Pack only after
bun run build; the generated directory is the npm artifact. - Keep the two
bintargets unique:mscuses thedist/msc.jsshim. - Run the repository's
bun run package:cli:checkgate before publishing.
License
Apache-2.0
