@minimax-ai/code 0.6.1 → 0.6.3

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 (29) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/CHANGELOG.zh-CN.md +15 -0
  3. package/README.md +21 -0
  4. package/README.zh-CN.md +15 -0
  5. package/chunks/{auth-command-7CDRKDVD.js → auth-command-CO6IUQQ5.js} +1 -1
  6. package/chunks/{chunk-UNHOACX2.js → chunk-7CKVJIAL.js} +1 -1
  7. package/chunks/{chunk-UI7OHI22.js → chunk-EL5XOH23.js} +510 -510
  8. package/chunks/chunk-G7Q4HUMC.js +23 -0
  9. package/chunks/{chunk-JVKXU2EF.js → chunk-K7X2ELVZ.js} +2 -2
  10. package/chunks/{chunk-H2MLHV4N.js → chunk-T4F6MBL2.js} +1 -1
  11. package/chunks/{chunk-FD7DWNRT.js → chunk-T6KXDH7B.js} +1 -1
  12. package/chunks/{chunk-PUFWXRWS.js → chunk-U7ACBEGU.js} +5 -5
  13. package/chunks/{chunk-K3IQFB2P.js → chunk-VN3EYAMT.js} +1 -1
  14. package/chunks/chunk-WROGTDVD.js +3 -0
  15. package/chunks/{chunk-5DNOXYNO.js → chunk-YC47AWPX.js} +1 -1
  16. package/chunks/{data-dir-3FQYZA5W.js → data-dir-4GSZVAMG.js} +1 -1
  17. package/chunks/{launcher-Z2CKZB4R.js → launcher-ST7GNBTY.js} +152 -152
  18. package/chunks/{lifecycle-SQHUVIJ7.js → lifecycle-MEDWAANQ.js} +1 -1
  19. package/chunks/main-7X6VQMDB.js +9 -0
  20. package/chunks/{plugin-command-YRAYZBNS.js → plugin-command-EZNOWONW.js} +1 -1
  21. package/chunks/{provider-command-GJYV7UUM.js → provider-command-OJLRQ76A.js} +1 -1
  22. package/chunks/{run-acp-command-MUUZAUTS.js → run-acp-command-Z5CVNHZZ.js} +2 -2
  23. package/chunks/run-exec-command-MT4Y6VPF.js +17 -0
  24. package/cli.js +2 -2
  25. package/package.json +1 -1
  26. package/chunks/chunk-Q45WUEPQ.js +0 -3
  27. package/chunks/chunk-RO4BB34M.js +0 -2
  28. package/chunks/main-2G4XWJUW.js +0 -30
  29. package/chunks/run-exec-command-NWUGZRC4.js +0 -17
package/CHANGELOG.md CHANGED
@@ -7,6 +7,25 @@ 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.3 · 2026-10-05
11
+
12
+ ### Added
13
+
14
+ - Customize the main Agent's system prompt at startup with `--system-prompt` or
15
+ `--system-prompt-file`, or extend it with `--append-system-prompt` or
16
+ `--append-system-prompt-file`. Available in the interactive TUI, `exec`, `exec review`, and ACP.
17
+ - Replacement and appended prompts can be combined. They apply only to the current process,
18
+ preserve runtime rules and project instructions, and do not affect Task child Agents.
19
+
20
+ ## 0.6.2 · 2026-10-02
21
+
22
+ ### Fixed
23
+
24
+ - In a `/btw` side session, pressing Esc on an empty Composer no longer suggests editing the latest
25
+ message; `/edit` is unavailable there.
26
+ - Switching between a side session and the main conversation no longer resets the main run's
27
+ Running/Loading timer to zero.
28
+
10
29
  ## 0.6.1 · 2026-10-01
11
30
 
12
31
  ### Added
@@ -8,6 +8,21 @@ TUI 正式版中用户能直接感知的重要变化。收录范围以 TUI 用
8
8
 
9
9
  仅内部重构、测试调整,或只影响其他产品界面且不改变 TUI 行为的变化不记录。
10
10
 
11
+ ## 0.6.3 · 2026-10-05
12
+
13
+ ### 新增功能
14
+
15
+ - 启动时可通过 `--system-prompt`、`--system-prompt-file` 替换主 Agent 的系统提示词,或通过
16
+ `--append-system-prompt`、`--append-system-prompt-file` 追加内容;交互式 TUI、`exec`、`exec review` 和 ACP 均支持。
17
+ - 替换与追加可同时使用,只对当前进程生效,保留运行规则和项目指令,不影响 Task 子 Agent。
18
+
19
+ ## 0.6.2 · 2026-10-02
20
+
21
+ ### 问题修复
22
+
23
+ - `/btw` 侧会话中,在空 Composer 按 Esc 不再提示“再按一次编辑最后一条消息”;侧会话本身不支持 `/edit`。
24
+ - 在侧会话和主会话之间来回切换时,主任务 Running/Loading 的计时不再被清零。
25
+
11
26
  ## 0.6.1 · 2026-10-01
12
27
 
13
28
  ### 新增功能
package/README.md CHANGED
@@ -168,6 +168,27 @@ mode, version, and content hashes. A resumed Task must have a saved matching mod
168
168
  benchmark Session for older Tasks without that information. This option applies to regular `exec`
169
169
  tasks.
170
170
 
171
+ The interactive TUI, `exec`, `exec review`, and `mcode acp` can replace or extend the main Agent
172
+ system prompt:
173
+
174
+ ```bash
175
+ # Replace the identity section; runtime rules, project instructions, Environment, Memory, and Skills stay
176
+ mcode --system-prompt-file ./identity.md
177
+
178
+ # Append text after the identity section
179
+ mcode exec --append-system-prompt "List the files you will change first." "Complete this task."
180
+ ```
181
+
182
+ Use either `--system-prompt` or `--system-prompt-file`, and either `--append-system-prompt` or
183
+ `--append-system-prompt-file`; replace and append can be combined. Files are read once at startup
184
+ relative to the current directory, and a missing or empty file fails the launch. The same flags
185
+ also apply when placed before `exec`, `exec review`, or `acp`. Replace and append are resolved
186
+ separately, and the one written closest to the subcommand wins in either form:
187
+ `mcode --system-prompt-file a.md exec --system-prompt "..."` uses the inline text and does not
188
+ read `a.md`. Other subcommands, such as `login` or `init`, reject these flags. The flags apply only
189
+ to the current process, are never saved to the Session or configuration, and do not affect Task
190
+ child Agents.
191
+
171
192
  Run `mcode exec --help` for the complete set of headless options.
172
193
 
173
194
  ### Browser operations
package/README.zh-CN.md CHANGED
@@ -291,6 +291,21 @@ mcode exec --prompt-mode work "完成本次评测任务。"
291
291
  `tui`、`coding`、`work`,每种模式各使用一个完整模板,包含身份、规则与按当前开关渲染的 Memory 条件段。运行期间使用固定的随包 Prompt 内容,工具和权限沿用当前 TUI 配置。评测快照记录实际 Prompt、模式、版本及内容摘要。续跑 Task 需要保存的模式与所选模式匹配;历史 Task 缺少模式信息时,为评测新建会话。
292
292
  `--prompt-mode` 用于普通 `exec` 任务。
293
293
 
294
+ 需要替换或追加主 Agent 的 System Prompt 时,交互式 TUI、`exec`、`exec review` 和 `mcode acp`
295
+ 都支持以下参数:
296
+
297
+ ```bash
298
+ # 替换身份段(内置角色与模式正文),运行规则、项目指令、Environment、Memory 和 Skills 保留
299
+ mcode --system-prompt-file ./identity.md
300
+
301
+ # 在身份段之后追加内容
302
+ mcode exec --append-system-prompt "回答前先列出要修改的文件。" "完成本次任务。"
303
+ ```
304
+
305
+ `--system-prompt` 与 `--system-prompt-file` 二选一,`--append-system-prompt` 与
306
+ `--append-system-prompt-file` 二选一;替换和追加可以同时使用。文件在启动时读取一次,相对路径按当前目录解析,
307
+ 读取失败或内容为空会直接报错。写在 `exec`、`exec review` 或 `acp` 前面同样生效;替换和追加分别取离子命令最近的那一处,内联文本和文件算同一项,例如 `mcode --system-prompt-file a.md exec --system-prompt "..."` 使用内联文本,不读取 `a.md`。`login`、`init` 等其他子命令遇到这些参数会直接报错。参数只对当前进程生效,不写入 Session 或配置;Task 子 Agent 不受影响。
308
+
294
309
  运行 `mcode exec --help` 查看完整的 Headless 参数。
295
310
 
296
311
  ### Exec 诊断与超时恢复
@@ -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-5DNOXYNO.js";import"./chunk-FD7DWNRT.js";import{d as p}from"./chunk-H2MLHV4N.js";import"./chunk-UNHOACX2.js";import"./chunk-XYED4XTT.js";import"./chunk-Z4VKGZFA.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-YC47AWPX.js";import"./chunk-T6KXDH7B.js";import{d as p}from"./chunk-T4F6MBL2.js";import"./chunk-7CKVJIAL.js";import"./chunk-XYED4XTT.js";import"./chunk-Z4VKGZFA.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.
@@ -2,4 +2,4 @@ import { createRequire as __mavis_cR } from "module"; import { basename as __mav
2
2
  import{Aa as re,a as Te,ia as ne,za as ie}from"./chunk-XYED4XTT.js";import{c as oe}from"./chunk-Z4VKGZFA.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
- `,{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"]),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};
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};