@minimax-ai/code 0.6.9 → 0.6.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CHANGELOG.zh-CN.md +16 -0
  3. package/README.md +81 -27
  4. package/README.zh-CN.md +15 -8
  5. package/assets/agents/mavis/skills/control-in-app-browser/SKILL.md +107 -24
  6. package/chunks/{auth-command-V2XHLCT4.js → auth-command-YIBIYLYL.js} +1 -1
  7. package/chunks/{chunk-S3AA7ARE.js → chunk-2LP3AAE5.js} +1 -1
  8. package/chunks/{chunk-VF6QBYDX.js → chunk-7FUBWI5L.js} +600 -599
  9. package/chunks/{chunk-YD3QXMMM.js → chunk-CRTW4JM6.js} +1 -1
  10. package/chunks/{chunk-5URK63JW.js → chunk-FNHS672G.js} +1154 -702
  11. package/chunks/{chunk-F6CPFGSE.js → chunk-FPCUX6KP.js} +1 -1
  12. package/chunks/{chunk-EYZOZ75Y.js → chunk-G7FSWJID.js} +58 -58
  13. package/chunks/{chunk-55CEUKGL.js → chunk-UQ2YIDWV.js} +1 -1
  14. package/chunks/{chunk-KLBEPNUI.js → chunk-VUXFNHQE.js} +1 -1
  15. package/chunks/{data-dir-6QRNHAEN.js → data-dir-AVW455BT.js} +1 -1
  16. package/chunks/{dist-TA4FX7XC.js → dist-B52TV5OC.js} +1 -1
  17. package/chunks/{launcher-QGDE2E5R.js → launcher-BADSPVA5.js} +27 -27
  18. package/chunks/{lifecycle-GLENYWF7.js → lifecycle-7W6GXLEL.js} +1 -1
  19. package/chunks/{main-RCN26DGX.js → main-LWOWUP76.js} +2 -2
  20. package/chunks/{plugin-command-O4T4MWJK.js → plugin-command-QSDS4V7E.js} +1 -1
  21. package/chunks/{provider-command-ILB6EPHT.js → provider-command-ZE4ODVR3.js} +1 -1
  22. package/chunks/{run-acp-command-OK6OSA2P.js → run-acp-command-LM4IFM5B.js} +2 -2
  23. package/chunks/{run-exec-command-B6CKVBZL.js → run-exec-command-B7H55F5B.js} +1 -1
  24. package/cli.js +2 -2
  25. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ This changelog covers important changes that directly affect MCode TUI users. It
7
7
 
8
8
  Internal refactors, test-only changes, and changes limited to other product surfaces are excluded.
9
9
 
10
+ ## 0.6.11 · 2026-10-14
11
+
12
+ ### Improved
13
+
14
+ - Context compaction for custom providers (BYOK) reuses the main request's prompt-cache prefix, making compaction faster and cheaper; if the provider does not accept it, compaction falls back to the previous standalone request.
15
+
16
+ ### Fixed
17
+
18
+ - When a gateway returns HTTP 200 and then reports an oversized request inside the stream (such as `Input is too long`), the request is no longer resent unchanged and goes straight to compaction recovery; a compaction request that hits the same rejection switches to a smaller summary candidate.
19
+
20
+ ## 0.6.10 · 2026-10-13
21
+
22
+ ### Added
23
+
24
+ - Browser Use adds a `run_script` action for page checks that single actions cannot express: holding keys while moving, modifier keys combined with mouse input, timed or repeated input, and loops that read page state before deciding where to click. Scripts drive the current tab and its signed-in state without starting another browser or installing extra tools; keys and mouse buttons still held are released when a script finishes, fails, times out, or is cancelled. Results include the return value, logs, the failing line, and screenshots. Available only in the TUI headless browser.
25
+
10
26
  ## 0.6.9 · 2026-10-12
11
27
 
12
28
  ### Added
@@ -8,6 +8,22 @@ TUI 正式版中用户能直接感知的重要变化。收录范围以 TUI 用
8
8
 
9
9
  仅内部重构、测试调整,或只影响其他产品界面且不改变 TUI 行为的变化不记录。
10
10
 
11
+ ## 0.6.11 · 2026-10-14
12
+
13
+ ### 体验改进
14
+
15
+ - 自定义 Provider(BYOK)的上下文压缩复用主请求的提示缓存前缀,压缩请求更快、成本更低;Provider 不接受时自动改用原有的独立压缩请求。
16
+
17
+ ### 问题修复
18
+
19
+ - 网关先返回 HTTP 200、再在流中报告请求过大(如 `Input is too long`)时,不再原样重试,直接走压缩恢复;压缩请求遇到同样的拒绝时改用更小的摘要候选。
20
+
21
+ ## 0.6.10 · 2026-10-13
22
+
23
+ ### 新增功能
24
+
25
+ - Browser Use 新增 `run_script` 动作,用于单步动作无法表达的页面验证:按住按键移动、修饰键加鼠标组合、定时或重复输入,以及先读取页面状态再决定点击位置。脚本直接操作当前标签页和登录状态,不需要另起浏览器或安装额外工具;脚本结束、出错、超时或被取消时,仍按住的键和鼠标键会自动松开。结果包含返回值、日志、失败行号和截图。仅 TUI 的 Headless Browser 提供。
26
+
11
27
  ## 0.6.9 · 2026-10-12
12
28
 
13
29
  ### 新增功能
package/README.md CHANGED
@@ -228,22 +228,24 @@ limit still applies.
228
228
 
229
229
  Each model request carries at most 100 images (20 for MiniMax M3 models, 8 for Mistral's API) and
230
230
  two thirds of the request body limit of image data. The request body limit is
231
- `max_request_body_bytes` on the model, else 28 MiB for `https://api.anthropic.com`, 26 MiB for the
232
- Messages API on Google Cloud, 64 MiB for `api.openai.com` and 18 MiB for any other endpoint. When either limit is
233
- exceeded, the oldest tool result images are removed from the history until half of each limit
234
- remains, each replaced with a note naming its file (images without one are first saved under the
235
- session's `tool-outputs` folder). Images you attach are never removed from the history; when they
236
- alone exceed a limit, the oldest are left out of that request only. If the provider still rejects a
237
- request for its size or images, the request is repeated once with half of the images it carried
238
- (`requestMedia.recoveryDivisor` in `config.yaml` sets the divisor, default `2`), older tool result
239
- images removed from the history the same way. When images push the context over the automatic
240
- compaction threshold while the rest of it fits, older tool result images are removed from the
241
- history the same way instead of summarizing the conversation: the newest images stay, using at most
242
- half of the room the rest of the context leaves below the threshold. A context summary request
243
- carries every image as a note naming its file, and the summary ends with the session folders that
244
- keep the full history before each compaction (`snapshots`) and tool images and outputs
245
- (`reports/tool-outputs`). If a
246
- provider allows fewer images per request, set `max_images_per_request` on the model:
231
+ `max_request_body_bytes` on the model, else 28 MiB for `https://api.anthropic.com`, 64 MiB for
232
+ `api.openai.com` and 64 MiB for any other endpoint, including gateways. When either limit is exceeded, the oldest
233
+ images are left out of that request only, until half of each limit remains; the history keeps
234
+ them. Models whose prompt cache needs an unchanged prefix skip this limit, so every request
235
+ carries every image in the history. If the provider rejects a request for its size, its images or
236
+ the context length, or the request exceeds the body limit before it is sent, the conversation is compacted once and the request repeated. That compaction moves all images out
237
+ of the history and always ends in a summary, images you attached included, each replaced with a note naming its file (images
238
+ without one are first saved under the session's `tool-outputs` folder); compactions triggered by
239
+ context length or large tool outputs leave images in place. Models whose prompt cache needs an
240
+ unchanged prefix are never compacted for request size alone; only a rejection compacts them. Past the context-length
241
+ threshold they are summarized directly, without archiving tool outputs first. For models whose prompt cache needs an
242
+ unchanged prefix, a compaction that keeps earlier turns and only archives or removes tool outputs
243
+ also removes their thinking blocks, as the signatures no longer match the rewritten prefix; a
244
+ summary compaction keeps no earlier turn, and its summary request carries no thinking either, as it uses its own system prompt. A context summary request carries every image as a
245
+ note naming its file, and the summary ends with the session folders that keep the full history
246
+ before each compaction (`snapshots`) and tool images and outputs (`reports/tool-outputs`). A
247
+ gateway with a lower body limit, such as Bedrock's 20 MB, should declare `max_request_body_bytes`;
248
+ if a provider allows fewer images per request, set `max_images_per_request` on the model:
247
249
 
248
250
  ```yaml
249
251
  custom_provider:
@@ -265,7 +267,7 @@ requestMedia:
265
267
  image:
266
268
  max_width: 2000 # pixels, default 2000
267
269
  max_height: 2000 # pixels, default 2000
268
- max_base64_bytes: 4718592 # base64 bytes of one image, default 4.5 MiB, at most 5 MiB
270
+ max_base64_bytes: 3670016 # base64 bytes of one image, default 3.5 MiB, at most 5 MiB
269
271
  ```
270
272
 
271
273
  This is the only resize: the Read tool, attached images and browser screenshots pass on the original
@@ -278,8 +280,29 @@ replaced with a note giving its type and size, and an attached one is not sent i
278
280
  its file path.
279
281
 
280
282
  Deterministic provider rejections, such as an image count, size or dimension limit, a 413 reported
281
- in the error, or an HTTP 400 `invalid_request_error`, are not retried; size and image rejections go
282
- straight to the image recovery above.
283
+ in the error, or an HTTP 400 `invalid_request_error`, are not retried; size, image and context
284
+ rejections go straight to the compaction recovery above.
285
+
286
+ ### Parent-death Guardian 配置
287
+
288
+ TUI(包括 `mcode exec` / ACP)默认为托管前台与后台 Bash 命令启用 Guardian:
289
+ MCode 异常退出时,它负责清理仍在运行的子进程。若受控评测环境遇到
290
+ `Parent-death guardian target registration timed out`,可在当前 profile 的
291
+ `config.yaml` 顶层显式设置:
292
+
293
+ ```yaml
294
+ skipParentDeathGuard: true
295
+ ```
296
+
297
+ 该配置默认 `false`,只接受 YAML 布尔值;字符串 `"true"` 不生效。
298
+ 它同时作用于 TUI 的 `!` / `!!` 命令,不影响 Desktop / 旧 CLI owner。
299
+ `mcode exec --config` 使用指定的配置文件,交互 TUI 使用当前 dataDir 的 `config.yaml`。
300
+ 修改后重启对应 Runtime。恢复默认保护时删除该字段或设为 `false`。
301
+
302
+ 跳过后不再创建 Guardian 或等待其注册 ACK,命令取消、超时、沙箱和权限检查继续生效。
303
+ 这只是绕开 Guardian 启动故障:MCode 被强杀或崩溃后,子进程可能继续运行,
304
+ 因此仅建议在有独立进程/虚拟机清理兜底的环境中显式启用。
305
+ `skipWindowsHardSafetyChecks` 是另一个独立配置,不控制 Guardian。
283
306
 
284
307
  ### Browser operations
285
308
 
@@ -353,16 +376,47 @@ CPU rendering can verify visuals and interactions, but is unsuitable for measuri
353
376
  It does not additionally disable Chrome's process sandbox. An image that already includes a
354
377
  SwiftShader-capable Chrome needs neither an image change nor a separate renderer installation.
355
378
 
379
+ #### Scripted input (`run_script`)
380
+
381
+ The headless Browser also exposes `browser` action `run_script` for checks that single-step
382
+ actions cannot express: holding keys while moving, modifier plus mouse combinations, timed or
383
+ repeated input, and loops that read page state before acting. The agent passes an async function
384
+ body as `code`, or an active-workspace `.js`/`.mjs` file as `path` so the script can be kept and
385
+ rerun, plus an optional `timeout` (1000-120000 ms, default 30000). The script drives the current
386
+ Browser tab and login state; no separate Chrome or Playwright install is involved.
387
+
388
+ Scripts receive `page.keyboard`, `page.mouse`, `page.waitForTimeout`, `page.waitForFunction`,
389
+ `page.evaluate`, `page.screenshot`, `page.consoleMessages`, `assert` and `console`. The script body
390
+ itself runs in an isolated worker with no Node.js, filesystem or network APIs. `page.evaluate` is
391
+ different: it runs JavaScript inside the page with that page's full capabilities, including `fetch`
392
+ with the session's cookies (HttpOnly cookies are sent automatically on same-site requests) and
393
+ access to page storage. Treat `run_script` as having the same trust level as the agent's shell
394
+ tools for the pages it opens. The headless Browser uses a per-session profile with no Chrome
395
+ profile import, so its cookies are only those created while the agent browsed.
396
+
397
+ Every key and mouse button still held when a script ends, fails, times out or is cancelled is
398
+ released on the page; if the release cannot be delivered, the Browser session is recreated.
399
+ Results include the return value, logs, the failing script line, page errors, up to four script
400
+ screenshots plus one failure screenshot, and each `page.evaluate` call site so reviewers can tell
401
+ real input from page-state reads. The Electron FilePanel Browser does not offer `run_script`.
402
+
356
403
  ### MCP cold-start discovery budget
357
404
 
358
- The default stdio MCP turn discovery budget is 30,000 ms, allowing more time for servers
359
- that install dependencies on first launch. It covers connection preparation, process startup,
360
- initialize and tools/list. The effective budget is the minimum of this default and each server's
361
- `mcp.json` `timeout` (milliseconds, default 120,000).
362
- Remote HTTP/SSE discovery remains at 2,000 ms. Tool-call timeouts and the existing empty-list
363
- fallback on discovery failure are unchanged. A broken stdio server can therefore delay a turn
364
- for up to 30 seconds. This default requires a build containing the change; no new environment
365
- variable is needed.
405
+ stdio MCP 的工具发现/注入默认等待 30,000 ms。可在启动 MCode 的进程环境中设置
406
+ `MCODE_MCP_STDIO_DISCOVERY_TIMEOUT_MS`,例如:
407
+
408
+ ```bash
409
+ MCODE_MCP_STDIO_DISCOVERY_TIMEOUT_MS=60000 mcode
410
+ ```
411
+
412
+ 该变量接受十进制正整数毫秒(1–2,147,483,647,可带首尾空白);未设置、空值、零、负数、
413
+ 小数、非法文本及超出 Node timer 安全范围的值均回退至 30,000 ms,不会关闭超时。
414
+ 连接准备、进程启动、initialize 与 tools/list 共用一个总预算,不会每阶段重新计时。
415
+ 实际预算仍取该值与每个 server 的 `mcp.json` `timeout` 的最小值(后者默认 120,000 ms);
416
+ 因此需要等待超过 120 秒时,也要相应提高 server 的 `timeout`。
417
+ 内部显式 discovery options 保持优先于该环境变量。HTTP/SSE 发现仍默认 2,000 ms,
418
+ 工具调用 timeout 与发现失败返回空列表的行为均不变。仅增大等待上限,不保证故障 server 能成功启动。
419
+ 需使用包含此变更的构建,并在启动前设置变量;既有运行中的进程不会自动读取外部 shell 的变更。
366
420
 
367
421
  ### ACP clients
368
422
 
package/README.zh-CN.md CHANGED
@@ -369,12 +369,11 @@ artifacts 访问权限与保留时间。
369
369
  以毫秒覆盖这两个时限,设为 `0` 表示关闭。超时错误会写明触发的是哪项设置,20 分钟整体上限仍然有效。
370
370
 
371
371
  单次模型请求默认最多携带 100 张图片(MiniMax M3 系列为 20 张,Mistral API 为 8 张),图片数据最多占请求体上限的三分之二。请求体上限取模型的
372
- `max_request_body_bytes`;未配置时 `https://api.anthropic.com` 为 28 MiB,Google Cloud 上的 Messages API 为 26 MiB,`api.openai.com`
373
- 为 64 MiB,其他地址为 18 MiB。超过任一上限时,最早的工具结果图片会从历史中移除,直到降到上限的一半,每张换成一行写明文件路径的说明(没有路径的图片先保存到会话的
374
- `tool-outputs` 目录)。你附加的图片不会从历史中移除,只在它们单独超限时从本次请求里去掉最早的几张。Provider
375
- 仍因体积或图片拒绝请求时,会带着原请求一半的图片重发一次(分母可用 `config.yaml` 的 `requestMedia.recoveryDivisor`
376
- 配置,默认 `2`),较早的工具结果图片同样从历史中移除。上下文其余部分未超限、只因图片超过自动压缩阈值时,同样从历史中移除较早的工具结果图片,而不是把对话压成摘要:保留最新的图片,所占不超过其余部分到阈值剩余空间的一半。上下文摘要请求不携带图片,每张图片都换成写明文件路径的说明;生成的摘要末尾附上会话的 `snapshots`(每次压缩前的完整历史)和 `reports/tool-outputs`(工具图片与输出)两个目录。Provider
377
- 允许的单次图片数更少时,可在模型上设置 `max_images_per_request`:
372
+ `max_request_body_bytes`;未配置时 `https://api.anthropic.com` 为 28 MiB,`api.openai.com` 为 64 MiB,其他地址(包括网关)为 64 MiB。超过任一上限时,只在本次请求里去掉最早的图片,直到降到上限的一半,历史中仍保留这些图片。提示缓存要求前缀不变的模型
373
+ 不做这项限制,所以每次请求都携带历史里的全部图片。Provider
374
+ 因体积、图片或上下文长度拒绝请求,或请求在发出前就超过请求体上限时,先压缩一次上下文再重发。这次压缩会把历史中的全部图片移出并一定生成摘要,包括你附加的图片,每张换成一行写明文件路径的说明(没有路径的图片先保存到会话的
375
+ `tool-outputs` 目录);因上下文长度或工具输出过大触发的压缩不移出图片;提示缓存要求前缀不变的模型不会仅因请求体大小触发压缩,只有被拒后才压缩;超过上下文长度触发线时直接生成摘要,不先归档工具输出。对提示缓存要求前缀不变的模型,只归档或删除工具输出、保留之前轮次的压缩会同时删除这些轮次的 thinking 块,因为前缀改写后其签名不再有效;生成摘要的压缩不保留之前的轮次,摘要请求使用自己的 system prompt,因此也不携带 thinking。上下文摘要请求不携带图片,每张图片都换成写明文件路径的说明;生成的摘要末尾附上会话的 `snapshots`(每次压缩前的完整历史)和 `reports/tool-outputs`(工具图片与输出)两个目录。请求体上限更低的网关(例如 Bedrock 的 20 MB)应配置
376
+ `max_request_body_bytes`;Provider 允许的单次图片数更少时,可在模型上设置 `max_images_per_request`:
378
377
 
379
378
  ```yaml
380
379
  custom_provider:
@@ -394,12 +393,12 @@ requestMedia:
394
393
  image:
395
394
  max_width: 2000 # 像素,默认 2000
396
395
  max_height: 2000 # 像素,默认 2000
397
- max_base64_bytes: 4718592 # 单张图片的 base64 字节数,默认 4.5 MiB,最大 5 MiB
396
+ max_base64_bytes: 3670016 # 单张图片的 base64 字节数,默认 3.5 MiB,最大 5 MiB
398
397
  ```
399
398
 
400
399
  这是唯一一次缩放:Read 工具、附加的图片和 Browser 截图都交出原图,在上限内的图片原样发送,被缩小的图片只带一条说明。Browser 操作后自动截取的截图不超过 1280 px 和 1 MiB,上面的上限更小时以其为准。图片处理组件无法加载时,超过上限的工具结果图片会替换为一条说明。图片处理组件无法解码的图片(损坏、截断或格式不支持)不会进入对话,否则之后每次请求都会带上它并失败:工具结果里的这类图片替换为一条写明类型和大小的说明,你附加的这类图片不内联发送,只保留文件路径。
401
400
 
402
- 图片数量、体积或尺寸超限、报错中带有 413、HTTP 400 `invalid_request_error` 等确定性拒绝不再重试;体积和图片类拒绝直接走上面的图片恢复。
401
+ 图片数量、体积或尺寸超限、报错中带有 413、HTTP 400 `invalid_request_error` 等确定性拒绝不再重试;体积、图片和上下文长度类拒绝直接走上面的压缩恢复。
403
402
 
404
403
  ### Browser 操作
405
404
 
@@ -463,6 +462,14 @@ Use。SwiftShader 开关只接受
463
462
  `--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader`,仅用于受信任的本地页面测试;Chrome 的说明见
464
463
  [SwiftShader 文档](https://chromium.googlesource.com/chromium/src/+/main/docs/gpu/swiftshader.md)。它用 CPU 绘图,适合验证画面和交互,不适合测游戏帧率;不会额外关闭 Chrome 进程沙箱。镜像已包含支持 SwiftShader 的 Chrome 时,不需要更换镜像或安装独立渲染库。
465
464
 
465
+ #### 脚本化输入(`run_script`)
466
+
467
+ Headless Browser 还提供 `browser` 的 `run_script` 动作,用于单步动作表达不了的检查:按住按键移动、修饰键加鼠标组合、定时或重复输入,以及先读页面状态再决定点哪里的循环。Agent 传入异步函数体 `code`,或工作区内的 `.js`/`.mjs` 文件 `path`(脚本可保留后重跑),可选 `timeout`(1000–120000 ms,默认 30000)。脚本直接操作当前 Browser 标签页和登录状态,不另起 Chrome,也不需要安装 Playwright。
468
+
469
+ 脚本可用 `page.keyboard`、`page.mouse`、`page.waitForTimeout`、`page.waitForFunction`、`page.evaluate`、`page.screenshot`、`page.consoleMessages`、`assert` 和 `console`。脚本本身运行在隔离的 worker 中,没有 Node.js、文件系统和网络 API。`page.evaluate` 不同:它在页面内执行 JavaScript,拥有该页面的全部能力,包括带当前会话 Cookie 的 `fetch`(同站请求会自动携带 HttpOnly Cookie)和页面存储访问。对它打开的页面而言,`run_script` 与 Agent 的 shell 工具信任级别相同。Headless Browser 每个会话使用独立 profile,不支持导入 Chrome Profile,其中的 Cookie 只来自 Agent 自己浏览产生的登录状态。
470
+
471
+ 脚本结束、出错、超时或被取消时,仍按住的键和鼠标键都会在页面上松开;松开事件无法送达时会重建 Browser 会话。结果包含返回值、日志、失败的脚本行号、页面错误、最多 4 张脚本截图加 1 张失败截图,以及每个 `page.evaluate` 调用位置,审阅时能分清真实输入和页面状态读取。Electron FilePanel Browser 不提供 `run_script`。
472
+
466
473
  ### MCP 冷启动发现预算
467
474
 
468
475
  stdio MCP 在 turn 工具发现阶段的默认总预算为 30,000 ms,为首次启动需要安装依赖的 Server
@@ -114,16 +114,15 @@ path:
114
114
  and `nextOffset`; do not restart inspection or guess a selector or coordinate.
115
115
  3. Call `click_and_wait_for_navigation` with that stable opaque `ref`.
116
116
  4. Call `inspect` once on the destination and verify that the login form is present.
117
- 5. Treat email, phone number, password, verification code, CAPTCHA, security-key response, recovery
118
- code, and every other authentication input as user-controlled. If the provider exposes a visible
119
- same-tab takeover surface, make an actual `ask_user` tool call for takeover and end the turn. If
120
- it is headless and has no takeover surface, stop and report that interactive login is required;
121
- do not issue another Browser action.
117
+ 5. If the provider exposes a visible same-tab takeover surface, treat email, phone number, password,
118
+ verification code, CAPTCHA, security-key response, recovery code, and every other authentication
119
+ input as user-controlled: make an actual `ask_user` tool call for takeover and end the turn. If
120
+ it is headless and has no takeover surface, follow the headless sign-in paragraph below.
122
121
 
123
- If the requested workflow reaches a login or sign-in form, inspect only enough page state to explain
124
- what the user must do. Never read, request, generate, reveal, type, or fill an email address, phone
125
- number, password, verification code, CAPTCHA, security key response, recovery code, or another
126
- authentication input.
122
+ If the requested workflow reaches a login or sign-in form on a provider with a visible takeover
123
+ surface, inspect only enough page state to explain what the user must do. On such a provider, never
124
+ read, request, generate, reveal, type, or fill an email address, phone number, password,
125
+ verification code, CAPTCHA, security key response, recovery code, or another authentication input.
127
126
 
128
127
  When the provider exposes a visible interactive surface, use `ask_user` to pause the turn and ask
129
128
  the user to take over the existing FilePanel Browser for the authentication step. Keep the question
@@ -131,13 +130,21 @@ specific to the current site and explain that the same Browser tab and profile w
131
130
  not substitute Computer Use, shell credential reads, standalone Playwright, or a second browser. Do
132
131
  not click a final sign-in or authorization button on the user's behalf when it would submit
133
132
  credentials or grant account access. After the actual `ask_user` call reports that it is waiting,
134
- stop the turn immediately. A headless provider without a visible takeover surface must stop at the
135
- login boundary instead of asking the user to interact with a panel that does not exist.
133
+ stop the turn immediately.
136
134
 
137
- After the user reports that they completed login, call `inspect` again on the same Browser session
135
+ On headless Chrome there is no surface to take over, so complete the sign-in yourself: fill the
136
+ credentials the user or task supplied, or an account the site's sign-in page publishes for that
137
+ user or task, and submit. If required values are missing, request them with `ask_user` when that
138
+ tool is available; otherwise report which site needs which value and continue the rest of the
139
+ task. Never guess credentials or echo secret values in prose; report CAPTCHA and security-key
140
+ challenges.
141
+
142
+ After login completes, call `inspect` again on the same Browser session
138
143
  and verify a signed-in page marker before continuing. Do not inspect cookies, local storage, tokens,
139
144
  or profile files to prove authentication. If the page still shows login, ask the user to take over
140
- again or report the site-provided failure; never guess credentials or retry secrets.
145
+ again when a visible surface exists; on headless Chrome, check the entered values against their
146
+ source once, then request corrected values with `ask_user` when available or report the
147
+ site-provided failure. Never guess credentials or retry the same rejected values.
141
148
 
142
149
  When Electron is the active provider, never tell the user that this tool cannot see the right-side
143
150
  Browser because it is a different browser instance. Do not switch to desktop screenshots merely to
@@ -170,7 +177,10 @@ the user refers to a page that is already or currently open in this Browser.
170
177
  When the active provider exposes `return_to_previous_tab`, use it to close the current headless tab
171
178
  and resume the page most recently preserved by `open_tab`. `back` and `forward` only traverse
172
179
  history inside the active tab and never return to a preserved tab. Do not call the return action
173
- when the provider does not expose it.
180
+ when the provider does not expose it. Prefer `back` over re-`navigate` when returning to the
181
+ previous page in the same tab and its state may not be reconstructable from its URL — form drafts,
182
+ one-time or session-scoped results, post-redirect pages; re-navigating rebuilds the page and may
183
+ replay server-side effects. After `back`, use `forward` to return instead of re-navigating.
174
184
 
175
185
  If the user says the page is already or currently open in the Browser, inspect that existing page
176
186
  first. Do not navigate or reload it merely because the request also mentions its URL or domain. Use
@@ -188,7 +198,7 @@ browser({ action: "inspect", input: {} })
188
198
  refs. Do not ask the user to provide the URL or a screenshot before trying `inspect`.
189
199
 
190
200
  `actionable` means Chromium identified the element as interactable. Before `click`, `double_click`,
191
- `hover`, `drag`, `check`, or `uncheck`, also require `pointerActionable: true`. A ref with
201
+ `triple_click`, `hover`, `drag`, `check`, or `uncheck`, also require `pointerActionable: true`. A ref with
192
202
  `coordinateSpace: "unavailable"` is intentionally unsafe for pointer input; do not guess coordinates
193
203
  or fall back to a position. Non-pointer actions that accept the ref, such as ordinary `fill`/`type`,
194
204
  `select_option`, `paste`, or `upload_files`, may still operate through its DOM identity.
@@ -380,8 +390,10 @@ indices, or local map paths in compact action results.
380
390
  An ordinary `click` result means the input was dispatched, but the requested page effect is not
381
391
  verified. Its `effect.verified` remains `false` and `verificationRequired` remains `true`. Use
382
392
  `inspect`, `query`, or `screenshot` and observe the expected panel, control, text, or state before
383
- claiming that the click achieved the user's goal. `UNEXPECTED_NAVIGATION` means an ordinary in-page
384
- click changed the document or URL; inspect the current page before deciding whether to go back or
393
+ claiming that the click achieved the user's goal. When an ordinary click navigates the page, the
394
+ result reports `navigation.detected: true`; every earlier ref is invalid, so inspect the new page
395
+ before the next interaction. A provider that treats that navigation as unexpected reports
396
+ `UNEXPECTED_NAVIGATION`; inspect the current page before deciding whether to go back or
385
397
  retry with a newly observed target. An attached `visualObservation` can establish a visible UI
386
398
  effect, but it does not rewrite the structured click effect or navigation status.
387
399
 
@@ -404,8 +416,8 @@ and other in-page buttons default to plain `click`; use the atomic navigation ac
404
416
  inspected link or a control whose page state explicitly indicates main-document navigation.
405
417
 
406
418
  Compact Browser actions never accept ElementMap `index` or editable-query ordinals. Use the opaque
407
- `ref` returned by the latest `inspect` or `query`. For `click`, `double_click`, `hover`, and drag
408
- endpoints, `ref` or `selector` means the center of that DOM element. Use `position: { x, y }` only
419
+ `ref` returned by the latest `inspect` or `query`. For `click`, `double_click`, `triple_click`,
420
+ `hover`, and drag endpoints, `ref` or `selector` means the center of that DOM element. Use `position: { x, y }` only
409
421
  for a precise non-DOM target such as a canvas square, map point, or drawing surface; its values are
410
422
  absolute CSS pixels in the main Frame's current viewport. An inspected element `rect`, when present,
411
423
  uses that same coordinate space and is equivalent to its main-Frame `getBoundingClientRect()`.
@@ -417,14 +429,20 @@ stable element or absolute position is available.
417
429
 
418
430
  Do not combine `ref` or `selector` with `position` or `normalized_position`, and do not combine
419
431
  `position` with `normalized_position`; ambiguous targets fail validation instead of silently
420
- choosing one. `fill` and `type` may use `ref`, `selector`, or `normalized_position` as allowed by
421
- their schemas; prefer the latest opaque ref. `paste` and `upload_files` require an opaque ref from
432
+ choosing one. Every element action (`click`, `double_click`, `triple_click`, `hover`, `fill`,
433
+ `type`, `check`, `uncheck`, `select_option`) accepts the same locator family: `ref`, `selector`,
434
+ `position`, or `normalized_position`; prefer the latest opaque ref. `scroll` takes the same locator
435
+ fields directly inside `input` together with `direction` and `distance`; only `drag` nests its two
436
+ endpoints as `source` and `target`, so never wrap a scroll or other single-target locator in a
437
+ `target` object. With a coordinate locator,
438
+ `fill`/`type` click the point and type into the focused field, and `check`/`uncheck`/
439
+ `select_option` act on the checkbox, radio, or select under the point (a point on its label also
440
+ resolves to the control). Use `triple_click` to select a whole line or field of text. `paste` and `upload_files` require an opaque ref from
422
441
  the latest inspect/query. Compact `paste` is available only when the active provider advertises it
423
442
  and requires explicit non-empty plain text:
424
443
  `browser({ action: "paste", input: { ref: "<opaque-ref>", text: "<plain-text>" } })`. Do not omit
425
444
  `text` to read ambient OS clipboard contents, and do not pass legacy `html` or `waitMs` fields. The
426
- TUI headless provider keeps clipboard state isolated to the logical Browser session. `check`,
427
- `uncheck`, and `select_option` do not accept coordinates. `fill` always clears before entering text,
445
+ TUI headless provider keeps clipboard state isolated to the logical Browser session. `fill` always clears before entering text,
428
446
  so do not pass a `clear` field to `fill`; use `type` with `clear: true` only when per-key typing
429
447
  behavior is required.
430
448
 
@@ -454,6 +472,68 @@ read, stat, `test`, `ls`, or another filesystem tool; call `upload_files` direct
454
472
  returned recovery guidance; do not fall back to shell, standalone Playwright, AppleScript, or
455
473
  Computer Use.
456
474
 
475
+ ## Scripted Input With run_script
476
+
477
+ Use `run_script` only when the active provider advertises it and single-step actions cannot
478
+ express the check: holding keys (game movement), modifier plus mouse combinations, timed or repeated
479
+ input, or a loop that reads page state before choosing where to act. Ordinary forms, links and
480
+ one-off key presses stay on the single-step actions.
481
+
482
+ The input is an async function body, either inline `code` or a saved active-workspace `.js` `path`
483
+ (exactly one), with an optional `timeout` (1000-120000 ms, default 30000). The script body runs in an
484
+ isolated worker with no Node.js APIs, filesystem, network or `require`; `page.evaluate` runs inside
485
+ the page with that page's full capabilities, including `fetch` with its cookies. In scope:
486
+
487
+ - `page.keyboard.down/up/press/type` and `page.mouse.move/down/up/click/wheel`: real input to the
488
+ page. Keys accept `KeyW`, `ArrowUp`, `Shift`, `Enter` style names; clicks made while a modifier is
489
+ held carry that modifier. Coordinates are main-Frame viewport CSS pixels. The pointer position
490
+ does not carry over between actions: call `page.mouse.move` or `page.mouse.click` before
491
+ `mouse.down`/`mouse.up`/`mouse.wheel` in every script.
492
+ - `page.waitForTimeout(ms)`, `page.waitForFunction(fn, arg, { timeout, polling })`.
493
+ - `page.evaluate(fn, arg)`: page JavaScript returning a JSON value.
494
+ - `page.screenshot({ label })`, `page.consoleMessages({ levels })`, `page.url()`, `page.title()`,
495
+ `page.viewportSize()`.
496
+ - `assert.ok/equal/notEqual/deepEqual/fail` and `console.log`.
497
+
498
+ Example:
499
+
500
+ ```js
501
+ await page.keyboard.down('Shift');
502
+ await page.keyboard.down('KeyD');
503
+ for (let i = 0; i < 7; i += 1) {
504
+ await page.waitForTimeout(140);
505
+ await page.mouse.click(520, 330);
506
+ }
507
+ await page.keyboard.up('KeyD');
508
+ await page.keyboard.up('Shift');
509
+ const state = await page.evaluate(() => window.__game.previewMismatches);
510
+ assert.equal(state, 0, 'preview and click disagreed');
511
+ await page.screenshot({ label: 'after-clicks' });
512
+ return { mismatches: state };
513
+ ```
514
+
515
+ Evidence rules:
516
+
517
+ - Drive the behavior under test with `page.keyboard` and `page.mouse`. Use `page.evaluate` to read
518
+ state or arrange a precondition, never to perform the action being verified. The result lists every
519
+ `page.evaluate` call site in `pageEvaluate`; report a conclusion as input-verified only when the
520
+ asserted behavior came from real input.
521
+ - Every key and mouse button still held when the script returns, throws, times out or is cancelled is
522
+ released automatically and listed in `input.autoReleased`. Treat a non-empty list as a script bug
523
+ to fix, not as a verified release.
524
+ - A failure returns `code`, `error.message` and `error.location` (script line and column) plus one
525
+ failure screenshot. Fix the script or the page and rerun; do not retry an unchanged script.
526
+ - Refs from earlier `inspect` calls are invalid after `run_script`; inspect again before a ref
527
+ action.
528
+ - Keep `page.evaluate` short and synchronous where possible. An async `page.evaluate` interrupted by
529
+ a timeout or cancellation can still finish in the page later; when `pageEvaluate.interrupted` is
530
+ present, reload or re-inspect the page before trusting its state.
531
+ - `assert.deepEqual` compares JSON data only; convert a Set, Map or Date first (for example
532
+ `[...set].sort()`, `date.getTime()`).
533
+ - Save scripts that should be rerun after code changes under the workspace and call them by `path`.
534
+ - Headless rendering may be software rendering. Do not report frame rate or GPU performance from a
535
+ script as real-hardware performance.
536
+
457
537
  ## Screenshot Visibility Boundary
458
538
 
459
539
  A Browser `screenshot` result is model-visible inspection evidence and is not shown to the user by
@@ -472,7 +552,10 @@ Element and frame refs are snapshot-scoped. After navigation, reload, or a stale
472
552
 
473
553
  ## Safety And Recovery
474
554
 
475
- - Arbitrary JavaScript execution is unavailable and must not be simulated through another tool.
555
+ - Arbitrary JavaScript execution is unavailable outside `run_script`: when the active provider
556
+ exposes `run_script`, page JavaScript runs only through its `page.evaluate` under the evidence
557
+ rules above; otherwise it is unavailable entirely. Never simulate JavaScript execution through
558
+ another tool.
476
559
  - Do not inspect cookies, local storage, passwords, profiles, or authentication secrets.
477
560
  - A passive read request must not trigger interaction. An explicitly requested read-only search may
478
561
  fill its filters and activate a clearly non-mutating search control, but must not submit, save,
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as o,b as l,c as u}from"./chunk-55CEUKGL.js";import"./chunk-F6CPFGSE.js";import{d as p}from"./chunk-YD3QXMMM.js";import"./chunk-S3AA7ARE.js";import"./chunk-EYZOZ75Y.js";import"./chunk-3FETZOUF.js";import"./chunk-CWWDVX6C.js";import"./chunk-ZITT4GJK.js";import"./chunk-D76SO2ME.js";async function A(r={}){let a=r.createApplication?r.createApplication(r.region):await c(r.region,r.prepareDataDir),t=r.writeError??(e=>process.stderr.write(e));return(await a.login(e=>{let n=l(e.verificationUriComplete??e.verificationUri);if(t(`Open: ${n}
2
+ import{a as o,b as l,c as u}from"./chunk-UQ2YIDWV.js";import"./chunk-FPCUX6KP.js";import{d as p}from"./chunk-CRTW4JM6.js";import"./chunk-2LP3AAE5.js";import"./chunk-G7FSWJID.js";import"./chunk-3FETZOUF.js";import"./chunk-CWWDVX6C.js";import"./chunk-ZITT4GJK.js";import"./chunk-D76SO2ME.js";async function A(r={}){let a=r.createApplication?r.createApplication(r.region):await c(r.region,r.prepareDataDir),t=r.writeError??(e=>process.stderr.write(e));return(await a.login(e=>{let n=l(e.verificationUriComplete??e.verificationUri);if(t(`Open: ${n}
3
3
  Code: ${e.userCode}
4
4
  Waiting for authorization\u2026
5
5
  `),r.openBrowser===!1)return;(r.openExternalTarget??o(process.cwd()))(n).catch(()=>{t(`Couldn't open the default browser. Open the authorization URL above manually.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{Ba as ie,Ca as re,a as Te,ka as ne}from"./chunk-EYZOZ75Y.js";import{c as oe}from"./chunk-3FETZOUF.js";import{e as Se}from"./chunk-D76SO2ME.js";var u="mcode-public",c=["agent.default"],p="agent-backend";var Me={cn:{dev:"https://account.minimax.cn",test:"https://account.minimax.cn",staging:"https://account.minimax.cn",prod:"https://account.minimax.cn"},en:{dev:"https://account.minimax.io",test:"https://account.minimax.io",staging:"https://account.minimax.io",prod:"https://account.minimax.io"}};function Mt(t,e){if([t.MCODE_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT,t.MCODE_OAUTH_TOKEN_ENDPOINT,t.MCODE_OAUTH_REVOCATION_ENDPOINT].every(s=>!s?.trim())){let s=Me[e.region][e.buildEnv];return{deviceAuthorizationEndpoint:`${s}/oauth2/device/code`,...se(e.buildEnv),tokenEndpoint:`${s}/oauth2/token`,revocationEndpoint:`${s}/oauth2/revoke`}}let i=H(t.MCODE_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT),r=H(t.MCODE_OAUTH_TOKEN_ENDPOINT),o=H(t.MCODE_OAUTH_REVOCATION_ENDPOINT);if(!i||!r||!o)throw new TypeError("Shared MCode OAuth requires all three public OAuth endpoints to be configured.");return{deviceAuthorizationEndpoint:i,...se(e.buildEnv),tokenEndpoint:r,revocationEndpoint:o}}function se(t){return t==="staging"?{deviceAuthorizationHeaders:{"X-User-Pre":"1"}}:{}}function H(t){if(t?.trim())try{let e=new URL(t);return e.protocol!=="https:"||e.username||e.password||e.hash?void 0:e.toString()}catch{return}}import{randomUUID as $}from"node:crypto";import{watchFile as Ke,unwatchFile as $e}from"node:fs";var ce=Se(Te(),1);import{open as be}from"node:fs/promises";import{chmod as ae,mkdir as Ie,open as Ce,rename as Oe,unlink as ke}from"node:fs/promises";import{dirname as Pe}from"node:path";async function O(t){await Ie(t,{recursive:!0,mode:448}),process.platform!=="win32"&&await ae(t,448)}async function b(t,e){let n=Pe(t);await O(n);let i=`${t}.${process.pid}.${Date.now()}.tmp`,r=await Ce(i,"wx",384);try{await r.writeFile(e,{encoding:"utf8"}),await r.sync()}finally{await r.close()}try{process.platform!=="win32"&&await ae(i,384),await Oe(i,t)}catch(o){throw await ke(i).catch(()=>{}),o}}import{dirname as xe}from"node:path";var w=class{lockPath;staleMs;retries;constructor(e,n={}){this.lockPath=e,this.staleMs=n.staleMs??3e4,this.retries=n.retries??120}async withLock(e){await O(xe(this.lockPath)),await(await be(this.lockPath,"a",384)).close();let i,r=await ce.default.lock(this.lockPath,{realpath:!1,stale:this.staleMs,retries:{retries:this.retries,factor:1.15,minTimeout:5,maxTimeout:250},onCompromised:o=>{i??=o}});try{return await e()}finally{try{await r()}catch(o){if(!i)throw o}if(i)throw i}}};import{createHash as Re,randomBytes as Ne}from"node:crypto";var Ue="urn:ietf:params:oauth:grant-type:device_code",l=class extends Error{code;httpStatus;constructor(e,n,i){super(n??`The OAuth server rejected the request (${e}${i?`, HTTP ${i}`:""}).`),this.code=e,this.httpStatus=i,this.name="OAuthProtocolError"}},j=class{options;fetchImpl;sleep;now;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.sleep=e.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.now=e.now??Date.now}async startDeviceAuthorization(e={}){let n=Ne(32).toString("base64url"),i=Re("sha256").update(n,"ascii").digest("base64url"),r=await this.postForm(this.options.deviceAuthorizationEndpoint,{client_id:u,scope:c.join(" "),audience:p,code_challenge:i,code_challenge_method:"S256"},{headers:this.options.deviceAuthorizationHeaders,signal:e.signal}),o=d(r,"user_code"),s=d(r,"device_code"),a=R(r,"expired_in"),h=!s&&!!o&&a!==void 0,C=s??(h?o:void 0),B=d(r,"verification_uri")??d(r,"verification_url"),te=R(r,"expires_in")??ze(a,this.now()),V=R(r,"interval"),Ae=h&&V!==void 0?V/1e3:V??5;if(!C||!o||!B||!te)throw new l("invalid_device_authorization_response");return{deviceCode:C,codeVerifier:n,...h?{tokenPollingParameter:"user_code"}:{},userCode:o,verificationUri:B,...d(r,"verification_uri_complete")||h?{verificationUriComplete:d(r,"verification_uri_complete")??B}:{},expiresInSec:te,intervalSec:Ae}}async pollDeviceToken(e,n={}){let i=this.now()+e.expiresInSec*1e3,r=e.intervalSec*1e3;for(;this.now()<i;){n.signal?.throwIfAborted();let o=e.tokenPollingParameter==="user_code"?{user_code:e.userCode}:{device_code:e.deviceCode},s=await this.postFormAllowOAuthError(this.options.tokenEndpoint,{grant_type:Ue,...o,client_id:u,code_verifier:e.codeVerifier},{signal:n.signal}),a=d(s.body,"status");if(s.ok&&a==="pending"){await x(this.sleep,r,n.signal);continue}if(s.ok&&a==="slow_down"){r+=5e3,await x(this.sleep,r,n.signal);continue}if(s.ok&&(a==="denied"||a==="access_denied"))throw new l("access_denied");if(s.ok&&(a==="expired"||a==="expired_token"))throw new l("expired_token");if(s.ok)return de(s.body);if(s.error==="authorization_pending"){await x(this.sleep,r,n.signal);continue}if(s.error==="slow_down"){r+=5e3,await x(this.sleep,r,n.signal);continue}throw new l(s.error??"device_authorization_failed",void 0,s.status)}throw new l("expired_token","The OAuth device authorization expired.")}async refreshToken(e){let n=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:u,scope:c.join(" "),audience:p});return de(n,e)}async revokeToken(e){let n=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:u},{allowEmptySuccess:!0});if(!n.ok)throw new l(n.error??"oauth_request_failed",void 0,n.status)}async postForm(e,n,i={}){let r=await this.postFormAllowOAuthError(e,n,i);if(!r.ok)throw new l(r.error??"oauth_request_failed",void 0,r.status);return r.body}async postFormAllowOAuthError(e,n,i={}){let r=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...i.headers},body:new URLSearchParams(n),signal:i.signal}),o=N(await r.json().catch(()=>{}));if(!o&&r.ok&&i.allowEmptySuccess)return{ok:!0,status:r.status,body:{}};if(!o)throw new l("invalid_json_response",void 0,r.status);let s=d(o,"error");return{ok:r.ok&&!s,status:r.status,body:o,...s?{error:s}:{}}}};async function x(t,e,n){if(!n){await t(e);return}n.throwIfAborted();let i,r=()=>i(n.reason),o=new Promise((s,a)=>{i=a});n.addEventListener("abort",r,{once:!0});try{await Promise.race([t(e),o])}finally{n.removeEventListener("abort",r)}}function de(t,e){let n=d(t,"access_token"),i=d(t,"refresh_token")??e,r=d(t,"token_type"),o=R(t,"expires_in"),s=n?De(n):void 0,a=Le(t.scope??s?.scope??s?.scp);if(!n||!i||r?.toLowerCase()!=="bearer"||!o||!a.includes(c[0]))throw new l("invalid_token_response");return{accessToken:n,refreshToken:i,tokenType:"Bearer",scopes:a,audience:p,expiresInSec:o,...d(s,"sub")?{subject:d(s,"sub")}:{},...d(s,"account_id")?{accountId:d(s,"account_id")}:{}}}function De(t){let e=t.split(".");if(!(e.length!==3||!e[1]))try{return N(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return}}function Le(t){return typeof t=="string"?t.split(/\s+/u).filter(Boolean):Array.isArray(t)&&t.every(e=>typeof e=="string")?t:[]}function N(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function d(t,e){let i=N(t)?.[e];return typeof i=="string"&&i.trim()?i.trim():void 0}function R(t,e){let i=N(t)?.[e];return typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0}function ze(t,e){if(t===void 0)return;if(t<1e12)return t;let n=t-e;return n>0?Math.ceil(n/1e3):void 0}import{readFile as Be}from"node:fs/promises";var E=2,Ve=1,He=/access[_-]?token|refresh[_-]?token|device[_-]?code|code[_-]?verifier/iu;function he(t){if(!(typeof t!="object"||t===null))for(let[e,n]of Object.entries(t)){if(He.test(e))throw new TypeError("Sensitive OAuth fields cannot be persisted in auth-state.json.");he(n)}}function ue(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Invalid OAuth state.");let e=t;if(!(typeof e.schemaVersion=="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=Ve&&e.schemaVersion<=E&&["anonymous","authorizing","authenticated","refreshing","scope_upgrade_required","logging_out","logout_pending","expired","error"].includes(e.status)&&(e.schemaVersion===1&&(e.storeKind==="os-keyring"||e.storeKind==="file")||e.schemaVersion===E&&e.storeKind==="file")&&e.clientId==="mcode-public"&&Array.isArray(e.scopes)&&e.scopes.every(i=>typeof i=="string")&&e.audience==="agent-backend"&&je(e.buildEnv,e.region)&&(e.expiresAtMs===void 0||typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs))&&Number.isSafeInteger(e.generation)&&e.generation>=0&&(e.authorization===void 0||Fe(e.authorization))))throw new TypeError("Invalid OAuth state.");return he(e),e}function je(t,e){return t===void 0&&e===void 0?!0:(t==="dev"||t==="test"||t==="staging"||t==="prod")&&(e==="cn"||e==="en")}function Fe(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return typeof e.leaseId=="string"&&e.leaseId.length>0&&typeof e.leaseExpiresAtMs=="number"&&Number.isFinite(e.leaseExpiresAtMs)&&F(e.userCode)&&F(e.verificationUri)&&F(e.verificationUriComplete)}function F(t){return t===void 0||typeof t=="string"}var y=class{path;constructor(e){this.path=e}async read(){let e;try{e=await Be(this.path,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{return ue(JSON.parse(e))}catch(n){throw n instanceof TypeError?n:new TypeError("Invalid OAuth state.")}}async write(e){let n=ue(e);await b(this.path,`${JSON.stringify(n,null,2)}
2
+ import{Ba as ie,Ca as re,a as Te,ka as ne}from"./chunk-G7FSWJID.js";import{c as oe}from"./chunk-3FETZOUF.js";import{e as Se}from"./chunk-D76SO2ME.js";var u="mcode-public",c=["agent.default"],p="agent-backend";var Me={cn:{dev:"https://account.minimax.cn",test:"https://account.minimax.cn",staging:"https://account.minimax.cn",prod:"https://account.minimax.cn"},en:{dev:"https://account.minimax.io",test:"https://account.minimax.io",staging:"https://account.minimax.io",prod:"https://account.minimax.io"}};function Mt(t,e){if([t.MCODE_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT,t.MCODE_OAUTH_TOKEN_ENDPOINT,t.MCODE_OAUTH_REVOCATION_ENDPOINT].every(s=>!s?.trim())){let s=Me[e.region][e.buildEnv];return{deviceAuthorizationEndpoint:`${s}/oauth2/device/code`,...se(e.buildEnv),tokenEndpoint:`${s}/oauth2/token`,revocationEndpoint:`${s}/oauth2/revoke`}}let i=H(t.MCODE_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT),r=H(t.MCODE_OAUTH_TOKEN_ENDPOINT),o=H(t.MCODE_OAUTH_REVOCATION_ENDPOINT);if(!i||!r||!o)throw new TypeError("Shared MCode OAuth requires all three public OAuth endpoints to be configured.");return{deviceAuthorizationEndpoint:i,...se(e.buildEnv),tokenEndpoint:r,revocationEndpoint:o}}function se(t){return t==="staging"?{deviceAuthorizationHeaders:{"X-User-Pre":"1"}}:{}}function H(t){if(t?.trim())try{let e=new URL(t);return e.protocol!=="https:"||e.username||e.password||e.hash?void 0:e.toString()}catch{return}}import{randomUUID as $}from"node:crypto";import{watchFile as Ke,unwatchFile as $e}from"node:fs";var ce=Se(Te(),1);import{open as be}from"node:fs/promises";import{chmod as ae,mkdir as Ie,open as Ce,rename as Oe,unlink as ke}from"node:fs/promises";import{dirname as Pe}from"node:path";async function O(t){await Ie(t,{recursive:!0,mode:448}),process.platform!=="win32"&&await ae(t,448)}async function b(t,e){let n=Pe(t);await O(n);let i=`${t}.${process.pid}.${Date.now()}.tmp`,r=await Ce(i,"wx",384);try{await r.writeFile(e,{encoding:"utf8"}),await r.sync()}finally{await r.close()}try{process.platform!=="win32"&&await ae(i,384),await Oe(i,t)}catch(o){throw await ke(i).catch(()=>{}),o}}import{dirname as xe}from"node:path";var w=class{lockPath;staleMs;retries;constructor(e,n={}){this.lockPath=e,this.staleMs=n.staleMs??3e4,this.retries=n.retries??120}async withLock(e){await O(xe(this.lockPath)),await(await be(this.lockPath,"a",384)).close();let i,r=await ce.default.lock(this.lockPath,{realpath:!1,stale:this.staleMs,retries:{retries:this.retries,factor:1.15,minTimeout:5,maxTimeout:250},onCompromised:o=>{i??=o}});try{return await e()}finally{try{await r()}catch(o){if(!i)throw o}if(i)throw i}}};import{createHash as Re,randomBytes as Ne}from"node:crypto";var Ue="urn:ietf:params:oauth:grant-type:device_code",l=class extends Error{code;httpStatus;constructor(e,n,i){super(n??`The OAuth server rejected the request (${e}${i?`, HTTP ${i}`:""}).`),this.code=e,this.httpStatus=i,this.name="OAuthProtocolError"}},j=class{options;fetchImpl;sleep;now;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.sleep=e.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.now=e.now??Date.now}async startDeviceAuthorization(e={}){let n=Ne(32).toString("base64url"),i=Re("sha256").update(n,"ascii").digest("base64url"),r=await this.postForm(this.options.deviceAuthorizationEndpoint,{client_id:u,scope:c.join(" "),audience:p,code_challenge:i,code_challenge_method:"S256"},{headers:this.options.deviceAuthorizationHeaders,signal:e.signal}),o=d(r,"user_code"),s=d(r,"device_code"),a=R(r,"expired_in"),h=!s&&!!o&&a!==void 0,C=s??(h?o:void 0),B=d(r,"verification_uri")??d(r,"verification_url"),te=R(r,"expires_in")??ze(a,this.now()),V=R(r,"interval"),Ae=h&&V!==void 0?V/1e3:V??5;if(!C||!o||!B||!te)throw new l("invalid_device_authorization_response");return{deviceCode:C,codeVerifier:n,...h?{tokenPollingParameter:"user_code"}:{},userCode:o,verificationUri:B,...d(r,"verification_uri_complete")||h?{verificationUriComplete:d(r,"verification_uri_complete")??B}:{},expiresInSec:te,intervalSec:Ae}}async pollDeviceToken(e,n={}){let i=this.now()+e.expiresInSec*1e3,r=e.intervalSec*1e3;for(;this.now()<i;){n.signal?.throwIfAborted();let o=e.tokenPollingParameter==="user_code"?{user_code:e.userCode}:{device_code:e.deviceCode},s=await this.postFormAllowOAuthError(this.options.tokenEndpoint,{grant_type:Ue,...o,client_id:u,code_verifier:e.codeVerifier},{signal:n.signal}),a=d(s.body,"status");if(s.ok&&a==="pending"){await x(this.sleep,r,n.signal);continue}if(s.ok&&a==="slow_down"){r+=5e3,await x(this.sleep,r,n.signal);continue}if(s.ok&&(a==="denied"||a==="access_denied"))throw new l("access_denied");if(s.ok&&(a==="expired"||a==="expired_token"))throw new l("expired_token");if(s.ok)return de(s.body);if(s.error==="authorization_pending"){await x(this.sleep,r,n.signal);continue}if(s.error==="slow_down"){r+=5e3,await x(this.sleep,r,n.signal);continue}throw new l(s.error??"device_authorization_failed",void 0,s.status)}throw new l("expired_token","The OAuth device authorization expired.")}async refreshToken(e){let n=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:u,scope:c.join(" "),audience:p});return de(n,e)}async revokeToken(e){let n=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:u},{allowEmptySuccess:!0});if(!n.ok)throw new l(n.error??"oauth_request_failed",void 0,n.status)}async postForm(e,n,i={}){let r=await this.postFormAllowOAuthError(e,n,i);if(!r.ok)throw new l(r.error??"oauth_request_failed",void 0,r.status);return r.body}async postFormAllowOAuthError(e,n,i={}){let r=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...i.headers},body:new URLSearchParams(n),signal:i.signal}),o=N(await r.json().catch(()=>{}));if(!o&&r.ok&&i.allowEmptySuccess)return{ok:!0,status:r.status,body:{}};if(!o)throw new l("invalid_json_response",void 0,r.status);let s=d(o,"error");return{ok:r.ok&&!s,status:r.status,body:o,...s?{error:s}:{}}}};async function x(t,e,n){if(!n){await t(e);return}n.throwIfAborted();let i,r=()=>i(n.reason),o=new Promise((s,a)=>{i=a});n.addEventListener("abort",r,{once:!0});try{await Promise.race([t(e),o])}finally{n.removeEventListener("abort",r)}}function de(t,e){let n=d(t,"access_token"),i=d(t,"refresh_token")??e,r=d(t,"token_type"),o=R(t,"expires_in"),s=n?De(n):void 0,a=Le(t.scope??s?.scope??s?.scp);if(!n||!i||r?.toLowerCase()!=="bearer"||!o||!a.includes(c[0]))throw new l("invalid_token_response");return{accessToken:n,refreshToken:i,tokenType:"Bearer",scopes:a,audience:p,expiresInSec:o,...d(s,"sub")?{subject:d(s,"sub")}:{},...d(s,"account_id")?{accountId:d(s,"account_id")}:{}}}function De(t){let e=t.split(".");if(!(e.length!==3||!e[1]))try{return N(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return}}function Le(t){return typeof t=="string"?t.split(/\s+/u).filter(Boolean):Array.isArray(t)&&t.every(e=>typeof e=="string")?t:[]}function N(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function d(t,e){let i=N(t)?.[e];return typeof i=="string"&&i.trim()?i.trim():void 0}function R(t,e){let i=N(t)?.[e];return typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0}function ze(t,e){if(t===void 0)return;if(t<1e12)return t;let n=t-e;return n>0?Math.ceil(n/1e3):void 0}import{readFile as Be}from"node:fs/promises";var E=2,Ve=1,He=/access[_-]?token|refresh[_-]?token|device[_-]?code|code[_-]?verifier/iu;function he(t){if(!(typeof t!="object"||t===null))for(let[e,n]of Object.entries(t)){if(He.test(e))throw new TypeError("Sensitive OAuth fields cannot be persisted in auth-state.json.");he(n)}}function ue(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Invalid OAuth state.");let e=t;if(!(typeof e.schemaVersion=="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=Ve&&e.schemaVersion<=E&&["anonymous","authorizing","authenticated","refreshing","scope_upgrade_required","logging_out","logout_pending","expired","error"].includes(e.status)&&(e.schemaVersion===1&&(e.storeKind==="os-keyring"||e.storeKind==="file")||e.schemaVersion===E&&e.storeKind==="file")&&e.clientId==="mcode-public"&&Array.isArray(e.scopes)&&e.scopes.every(i=>typeof i=="string")&&e.audience==="agent-backend"&&je(e.buildEnv,e.region)&&(e.expiresAtMs===void 0||typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs))&&Number.isSafeInteger(e.generation)&&e.generation>=0&&(e.authorization===void 0||Fe(e.authorization))))throw new TypeError("Invalid OAuth state.");return he(e),e}function je(t,e){return t===void 0&&e===void 0?!0:(t==="dev"||t==="test"||t==="staging"||t==="prod")&&(e==="cn"||e==="en")}function Fe(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return typeof e.leaseId=="string"&&e.leaseId.length>0&&typeof e.leaseExpiresAtMs=="number"&&Number.isFinite(e.leaseExpiresAtMs)&&F(e.userCode)&&F(e.verificationUri)&&F(e.verificationUriComplete)}function F(t){return t===void 0||typeof t=="string"}var y=class{path;constructor(e){this.path=e}async read(){let e;try{e=await Be(this.path,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{return ue(JSON.parse(e))}catch(n){throw n instanceof TypeError?n:new TypeError("Invalid OAuth state.")}}async write(e){let n=ue(e);await b(this.path,`${JSON.stringify(n,null,2)}
3
3
  `)}};var qe=600*1e3,Ge=250,f=class extends Error{code="AUTH_REQUIRED";constructor(e){super("MCode authentication is required.",e),this.name="AuthRequiredError"}},T=class extends Error{code="AUTH_LOGIN_CANCELLED";constructor(){super("MCode OAuth device authorization was cancelled."),this.name="AuthLoginCancelledError"}},U=class extends Error{code="AUTH_SESSION_CHANGED";constructor(){super("The login changed while this request was in progress."),this.name="AuthSessionChangedError"}};function Je(t,e){if(!t||t!==e)throw new U}var M=class extends Error{missingScopes;code="AUTH_SCOPE_UPGRADE_REQUIRED";constructor(e){super("The current MCode authorization does not include the required scope."),this.missingScopes=e,this.name="AuthScopeUpgradeRequiredError"}},I=class extends Error{code="AUTH_RESOURCE_CONTRACT_MISMATCH";constructor(){super("The stored credential does not match the MCode resource contract."),this.name="AuthResourceContractMismatchError"}};function le(t){return t instanceof f||t instanceof M||t instanceof I}var q=class extends Error{active;requested;code="AUTH_DOMAIN_CONFLICT";constructor(e,n){super(`MCode is signed in to ${e.buildEnv}/${e.region}; sign out before using ${n.buildEnv}/${n.region}.`),this.active=e,this.requested=n,this.name="AuthDomainConflictError"}},G=class{options;stateStore;lock;now;sleep;authorizationLeaseMs;statePollIntervalMs;createLeaseId;loginPromise;loginAbortController;initializePromise;constructor(e){this.options=e,this.stateStore=new y(e.namespace.statePath),this.lock=new w(e.namespace.lockPath),this.now=e.now??Date.now,this.sleep=e.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.authorizationLeaseMs=e.authorizationLeaseMs??qe,this.statePollIntervalMs=e.statePollIntervalMs??Ge,this.createLeaseId=e.createLeaseId??$}async getStatus(){await this.initialize();let e=await this.stateStore.read();if(!e)return{status:"anonymous",generation:0,scopes:[]};if(e.status==="authorizing"||e.status==="refreshing"){let n=await this.recoverInterruptedCredentialCommit(e);return _(n)}if(e.status==="authenticated"||e.status==="expired"){let n=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!n||n.generation!==e.generation)return _({...e,status:"error"});try{S(n,[...c])}catch(r){if(r instanceof M)return _({...k(n,this.options.credentialStore.kind,this.options.namespace),status:"scope_upgrade_required"});if(r instanceof I)return _({...e,status:"error"});throw r}let i=k(n,this.options.credentialStore.kind,this.options.namespace);return e.status==="expired"||n.expiresAtMs<=this.now()?_({...i,status:"expired"}):_(i)}return _(e)}login(e={}){if(!this.loginPromise){let n=new AbortController,i=this.initialize().then(()=>this.runLogin(e,n.signal)).finally(()=>{this.loginPromise===i&&(this.loginPromise=void 0,this.loginAbortController=void 0)});this.loginAbortController=n,this.loginPromise=i}return this.loginPromise}async cancelLogin(){let e=this.loginAbortController,n=this.loginPromise;if(!(!e||!n)){e.abort();try{await n}catch(i){if(!(i instanceof T))throw i}}}async getAccessToken(e){await this.initialize(),Ye(e.requiredScopes);try{let n=await this.readUsableCredential(e.requiredScopes);if(this.satisfiesMinValidity(n,e.minValidityMs))return K(n.credential)}catch(n){if(!(n instanceof f))throw n}return this.lock.withLock(async()=>{let n=await this.readUsableCredential(e.requiredScopes);return this.satisfiesMinValidity(n,e.minValidityMs)?K(n.credential):this.refreshCredential(n)})}satisfiesMinValidity(e,n){if(e.state.status!=="authenticated")return!1;let i=e.credential.expiresAtMs-this.now();return i>0&&i>=n}async handleUnauthorized(e){await this.initialize();try{return await this.lock.withLock(async()=>{let n=await this.readUsableCredential([...c]);if(e.loginEpoch!==void 0)Je(e.loginEpoch,n.credential.loginEpoch);else if(n.credential.generation>e.generation)throw new U;return n.credential.generation>e.generation?"retry":n.credential.generation<e.generation?"logout":(await this.refreshCredential(n,{rejected:!0}),"retry")})}catch(n){if(le(n))return"logout";throw n}}async logout(e){return await this.initialize(),this.lock.withLock(async()=>{let n=await this.stateStore.read(),i=await this.options.credentialStore.get(this.options.namespace.credentialKey),r=Math.max(n?.generation??0,i?.generation??0);if(!i&&(!n||n.status==="anonymous"))return{status:"anonymous",generation:r};let o=r+1;if(await this.stateStore.write(A({status:"logging_out",generation:o,storeKind:this.options.credentialStore.kind},this.options.namespace)),e.revoke&&i)try{await this.options.oauthClient.revokeToken(i.refreshToken)}catch{return await this.stateStore.write(A({status:"logout_pending",generation:o,storeKind:this.options.credentialStore.kind},this.options.namespace)),{status:"logout_pending",generation:o}}return await this.options.credentialStore.delete(this.options.namespace.credentialKey),await this.stateStore.write(A({status:"anonymous",generation:o,storeKind:this.options.credentialStore.kind},this.options.namespace)),{status:"anonymous",generation:o}})}watch(e){let n=()=>{this.getStatus().then(e).catch(()=>{})};return Ke(this.options.namespace.statePath,{interval:this.statePollIntervalMs},n),()=>$e(this.options.namespace.statePath,n)}initialize(){return this.initializePromise??=(async()=>{await this.options.initialize?.(),await this.options.credentialStore.healthCheck()})().catch(e=>{throw this.initializePromise=void 0,e}),this.initializePromise}async runLogin(e,n){for(;;){v(n);let i=this.createLeaseId(),r=await this.lock.withLock(async()=>{let o=await this.stateStore.read();Xe(o,this.options.namespace);let s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(o&&s&&o.generation===s.generation&&(o.status==="authenticated"||o.status==="expired"||o.status==="refreshing"))try{return S(s,[...c]),o.status==="authenticated"&&s.expiresAtMs>this.now()?{kind:"authenticated",generation:s.generation}:{kind:"refresh",generation:s.generation}}catch(h){if(!(h instanceof M)&&!(h instanceof I))throw h}if(o?.status==="authorizing"&&o.authorization&&o.authorization.leaseExpiresAtMs>this.now())return{kind:"wait",leaseExpiresAtMs:o.authorization.leaseExpiresAtMs};let a=Math.max(o?.generation??0,s?.generation??0);return await this.stateStore.write({...A({status:"authorizing",generation:a,storeKind:this.options.credentialStore.kind},this.options.namespace),authorization:{leaseId:i,leaseExpiresAtMs:this.now()+this.authorizationLeaseMs}}),{kind:"owner"}});if(r.kind==="authenticated")return{status:"authenticated",generation:r.generation};if(r.kind==="refresh"){try{await this.lock.withLock(async()=>{let s=await this.readUsableCredential([...c]);s.credential.generation>r.generation&&this.satisfiesMinValidity(s,1)||await this.refreshCredential(s)})}catch(s){if(le(s))continue;throw s}let o=await this.stateStore.read();if(o?.status==="authenticated")return{status:"authenticated",generation:o.generation};continue}if(r.kind==="wait"){let o=await this.waitForAuthorization(r.leaseExpiresAtMs,e.onDeviceAuthorization,n);if(o)return o;continue}try{let o=await this.options.oauthClient.startDeviceAuthorization({signal:n});await this.publishAuthorizationProgress(i,o),e.onDeviceAuthorization?.(Qe(o));let s=await this.options.oauthClient.pollDeviceToken(o,{signal:n});return await this.commitLogin(i,s,n)}catch(o){let s=n.aborted;throw await this.releaseAuthorizationLease(i,s?"anonymous":"error"),s?new T:o}}}async commitLogin(e,n,i){return this.lock.withLock(async()=>{v(i);let r=await this.stateStore.read();if(r?.status!=="authorizing"||r.authorization?.leaseId!==e)throw new f;let o=await this.options.credentialStore.get(this.options.namespace.credentialKey);v(i);let s=Math.max(r.generation,o?.generation??0)+1,a=pe(n,s,this.now(),$());await this.options.credentialStore.put(this.options.namespace.credentialKey,a);try{v(i),await this.stateStore.write(k(a,this.options.credentialStore.kind,this.options.namespace)),v(i)}catch(h){throw h instanceof T&&(await this.stateStore.write(r),o?await this.options.credentialStore.put(this.options.namespace.credentialKey,o):await this.options.credentialStore.delete(this.options.namespace.credentialKey)),h}return{status:"authenticated",generation:s}})}async waitForAuthorization(e,n,i){let r=!1;for(;this.now()<e;){v(i);let o=await this.stateStore.read();if(!r&&o?.status==="authorizing"&&o.authorization?.userCode&&o.authorization.verificationUri&&(n?.({userCode:o.authorization.userCode,verificationUri:o.authorization.verificationUri,...o.authorization.verificationUriComplete?{verificationUriComplete:o.authorization.verificationUriComplete}:{},expiresInSec:Math.max(1,Math.ceil((o.authorization.leaseExpiresAtMs-this.now())/1e3))}),r=!0),o?.status==="authenticated"){let s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(s&&s.generation===o.generation)return S(s,[...c]),{status:"authenticated",generation:o.generation}}if(o?.status!=="authorizing")return;await Ze(this.sleep,this.statePollIntervalMs,i)}}async publishAuthorizationProgress(e,n){await this.lock.withLock(async()=>{let i=await this.stateStore.read();if(i?.status!=="authorizing"||i.authorization?.leaseId!==e)throw new f;await this.stateStore.write({...i,authorization:{...i.authorization,userCode:n.userCode,verificationUri:n.verificationUri,...n.verificationUriComplete?{verificationUriComplete:n.verificationUriComplete}:{}}})})}async releaseAuthorizationLease(e,n){await this.lock.withLock(async()=>{let i=await this.stateStore.read();i?.status!=="authorizing"||i.authorization?.leaseId!==e||await this.stateStore.write(A({status:n,generation:i.generation,storeKind:this.options.credentialStore.kind},this.options.namespace))})}async recoverInterruptedCredentialCommit(e){let n=await this.options.credentialStore.get(this.options.namespace.credentialKey);return!n||n.generation<=e.generation?e:(S(n,[...c]),this.lock.withLock(async()=>{let i=await this.stateStore.read(),r=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!i||!r||i.status!=="authorizing"&&i.status!=="refreshing"||r.generation<=i.generation)return i??e;S(r,[...c]);let o=k(r,this.options.credentialStore.kind,this.options.namespace);return await this.stateStore.write(o),o}))}async readUsableCredential(e){let n=await this.stateStore.read();if(!n||n.status!=="authenticated"&&n.status!=="expired"&&n.status!=="refreshing")throw new f;let i=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!i||n.generation!==i.generation)throw new f;return S(i,e),{state:n,credential:i}}async refreshCredential(e,n={}){await this.stateStore.write({...e.state,status:"refreshing"});let i;try{i=await this.options.oauthClient.refreshToken(e.credential.refreshToken)}catch(o){if(We(o))throw await this.stateStore.write(A({status:"anonymous",generation:e.credential.generation+1,storeKind:this.options.credentialStore.kind},this.options.namespace)),await this.options.credentialStore.delete(this.options.namespace.credentialKey),new f({cause:o});{let s=!n.rejected&&e.state.status==="authenticated"&&e.credential.expiresAtMs>this.now();await this.stateStore.write({...e.state,status:s?"authenticated":"expired"})}throw o}let r=pe(i,Math.max(e.state.generation,e.credential.generation)+1,this.now(),e.credential.loginEpoch);return await this.options.credentialStore.put(this.options.namespace.credentialKey,r),await this.stateStore.write(k(r,this.options.credentialStore.kind,this.options.namespace)),K(r)}};function v(t){if(t?.aborted)throw new T}function We(t){return t instanceof l&&t.code==="invalid_grant"&&t.httpStatus===400}async function Ze(t,e,n){if(!n){await t(e);return}v(n);let i,r=()=>i(new T),o=new Promise((s,a)=>{i=a});n.addEventListener("abort",r,{once:!0});try{await Promise.race([t(e),o])}finally{n.removeEventListener("abort",r)}}function Qe(t){return{userCode:t.userCode,verificationUri:t.verificationUri,...t.verificationUriComplete?{verificationUriComplete:t.verificationUriComplete}:{},expiresInSec:t.expiresInSec}}function A(t,e){return{schemaVersion:E,status:t.status,storeKind:t.storeKind,clientId:u,scopes:[...c],audience:p,buildEnv:e.buildEnv,region:e.region,generation:t.generation}}function k(t,e,n){return{...A({status:"authenticated",generation:t.generation,storeKind:e},n),scopes:t.scopes,expiresAtMs:t.expiresAtMs}}function pe(t,e,n,i=$()){let r={schemaVersion:1,accessToken:t.accessToken,refreshToken:t.refreshToken,tokenType:t.tokenType,clientId:u,scopes:t.scopes,audience:p,expiresAtMs:n+t.expiresInSec*1e3,generation:e,loginEpoch:i,...t.subject?{subject:t.subject}:{},...t.accountId?{accountId:t.accountId}:{}};if(S(r,[...c]),t.audience!==p)throw new I;return r}function Ye(t){let e=t.filter(n=>!c.includes(n));if(e.length>0)throw new M(e)}function S(t,e){if(t.clientId!==u||t.audience!==p||t.tokenType!=="Bearer")throw new I;let n=e.filter(i=>!t.scopes.includes(i));if(n.length>0)throw new M(n)}function _(t){return{status:t.status,generation:t.generation,scopes:t.scopes,...t.buildEnv===void 0?{}:{buildEnv:t.buildEnv},...t.region===void 0?{}:{region:t.region},...t.expiresAtMs===void 0?{}:{expiresAtMs:t.expiresAtMs}}}function Xe(t,e){if(!(!t||t.status==="anonymous"||t.buildEnv===void 0||t.region===void 0||t.buildEnv===e.buildEnv&&t.region===e.region))throw new q({buildEnv:t.buildEnv,region:t.region},{buildEnv:e.buildEnv,region:e.region})}function K(t){return{accessToken:t.accessToken,...t.loginEpoch?{loginEpoch:t.loginEpoch}:{},expiresAtMs:t.expiresAtMs,generation:t.generation,scopes:c,audience:p}}import{createHash as et}from"node:crypto";import{join as g,resolve as tt}from"node:path";function J(t){let e=g(tt(t.dataDir),"auth"),n=g(e,t.buildEnv,t.region,u),i=`com.minimax.mcode.oauth.${t.buildEnv}.${t.region}`,r=et("sha256").update(`${e}\0${u}`).digest("base64url");return{authHome:e,namespaceHome:n,lockPath:g(n,"auth.lock"),statePath:g(n,"auth-state.json"),credentialPath:g(n,"auth.json"),legacyLockPath:g(e,"auth.lock"),legacyStatePath:g(e,"auth-state.json"),legacyEncryptedCredentialPath:g(e,"credentials.enc"),buildEnv:t.buildEnv,region:t.region,credentialKey:{service:i,account:r}}}async function nt(t){let e=await it(t),n=new y(t.statePath);await new w(t.lockPath).withLock(async()=>{let r=await n.read();if(r?.schemaVersion===E)return;let o=r??e;o&&await n.write(ot(o,t))})}async function it(t){let e=new y(t.legacyStatePath);return new w(t.legacyLockPath).withLock(async()=>{let i=await e.read();if(!rt(i,t))return null;let{authorization:r,...o}=i;return await e.write({...o,status:"error"}),i})}function rt(t,e){return t!==null&&t.status!=="error"&&t.buildEnv===e.buildEnv&&t.region===e.region}function ot(t,e){return{schemaVersion:E,status:"anonymous",storeKind:"file",clientId:"mcode-public",scopes:["agent.default"],audience:"agent-backend",buildEnv:e.buildEnv,region:e.region,generation:t.generation+1}}import{readFile as ct,stat as fe}from"node:fs/promises";import{join as dt}from"node:path";var st=1,at=1,m=class extends Error{code="CREDENTIAL_RECORD_CORRUPT";constructor(){super("The stored OAuth credential record is invalid."),this.name="CredentialRecordCorruptError"}},D=class extends Error{code="AUTH_CREDENTIAL_STORE_PERMISSION";constructor(){super("The OAuth credential file permissions are not private."),this.name="CredentialStorePermissionError"}};function W(t){return t===void 0||typeof t=="string"}function Z(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new m;let e=t,n=e.scopes,i=Array.isArray(n)&&n.every(o=>typeof o=="string");if(!(typeof e.schemaVersion=="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=at&&e.schemaVersion<=st&&typeof e.accessToken=="string"&&e.accessToken.length>0&&typeof e.refreshToken=="string"&&e.refreshToken.length>0&&e.tokenType==="Bearer"&&e.clientId===u&&i&&e.audience===p&&typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs)&&Number.isSafeInteger(e.generation)&&e.generation>=0&&W(e.subject)&&W(e.accountId)&&W(e.loginEpoch)))throw new m;return e}var Y=1;function Q(t){return`${t.service}\0${t.account}`}function me(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new m;let e=t;if(e.schemaVersion!==Y||typeof e.records!="object"||e.records===null||Array.isArray(e.records))throw new m;let n=Object.fromEntries(Object.entries(e.records).map(([i,r])=>[i,Z(r)]));return{schemaVersion:Y,records:n}}var L=class{kind="file";authHome;path;constructor(e){this.authHome=e.authHome,this.path=dt(e.authHome,"auth.json")}async get(e){return(await this.readPayload()).records[Q(e)]??null}async put(e,n){let i=await this.readPayload();i.records[Q(e)]=Z(n),await this.writePayload(i)}async delete(e){let n=await this.readPayload();delete n.records[Q(e)],await this.writePayload(n)}async healthCheck(){await O(this.authHome),await this.assertPrivatePermissions()}async readPayload(){let e;try{await this.assertPrivatePermissions(),e=await ct(this.path,"utf8")}catch(n){if(n.code==="ENOENT")return{schemaVersion:Y,records:{}};throw n}try{return me(JSON.parse(e))}catch(n){throw n instanceof m?n:new m}}async assertPrivatePermissions(){if(process.platform!=="win32")try{let[e,n]=await Promise.all([fe(this.authHome),fe(this.path)]);if((e.mode&63)!==0||(n.mode&63)!==0)throw new D}catch(e){if(e.code==="ENOENT")return;throw e}}async writePayload(e){let n=me(e);await b(this.path,`${JSON.stringify(n,null,2)}
4
4
  `)}};function ut(t){return new L(t)}var X;function ge(t){X=t}function ht(t={}){let e=t.embeddedBuildEnvironment??we(),n=t.embeddedBuildVariant??lt(),i=t.runtimeBuildEnv??ne();return oe({buildEnv:e??pt(i),internalBuild:n==="internal"})}function z(t={}){let e=ht(t);return{region:t.runtimeRegion??"cn",buildEnv:X??e.buildEnv??"test"}}function zn(t=we()){return X??t??"dev"}function we(){return"prod"}function lt(){return"standard"}function pt(t){return t==="dev"?"test":t}import gt from"node:fs";import P from"node:fs";import Ee from"node:path";var ye="preferences",ft="mcode-region.json";function _e(t,e){try{let n=JSON.parse(P.readFileSync(ve(t),"utf8"));if(n.version!==1||!n.regions||typeof n.regions!="object")return;let i=n.regions[e];return i==="cn"||i==="en"?i:void 0}catch{return}}function jn(t,e){let n=Ee.join(t,ye);P.mkdirSync(n,{recursive:!0,mode:448});let i=ve(t),o={version:1,regions:{...mt(i),[e.buildEnv]:e.region},updatedAtMs:Date.now()},s=`${i}.${process.pid}.${Date.now()}.tmp`;return P.writeFileSync(s,`${JSON.stringify(o,null,2)}
5
5
  `,{encoding:"utf8",mode:384}),P.renameSync(s,i),i}function ve(t){return Ee.join(t,ye,ft)}function mt(t){try{let e=JSON.parse(P.readFileSync(t,"utf8"));return e.version!==1||!e.regions||typeof e.regions!="object"?{}:Object.fromEntries(Object.entries(e.regions).filter(([n,i])=>(n==="dev"||n==="test"||n==="staging"||n==="prod")&&(i==="cn"||i==="en")))}catch{return{}}}var wt=/^[A-Za-z0-9._-]+$/u,ee="--env",Et=new Set(["--lane","--resume","--tui-mode","-m","--model","--system-prompt","--system-prompt-file","--append-system-prompt","--append-system-prompt-file"]),yt=Object.freeze({test:"test",pre:"staging",staging:"staging",prod:"prod"});function Wn(t={}){ie(!1),re(!1);let{target:e=process.env,dataDir:n,startupBuildEnvironment:i,...r}=t;i&&ge(i);let o=z(r),s=n?_e(n,o.buildEnv):void 0,a=n?vt(n,o.buildEnv):void 0,h=St(e.MAVIS_REGION),C=z({...r,runtimeRegion:r.runtimeRegion??h??s??a?.region??"cn"});return n&&(e.MINIMAX_DATA_DIR=n,e.MAVIS_DATA_DIR=n),e.MAVIS_REGION=C.region,e.MAVIS_BUILD_ENV=C.buildEnv,e.__MAVIS_RUNTIME_MANAGED="1",C}function _t(t){let e=yt[t.trim()];if(!e)throw new Error("--env must be test, staging, pre, or prod.");return e}function Zn(t,e){let n=[];for(let i=0;i<t.length;i+=1){let r=t[i];if(r!==void 0){if(r==="--")break;if(r===ee){let o=t[i+1];if(!o||o.startsWith("-"))throw new Error("--env requires a value.");n.push(o),i+=1;continue}if(r.startsWith(`${ee}=`)){n.push(r.slice(ee.length+1));continue}if(Et.has(r)){i+=1;continue}if(r==="--session"&&t[i+1]&&!t[i+1]?.startsWith("-")){i+=1;continue}if(!r.startsWith("-"))break}}if(n.length!==0){if(!e)throw new Error("--env is only available in the internal MCode package.");if(n.length>1)throw new Error("--env may only be specified once.");return _t(n[0]??"")}}function Qn(t,e=z().buildEnv){if(t===void 0)return;if(e!=="test"&&e!=="staging")throw new Error("--lane is only supported in test or staging builds.");let n=t.trim();if(!wt.test(n))throw new Error("--lane only accepts letters, numbers, dot, underscore, and hyphen.");return n}function vt(t,e){let n=["cn","en"].filter(r=>{try{let o=J({dataDir:t,buildEnv:e,region:r}),s=JSON.parse(gt.readFileSync(o.statePath,"utf8"));return s.buildEnv===e&&s.region===r&&At(s.status)}catch{return!1}}),i=n.length===1?n[0]:void 0;return i?{buildEnv:e,region:i}:void 0}function At(t){return t==="authorizing"||t==="authenticated"||t==="refreshing"||t==="scope_upgrade_required"||t==="expired"}function St(t){return t==="cn"||t==="en"?t:void 0}export{c as a,J as b,nt as c,j as d,Mt as e,U as f,le as g,G as h,ut as i,ht as j,z as k,zn as l,jn as m,Wn as n,_t as o,Zn as p,Qn as q};