{"_id":"@minimax-ai/code-sdk","_rev":"2-bbc697ebf4295bdd7f7e520efdb531f5","name":"@minimax-ai/code-sdk","dist-tags":{"latest":"0.1.0"},"versions":{"0.0.0-stage":{"name":"@minimax-ai/code-sdk","version":"0.0.0-stage","_id":"@minimax-ai/code-sdk@0.0.0-stage","stub":true,"maintainers":[{"name":"ronnyhe","email":"hetaobackend@gmail.com"}],"dist":{"shasum":"784c4054b0551bd0cb5cd0820179fc2fb8192ba1","tarball":"https://registry.npmjs.org/@minimax-ai/code-sdk/-/code-sdk-0.0.0-stage.tgz","fileCount":2,"integrity":"sha512-W9+hArsuHH/r2G+cWEnKGCz0BTcVl8Y8bhBB9QlKowPPWbvIiGixVjJXr05ZWfTiNeWiw8cvaFON5w2r1pt3Ng==","signatures":[{"sig":"MEUCIQCmqq7AwhDApJ6GwU+9gJokdm3IB5V7H8FFvwq80Jz4WwIgZqmkX9R71n453MMnnj7m4S4yAqFewvspLxYUK4sLxe8=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":342},"_npmUser":{"name":"ronnyhe","email":"hetaobackend@gmail.com"},"description":"Temporary package placeholder for staged publishing","directories":{}},"0.1.0":{"_id":"@minimax-ai/code-sdk@0.1.0","bugs":{"url":"https://github.com/MiniMax-AI/minimax-code/issues"},"dist":{"shasum":"3e0436bf5df777ee81c55d13dced08b24f58a42b","tarball":"https://registry.npmjs.org/@minimax-ai/code-sdk/-/code-sdk-0.1.0.tgz","fileCount":64,"integrity":"sha512-4OTj1HcC/PlqPw/Qq/mY8R8TqjheWvkKlliyjl3HpDA7h5eI+whyj9y86vIbU8Dcw7pDnP8b1//pi8lBZvloAQ==","signatures":[{"sig":"MEUCIQC8/8mqn8wL1nQtYhHlLoBi/SHw247R9428ZCt5KEvMlwIgfOKQRfUH07DSomAna7/NSuwlwEcJK3P7aA0O5S0tofE=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIAT5P6saUfDL4jqcbw5suWqGrQjLsjCBKP1l89AqvRGZAiEAqeCOGiKu/VqBSd+nAe/HLefUAgcEyoQTyw+8Hz3Gx/Y="}],"unpackedSize":235894},"main":"./dist/index.js","name":"@minimax-ai/code-sdk","type":"module","_from":"file:minimax-ai-code-sdk-0.1.0.tgz","types":"./dist/index.d.ts","engines":{"node":">=22.19 <23 || >=24.2 <27"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"},"./package.json":"./package.json"},"license":"MIT","scripts":{"test":"node ../../scripts/run-vitest-suite.mjs code-sdk","build":"pnpm run clean:build && tsc --build --force","typecheck":"tsc --noEmit -p tsconfig.check.json","clean:build":"node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"","release:check":"node scripts/release-check.mjs","prepublishOnly":"node scripts/release-tools.mjs"},"version":"0.1.0","_npmUser":{"name":"ronnyhe","email":"hetaobackend@gmail.com"},"homepage":"https://agent.minimax.io","keywords":["minimax","minimax-code","mcode","agent","coding-agent","sdk"],"_resolved":"/tmp/code-sdk-release-qGm3Dy/minimax-ai-code-sdk-0.1.0.tgz","_integrity":"sha512-4OTj1HcC/PlqPw/Qq/mY8R8TqjheWvkKlliyjl3HpDA7h5eI+whyj9y86vIbU8Dcw7pDnP8b1//pi8lBZvloAQ==","repository":{"url":"git+https://github.com/MiniMax-AI/minimax-code.git","type":"git","directory":"packages/code-sdk"},"_npmVersion":"11.19.0","description":"TypeScript SDK for driving the local MiniMax Code (mcode) agent from Node.js.","directories":{},"maintainers":[{"name":"ronnyhe","email":"hetaobackend@gmail.com"},{"name":"ryanlee-dev","email":"yuanhe@minimax.io"},{"name":"zhangyxy","email":"zhangyxy94@gmail.com"},{"name":"dyh_sjtu","email":"dyh_sjtu@163.com"}],"sideEffects":false,"_nodeVersion":"24.21.0","dependencies":{},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"@minimax-ai/code":"link:test/fixtures/cli-package"},"peerDependencies":{"@minimax-ai/code":">=0.6.3"},"peerDependenciesMeta":{"@minimax-ai/code":{"optional":true}},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/code-sdk_0.1.0_1793286179055_0.4411880747590564"}}},"time":{"created":"2026-10-29T15:02:01.351Z","modified":"2026-10-29T15:03:00.210Z","0.0.0-stage":"2026-10-29T15:02:01.351Z","0.1.0":"2026-10-29T15:02:59.196Z"},"description":"TypeScript SDK for driving the local MiniMax Code (mcode) agent from Node.js.","maintainers":[{"name":"ronnyhe","email":"hetaobackend@gmail.com"},{"name":"ryanlee-dev","email":"yuanhe@minimax.io"},{"name":"zhangyxy","email":"zhangyxy94@gmail.com"},{"name":"dyh_sjtu","email":"dyh_sjtu@163.com"}],"readme":"# `@minimax-ai/code-sdk`\n\nA TypeScript SDK for driving the local MiniMax Code (`mcode`) agent programmatically from Node.js,\nmodeled after the [Codex TypeScript SDK](https://learn.chatgpt.com/docs/codex-sdk). Use it to run\nMiniMax Code in CI/CD (fixes, reviews, code generation), embed it in internal tools or your own\nagents, or orchestrate multi-turn conversations from code.\n\n> [!NOTE]\n>\n> The SDK is in Phase 1 (`0.x`): the API may change between minor versions until `1.0`. It is\n> versioned independently of the CLI; see [CHANGELOG.md](CHANGELOG.md).\n\n## How it works\n\n- Each `run()` / `runStreamed()` starts one\n  `mcode exec --output-format stream-json --input - --input-format json` process, writes the prompt\n  to its stdin as `{\"prompt\": \"...\"}`, and closes stdin. **One run = one CLI process = one Turn.**\n- A `Thread` only holds the Session id inside the SDK; later Turns continue the Session with\n  `--session <id>`. The CLI's embedded runtime persists Sessions in its data directory, so a\n  crashed host can resume a Thread from its id with `resumeThread`.\n- The SDK consumes only the public `mcode exec` contract (stdout JSONL plus exit code) and never\n  reads runtime-internal data.\n- No runtime dependencies. The package is ESM; its `exports` have `import` and `default`\n  conditions and no separate CommonJS build. CommonJS callers can still `require()` it, because\n  every Node.js version in the supported range loads ES modules through `require(esm)`.\n\n## Installation and CLI resolution\n\nThe SDK does not hard-depend on the CLI, which is large and ships native dependencies.\n`@minimax-ai/code` is an optional peer dependency:\n\n```bash\nnpm install @minimax-ai/code-sdk\nnpm install @minimax-ai/code   # optional; a globally installed mcode works too\n```\n\n`@minimax-ai/code` runs install scripts for its native dependencies. npm 11 rejects\n`--allow-scripts` for project-scoped installs (`EALLOWSCRIPTS`), so approve them in the project's\n`package.json` before installing the CLI into the project:\n\n```json\n{\n  \"allowScripts\": {\n    \"@minimax-ai/code\": true,\n    \"better-sqlite3\": true\n  }\n}\n```\n\nOther package managers that gate install scripts need the equivalent approval for the same two\npackages.\n\nThe SDK looks for the CLI in this order:\n\n1. The `bin` constructor option (an executable, a JS entry, or a command name on `PATH`).\n2. An installed `@minimax-ai/code` resolved from the SDK's own location (where the optional peer\n   dependency is installed). The SDK reads `bin.mcode` from that `package.json` and runs the JS\n   entry with `process.execPath`.\n3. `mcode` on `PATH`.\n\nSet `resolveFromCwd: true` to also search the host's working directory, after the SDK-local package\nand before `PATH`:\n\n- `@minimax-ai/code` resolved from `process.cwd()/package.json`.\n- The nearest `node_modules/.bin/mcode` (`mcode.cmd` / `mcode.ps1` on Windows) found walking up from\n  `process.cwd()`. The SDK prefers the JS entry behind the symlink or npm/pnpm shim and runs it with\n  `process.execPath`, so the CLI package name does not matter.\n\nLeave `resolveFromCwd` off (the default) when the working directory may be untrusted, for example a\nCI job checking out a pull request. A checkout can contain `node_modules/.bin/mcode`, and the SDK\nwould execute it with the host environment. Pass `bin`, or install the CLI next to the SDK or on\n`PATH`, instead.\n\nThe SDK never starts the CLI through a shell. On Windows, `mcode.cmd` is followed to the JS entry it\nruns, which the SDK then starts with `process.execPath`. Supported Windows installations:\n\n- the official installer (`install.ps1`): `mcode.cmd` reads the `current` release pointer and calls\n  `releases\\<release>\\.mcode-launcher.cmd`. The pointer is read again before every run, so a CLI\n  self-update between Turns is picked up;\n- npm and pnpm installs, global or project-local, through their generated `.cmd` / `.ps1` shims.\n\nIf a `.cmd` launcher is found but its JS entry cannot be determined, resolution fails with\n`MCodeNotFoundError`; pass the CLI's JS entry as `bin`.\n\nBefore the first run, each `MCode` instance runs `mcode --version` once and caches the result. A\nCLI older than `MIN_CLI_VERSION` (currently `0.6.3`) fails with `MCodeVersionError`. Only\n`major.minor.patch` is compared, so `0.6.3-preview.N` satisfies `0.6.3`. `0.6.3` is the first CLI\nrelease that includes every `mcode exec` flag the SDK passes (`--system-prompt-file`,\n`--append-system-prompt-file` and `--mode` landed there; `stream-json` was already present). A\nsource build of this repository reports `0.6.5` and meets the minimum.\n\n### Compatibility\n\n| `@minimax-ai/code-sdk` | MiniMax Code CLI (`mcode`)    | Node.js                       | Event `schemaVersion` |\n| ---------------------- | ----------------------------- | ----------------------------- | --------------------- |\n| `0.1.x`                | `>=0.6.3` (`MIN_CLI_VERSION`) | `>=22.19 <23 \\|\\| >=24.2 <27` | `1`                   |\n\nThe SDK and the CLI are released separately. Upgrading the SDK does not require upgrading the CLI\nas long as the CLI meets `MIN_CLI_VERSION`. If the CLI ever emits a new event `schemaVersion`,\nupgrade to an SDK release that supports it. The Node.js range matches the CLI's.\n\n## Quick start\n\n```ts\nimport { MCode } from \"@minimax-ai/code-sdk\";\n\nconst mcode = new MCode({ dataDir: \"/srv/mcode-data\" });\nconst thread = mcode.startThread({\n  cwd: \"/path/to/repo\",\n  model: \"minimax/MiniMax-M3\",\n  permission: \"smart\",\n});\n\nconst turn = await thread.run(\"Diagnose and fix the failing CI job\", {\n  files: [\"./ci.log\"],\n  timeoutMs: 10 * 60_000,\n});\nconsole.log(thread.id, turn.finalResponse, turn.usage);\n\n// Continue the same Thread\nawait thread.run(\"Add unit tests for the fix\");\n\n// Resume an earlier Session\nconst resumed = mcode.resumeThread(\"mvs_xxx\", { cwd: \"/path/to/repo\" });\nawait resumed.run(\"Continue where you left off\");\n```\n\nStreaming:\n\n```ts\nconst { events } = await thread.runStreamed(\"Implement the plan\");\nfor await (const event of events) {\n  switch (event.type) {\n    case \"item.completed\":\n      console.log(event.item);\n      break;\n    case \"turn.failed\":\n      console.error(event.status, event.error);\n      break;\n    default:\n      // Newer CLIs may add event types; the SDK passes them through unchanged.\n      break;\n  }\n}\n```\n\n## API\n\n### `new MCode(options?)`\n\n| Option           | Description                                                                                                                                                                      |\n| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `bin`            | Explicit `mcode` path or command name; skips package and `PATH` lookup                                                                                                          |\n| `resolveFromCwd` | Also search `process.cwd()` for `@minimax-ai/code` and for `node_modules/.bin/mcode` in parent directories. Default `false`. See [CLI resolution](#installation-and-cli-resolution) |\n| `dataDir`        | Data directory, passed to the CLI as the `MINIMAX_DATA_DIR` environment variable                                                                                                |\n| `env`            | Child process environment. **Replaces** `process.env` when set (no merge); defaults to `process.env`                                                                            |\n| `configPath`     | Runtime config file, passed as `--config`                                                                                                                                        |\n\n`env` replaces the environment entirely: passing only custom variables drops `PATH`, `HOME` and so\non, so the CLI may fail to find Node.js or tools, or to read its credentials. To add variables,\nspread `process.env`:\n\n```ts\nconst mcode = new MCode({ env: { ...process.env, FOO: \"bar\" } });\n```\n\n### `startThread(options?)` / `resumeThread(id, options?)`\n\nThread options are passed to the CLI on every Turn of the Thread:\n\n| Option               | CLI flag                                                                        |\n| -------------------- | ------------------------------------------------------------------------------- |\n| `cwd`                | `--cwd` (defaults to the host process working directory)                        |\n| `model` / `effort`   | `--model` / `--effort`                                                          |\n| `permission`         | `--permission`: `smart` / `full` / `off`                                        |\n| `mode`               | `--mode`: `standard` / `lightweight`, only on the Turn that creates the Session |\n| `promptMode`         | `--prompt-mode`: `tui` / `coding` / `work`                                      |\n| `systemPrompt`       | `--system-prompt-file` (the SDK writes a temporary file)                        |\n| `appendSystemPrompt` | `--append-system-prompt-file` (the SDK writes a temporary file)                 |\n\n- `mode: 'lightweight'` is only valid for a new Thread; passing it to `resumeThread` throws\n  `MCodeInvocationError` immediately.\n- There is no `ask` permission: headless runs cannot ask for approval. MiniMax Code's\n  `smart` / `full` / `off` policies are not equivalent to Codex's OS-level sandbox modes, and the\n  SDK does not map between them.\n- `thread.id` becomes available once the first Turn emits its first event, even if that Turn fails.\n\n### `thread.run(input, options?)` / `thread.runStreamed(input, options?)`\n\n| Option      | Description                                                                                                                                                                                             |\n| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `files`     | Attachments, `--file` (repeatable); relative paths resolve against `cwd`                                                                                                                                |\n| `signal`    | `AbortSignal`; see [Cancellation](#cancellation-timeouts-and-process-cleanup)                                                                                                                           |\n| `timeoutMs` | Passed to the CLI as `--timeout <n>ms`; the SDK force-stops the CLI at `timeoutMs + 90s` (60s CLI shutdown plus 30s startup slack). At most `MAX_TIMEOUT_MS` (about 24.8 days, a Node.js timer limit); larger values throw `MCodeInvocationError` |\n| `maxSteps`  | `--max-steps`                                                                                                                                                                                           |\n\n- `run()` resolves only when the status is `succeeded`, with a `Turn` (`finalResponse`, normalized\n  `items`, `usage`, `model`, `sessionId`, `turnId`, `durationMs` and the full `result`). Every other\n  outcome rejects; see [Errors](#errors).\n- `runStreamed()` yields the CLI events unchanged. `turn.failed` is an ordinary event; the iterator\n  throws only for process or protocol failures. Breaking out of the loop cancels the Turn.\n- A Thread runs one Turn at a time. A concurrent call throws `ThreadBusyError`; Turns are not queued.\n- After breaking out of the iterator, or after a protocol error, the SDK sends the CLI a cancel\n  signal. Until the process exits (about one second for a cooperating CLI, at most the CLI's 60\n  second shutdown budget: SIGTERM, then SIGKILL), the Thread stays busy and further `run()` /\n  `runStreamed()` calls throw `ThreadBusyError`. The `for await` loop you broke out of also waits\n  for the process to exit.\n- The prompt only travels over stdin, and system prompts through temporary files (mode `0600`).\n  The files are removed before `run()` settles and before a `runStreamed()` iterator ends. If the\n  host calls `process.exit()` during a Turn, the SDK's `exit` hook deletes those directories with\n  `rmSync`. argv contains only SDK-generated flags, identifiers and paths.\n\n### Events and items\n\nEvent types match the CLI: `exec.started`, `session.started` / `session.resumed`, `turn.started`,\n`item.started` / `item.updated` / `item.completed`, `turn.completed`, `turn.failed` and\n`exec.completed`. Every stdout line must be JSON with `schemaVersion === 1`; anything else is a\nprotocol error.\n\n`Turn.items` are SDK-normalized items (`agent_message`, `reasoning`, `tool_call`):\n\n- Items are merged by `item.id` without assuming any order (events of different items interleave);\n  the list is in order of first appearance.\n- While streaming, an `item.updated` identical to the previous snapshot of the same item is dropped.\n  This applies to snapshots only, never to text deltas (`contentDelta`).\n- Items without an `item.completed` when the Turn ends are marked `incomplete: true` (for example,\n  a tool that was running when the Turn was cancelled).\n- `tool_call.toolCall` is an `@experimental` `RawToolCall`: `status` is `string | number` (often an\n  internal numeric enum) and `input` / `output` are tool-specific structures. Neither is covered by\n  the compatibility promise.\n\n`usage.totalTokens = inputTokens + outputTokens` and **excludes** `cacheReadTokens` /\n`cacheWriteTokens`; `reasoningTokens` may overlap `outputTokens`.\n\n## Errors\n\nEvery error extends `MCodeError` and carries `exitCode`, `signal` and the last 64 KiB of the CLI\nstderr (`stderr`, for diagnostics only).\n\nWhen the CLI emits `exec.completed`, its `result.status` decides the error:\n\n| `result.status`  | Error                                                                               |\n| ---------------- | ----------------------------------------------------------------------------------- |\n| `failed`         | `MCodeRunError` with `category` from the result (`config` / `runtime` / `internal`) |\n| `timeout`        | `MCodeRunError` with `status === 'timeout'`                                         |\n| `limit_exceeded` | `MCodeRunError` with `status === 'limit_exceeded'`                                  |\n| `cancelled`      | `MCodeAbortError` with `name === 'AbortError'`                                      |\n\nWhen the CLI exits without `exec.completed`, the exit code decides:\n\n| Exit code                              | Error                                                       |\n| -------------------------------------- | ----------------------------------------------------------- |\n| `2` (invalid invocation)               | `MCodeInvocationError`                                      |\n| `3`                                    | `MCodeRunError`, `status: 'failed'`, `category: 'config'`   |\n| `4`                                    | `MCodeRunError`, `status: 'failed'`, `category: 'runtime'`  |\n| `6`                                    | `MCodeRunError`, `status: 'timeout'`                        |\n| `7`                                    | `MCodeRunError`, `status: 'limit_exceeded'`                 |\n| `70`                                   | `MCodeRunError`, `status: 'failed'`, `category: 'internal'` |\n| `130`                                  | `MCodeAbortError`                                           |\n| `141` (broken pipe)                    | `MCodeProtocolError`                                        |\n| `0` (success without a result)         | `MCodeProtocolError`                                        |\n| Any other code (e.g. `1`), or a signal | `MCodeRunError`, `status: 'failed'`, `category: 'internal'` |\n\nIf the SDK itself cancelled the run (`signal`, or breaking out of `runStreamed()`), a missing\nresult is reported as `MCodeAbortError` unless the CLI exited with `2`. If the SDK force-stopped the\nCLI after `timeoutMs + 90s`, it is `MCodeRunError` with `status === 'timeout'`.\n\nErrors raised by the SDK itself:\n\n| Source                                                                                                                | Error                  |\n| --------------------------------------------------------------------------------------------------------------------- | ---------------------- |\n| An option the SDK rejects before starting the CLI                                                                     | `MCodeInvocationError` |\n| Non-JSON stdout or an event missing required fields                                                                   | `MCodeProtocolError`   |\n| No CLI found (includes the install command), or a found launcher whose JS entry cannot be determined (asks for `bin`) | `MCodeNotFoundError`   |\n| CLI older than `MIN_CLI_VERSION`, or an unsupported event `schemaVersion`                                             | `MCodeVersionError`    |\n| Concurrent Turn on the same Thread                                                                                    | `ThreadBusyError`      |\n\n`MCodeRunError` carries `result` (the full `ExecResult` when `exec.completed` was received),\n`items`, `retryable` (from `result.error.retryable`) and `sessionId`; `MCodeAbortError` also carries\n`sessionId`. `sessionId` is set whenever the CLI emitted at least one event (or the Thread came from\n`resumeThread`), even without `exec.completed`. The SDK never retries automatically, to avoid\nreplaying writes with unknown outcomes; call `resumeThread(error.sessionId)` to continue.\n\n## Cancellation, timeouts and process cleanup\n\n- When `signal` aborts, the SDK sends `SIGTERM`. The CLI treats `SIGTERM` the same way as `SIGINT`:\n  it cancels the Turn, shuts the runtime down (budget 60 seconds), then writes `exec.completed`\n  with status `cancelled`. If the process is still running after that budget, the SDK sends\n  `SIGKILL`. It does not send `SIGINT`.\n- **Ctrl+C.** The CLI stays in the host's process group, so Ctrl+C delivers `SIGINT` to the host and\n  the CLI together. That `SIGINT` already starts the CLI's cancel path and consumes its one-shot\n  `SIGINT` handler. If the host also aborts the `AbortSignal` from its own `SIGINT` handler, the\n  SDK follows with `SIGTERM`, which the CLI still handles as a cancel (`SIGTERM` is a separate\n  handler). A second `SIGINT` would take the default action and kill the CLI before it writes\n  `exec.completed`. The README example below aborts on `SIGTERM`, which does not collide with\n  Ctrl+C.\n- `timeoutMs` is enforced by the CLI. The CLI starts that timer after its access check, session\n  resolution and model selection, then ends the run with status `timeout` and may spend the same 60\n  second shutdown budget before writing the result. The SDK's timer starts at spawn and force-stops\n  the process at `timeoutMs + 90s` (60s shutdown plus 30s of startup slack).\n- **Only normal host exits are covered**: when the host emits `exit` (the event loop drains or\n  `process.exit()` is called), the SDK sends `SIGTERM` to any running CLI process, which the CLI\n  treats as a cancel, and deletes temporary prompt directories with `rmSync`. A host killed by a\n  signal such as `SIGTERM` or `SIGINT` does not emit `exit`, and its CLI processes keep running as\n  orphans. The SDK installs no signal handlers and Phase 1 has no `close()` / `dispose()`. Hosts\n  that need reliable cleanup should abort in-flight runs from their own signal handlers and wait\n  for them, for example:\n\n  ```ts\n  const controller = new AbortController();\n  process.once(\"SIGTERM\", () => controller.abort());\n  await thread\n    .run(prompt, { signal: controller.signal })\n    .catch(() => undefined);\n  ```\n\n- After the CLI exits, the SDK keeps reading stdout / stderr for at most about two seconds. If a\n  grandchild process inherited and holds the pipes, the SDK closes them and settles the Turn from\n  the events already received instead of waiting for the grandchild.\n- An unconsumed `runStreamed()` stream still runs to completion and frees the Thread.\n\n> [!WARNING]\n>\n> **Windows**: Node.js cannot deliver a catchable signal to a child process, so `SIGTERM` is a hard\n> kill and the runtime may leave the Turn unfinished. Phase 1 only supports the hard kill; graceful\n> cancellation needs a signal-independent cancel channel in the CLI.\n\n## Concurrency and data directories\n\nConcurrent `exec` processes sharing one data directory have had limited testing. Prefer a separate\n`dataDir` per SDK instance (or per concurrent task), with authentication configured in that\ndirectory beforehand.\n\n## Not available in Phase 1\n\n- `outputSchema` (MiniMax-hosted models do not reliably follow the schema yet).\n- Approval callbacks, steering a running Turn, continuing after an interrupt, and forking.\n- A Python SDK.\n\n## 中文\n\nSDK 在 Node.js 里驱动本机 MiniMax Code（`mcode`）。下面只覆盖本次行为；完整说明见上文英文。\n\n### CLI 查找\n\n默认顺序：\n\n1. 构造参数 `bin`（可执行文件、JS 入口，或 `PATH` 上的命令名）。\n2. 安装在 SDK 旁边的 `@minimax-ai/code`（可选 peer dependency）。SDK 读取其 `bin.mcode`，并用 `process.execPath` 运行该 JS 入口。\n3. `PATH` 上的 `mcode`。\n\n`resolveFromCwd` 默认为 `false`。设为 `true` 后，还会在 SDK 本地安装之后、`PATH` 之前搜索宿主的工作目录：先从 `process.cwd()/package.json` 解析 `@minimax-ai/code`，再从 `process.cwd()` 向上查找最近的 `node_modules/.bin/mcode`（Windows 上为 `mcode.cmd` / `mcode.ps1`）。工作目录不可信时（例如 CI 检出的拉取请求）请保持关闭：检出内容可以自带 `node_modules/.bin/mcode`，SDK 会带着宿主环境执行它。此时应传入 `bin`，或把 CLI 装在 SDK 旁边 / `PATH` 上。\n\nSDK 从不通过 shell 启动 CLI。要求的最低 CLI 版本是 `0.6.3`（`MIN_CLI_VERSION`）：该版本起具备 SDK 传入的全部 `mcode exec` 参数。本仓库源码构建的 CLI 是 `0.6.5`，满足该下限。只比较 `major.minor.patch`，因此 `0.6.3-preview.N` 视为满足 `0.6.3`。\n\n### 取消、超时和退出\n\n- `AbortSignal` 中止时，SDK 发送 `SIGTERM`。CLI 把 `SIGTERM` 与 `SIGINT` 同样视为取消：结束本轮、在 60 秒运行时关闭预算内收尾，然后写出 `exec.completed`（`cancelled`）。超过该预算进程仍在，SDK 才发送 `SIGKILL`。SDK 不发送 `SIGINT`。\n- 终端里的 Ctrl+C 会把 `SIGINT` 发给整个进程组，CLI 自己的一次性 `SIGINT` 处理函数会被用掉。若宿主也因此中止 `AbortSignal`，SDK 随后发送的 `SIGTERM` 仍走 CLI 的取消路径。再发一次 `SIGINT` 会直接杀死 CLI，来不及写出 `exec.completed`。\n- `timeoutMs` 由 CLI 在访问检查、会话解析和模型选择之后开始计时。SDK 从进程启动起计时，在 `timeoutMs + 90s`（60 秒关闭预算加 30 秒启动余量）时强制结束。\n- 宿主正常退出（事件循环排空或调用 `process.exit()`）时，SDK 向仍在运行的 CLI 发送 `SIGTERM`，并用 `rmSync` 删除临时 system prompt 目录。宿主被 `SIGTERM` / `SIGINT` 杀死时不会发出 `exit`，子进程会留下。Windows 上 `SIGTERM` 是硬终止，无法优雅取消。\n\n### 发布\n\n`@minimax-ai/code-sdk` 是本仓库里第一个非 `private` 的工作区包。不要在包目录里直接 `npm publish`：`prepublishOnly` 会拒绝。在最新的 `main` 上运行 `pnpm --filter @minimax-ai/code-sdk run release:check`，再发布它打印出的、已经检查过的 tarball。见 `RELEASING.md`。\n","readmeFilename":"README.md","homepage":"https://agent.minimax.io","keywords":["minimax","minimax-code","mcode","agent","coding-agent","sdk"],"repository":{"url":"git+https://github.com/MiniMax-AI/minimax-code.git","type":"git","directory":"packages/code-sdk"},"bugs":{"url":"https://github.com/MiniMax-AI/minimax-code/issues"},"license":"MIT"}