@minimax-ai/code 0.6.2 → 0.6.4
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.
- package/CHANGELOG.md +50 -2
- package/CHANGELOG.zh-CN.md +28 -1
- package/README.md +80 -0
- package/README.zh-CN.md +55 -0
- package/assets/agents/mavis/skills/minimax-code-product/SKILL.md +7 -6
- package/assets/agents/mavis/skills/minimax-code-product/references/account-models.md +13 -4
- package/assets/agents/mavis/skills/minimax-code-product/references/agents.md +1 -1
- package/assets/agents/mavis/skills/minimax-code-product/references/extensions.md +1 -1
- package/assets/agents/mavis/skills/minimax-code-product/references/workflows.md +1 -1
- package/chunks/{anthropic-HVUDB2UQ.js → anthropic-3PPUMUI5.js} +1 -1
- package/chunks/{application-JOJGAMXA.js → application-YV6I5PN3.js} +1 -1
- package/chunks/{auth-command-7CDRKDVD.js → auth-command-F6CMS6YE.js} +1 -1
- package/chunks/{azure-openai-responses-2XUN7HBR.js → azure-openai-responses-TINWNAR2.js} +1 -1
- package/chunks/{chunk-WJZDMLYV.js → chunk-3MHUE4DM.js} +1 -1
- package/chunks/{chunk-UJCQHSQD.js → chunk-76MC32T2.js} +1 -1
- package/chunks/{chunk-5DNOXYNO.js → chunk-77TNCP5I.js} +1 -1
- package/chunks/{chunk-FD7DWNRT.js → chunk-AQ73XBVZ.js} +1 -1
- package/chunks/{chunk-XYED4XTT.js → chunk-AVYSGYVY.js} +99 -99
- package/chunks/{chunk-UNHOACX2.js → chunk-C2QIYD6E.js} +2 -2
- package/chunks/{chunk-H2MLHV4N.js → chunk-DKHGVKVS.js} +1 -1
- package/chunks/chunk-G7Q4HUMC.js +23 -0
- package/chunks/{chunk-PUFWXRWS.js → chunk-IBPQKAN6.js} +596 -595
- package/chunks/{chunk-JVKXU2EF.js → chunk-K7X2ELVZ.js} +2 -2
- package/chunks/{chunk-K3IQFB2P.js → chunk-LOIYR2RZ.js} +1 -1
- package/chunks/{chunk-YPNDEPC5.js → chunk-NXXFMBAV.js} +1 -1
- package/chunks/{chunk-HVP63X6W.js → chunk-ONRKFD6S.js} +1 -1
- package/chunks/{chunk-GPPNWE6W.js → chunk-OQ7HN3XJ.js} +8 -3
- package/chunks/chunk-RDUENEEQ.js +2 -0
- package/chunks/{chunk-UI7OHI22.js → chunk-RWMY26JX.js} +532 -528
- package/chunks/{chunk-5GISCO53.js → chunk-U5SHMJ7Y.js} +1 -1
- package/chunks/{chunk-G64EFDMH.js → chunk-UOE7W4PK.js} +1 -1
- package/chunks/chunk-WROGTDVD.js +3 -0
- package/chunks/{data-dir-3FQYZA5W.js → data-dir-U4LWH2QP.js} +1 -1
- package/chunks/{dist-DQKO47DC.js → dist-KNYBCP4F.js} +1 -1
- package/chunks/{google-R5XVVF36.js → google-W4KKPJIU.js} +1 -1
- package/chunks/{google-vertex-IQCRUNEW.js → google-vertex-K2VBU5YX.js} +1 -1
- package/chunks/{install-source-KWOIXLTZ.js → install-source-REWTEDE3.js} +1 -1
- package/chunks/launcher-74Z5T4C2.js +273 -0
- package/chunks/{lifecycle-SQHUVIJ7.js → lifecycle-ADITN7NX.js} +1 -1
- package/chunks/main-WKTFLQ4A.js +9 -0
- package/chunks/{mistral-YGQW5B3K.js → mistral-5IVMGNIC.js} +1 -1
- package/chunks/{openai-codex-responses-2JCAFRE3.js → openai-codex-responses-HMN5LXLI.js} +1 -1
- package/chunks/{openai-completions-HCLBIIWV.js → openai-completions-A22BIUQL.js} +1 -1
- package/chunks/openai-responses-7MFUVUZA.js +2 -0
- package/chunks/{plugin-command-YRAYZBNS.js → plugin-command-7PC7EX65.js} +1 -1
- package/chunks/{provider-command-GJYV7UUM.js → provider-command-JWWVMDYX.js} +1 -1
- package/chunks/{run-acp-command-MUUZAUTS.js → run-acp-command-AAHBRZ4K.js} +2 -2
- package/chunks/run-exec-command-HGDHDSXT.js +17 -0
- package/chunks/{update-XSUZQSPB.js → update-X4G4FEY3.js} +1 -1
- package/cli.js +2 -2
- package/package.json +1 -1
- package/chunks/chunk-22LFXEGJ.js +0 -2
- package/chunks/chunk-Q45WUEPQ.js +0 -3
- package/chunks/chunk-RO4BB34M.js +0 -2
- package/chunks/launcher-63TKMRXF.js +0 -270
- package/chunks/main-RGVWZQBG.js +0 -30
- package/chunks/openai-responses-65UFQVVM.js +0 -2
- package/chunks/run-exec-command-NWUGZRC4.js +0 -17
|
@@ -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{Aa as re,a as Te,ia as ne,za as ie}from"./chunk-
|
|
2
|
+
import{Aa as re,a as Te,ia as ne,za as ie}from"./chunk-AVYSGYVY.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};
|
|
@@ -1,2 +1,2 @@
|
|
|
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{l as i,n as D}from"./chunk-
|
|
2
|
+
import{l as i,n as D}from"./chunk-C2QIYD6E.js";import{ua as a,y as n}from"./chunk-AVYSGYVY.js";function o(t,r=n,e=a){return r(void 0,e())}function u(){return o(i())}function m(t){let r=t.MINIMAX_DATA_DIR?.trim();return r||t.MAVIS_DATA_DIR?.trim()||void 0}function f(t=process.env,r=u){return m(t)??r()}function v(t=u,r=process.env){return f(r,t)}function p(t={}){let r=(t.getBuildEnv??i)(),e=v(t.getDefaultDataDir??(()=>o(r)),t.environment??process.env);return(t.configureRuntimeEnvironment??D)({dataDir:e}),Promise.resolve(e)}export{o as a,f as b,v as c,p as d};
|
|
@@ -0,0 +1,23 @@
|
|
|
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(`
|
|
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
|
+
`)}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
|
+
`,`
|
|
6
|
+
`),h=" ".repeat(i),p="\\s\u200B",b=new RegExp(`
|
|
7
|
+
|.{1,${l-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),m=u.match(b)||[];return a+m.map((O,S)=>O===`
|
|
8
|
+
`?"":(S>0?h:"")+O.trimEnd()).join(`
|
|
9
|
+
`)}};K.Help=I});var q=C(N=>{var{InvalidArgumentError:_e}=E(),M=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=be(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new _e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Oe(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},F=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return t.negate===(r===e)}};function Oe(o){return o.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function be(o){let e,t,i=o.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}N.Option=M;N.DualOptions=F});var Y=C(X=>{function Ce(o,e){if(Math.abs(o.length-e.length)>3)return Math.max(o.length,e.length);let t=[];for(let i=0;i<=o.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=o.length;n++){let r=1;o[n-1]===e[i-1]?r=0:r=1,t[n][i]=Math.min(t[n-1][i]+1,t[n][i-1]+1,t[n-1][i-1]+r),n>1&&i>1&&o[n-1]===e[i-2]&&o[n-2]===e[i-1]&&(t[n][i]=Math.min(t[n][i],t[n-2][i-2]+1))}return t[o.length][e.length]}function Ae(o,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=o.startsWith("--");t&&(o=o.slice(2),e=e.map(s=>s.slice(2)));let i=[],n=3,r=.4;return e.forEach(s=>{if(s.length<=1)return;let l=Ce(o,s),a=Math.max(o.length,s.length);(a-l)/a>r&&(l<n?(n=l,i=[s]):l===n&&i.push(s))}),i.sort((s,l)=>s.localeCompare(l)),t&&(i=i.map(s=>`--${s}`)),i.length>1?`
|
|
10
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
11
|
+
(Did you mean ${i[0]}?)`:""}X.suggestSimilar=Ae});var ee=C(Z=>{var ye=w("node:events").EventEmitter,D=w("node:child_process"),_=w("node:path"),j=w("node:fs"),d=w("node:process"),{Argument:we,humanReadableArgName:Ee}=$(),{CommanderError:W}=E(),{Help:ve}=T(),{Option:J,DualOptions:xe}=q(),{suggestSimilar:z}=Y(),R=class o extends ye{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>d.stdout.write(t),writeErr:t=>d.stderr.write(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,outputError:(t,i)=>i(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,r=i;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,s,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);return n&&(a.description(n),a._executableHandler=!0),r.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(r.noHelp||r.hidden),a._executableFile=r.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n?this:a}createCommand(e){return new o(e)}createHelp(){return Object.assign(new ve,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new we(e,t)}argument(e,t,i,n){let r=this.createArgument(e,t);return typeof i=="function"?r.default(n).argParser(i):r.default(i),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,n]=e.match(/([^ ]+) *(.*)/),r=t??"display help for command",s=this.createCommand(i);return s.helpOption(!1),n&&s.arguments(n),r&&s.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new W(e,t,i)),d.exit(e)}action(e){let t=i=>{let n=this.registeredArguments.length,r=i.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new J(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(r){if(r.code==="commander.invalidArgument"){let s=`${n} ${r.message}`;this.error(s,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),i=t(e).find(n=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),r=t(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,s,l)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let a=this.getOptionValue(i);r!==null&&e.parseArg?r=this._callParseArg(e,r,a,s):r!==null&&e.variadic&&(r=e._concatValue(r,a)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,l)};return this.on("option:"+t,r=>{let s=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,s,"cli")}),e.envVar&&this.on("optionEnv:"+t,r=>{let s=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,s,"env")}),this}_optionEx(e,t,i,n,r){if(typeof t=="object"&&t instanceof J)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,i);if(s.makeOptionMandatory(!!e.mandatory),typeof n=="function")s.default(r).argParser(n);else if(n instanceof RegExp){let l=n;n=(a,u)=>{let h=l.exec(a);return h?h[0]:u},s.default(r).argParser(n)}else s.default(n);return this.addOption(s)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){d.versions?.electron&&(t.from="electron");let n=d.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=d.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":d.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(h,c){let p=_.resolve(h,c);if(j.existsSync(p))return p;if(n.includes(_.extname(c)))return;let b=n.find(m=>j.existsSync(`${p}${m}`));if(b)return`${p}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let h;try{h=j.realpathSync(this._scriptPath)}catch{h=this._scriptPath}l=_.resolve(_.dirname(h),l)}if(l){let h=r(l,s);if(!h&&!e._executableFile&&this._scriptPath){let c=_.basename(this._scriptPath,_.extname(this._scriptPath));c!==this._name&&(h=r(l,`${c}-${e._name}`))}s=h||s}i=n.includes(_.extname(s));let a;d.platform!=="win32"?i?(t.unshift(s),t=Q(d.execArgv).concat(t),a=D.spawn(d.argv[0],t,{stdio:"inherit"})):a=D.spawn(s,t,{stdio:"inherit"}):(t.unshift(s),t=Q(d.execArgv).concat(t),a=D.spawn(d.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(c=>{d.on(c,()=>{a.killed===!1&&a.exitCode===null&&a.kill(c)})});let u=this._exitCallback;a.on("close",h=>{h=h??1,u?u(new W(h,"commander.executeSubCommandAsync","(close)")):d.exit(h)}),a.on("error",h=>{if(h.code==="ENOENT"){let c=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${s}' does not exist
|
|
15
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
+
- ${c}`;throw new Error(p)}else if(h.code==="EACCES")throw new Error(`'${s}' not executable`);if(!u)d.exit(1);else{let c=new W(1,"commander.executeSubCommandAsync","(error)");c.nestedError=h,u(c)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);n||this.help({error:!0});let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),r}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(i,n,r)=>{let s=n;if(n!==null&&i.parseArg){let l=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,n,r,l)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;i.variadic?n<this.args.length?(r=this.args.slice(n),i.parseArg&&(r=r.reduce((s,l)=>e(i,l,s),i.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],i.parseArg&&(r=e(i,r,i.defaultValue))),t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[t]!==void 0).forEach(r=>{r._lifeCycleHooks[t].forEach(s=>{n.push({hookedCommand:r,callback:s})})}),t==="postAction"&&n.reverse(),n.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{n=this._chainOrCall(n,()=>r(this,t))}),n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(r,e,t)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(r=>i.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t,r=e.slice();function s(a){return a.length>1&&a[0]==="-"}let l=null;for(;r.length;){let a=r.shift();if(a==="--"){n===i&&n.push(a),n.push(...r);break}if(l&&!s(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,s(a)){let u=this._findOption(a);if(u){if(u.required){let h=r.shift();h===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,h)}else if(u.optional){let h=null;r.length>0&&!s(r[0])&&(h=r.shift()),this.emit(`option:${u.name()}`,h)}else this.emit(`option:${u.name()}`);l=u.variadic?u:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let u=this._findOption(`-${a[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,a.slice(2)):(this.emit(`option:${u.name()}`),r.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let u=a.indexOf("="),h=this._findOption(a.slice(0,u));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,a.slice(u+1));continue}}if(s(a)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),r.length>0&&i.push(...r);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),r.length>0&&t.push(...r);break}else if(this._defaultCommandName){i.push(a),r.length>0&&i.push(...r);break}}if(this._passThroughOptions){n.push(a),r.length>0&&n.push(...r);break}n.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new xe(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=s=>{let l=s.attributeName(),a=this.getOptionValue(l),u=this.options.find(c=>c.negate&&l===c.attributeName()),h=this.options.find(c=>!c.negate&&l===c.attributeName());return u&&(u.presetArg===void 0&&a===!1||u.presetArg!==void 0&&a===u.presetArg)?u:h||s},n=s=>{let l=i(s),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let s=r.createHelp().visibleOptions(r).filter(l=>l.long).map(l=>l.long);n=n.concat(s),r=r.parent}while(r&&!r._enablePositionalOptions);t=z(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),t=z(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>Ee(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=_.basename(e,_.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=n=>this._outputConfiguration.writeErr(n):i=n=>this._outputConfiguration.writeOut(n),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation(i);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=d.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,r=>{let s;typeof t=="function"?s=t({error:r.error,command:r.command}):s=t,s&&r.write(`${s}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Q(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",n="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?t=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=r[1],i=r[3],n=r[4]),t&&n!=="0"?`${t}=${i}:${parseInt(n)+1}`:e})}Z.Command=R});var re=C(f=>{var{Argument:te}=$(),{Command:L}=ee(),{CommanderError:$e,InvalidArgumentError:ie}=E(),{Help:Se}=T(),{Option:ne}=q();f.program=new L;f.createCommand=o=>new L(o);f.createOption=(o,e)=>new ne(o,e);f.createArgument=(o,e)=>new te(o,e);f.Command=L;f.Option=ne;f.Argument=te;f.Help=Se;f.CommanderError=$e;f.InvalidArgumentError=ie;f.InvalidOptionArgumentError=ie});var g=Object.freeze({success:0,invocation:2,config:3,runtime:4,timeout:6,limit:7,internal:70,cancelled:130,brokenPipe:141}),y=class extends G{constructor(t,i,n){super(t,i,{code:`exec.${t}`,retryable:t==="runtime",...n});this.kind=t;this.name="TuiExecError"}};function Te(o){switch(o.status){case"succeeded":return g.success;case"failed":return o.error?.category==="config"?g.config:o.error?.category==="internal"?g.internal:g.runtime;case"timeout":return g.timeout;case"cancelled":return g.cancelled;case"limit_exceeded":return g.limit}return g.internal}function Me(o){return o instanceof y?g[o.kind]:g.internal}var ue=new Set(["none-thinking",""]),B="--model must use provider/model or provider/model#variant.";function he(o){let e=o.indexOf("/");if(e<1||e===o.length-1)throw A(B);let t=o.slice(0,e),i=o.slice(e+1),n=i.lastIndexOf("#"),r=n>0?i.slice(0,n):i,s=n>0?i.slice(n+1):void 0;if(!t||!r||n>0&&!s)throw A(B);return{providerId:t,modelId:r,...s?{variant:s}:{}}}async function De(o){let e=o.model?he(o.model):void 0,t=o.effort;if(t===void 0)return e?{...e}:void 0;let i=await de(o,t),n=e??me(o.session,i);if(!n)throw A("--effort could not resolve a model. Pass --model provider/model, or select a model for this Session first.");let r=i.find(u=>u.providerId===n.providerId&&u.modelId===n.modelId),s=U(r?.effortOptions),l=`${n.providerId}/${n.modelId}`,a=n.variant??r?.variant;if(a!==void 0&&ue.has(a))throw A(ce({requested:e,reference:l,effort:t,effectiveVariant:a,target:r}));if(!r)throw A(`${l} is not in this Session's model list, so --effort ${t} cannot be validated. Check the provider and model id.`);if(s.length===0)throw A(`${l} does not support reasoning effort selection, so --effort ${t} cannot be applied.`);if(!s.includes(t))throw A(`--effort ${t} is not available for ${l}. Available levels: ${s.join(", ")}.`);return{providerId:n.providerId,modelId:n.modelId,...n.variant===void 0?{}:{variant:n.variant},thinking:{effort:t}}}function ce(o){let{requested:e,reference:t,effort:i,effectiveVariant:n,target:r}=o;if(e?.variant!==void 0)return`--effort cannot be combined with the thinking-off variant "#${n}". Drop one of them.`;if(!e)return`--effort cannot be applied because this Session runs the thinking-off variant "#${n}". Switch the Session model, or pass --model with a thinking-capable variant.`;let s=r?.thinkingConfig?.mode==="switchable"?` Pass --model ${t}#thinking to turn thinking on.`:"";return`${t} runs with thinking off by default, so --effort ${i} would be discarded.${s}`}async function de(o,e){try{return await o.runtime.listModels(o.session.sessionId)}catch(t){throw new y("runtime",`--effort ${e} could not be validated because the model roster is unavailable: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function me(o,e){let t=e.find(n=>n.selected===!0);if(t)return{providerId:t.providerId,modelId:t.modelId,...t.variant===void 0?{}:{variant:t.variant}};let i=o.model;if(i?.providerId&&i.modelId)return{providerId:i.providerId,modelId:i.modelId,...i.variant===void 0?{}:{variant:i.variant}}}function A(o){return new y("invocation",o)}import{readFileSync as He}from"node:fs";import{resolve as Ve}from"node:path";var se=le(re(),1),{program:Xe,createCommand:Ye,createArgument:Je,createOption:ze,CommanderError:Qe,InvalidArgumentError:Ze,InvalidOptionArgumentError:et,Command:tt,Argument:it,Option:v,Help:nt}=se.default;var ke=["--system-prompt","--system-prompt-file","--append-system-prompt","--append-system-prompt-file"],ae=[["systemPrompt","systemPromptFile"],["appendSystemPrompt","appendSystemPromptFile"]],Pe=new Set(ae.flat());function lt(o){return o.addOption(new v("--system-prompt <text>","replace the main Agent identity prompt for this process")).addOption(new v("--system-prompt-file <path>","read the replacement main Agent identity prompt from a file")).addOption(new v("--append-system-prompt <text>","append text after the main Agent identity prompt for this process")).addOption(new v("--append-system-prompt-file <path>","read the appended main Agent prompt text from a file"))}function ut(o,e){let t=e;for(let i of ae)if(!i.some(n=>e[n]!==void 0))for(let n=o.parent;n;n=n.parent){let r=n,s=i.filter(l=>r.getOptionValueSource(l)==="cli");if(s.length!==0){for(let l of s)t={...t,[l]:r.getOptionValue(l)};break}}return t}function ht(o){if(!o.options.some(e=>e.attributeName()==="systemPrompt"))for(let e=o.parent;e;e=e.parent)for(let t of e.options){let i=t.attributeName();if(!Pe.has(i)||e.getOptionValueSource(i)!=="cli")continue;let n=[];for(let r=o;r?.parent;r=r.parent)n.unshift(r.name());o.error(`error: option '${t.long}' is not supported by '${n.join(" ")}'`,{code:"commander.unknownOption"})}}function ct(o,e=process.cwd()){let t=oe("--system-prompt",o.systemPrompt,o.systemPromptFile,e),i=oe("--append-system-prompt",o.appendSystemPrompt,o.appendSystemPromptFile,e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{customPrompt:t},...i===void 0?{}:{appendSystemPrompt:i}}}function dt(o){let e=[];for(let t=0;t<o.length;t+=1){let i=o[t];if(i===void 0||i==="--")break;let n=ke.find(s=>i===s||i.startsWith(`${s}=`));if(!n)continue;if(i!==n){e.push(i);continue}let r=o[t+1];if(r===void 0)break;e.push(n,r),t+=1}return e}function oe(o,e,t,i){if(e!==void 0&&t!==void 0)throw new Error(`${o} and ${o}-file cannot be combined.`);if(e!==void 0){if(!e.trim())throw new Error(`${o} cannot be empty.`);return e}if(t===void 0)return;if(!t.trim())throw new Error(`${o}-file requires a path.`);let n;try{n=He(Ve(i,t),"utf8")}catch(r){throw new Error(`Failed to read ${o}-file ${t}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!n.trim())throw new Error(`${o}-file ${t} is empty.`);return n}export{Ze as a,tt as b,v as c,g as d,y as e,Te as f,Me as g,he as h,De as i,Pe as j,lt as k,ut as l,ht as m,ct as n,dt as o};
|