@minimax-ai/code 0.6.8 → 0.6.10

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 (33) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/CHANGELOG.zh-CN.md +22 -0
  3. package/README.md +88 -20
  4. package/README.zh-CN.md +24 -9
  5. package/assets/agents/_default/prompt-base-windows.md +0 -1
  6. package/assets/agents/_default/prompt-base-windows.md.hbs +0 -1
  7. package/assets/agents/mavis/skills/control-in-app-browser/SKILL.md +66 -1
  8. package/chunks/{auth-command-VRPOVPAG.js → auth-command-YIBIYLYL.js} +1 -1
  9. package/chunks/chunk-2BNOPHYG.js +9 -0
  10. package/chunks/{chunk-TJWBPT2F.js → chunk-2LP3AAE5.js} +1 -1
  11. package/chunks/chunk-52LBQEEC.js +2 -0
  12. package/chunks/{chunk-G7Q4HUMC.js → chunk-5JU6ZMXS.js} +1 -1
  13. package/chunks/{chunk-TBUCWZJV.js → chunk-72PMKZ7Y.js} +1 -1
  14. package/chunks/{chunk-RCKQIK7B.js → chunk-CRTW4JM6.js} +1 -1
  15. package/chunks/{chunk-HTUJPI64.js → chunk-F5767MLW.js} +1030 -715
  16. package/chunks/{chunk-3LM4G7WV.js → chunk-FPCUX6KP.js} +1 -1
  17. package/chunks/{chunk-VRCVX3OX.js → chunk-G7FSWJID.js} +58 -58
  18. package/chunks/{chunk-W2YPWDHA.js → chunk-GZAO7QYD.js} +684 -682
  19. package/chunks/{chunk-WROGTDVD.js → chunk-MESLFKP6.js} +1 -1
  20. package/chunks/{chunk-F5BJTVSP.js → chunk-UQ2YIDWV.js} +1 -1
  21. package/chunks/{data-dir-5RSS75A3.js → data-dir-AVW455BT.js} +1 -1
  22. package/chunks/{dist-VUHPFVW3.js → dist-B52TV5OC.js} +1 -1
  23. package/chunks/{launcher-UXZG5P2R.js → launcher-AFCZTEJU.js} +147 -146
  24. package/chunks/{lifecycle-LWEBNCGO.js → lifecycle-RBCNKJ7Z.js} +1 -1
  25. package/chunks/{main-ZF4GAXGG.js → main-SSCI3MRX.js} +2 -2
  26. package/chunks/{plugin-command-DE7EI72Q.js → plugin-command-ZQV7YMWK.js} +1 -1
  27. package/chunks/{provider-command-WEUFNCBJ.js → provider-command-UMQZDUGQ.js} +1 -1
  28. package/chunks/{run-acp-command-RJGV3PNR.js → run-acp-command-YUXNSZ3D.js} +2 -2
  29. package/chunks/{run-exec-command-LDQWWWXK.js → run-exec-command-HAIRHPYT.js} +13 -13
  30. package/cli.js +2 -2
  31. package/package.json +1 -1
  32. package/chunks/chunk-CF3YFDG4.js +0 -2
  33. package/chunks/chunk-K7X2ELVZ.js +0 -9
package/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ 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.10 · 2026-10-13
11
+
12
+ ### Added
13
+
14
+ - 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.
15
+
16
+ ## 0.6.9 · 2026-10-12
17
+
18
+ ### Added
19
+
20
+ - `config.yaml` adds `permission.nativeDelete`, which defaults to `false`. When set to `true`, new Bash calls use the current shell's native delete commands instead of moving files to the trash, so deleted files may not be recoverable. Normal permission modes, sandboxing, root/home recursive-delete protection and network-share blocking remain active; Windows delete commands whose targets cannot be resolved statically are still rejected.
21
+
22
+ ### Improved
23
+
24
+ - The default tool-discovery budget for stdio MCP servers rises from 15 to 30 seconds, so servers that install dependencies on first launch (such as `npx` or `uvx`) are more likely to provide tools in the current turn. The effective budget is still the smaller of this default and the server `timeout` in `mcp.json`; HTTP/SSE discovery stays at 2 seconds and tool-call timeouts are unchanged. A failing stdio server can delay a turn by up to 30 seconds.
25
+
26
+ ### Fixed
27
+
28
+ - A turn no longer ends silently when the model uses the whole output limit while thinking, before producing any text. The cut-off response is discarded (an unfinished tool call in it does not run) and the request is retried with a hint to reason more briefly, up to 3 times; if it still does not finish, a dedicated error message is shown.
29
+ - Images that cannot be decoded (corrupt, truncated, or unsupported) no longer enter the conversation history, fixing a single bad image causing every later request to fail with 400 (2013). Such images in tool results are replaced by a note with their type and size; attached ones keep only their file path.
30
+ - The `agents` / `background` counts in the `tui.statusLine: [build-mode]` status line now follow notification receipts persisted by the Runtime: finished background tasks and sub-agents still count until their results are handed back to the agent, then drop to zero. The counts no longer get stuck or reach zero early because of event ordering or process restarts.
31
+
10
32
  ## 0.6.8 · 2026-10-11
11
33
 
12
34
  ### Added
@@ -8,6 +8,28 @@ TUI 正式版中用户能直接感知的重要变化。收录范围以 TUI 用
8
8
 
9
9
  仅内部重构、测试调整,或只影响其他产品界面且不改变 TUI 行为的变化不记录。
10
10
 
11
+ ## 0.6.10 · 2026-10-13
12
+
13
+ ### 新增功能
14
+
15
+ - Browser Use 新增 `run_script` 动作,用于单步动作无法表达的页面验证:按住按键移动、修饰键加鼠标组合、定时或重复输入,以及先读取页面状态再决定点击位置。脚本直接操作当前标签页和登录状态,不需要另起浏览器或安装额外工具;脚本结束、出错、超时或被取消时,仍按住的键和鼠标键会自动松开。结果包含返回值、日志、失败行号和截图。仅 TUI 的 Headless Browser 提供。
16
+
17
+ ## 0.6.9 · 2026-10-12
18
+
19
+ ### 新增功能
20
+
21
+ - `config.yaml` 新增 `permission.nativeDelete`,默认 `false`。设为 `true` 后,新的 Bash 调用使用当前 shell 的原生删除命令,不再改写为移入回收站,删除的文件可能无法恢复。普通权限模式、沙箱、root/home 递归删除保护和网络共享拦截继续生效;无法静态确定目标的 Windows 删除命令仍会被拒绝。
22
+
23
+ ### 体验改进
24
+
25
+ - stdio MCP Server 的工具发现默认时限从 15 秒提高到 30 秒,首次启动需要安装依赖的 Server(如 `npx`、`uvx`)更容易在本轮拿到工具。实际时限仍取该默认值与 `mcp.json` 中 Server `timeout` 的较小值;HTTP/SSE 仍为 2 秒,工具调用超时不变。故障的 stdio Server 最多可能让一轮等待 30 秒。
26
+
27
+ ### 问题修复
28
+
29
+ - 模型思考用完单次输出上限、没有输出任何文字时,本轮不再静默结束。被截断的回复会被丢弃(其中未写完的工具调用不会执行),并提示模型缩短思考后自动重试,最多 3 次;仍未完成时显示专门的错误说明。
30
+ - 无法解码的图片(损坏、截断或格式不支持)不再进入对话历史,修复一张坏图导致之后每轮请求都返回 400(2013)的问题。工具结果中的这类图片替换为写明类型和大小的说明,附加的这类图片只保留文件路径。
31
+ - `tui.statusLine: [build-mode]` 状态栏的 `agents` / `background` 计数改为以 Runtime 持久记录的通知回执为准:已结束但结果尚未交回 Agent 的后台任务和子 Agent 继续计入,结果交回后归零。计数不再因事件顺序、进程重启而卡住或提前归零。
32
+
11
33
  ## 0.6.8 · 2026-10-11
12
34
 
13
35
  ### 新增功能
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,18 +267,42 @@ 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
272
274
  image, so an image within the limits is sent unchanged and a scaled-down one carries a single note.
273
275
  A screenshot taken after a browser action stays within 1280 px and 1 MiB, or these limits when
274
276
  smaller. If the image processor cannot load, a tool result image over the limits is replaced with a
275
- note saying so.
277
+ note saying so. An image it cannot decode (corrupt, truncated or in an unsupported format) never
278
+ enters the conversation, because every later request would carry it and fail: a tool result image is
279
+ replaced with a note giving its type and size, and an attached one is not sent inline and keeps only
280
+ its file path.
276
281
 
277
282
  Deterministic provider rejections, such as an image count, size or dimension limit, a 413 reported
278
- in the error, or an HTTP 400 `invalid_request_error`, are not retried; size and image rejections go
279
- 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。
280
306
 
281
307
  ### Browser operations
282
308
 
@@ -350,6 +376,48 @@ CPU rendering can verify visuals and interactions, but is unsuitable for measuri
350
376
  It does not additionally disable Chrome's process sandbox. An image that already includes a
351
377
  SwiftShader-capable Chrome needs neither an image change nor a separate renderer installation.
352
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
+
403
+ ### MCP cold-start discovery budget
404
+
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 的变更。
420
+
353
421
  ### ACP clients
354
422
 
355
423
  Start the Agent Client Protocol server over stdin/stdout:
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
- 这是唯一一次缩放:Read 工具、附加的图片和 Browser 截图都交出原图,在上限内的图片原样发送,被缩小的图片只带一条说明。Browser 操作后自动截取的截图不超过 1280 px 和 1 MiB,上面的上限更小时以其为准。图片处理组件无法加载时,超过上限的工具结果图片会替换为一条说明。
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,22 @@ 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
+
473
+ ### MCP 冷启动发现预算
474
+
475
+ stdio MCP 在 turn 工具发现阶段的默认总预算为 30,000 ms,为首次启动需要安装依赖的 Server
476
+ 预留更多时间。预算包括连接准备、进程启动、initialize 和 tools/list;实际预算仍为该默认值与
477
+ 单个 Server 的 `mcp.json` `timeout` 的较小值(毫秒,Server 默认 120,000)。
478
+ 远程 HTTP/SSE 的发现预算仍为 2,000 ms,工具调用超时及发现失败时返回空列表的既有行为不变。
479
+ 故障 stdio Server 因此最多可能使 turn 等待 30 秒。需使用包含此改动的构建,无需新增环境变量。
480
+
466
481
  ### ACP 客户端
467
482
 
468
483
  通过 stdin/stdout 启动 Agent Client Protocol 服务:
@@ -3,4 +3,3 @@
3
3
  - Use the shell identified by the current Bash tool and follow its syntax and encoding guidance.
4
4
  - The tool already launches the selected shell. Use non-interactive CLI flags and avoid redundant `powershell -Command` or `cmd /c` wrappers.
5
5
  - Prefer dedicated `read`, `write`, `edit`, `grep`, and `glob` tools. For unavoidable shell file I/O, follow the selected shell's UTF-8 guidance; PowerShell 5.1 `-Encoding UTF8` writes a BOM. Avoid `Get-Content | ... | Set-Content` editing pipelines.
6
- - Recoverable deletion uses one top-level `rm -- "<target1>" "<target2>"`; Runtime routes it through the trusted launcher. If it fails, report the failure. Never bypass it with permanent deletion or another script. Permission checks still apply.
@@ -3,4 +3,3 @@
3
3
  - Use the shell identified by the current Bash tool and follow its syntax and encoding guidance.
4
4
  - The tool already launches the selected shell. Use non-interactive CLI flags and avoid redundant `powershell -Command` or `cmd /c` wrappers.
5
5
  - Prefer dedicated `read`, `write`, `edit`, `grep`, and `glob` tools. For unavoidable shell file I/O, follow the selected shell's UTF-8 guidance; PowerShell 5.1 `-Encoding UTF8` writes a BOM. Avoid `Get-Content | ... | Set-Content` editing pipelines.
6
- - Recoverable deletion uses one top-level `rm -- "<target1>" "<target2>"`; Runtime routes it through the trusted launcher. If it fails, report the failure. Never bypass it with permanent deletion or another script. Permission checks still apply.
@@ -454,6 +454,68 @@ read, stat, `test`, `ls`, or another filesystem tool; call `upload_files` direct
454
454
  returned recovery guidance; do not fall back to shell, standalone Playwright, AppleScript, or
455
455
  Computer Use.
456
456
 
457
+ ## Scripted Input With run_script
458
+
459
+ Use `run_script` only when the active provider advertises it and single-step actions cannot
460
+ express the check: holding keys (game movement), modifier plus mouse combinations, timed or repeated
461
+ input, or a loop that reads page state before choosing where to act. Ordinary forms, links and
462
+ one-off key presses stay on the single-step actions.
463
+
464
+ The input is an async function body, either inline `code` or a saved active-workspace `.js` `path`
465
+ (exactly one), with an optional `timeout` (1000-120000 ms, default 30000). The script body runs in an
466
+ isolated worker with no Node.js APIs, filesystem, network or `require`; `page.evaluate` runs inside
467
+ the page with that page's full capabilities, including `fetch` with its cookies. In scope:
468
+
469
+ - `page.keyboard.down/up/press/type` and `page.mouse.move/down/up/click/wheel`: real input to the
470
+ page. Keys accept `KeyW`, `ArrowUp`, `Shift`, `Enter` style names; clicks made while a modifier is
471
+ held carry that modifier. Coordinates are main-Frame viewport CSS pixels. The pointer position
472
+ does not carry over between actions: call `page.mouse.move` or `page.mouse.click` before
473
+ `mouse.down`/`mouse.up`/`mouse.wheel` in every script.
474
+ - `page.waitForTimeout(ms)`, `page.waitForFunction(fn, arg, { timeout, polling })`.
475
+ - `page.evaluate(fn, arg)`: page JavaScript returning a JSON value.
476
+ - `page.screenshot({ label })`, `page.consoleMessages({ levels })`, `page.url()`, `page.title()`,
477
+ `page.viewportSize()`.
478
+ - `assert.ok/equal/notEqual/deepEqual/fail` and `console.log`.
479
+
480
+ Example:
481
+
482
+ ```js
483
+ await page.keyboard.down('Shift');
484
+ await page.keyboard.down('KeyD');
485
+ for (let i = 0; i < 7; i += 1) {
486
+ await page.waitForTimeout(140);
487
+ await page.mouse.click(520, 330);
488
+ }
489
+ await page.keyboard.up('KeyD');
490
+ await page.keyboard.up('Shift');
491
+ const state = await page.evaluate(() => window.__game.previewMismatches);
492
+ assert.equal(state, 0, 'preview and click disagreed');
493
+ await page.screenshot({ label: 'after-clicks' });
494
+ return { mismatches: state };
495
+ ```
496
+
497
+ Evidence rules:
498
+
499
+ - Drive the behavior under test with `page.keyboard` and `page.mouse`. Use `page.evaluate` to read
500
+ state or arrange a precondition, never to perform the action being verified. The result lists every
501
+ `page.evaluate` call site in `pageEvaluate`; report a conclusion as input-verified only when the
502
+ asserted behavior came from real input.
503
+ - Every key and mouse button still held when the script returns, throws, times out or is cancelled is
504
+ released automatically and listed in `input.autoReleased`. Treat a non-empty list as a script bug
505
+ to fix, not as a verified release.
506
+ - A failure returns `code`, `error.message` and `error.location` (script line and column) plus one
507
+ failure screenshot. Fix the script or the page and rerun; do not retry an unchanged script.
508
+ - Refs from earlier `inspect` calls are invalid after `run_script`; inspect again before a ref
509
+ action.
510
+ - Keep `page.evaluate` short and synchronous where possible. An async `page.evaluate` interrupted by
511
+ a timeout or cancellation can still finish in the page later; when `pageEvaluate.interrupted` is
512
+ present, reload or re-inspect the page before trusting its state.
513
+ - `assert.deepEqual` compares JSON data only; convert a Set, Map or Date first (for example
514
+ `[...set].sort()`, `date.getTime()`).
515
+ - Save scripts that should be rerun after code changes under the workspace and call them by `path`.
516
+ - Headless rendering may be software rendering. Do not report frame rate or GPU performance from a
517
+ script as real-hardware performance.
518
+
457
519
  ## Screenshot Visibility Boundary
458
520
 
459
521
  A Browser `screenshot` result is model-visible inspection evidence and is not shown to the user by
@@ -472,7 +534,10 @@ Element and frame refs are snapshot-scoped. After navigation, reload, or a stale
472
534
 
473
535
  ## Safety And Recovery
474
536
 
475
- - Arbitrary JavaScript execution is unavailable and must not be simulated through another tool.
537
+ - Arbitrary JavaScript execution is unavailable outside `run_script`: when the active provider
538
+ exposes `run_script`, page JavaScript runs only through its `page.evaluate` under the evidence
539
+ rules above; otherwise it is unavailable entirely. Never simulate JavaScript execution through
540
+ another tool.
476
541
  - Do not inspect cookies, local storage, passwords, profiles, or authentication secrets.
477
542
  - A passive read request must not trigger interaction. An explicitly requested read-only search may
478
543
  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-F5BJTVSP.js";import"./chunk-3LM4G7WV.js";import{d as p}from"./chunk-RCKQIK7B.js";import"./chunk-TJWBPT2F.js";import"./chunk-VRCVX3OX.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.
@@ -0,0 +1,9 @@
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
+ var N=["local-task:","local-background-task:","team-plan:"],x=new Set(["explore","worker","verifier"]);function h(e){return e.sessionKind==="task"||N.some(n=>e.purpose?.startsWith(n))}function C(e){return e.sessionType!=="branch"||!e.parentSessionId?!1:h(e)}function v(e){let n=e.agentName?.trim().toLocaleLowerCase();return n!==void 0&&x.has(n)}function ke(e){return h(e)||v(e)}function we(e,n){let r=[],t=new Set,i=new Set([n]),s=!0;for(;s;){s=!1;for(let o of e)t.has(o.sessionId)||!C(o)||!i.has(o.parentSessionId)||(r.push(o),t.add(o.sessionId),i.add(o.sessionId),s=!0)}return r}function he(e){return{sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.agentName?{agentName:e.agentName}:{},...e.title?{task:e.title}:{},status:D(e.status),...w("createdAtMs",e.createdAt),...w("updatedAtMs",e.updatedAt),...e.errorMessage?{errorMessage:e.errorMessage}:{}}}function Se(e){return e.status==="queued"||e.status==="running"}function D(e){let n=e?.trim().toLocaleLowerCase().replaceAll("-","_");return n?n==="queued"||n==="pending"||n==="created"?"queued":n==="running"||n==="started"||n==="active"||n==="busy"||n==="processing"||n==="in_progress"?"running":n==="finished"||n==="completed"||n==="succeeded"||n==="success"||n==="idle"?"completed":n==="error"||n==="failed"||n==="lost"?"failed":n==="aborted"||n==="interrupted"||n==="cancelled"||n==="canceled"||n==="stopped"?"stopped":"unknown":"unknown"}function w(e,n){if(typeof n=="number"&&Number.isFinite(n))return{[e]:n};if(typeof n!="string")return{};let r=Number(n);if(Number.isFinite(r))return{[e]:r};let t=Date.parse(n);return Number.isFinite(t)?{[e]:t}:{}}var Me="mavis";function M(e){let n=q(e.toolName),r=p(e.input);if(!n)return;let t=F(e.status,e.error),i=J(n)?O(r??{},e.output):V(n)?r?B(r):[]:[];if(i.length!==0)return{schemaVersion:1,state:t,blocks:i}}function O(e,n){let r=g(e,["path","filePath","file_path"]),t=z(n);return t?[t.omitted===void 0?S(r,t.diff):L(r,t.diff,t.omitted)]:j(e).map(({oldText:i,newText:s})=>{let o=[...i.split(`
3
+ `).map(d=>`- ${d}`),...s.split(`
4
+ `).map(d=>`+ ${d}`)].join(`
5
+ `);return S(r,o)})}function B(e){let n=g(e,["path","filePath","file_path"]),r=g(e,["content","fileContent","file_content"]);if(r===void 0)return[];let t=m(r);return r.includes("\0")?[{kind:"summary",...n?{path:n}:{},message:"Binary content cannot be previewed safely.",reason:"binary",byteCount:t}]:t>65536?[{kind:"summary",...n?{path:n}:{},message:`File preview omitted because it is ${$(t)}.`,reason:"too-large",byteCount:t}]:[{kind:"file",...n?{path:n}:{},content:r,lineCount:r.split(`
6
+ `).length,truncated:!1}]}function S(e,n){let r=n.split(`
7
+ `),t=m(n),i=r.slice(0,400),s=t>65536,o=i.join(`
8
+ `);s&&(o=K(o,65536));let d=Math.max(0,r.length-o.split(`
9
+ `).length);return{kind:"diff",...e?{path:e}:{},diff:o,addedLines:b(r,"+"),removedLines:b(r,"-"),truncated:d>0||s,...d>0?{omittedLines:d}:{}}}function L(e,n,r){return{kind:"summary",...e?{path:e}:{},message:n,reason:r==="timeout"?"unavailable":"too-large"}}function z(e){let n=p(e);if(!n)return;let r=[n,p(n.result),p(n.output)].filter(t=>t!==void 0);for(let t of r){let i=p(t.details),s=i?g(i,["diff","previewDiff","preview_diff"]):void 0;if(s){let o=i?g(i,["diffOmitted","diff_omitted"]):void 0;return o===void 0?{diff:s}:{diff:s,omitted:o}}}}function j(e){let r=(G(e.edits)??[]).flatMap(s=>{let o=p(s),d=o?g(o,["oldText","old_text"]):void 0,f=o?g(o,["newText","new_text"]):void 0;return d!==void 0&&f!==void 0?[{oldText:d,newText:f}]:[]}),t=g(e,["oldText","old_text"]),i=g(e,["newText","new_text"]);return t!==void 0&&i!==void 0&&r.push({oldText:t,newText:i}),r}function F(e,n){return X(n)||W(e)?"not-applied":U(e)?"applied":"proposed"}function U(e){return e===2||e==="2"||e==="completed"||e==="complete"||e==="done"||e==="finished"||e==="succeeded"||e==="success"}function W(e){return e===3||e==="3"||e==="failed"||e==="error"}function X(e){return e!=null&&e!==""}function q(e){return e?.trim().toLocaleLowerCase().replace(/[^a-z0-9]/gu,"")||void 0}function J(e){return e==="edit"||e==="editfile"||e==="replace"}function V(e){return e==="write"||e==="writefile"||e==="createfile"}function p(e){let n=I(e);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function G(e){let n=I(e);return Array.isArray(n)?n:void 0}function I(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function g(e,n){for(let r of n){let t=e[r];if(typeof t=="string")return t}}function b(e,n){return e.filter(r=>r.startsWith(n)&&!r.startsWith(n.repeat(3))).length}function m(e){return new TextEncoder().encode(e).byteLength}function K(e,n){if(m(e)<=n)return e;let r=0,t=e.length;for(;r<t;){let i=Math.ceil((r+t)/2);m(e.slice(0,i))<=n?r=i:t=i-1}return e.slice(0,r)}function $(e){return e<1024?`${e} B`:`${(e/1024).toFixed(e<10*1024?1:0)} KiB`}var Y=2,H=6,Q=10,Z=3,ee=4;function Pe(e,n){let r=e.dataJson?.trim();if(!r)return;if(r==="[DONE]")return E({type:"done",turnId:n},e);let t;try{t=JSON.parse(r)}catch{return}let i=a(t);if(!i)return;let s=u(i,["turn_id","turnId"])??n,o=i.type,d;if(o===Q||o==="heartbeat")d={type:"heartbeat",turnId:s};else if(o===Y||o==="agent_message"){let f=a(i.agent_message)??a(i.agentMessage);d=f?te(f,s):void 0}else if(ne(i)){let f=a(i.agent_message_chunk)??a(i.agentMessageChunk);d=f?re(f,s):void 0}else if(o==="error")d={type:"error",message:u(i,["error","message"])??"Runtime stream failed",turnId:s};else if(o==="session_status")d=oe(i,s);else if(o===Z||o===ee)d=se(i,s);else if(o==="resume_overflow")d={type:"resync-required",turnId:s};else if(typeof o=="string"){let f={...i};delete f.type,delete f.turnId,d={type:"generic",eventType:o,data:f,turnId:s}}return d?E(d,e):void 0}function ne(e){return e.type===H&&("agent_message_chunk"in e||"agentMessageChunk"in e)||e.type==="agent_message_chunk"}function te(e,n){let r=ie(e,n);if(r)return r;let t=P(e,n);if(t.role!=="unknown")return t.role==="assistant"&&t.finishReason==="error"?{type:"error",message:t.content?.trim()||"Runtime stream failed",turnId:n}:{type:"message",message:t}}function re(e,n){let r=P(e,n);if(r.role==="assistant")return l({type:"delta",messageId:r.id,turnId:r.turnId??n,role:r.role,content:r.content,thinking:r.thinking,toolCalls:r.toolCalls,timestamp:r.timestamp,chunkIndex:c(e,["chunk_index","chunkIndex"]),finish:e.finish===!0?!0:void 0})}function ie(e,n){let r=u(e,["msg_content","msgContent","content"]);if(!r)return;let t;try{t=a(JSON.parse(r))}catch{return}let i=t?u(t,["eventType"]):void 0;if(!t||!i||!(c(e,["msg_type","msgType","message_type","messageType"])===3)&&!["session.spawned","communication.message","delegation.message","todo_updated"].includes(i))return;let o={...t};return delete o.eventType,l({type:"generic",eventType:i,data:o,turnId:u(e,["turn_id","turnId"])??n,messageId:u(e,["msg_id","msgId","id"]),timestamp:c(e,["timestamp"])})}function oe(e,n){let r=a(e.session_status)??{},t=ue(u(r,["type","status"]));return t?l({type:"session-status",status:t,message:u(r,["message"]),turnId:n}):void 0}function se(e,n){let r=a(e.payload)??{},t=de(c(r,["status"]));if(!t)return;let i=a(r.error);return l({type:"session-status",status:t,message:u(i??r,["message","detail"]),turnId:n})}function ue(e){if(e==="idle"||e==="started"||e==="finished"||e==="error"||e==="aborted"||e==="interrupted")return e}function de(e){if(e===1||e===2)return"started";if(e===3)return"idle";if(e===4)return"error";if(e===5)return"aborted";if(e===6)return"finished"}function E(e,n){return n.cursor?{...e,cursor:n.cursor}:e}function P(e,n){return ae(a(e)??{},n)}function ae(e,n){let r=a(T(e.rawJson??e.raw_json))??{};return l({id:u(e,["msg_id","msgId","id"]),turnId:u(e,["turn_id","turnId"])??n,role:Te(u(e,["role"]))??"unknown",kind:ge(u(e,["kind"])),source:u(e,["source"]),origin:T(e.origin??e.originJson??e.origin_json),error:u(e,["error"]),tokensBefore:c(e,["tokensBefore","tokens_before"]),tokensAfter:c(e,["tokensAfter","tokens_after"]),content:u(e,["msg_content","msgContent","content"]),editContent:u(e,["editContent"])??u(r,["editContent"]),thinking:u(e,["thinking_content","thinkingContent","thinking"]),thinkingDurationMs:c(e,["thinking_duration_ms","thinkingDurationMs"]),toolCalls:A(_(e,["tool_calls","toolCalls"])),toolResult:fe(a(e.toolResult??e.tool_result)),parts:pe(_(e,["parts"])),attachments:me(_(e,["attachments"])),timestamp:c(e,["timestamp","createdAt","created_at"]),finishReason:u(e,["finish_reason","finishReason"]),usage:le(a(e.usage)),actions:ce(a(e.actions))})}function ce(e){if(!e)return;let n=l({fork:R(e,["fork"]),rewind:R(e,["rewind"])});return Object.keys(n).length>0?n:void 0}function le(e){if(!e)return;let n=l({totalTokens:c(e,["total_tokens","totalTokens"]),inputTokens:c(e,["input_tokens","inputTokens"]),outputTokens:c(e,["output_tokens","outputTokens"]),reasoningTokens:c(e,["reasoning","reasoning_tokens","reasoningTokens"]),requestDurationMs:c(e,["request_duration_ms","requestDurationMs"]),decodeDurationMs:c(e,["decode_duration_ms","decodeDurationMs"]),cacheReadTokens:c(e,["cache_read","cacheRead","cache_read_tokens"]),cacheWriteTokens:c(e,["cache_write","cacheWrite","cache_write_tokens"])});return Object.keys(n).length>0?n:void 0}function fe(e){if(!e)return;let n=u(e,["toolCallId","tool_call_id"]);if(!n)return;let r=a(e.details),t=r?l({taskId:u(r,["taskId","task_id"]),subSessionId:u(r,["subSessionId","sub_session_id"]),subTurnId:u(r,["subTurnId","sub_turn_id"])}):void 0;return l({toolCallId:n,toolName:u(e,["toolName","tool_name"]),details:t&&Object.keys(t).length>0?t:void 0})}function ge(e){if(e==="preamble"||e==="final"||e==="compaction_start"||e==="compaction"||e==="compaction_failed"||e==="review_start"||e==="review_result"||e==="review_failed"||e==="review_aborted"||e==="review_interrupted")return e}function Ae(e){return e.parts?.length?[...e.parts]:[...e.thinking?.trim()?[l({type:"thinking",content:e.thinking,durationMs:e.thinkingDurationMs})]:[],...e.content?.trim()?[{type:"text",content:e.content}]:[],...(e.toolCalls??[]).map(n=>({type:"tool",toolCall:n}))]}function pe(e){if(!e)return;let n=e.flatMap(r=>{let t=a(r);if(!t)return[];let i=u(t,["id","part_id","partId"]),s=u(t,["type","kind"]);if(s==="thinking"||s==="cognitive_text"){let o=u(t,["content","text","thinking"]);return o===void 0?[]:[l({id:i,type:"thinking",content:o,durationMs:c(t,["durationMs","duration_ms"])})]}if(s==="text"){let o=u(t,["content","text"]);return o===void 0?[]:[l({id:i,type:"text",content:o})]}if(s==="tool"||s==="tool_call"||s==="toolCall"){let o=a(t.toolCall??t.tool_call)??t,[d]=A([o])??[];return d?[l({id:i,type:"tool",toolCall:d})]:[]}return[]});return n.length>0?n:void 0}function me(e){if(!e)return;let n=e.flatMap(r=>{let t=a(r);if(!t)return[];let i=a(t.meta)??t,s=a(t.local),o=a(t.cloud),d=u(i,["mimeType","mime_type"])??u(t,["mimeType","mime_type"])??"application/octet-stream",f=u(i,["attachmentType","attachment_type","type"])??u(t,["attachmentType","attachment_type","type"]);return[l({type:f==="image"||d.startsWith("image/")?"image":"file",fileName:u(i,["fileName","file_name"])??u(t,["fileName","file_name"])??"attachment",mimeType:d,sizeBytes:c(i,["sizeBytes","size_bytes"]),filePath:(s?u(s,["filePath","file_path"]):void 0)??u(t,["filePath","file_path"]),assetId:s?u(s,["assetId","asset_id"]):void 0,previewUrl:u(t,["previewUrl","preview_url"])??(o?u(o,["url"]):void 0)})]});return n.length>0?n:void 0}function A(e){if(!e)return;let n=e.flatMap(r=>{let t=a(r);if(!t)return[];let i=u(t,["tool_name","tool_call_name","toolName","name"]);if(!i)return[];let s=l({id:u(t,["tool_call_id","toolCallId","id"]),name:i,status:u(t,["tool_call_status","toolCallStatus","status"])??c(t,["tool_call_status","toolCallStatus","status"]),input:T(k(t,["tool_call_args","toolCallArgs","args","arguments","input"])),output:T(k(t,["tool_call_result_data","toolCallResultData","tool_call_result","toolCallResult","result","output"])),error:k(t,["tool_call_error","toolCallError","error"]),durationMs:c(t,["tool_call_duration_ms","toolCallDurationMs","durationMs","duration_ms"])}),o=M({toolName:s.name,status:s.status,input:s.input,output:s.output,error:s.error});return[{...s,...o?{structuredPreview:o}:{}}]});return n.length>0?n:void 0}function Te(e){return e==="user"||e==="assistant"||e==="system"?e:e===void 0?void 0:"unknown"}function a(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function u(e,n){for(let r of n)if(typeof e[r]=="string")return e[r]}function c(e,n){for(let r of n){let t=e[r];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()){let i=Number(t);if(Number.isFinite(i))return i}}}function R(e,n){for(let r of n)if(typeof e[r]=="boolean")return e[r]}function _(e,n){for(let r of n)if(Array.isArray(e[r]))return e[r]}function k(e,n){for(let r of n)if(Object.prototype.hasOwnProperty.call(e,r))return e[r]}function T(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function l(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}var y=["default","auto","bypassPermissions"],ye={default:"Ask",auto:"Auto",bypassPermissions:"Full access",off:"Off"},_e={default:"ASK",auto:"AUTO",bypassPermissions:"FULL",off:"OFF"};function xe(e){return y.find(n=>n===e)}function Ce(e){return ye[e]}function ve(e){return _e[e]}function De(e){return e==="bypassPermissions"}function Oe(e){if(e==="off")return"default";let n=y.indexOf(e);return y[(n+1)%y.length]}export{C as a,v as b,ke as c,we as d,he as e,Se as f,M as g,Pe as h,P as i,Ae as j,y as k,xe as l,Ce as m,ve as n,De as o,Oe as p,Me as q};
@@ -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-VRCVX3OX.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};
@@ -0,0 +1,2 @@
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{stripVTControlCharacters as f}from"node:util";var c=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/gu;function T(e,t){let r=[t.summary,t.nextStep,t.preservation].map(i=>i?.trim()).filter(i=>!!i).join(" "),n=a(e);return{message:r,...n&&n!==r?{diagnostic:n}:{}}}function _(e,t){let r=t.summary.trim(),n=a(e);return[n?`${r.replace(/[.:;!?]+$/u,"")}: ${n}`:r,t.nextStep,t.preservation].map(s=>s?.trim()).filter(s=>!!s).map(l).join(" ")}var d="output_limit_exhausted",h="The model ran out of output space while still thinking and did not finish after several automatic retries.";function E(e){return e?.trim()===d}function a(e){if(e==null)return"";let t=e instanceof Error?e.message:String(e);return p(t).trim()}function p(e){return f(e).replace(c,"").replace(/-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/giu,"[redacted private key]").replace(/\bsk-[A-Za-z0-9._-]{8,}\b/gu,"sk-[redacted]").replace(/\b(?:sk|pk|ghp|github_pat|xox[baprs])[-_][A-Za-z0-9_-]{12,}\b/giu,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu,"[redacted]").replace(/\bBearer\s+[^\s,;]+/giu,"Bearer [redacted]").replace(/\b(Authorization)(\s*[:=]\s*)((?:Bearer|Basic|Token)\s+)?(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,"$1$2$3[redacted]").replace(/\b(api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,"$1$2[redacted]")}function l(e){return/[.!?…]$/u.test(e)?e:`${e}.`}function u(e){return e?.length?Array.from(new Set(e.map(t=>t.trim()).filter(t=>t.length>0))):[]}function x(e){return u(e?.effortOptions).length>0}var g="thinking";function k(e,t){let r=e?.variant;if(e?.thinkingConfig?.mode==="forced_off"||r===""||r==="none-thinking")return;let n=u(e?.effortOptions),i=e?.defaultEffort?.trim(),s=n.length>0?n:i?[i]:[],o=(t??(e?.selected?e.thinking?.effort:void 0))?.trim();if(o&&s.includes(o))return o;if(!(r!==void 0&&r!==g))return i&&s.includes(i)?i:n[Math.floor(n.length/2)]}export{u as a,x as b,k as c,T as d,_ as e,h as f,E as g,a as h,p as i};
@@ -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 U}from"./chunk-CF3YFDG4.js";import{a as G}from"./chunk-PRXIML4F.js";import{a as w,c as C,e as le}from"./chunk-D76SO2ME.js";var E=C(V=>{var x=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},H=class extends x{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};V.CommanderError=x;V.InvalidArgumentError=H});var $=C(P=>{var{InvalidArgumentError:pe}=E(),k=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new pe(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function fe(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}P.Argument=k;P.humanReadableArgName=fe});var T=C(K=>{var{humanReadableArgName:ge}=$(),I=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,r)=>n.name().localeCompare(r.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);!n&&!r?t.push(i):i.long&&!r?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>ge(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth||80,r=2,s=2;function l(m,O){if(O){let S=`${m.padEnd(i+s)}${O}`;return t.wrap(S,n-r,i+s)}return m}function a(m){return m.join(`
2
+ import{a as U}from"./chunk-52LBQEEC.js";import{a as G}from"./chunk-PRXIML4F.js";import{a as w,c as C,e as le}from"./chunk-D76SO2ME.js";var E=C(V=>{var x=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},H=class extends x{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};V.CommanderError=x;V.InvalidArgumentError=H});var $=C(P=>{var{InvalidArgumentError:pe}=E(),k=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new pe(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function fe(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}P.Argument=k;P.humanReadableArgName=fe});var T=C(K=>{var{humanReadableArgName:ge}=$(),I=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,r)=>n.name().localeCompare(r.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);!n&&!r?t.push(i):i.long&&!r?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>ge(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth||80,r=2,s=2;function l(m,O){if(O){let S=`${m.padEnd(i+s)}${O}`;return t.wrap(S,n-r,i+s)}return m}function a(m){return m.join(`
3
3
  `).replace(/^/gm," ".repeat(r))}let u=[`Usage: ${t.commandUsage(e)}`,""],h=t.commandDescription(e);h.length>0&&(u=u.concat([t.wrap(h,n,0),""]));let c=t.visibleArguments(e).map(m=>l(t.argumentTerm(m),t.argumentDescription(m)));c.length>0&&(u=u.concat(["Arguments:",a(c),""]));let p=t.visibleOptions(e).map(m=>l(t.optionTerm(m),t.optionDescription(m)));if(p.length>0&&(u=u.concat(["Options:",a(p),""])),this.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(O=>l(t.optionTerm(O),t.optionDescription(O)));m.length>0&&(u=u.concat(["Global Options:",a(m),""]))}let b=t.visibleCommands(e).map(m=>l(t.subcommandTerm(m),t.subcommandDescription(m)));return b.length>0&&(u=u.concat(["Commands:",a(b),""])),u.join(`
4
4
  `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,n=40){let r=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",s=new RegExp(`[\\n][${r}]+`);if(e.match(s))return e;let l=t-i;if(l<n)return e;let a=e.slice(0,i),u=e.slice(i).replace(`\r
5
5
  `,`