@minimax-ai/code 0.6.10 → 0.6.12
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 +33 -0
- package/CHANGELOG.zh-CN.md +33 -0
- package/README.md +1 -1
- package/README.zh-CN.md +11 -1
- package/assets/agents/_default/prompt-base-windows.md +1 -1
- package/assets/agents/_default/prompt-base-windows.md.hbs +1 -1
- package/assets/agents/desktop-task/checkpoint/system.md +6 -2
- package/assets/agents/managed-prompts.json +1 -0
- package/assets/agents/mavis/skills/control-in-app-browser/SKILL.md +41 -23
- package/assets/agents/memory-v2-consolidation.md +2 -2
- package/assets/agents/workflow/goal/budget-limit.md +4 -1
- package/assets/agents/workflow/goal/completion-summary.md +2 -0
- package/assets/agents/workflow/goal/recovery-terminal-audit.md +3 -2
- package/assets/agents/workflow/goal/recovery.md +2 -2
- package/chunks/{clipboard-image-Q5NH3BUQ.js → application-FYXBCFKS.js} +1 -1
- package/chunks/{auth-command-YIBIYLYL.js → auth-command-UUTBKVM2.js} +3 -3
- package/chunks/chunk-25R53L7J.js +23 -0
- package/chunks/chunk-334CV6RF.js +2 -0
- package/chunks/{chunk-GZAO7QYD.js → chunk-47KWM23C.js} +917 -866
- package/chunks/{chunk-F5767MLW.js → chunk-5ADYFF2U.js} +3402 -2277
- package/chunks/{chunk-NXXFMBAV.js → chunk-AMLNR7IO.js} +1 -1
- package/chunks/{chunk-3MHUE4DM.js → chunk-DCFP5ZHZ.js} +6 -6
- package/chunks/{chunk-X4N2MWNJ.js → chunk-G3BYCHZS.js} +1 -1
- package/chunks/{chunk-3FETZOUF.js → chunk-I2T4QMR7.js} +3 -3
- package/chunks/{chunk-FPCUX6KP.js → chunk-I5CQQ3J6.js} +1 -1
- package/chunks/{chunk-72PMKZ7Y.js → chunk-I7MLO7YD.js} +1 -1
- package/chunks/{chunk-CRTW4JM6.js → chunk-IO46JRII.js} +1 -1
- package/chunks/chunk-KGAIRLNO.js +3 -0
- package/chunks/chunk-L43V3NKW.js +2 -0
- package/chunks/chunk-NJVLEZ3I.js +2 -0
- package/chunks/{chunk-YPMJNO4T.js → chunk-OHWTK4KK.js} +1 -1
- package/chunks/{chunk-2LP3AAE5.js → chunk-QJ2FEPC2.js} +4 -4
- package/chunks/{chunk-UQ2YIDWV.js → chunk-QXUSWEWV.js} +1 -1
- package/chunks/{application-ZJ5NM3DF.js → chunk-SLFKHVQC.js} +1 -1
- package/chunks/chunk-VAVHH4XP.js +16 -0
- package/chunks/chunk-X3PES5WL.js +193 -0
- package/chunks/chunk-X7FQ5SBJ.js +40 -0
- package/chunks/{chunk-S6GSNWAM.js → chunk-ZPSMBMGA.js} +119 -119
- package/chunks/clipboard-image-SRYRNKLQ.js +2 -0
- package/chunks/{data-dir-AVW455BT.js → data-dir-C6MQE6W2.js} +1 -1
- package/chunks/dist-K652HFOW.js +2 -0
- package/chunks/{google-W4KKPJIU.js → google-ZWZWHJZZ.js} +1 -1
- package/chunks/{google-vertex-K2VBU5YX.js → google-vertex-C3BYAM6A.js} +1 -1
- package/chunks/{install-source-REWTEDE3.js → install-source-FIUDUO7G.js} +1 -1
- package/chunks/launcher-AVQRYDKB.js +275 -0
- package/chunks/{lifecycle-RBCNKJ7Z.js → lifecycle-VXPE5MII.js} +1 -1
- package/chunks/main-JXKRTY5N.js +11 -0
- package/chunks/{plugin-command-ZQV7YMWK.js → plugin-command-ZZLA7IRM.js} +1 -1
- package/chunks/{provider-command-UMQZDUGQ.js → provider-command-PVOKX3IV.js} +1 -1
- package/chunks/{run-acp-command-YUXNSZ3D.js → run-acp-command-MV4O4NBX.js} +32 -32
- package/chunks/run-app-server-command-DEX4FRZJ.js +24 -0
- package/chunks/{run-exec-command-HAIRHPYT.js → run-exec-command-EJMP5IF3.js} +1 -1
- package/chunks/{tools-L7RFN554.js → tools-VTXR5JSH.js} +1 -1
- package/chunks/{update-HOQ5YQFF.js → update-4XVOPCYB.js} +1 -1
- package/cli.js +2 -2
- package/package.json +1 -1
- package/chunks/chunk-5JU6ZMXS.js +0 -23
- package/chunks/chunk-G7FSWJID.js +0 -193
- package/chunks/chunk-LQIEYG3O.js +0 -39
- package/chunks/chunk-MESLFKP6.js +0 -3
- package/chunks/chunk-NICEDCLM.js +0 -2
- package/chunks/chunk-NP5G53PV.js +0 -16
- package/chunks/chunk-RDUENEEQ.js +0 -2
- package/chunks/dist-B52TV5OC.js +0 -2
- package/chunks/launcher-AFCZTEJU.js +0 -274
- package/chunks/main-SSCI3MRX.js +0 -9
|
@@ -0,0 +1,24 @@
|
|
|
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 me}from"./chunk-L43V3NKW.js";import{c as Bt,d as ke,e as Ht,f as $t,g as Kt,h as zt}from"./chunk-X7FQ5SBJ.js";import{b as $e,c as jt,d as Ke,e as ze,f as Wt,g as Gt,i as qt}from"./chunk-5ADYFF2U.js";import"./chunk-4ESEMCSG.js";import"./chunk-EFVDRFCG.js";import"./chunk-25R53L7J.js";import"./chunk-47KWM23C.js";import"./chunk-2BNOPHYG.js";import{a as Ft}from"./chunk-I5CQQ3J6.js";import"./chunk-52LBQEEC.js";import"./chunk-PRXIML4F.js";import"./chunk-PPIEC7ZM.js";import"./chunk-FKQFVOLR.js";import{a as j,b as Vt}from"./chunk-G3BYCHZS.js";import"./chunk-75PL5LYJ.js";import"./chunk-VYI2WX6B.js";import"./chunk-ONRKFD6S.js";import"./chunk-ZPSMBMGA.js";import"./chunk-U5SHMJ7Y.js";import"./chunk-LOQ4VVEN.js";import"./chunk-76MC32T2.js";import"./chunk-PWQHCWDV.js";import"./chunk-SHXPTUWI.js";import"./chunk-IIHJNKC3.js";import"./chunk-II4JKPH5.js";import"./chunk-UOE7W4PK.js";import"./chunk-6UEFDGWN.js";import"./chunk-WFWSBUYD.js";import{b as he,c as Me,d as Lt}from"./chunk-DCFP5ZHZ.js";import"./chunk-4Y64C4JT.js";import"./chunk-GMLXHJYG.js";import{D as Ot,i as He,k as Ct}from"./chunk-334CV6RF.js";import"./chunk-HQ2U4QVQ.js";import{c as Nt,d as Ut}from"./chunk-IO46JRII.js";import{d as wt,f as Rt,h as Et,j as bt,k as Tt,l as xt,o as Dt,r as It}from"./chunk-QJ2FEPC2.js";import{Qa as _t,wa as Mt,xa as kt}from"./chunk-X3PES5WL.js";import"./chunk-I2T4QMR7.js";import"./chunk-CWWDVX6C.js";import"./chunk-ZITT4GJK.js";import"./chunk-KTNHM6NK.js";import"./chunk-D76SO2ME.js";import{Console as Bo}from"node:console";import{randomUUID as Ho}from"node:crypto";import{mkdir as $o}from"node:fs/promises";import{resolve as B}from"node:path";function je(t){if(!Qr(t))return{ok:!1,message:"Runtime auth context must be an object."};let e=t.authState;if(e!=="pending"&&e!=="authenticated"&&e!=="logged_out")return{ok:!1,message:"Runtime auth context contains an invalid authState."};let r=fe(t.accessToken,1024*1024),n=fe(t.realUserID,16*1024),o=fe(t.userEmail,16*1024),i=fe(t.userName,16*1024),a=fe(t.subUserName,16*1024),s=t.expiresAtMs;return s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0||e!=="authenticated")?{ok:!1,message:"Runtime auth context contains an invalid token expiry."}:!r.ok||!n.ok||!o.ok||!i.ok||!a.ok?{ok:!1,message:"Runtime auth context contains an invalid identity field."}:e==="logged_out"&&(r.value||n.value)?{ok:!1,message:"Logged-out Runtime auth context cannot contain credentials."}:e==="authenticated"&&(!r.value||!n.value)?{ok:!1,message:"Authenticated Runtime auth context requires an access token and user id."}:{ok:!0,context:{authState:e,...s===void 0?{}:{expiresAtMs:s},...r.value?{accessToken:r.value}:{},...n.value?{realUserID:n.value}:{},...o.value?{userEmail:o.value}:{},...i.value?{userName:i.value}:{},...a.value?{subUserName:a.value}:{}}}}function Qr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fe(t,e){if(t==null||t==="")return{ok:!0};if(typeof t!="string"||t.length>e)return{ok:!1};let r=t.trim();return r?{ok:!0,value:r}:{ok:!1}}var We=["binaryFrame","base64"],Zr=new TextEncoder,Qo=new TextDecoder("utf-8",{fatal:!1});function Jt(t){let e=new Set(Array.isArray(t)?t.filter(r=>typeof r=="string"):[]);for(let r of We)if(e.has(r))return r;return"base64"}function Yt(t,e){let r=JSON.stringify({...t,byteLength:e.byteLength}),n=Zr.encode(r),o=new Uint8Array(1+n.byteLength+1+e.byteLength);return o[0]=30,o.set(n,1),o[1+n.byteLength]=10,o.set(e,1+n.byteLength+1),o}var O=1,W=16*1024*1024,V="desktopService/transport",ve="runtime/authContext",ye="account/read",Se="account/login/start",re="account/login/cancel",ne="account/logout",er="account/login/completed",tr="account/updated",K="server/prepareRestart",rr=[ye,Se,re,ne,K],Ge=["initialize",...rr,V],qe=["initialized",V],Je=[er,tr,V],T={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603,overloaded:-32001,notInitialized:-32002,alreadyInitialized:-32003,unsupportedTransport:-32004,unsupportedProtocol:-32005,authOperationFailed:-32010},G={contract:"DesktopService",transportMethod:V,transportProtocolVersion:2,requestFrame:"RuntimeTransportWireRequestFrame",responseFrames:["response-start","stream-chunk","stream-done","stream-error"],binaryPayloadEncoding:"base64",binaryPayloadEncodings:We,flowControl:["streamWindow","stream-credit","abort"],defaultStreamWindow:16,maxStreamWindow:256},ge=1;var en="protocolMismatch",tn="transportProtocolMismatch";function nr(t){let e=De(t.clientTransportProtocolVersion),r=De(t.serverTransportProtocolVersion);if(r===void 0)throw new Error("The server RuntimeTransport protocol version must be a positive integer.");return e===r?{compatible:!0,transportProtocolVersion:r}:e===void 0?Ye(t.clientTransportProtocolVersion===void 0||t.clientTransportProtocolVersion===null?"clientTransportProtocolMissing":"clientTransportProtocolInvalid","upgradeClient",null,r):e<r?Ye("clientTransportProtocolTooOld","upgradeClient",e,r):Ye("serverTransportProtocolTooOld","upgradeRemoteCli",e,r)}function or(t){let e=`(client transport ${Xe(t.clientTransportProtocolVersion)}, server transport ${t.serverTransportProtocolVersion})`;return t.recommendedAction==="upgradeClient"?`MCode RuntimeTransport protocol mismatch ${e}. Upgrade the MCode client and reconnect.`:`MCode RuntimeTransport protocol mismatch ${e}. Upgrade MCode CLI on the SSH host and reconnect.`}function ir(t){let e=De(t.clientProtocolVersion),r=De(t.serverProtocolVersion);return e===void 0?_e(t.clientProtocolVersion===void 0||t.clientProtocolVersion===null?"clientProtocolMissing":"clientProtocolInvalid","upgradeClient",null,r??null,t):r===void 0?_e(t.serverProtocolVersion===void 0||t.serverProtocolVersion===null?"serverProtocolMissing":"serverProtocolInvalid","upgradeRemoteCli",e,null,t):e===r?{compatible:!0,protocolVersion:e}:e<r?_e("clientProtocolTooOld","upgradeClient",e,r,t):_e("serverProtocolTooOld","upgradeRemoteCli",e,r,t)}function ar(t){let e=`(client protocol ${Xe(t.clientProtocolVersion)}, server protocol ${Xe(t.serverProtocolVersion)})`;return t.recommendedAction==="upgradeClient"?`MCode SSH app-server protocol mismatch ${e}. Upgrade the MCode client and reconnect.`:`MCode SSH app-server protocol mismatch ${e}. Upgrade MCode CLI on the SSH host and reconnect.`}function _e(t,e,r,n,o){return{compatible:!1,mismatch:{kind:en,reason:t,clientProtocolVersion:r,serverProtocolVersion:n,...o.clientVersion?{clientVersion:o.clientVersion}:{},...o.serverVersion?{serverVersion:o.serverVersion}:{},recommendedAction:e}}}function Ye(t,e,r,n){return{compatible:!1,mismatch:{kind:tn,reason:t,clientTransportProtocolVersion:r,serverTransportProtocolVersion:n,recommendedAction:e}}}function De(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?t:void 0}function Xe(t){return t===null?"unknown":String(t)}var Ie="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rn=new TextEncoder,nn=new TextDecoder("utf-8");function on(t){let e="";for(let r=0;r<t.length;r+=3){let n=t[r],o=t[r+1],i=t[r+2];e+=Ie[n>>2],e+=Ie[(n&3)<<4|(o??0)>>4],e+=o===void 0?"=":Ie[(o&15)<<2|(i??0)>>6],e+=i===void 0?"=":Ie[i&63]}return e}function pr(t,e={}){let r=typeof t=="string"?t:nn.decode(t),n=e.maxMessageBytes??W;if(!Number.isSafeInteger(n)||n<=0)return{ok:!1,error:{code:T.invalidRequest,message:"The app-server message limit must be a positive safe integer."}};let o=rn.encode(r).length;if(o>n)return{ok:!1,error:{code:T.invalidRequest,message:`Message exceeds the ${n}-byte app-server limit.`,data:{sizeBytes:o,maxMessageBytes:n}}};let i;try{i=JSON.parse(r)}catch{return{ok:!1,error:{code:T.parseError,message:"Invalid JSON."}}}return an(i)}function Ce(t){return`${JSON.stringify(Ae(t))}
|
|
3
|
+
`}function I(t,e,r){return r===void 0?{code:t,message:e}:{code:t,message:e,data:Ae(r)}}function _(t,e){return{id:t,error:e}}function z(t,e){return{id:t,result:Ae(e)}}function cr(t){return"id"in t&&"method"in t}function dr(t){return"method"in t&&!("id"in t)}function lr(t){return"id"in t&&!("method"in t)}function Ae(t,e=new WeakSet){if(typeof t=="bigint")return t.toString();if(t===null||typeof t!="object")return t;if(e.has(t))return"[Circular]";e.add(t);try{if(Array.isArray(t))return t.map(n=>Ae(n,e));if(t instanceof Uint8Array)return on(t);let r={};for(let[n,o]of Object.entries(t))r[n]=Ae(o,e);return r}finally{e.delete(t)}}function an(t){if(!Qe(t))return q("Message must be a JSON object.");if(t.jsonrpc!==void 0&&t.jsonrpc!=="2.0")return q("Only JSON-RPC 2.0 messages are supported.");let e=t.method;return typeof e=="string"&&e.trim().length>0?t.params!==void 0&&!Qe(t.params)?sn("Request params must be an object."):t.id===void 0?{ok:!0,message:{method:e,...t.params?{params:t.params}:{}}}:sr(t.id)?{ok:!0,message:{id:t.id,method:e,...t.params?{params:t.params}:{}}}:q("Request id must be a string or number."):t.id!==void 0&&(t.result!==void 0||t.error!==void 0)?!sr(t.id)&&t.id!==null?q("Response id must be a string, number, or null."):t.result!==void 0&&t.error!==void 0?q("Response cannot contain both result and error."):t.error!==void 0?!Qe(t.error)||typeof t.error.code!="number"?q("Response error must contain a numeric code."):{ok:!0,message:{id:t.id,error:{code:t.error.code,message:typeof t.error.message=="string"?t.error.message:"Remote error.",...t.error.data!==void 0?{data:t.error.data}:{}}}}:{ok:!0,message:{id:t.id,result:t.result}}:q("Message must be a request, notification, or response.")}function q(t){return{ok:!1,error:I(T.invalidRequest,t)}}function sn(t){return{ok:!1,error:I(T.invalidParams,t)}}function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sr(t){return typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isFinite(t)}function Ze(t){let e=Wt({handleRequest:t.handleRequest,post:t.post,...t.streamScope?{streamScope:t.streamScope}:{},...t.coalesceIntervalMs!==void 0?{coalesceIntervalMs:t.coalesceIntervalMs}:{},...t.maxFrameBytes!==void 0?{maxFrameBytes:t.maxFrameBytes}:{},...t.onWarning?{onWarning:t.onWarning}:{}});return{handleFrame(r){e.handleFrame(r)},close:()=>e.close(),inFlightCount:()=>e.inFlightCount(),blockingRequestCount:()=>e.blockingRequestCount()}}function et(t){if(!jt(t))throw new TypeError("Cannot encode an invalid Runtime transport server frame.");return t.type==="stream-chunk"?{...t,payload:Ke(t.payload)}:{...t}}function Le(t){if(!cn(t))return Oe("DesktopService frame must be an object.");if(t.type==="request"){let e=pn(t.body,"body");if(!e.ok)return e;let r={...t};return e.value===void 0?delete r.body:r.body=e.value,$e(r)?{ok:!0,frame:r}:Oe("DesktopService request frame must contain a valid id, method, url, and headers.")}return t.type==="stream-credit"||t.type==="abort"?$e(t)?{ok:!0,frame:t}:Oe(`Invalid DesktopService ${String(t.type)} frame.`):Oe("DesktopService frame type must be request, stream-credit, or abort.")}function pn(t,e){if(t===void 0||typeof t=="string")return{ok:!0,value:t};let r=ze(t);return!r.ok&&r.reason==="invalidType"?{ok:!1,message:`DesktopService ${e} must be text or a base64 payload.`}:r.ok?{ok:!0,value:r.value}:{ok:!1,message:`DesktopService ${e} contains invalid base64.`}}function Oe(t){return{ok:!1,message:t}}function cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{randomUUID as dn}from"node:crypto";var ie=class extends Error{constructor(r){super(r.message);this.failure=r;this.name="RemoteAuthError"}},Pe=class{constructor(e){this.options=e;this.now=e.now??Date.now,this.createLoginId=e.createLoginId??dn,this.stopWatch=e.auth.watch(r=>{this.closed||(this.lastFailure=void 0,this.emit({method:"account/updated",params:this.project(r)}))})}listeners=new Set;now;createLoginId;stopWatch;activeLogin;loginTask;startQueue=Promise.resolve();lastFailure;closed=!1;async read(e=!0){try{let r=await this.options.auth.getStatus();if(e&&r.status==="expired")try{await this.options.auth.getAccessToken({minValidityMs:0}),this.lastFailure=void 0,r=await this.options.auth.getStatus()}catch(n){if(!Et(n))throw n;r=await this.options.auth.getStatus()}return r.status==="authenticated"&&(this.lastFailure=void 0),this.project(r)}catch(r){let n=oe(r);return this.lastFailure=n,{state:"temporarily_unavailable",generation:0,region:this.options.region,buildEnv:this.options.buildEnv,failure:n}}}startLogin(){return this.serialize(()=>this.ensureLoginStarted())}serialize(e){let r=this.startQueue.then(e);return this.startQueue=r.then(()=>{},()=>{}),r}cancelLogin(e){return this.serialize(async()=>(this.activeLogin?.loginId===e&&(this.activeLogin.cancelled=!0,await this.options.auth.cancelLogin(),await this.loginTask,this.lastFailure=void 0),this.read()))}logout(){return this.serialize(async()=>(this.activeLogin&&(this.activeLogin.cancelled=!0),await this.options.auth.cancelLogin(),await this.loginTask,await this.options.auth.logout({revoke:!0}),this.lastFailure=void 0,this.read()))}subscribe(e){return this.closed?()=>{}:(this.listeners.add(e),()=>this.listeners.delete(e))}async close(){this.closed||(this.closed=!0,this.stopWatch(),this.listeners.clear(),await this.options.auth.cancelLogin())}async ensureLoginStarted(){if(this.closed)throw new Error("The remote authentication service is closed.");if(this.activeLogin)return this.activeLogin.start;let e=await this.options.auth.getStatus().catch(n=>{throw new ie(oe(n))});if(this.closed)throw new Error("The remote authentication service is closed.");if(e.status==="authenticated"||e.status==="refreshing")return{state:"authenticated",generation:e.generation};let r=ln(this.createLoginId());return this.activeLogin=r,this.loginTask=this.runLogin(r),r.start}login(e){return this.options.auth.login({onDeviceAuthorization:r=>{if(this.activeLogin!==e||e.cancelled||this.closed)return;let n={state:"authorizing",loginId:e.loginId,verificationUri:r.verificationUri,...r.verificationUriComplete?{verificationUriComplete:r.verificationUriComplete}:{},userCode:r.userCode,expiresAtMs:this.now()+r.expiresInSec*1e3};e.descriptor=n,ur(e,n),this.emitCurrentSnapshot()}})}async runLogin(e){try{let r=await this.login(e);this.lastFailure=void 0,ur(e,{state:"authenticated",generation:r.generation}),this.emit({method:"account/login/completed",params:{loginId:e.loginId,success:!0,generation:r.generation}})}catch(r){let n=oe(r);e.cancelled||(this.lastFailure=n),e.startSettled||(e.startSettled=!0,e.rejectStart(new ie(n))),this.emit({method:"account/login/completed",params:{loginId:e.loginId,success:!1,error:n}})}finally{this.activeLogin===e&&(this.activeLogin=void 0),await this.emitCurrentSnapshot()}}project(e){return{state:e.status==="expired"&&this.lastFailure?"temporarily_unavailable":un(e.status),generation:e.generation,region:this.options.region,buildEnv:this.options.buildEnv,...e.expiresAtMs===void 0?{}:{expiresAtMs:e.expiresAtMs},...e.status==="refreshing"?{refreshing:!0}:{},...this.activeLogin?.descriptor&&!this.activeLogin.cancelled?{pendingLogin:this.activeLogin.descriptor}:{},...this.lastFailure?{failure:this.lastFailure}:{}}}async emitCurrentSnapshot(){this.closed||this.emit({method:"account/updated",params:await this.read(!1)})}emit(e){if(!this.closed)for(let r of this.listeners)try{r(e)}catch{}}};function ln(t){let e,r,n=new Promise((o,i)=>{e=o,r=i});return{loginId:t,start:n,resolveStart:e,rejectStart:r,startSettled:!1}}function ur(t,e){t.startSettled||(t.startSettled=!0,t.resolveStart(e))}function un(t){switch(t){case"authenticated":case"refreshing":return"authenticated";case"authorizing":return"authorizing";case"expired":case"scope_upgrade_required":case"error":return"reauthentication_required";case"anonymous":case"logging_out":case"logout_pending":return"login_required"}}function oe(t){if(t instanceof ie)return t.failure;if(t instanceof xt||t instanceof Tt)return{code:t.code,message:t.message,retryable:!1};if(t instanceof wt)return{code:`OAUTH_${t.code.toUpperCase()}`,message:t.message,retryable:t.httpStatus!==400||t.code!=="invalid_grant"};let e=t,r=typeof e?.code=="string"?e.code:"AUTH_OPERATION_FAILED",n=t instanceof Error?t.message:"The authentication operation failed.";return{code:r,message:n,retryable:!0}}var J=class{constructor(e){this.options=e;this.transport=Ze({handleRequest:e.handleRequest,workspaceDir:e.workspaceDir,post:r=>this.sendDesktopServiceFrame(r),...e.streamScope?{streamScope:e.streamScope}:{},...e.onWarning?{onWarning:e.onWarning}:{}})}transport;receiveQueue=Promise.resolve();queuedBytes=0;queuedMessages=0;initialized=!1;initializedNotification=!1;binaryPayloadEncoding="base64";closed=!1;notificationsSent=0;unsubscribeRemoteAuth;receive(e){if(this.closed)return Promise.resolve();let r=Buffer.byteLength(e);if(this.queuedBytes+r>(this.options.maxQueuedBytes??32*1024*1024)||this.queuedMessages>=(this.options.maxQueuedMessages??128))return this.options.onWarning?.("App-server client exceeded the receive queue limit."),this.close(),Promise.resolve();this.queuedBytes+=r,this.queuedMessages+=1;let n=this.receiveQueue.then(()=>this.process(e)).finally(()=>{this.queuedBytes-=r,this.queuedMessages-=1});return this.receiveQueue=n.catch(()=>{}),n}close(){this.closed||(this.closed=!0,this.unsubscribeRemoteAuth?.(),this.unsubscribeRemoteAuth=void 0,this.transport.close(),this.options.onClose?.())}snapshot(){let e=this.transport.inFlightCount();return{initialized:this.initialized,initializedNotification:this.initializedNotification,activeStreams:e,activeRequests:e,blockingRequests:this.transport.blockingRequestCount(),notificationsSent:this.notificationsSent}}async process(e){if(this.closed)return;let r=pr(e,{...this.options.maxMessageBytes!==void 0?{maxMessageBytes:this.options.maxMessageBytes}:{}});if(!r.ok){this.send(_(null,r.error));return}let n=r.message;if(!lr(n)){if(dr(n)){await this.processNotification(n.method,n.params??{});return}cr(n)&&await this.processRequest(n)}}async processNotification(e,r){if(e==="initialized"){if(!this.initialized)return;this.initializedNotification=!0,this.options.remoteAuth&&!this.unsubscribeRemoteAuth&&(this.unsubscribeRemoteAuth=this.options.remoteAuth.subscribe(n=>{this.notificationsSent+=1,this.send({method:n.method,params:n.params})}));return}if(e===ve){if(!this.requireInitialized())return;let n=je(r.context);if(!n.ok){this.options.onWarning?.(`Invalid Runtime auth context: ${n.message}`);return}try{await this.options.onRuntimeAuthContext?.(n.context)}catch{this.options.onWarning?.("Failed to apply Runtime auth context.")}return}if(e===V){if(!this.requireInitialized())return;let n=Le(r.frame);if(!n.ok){this.options.onWarning?.(`Invalid DesktopService notification frame: ${n.message}`);return}if(n.frame.type==="request"&&!this.canAcceptRequest()){this.sendDesktopServiceFrame({type:"stream-error",id:n.frame.id,seq:0,code:this.options.canAcceptDesktopServiceRequest?.()===!1?"runtime_restarting":"overloaded",message:this.options.canAcceptDesktopServiceRequest?.()===!1?"MCode app-server is preparing to restart. Retry after reconnecting.":"MCode app-server admission is closed or this connection has too many active requests."});return}this.transport.handleFrame(n.frame)}}async processRequest(e){if(e.method==="initialize"){await this.initialize(e);return}if(!this.requireInitialized(e.id))return;if(e.method===ve&&this.options.onRuntimeAuthContext){let n=je(e.params?.context);if(!n.ok){this.send(_(e.id,hr(n.message)));return}try{await this.options.onRuntimeAuthContext(n.context),this.send(z(e.id,{accepted:!0}))}catch(o){this.sendAuthError(e.id,o)}return}if(e.method===ye){await this.processAccountRead(e);return}if(e.method===Se){await this.processAccountLoginStart(e);return}if(e.method===re||e.method===ne){if(!this.options.remoteAuth){this.sendUnsupportedAuth(e);return}try{if(e.method===re&&(typeof e.params?.loginId!="string"||!e.params.loginId)){this.send(_(e.id,I(T.invalidParams,"loginId is required.")));return}let n=e.method===ne?await this.options.remoteAuth.logout():await this.options.remoteAuth.cancelLogin(e.params.loginId);this.send(z(e.id,n))}catch(n){this.sendAuthError(e.id,n)}return}if(e.method===K){if(!this.options.prepareRestart){this.send(_(e.id,I(T.methodNotFound,`Unknown app-server method: ${e.method}`)));return}try{this.send(z(e.id,await this.options.prepareRestart()))}catch(n){this.send(_(e.id,mr(n)))}return}if(!Ge.includes(e.method)){this.send(_(e.id,I(T.methodNotFound,`Unknown app-server method: ${e.method}`)));return}let r=Le((e.params??{}).frame);if(!r.ok){this.send(_(e.id,hr(r.message)));return}if(r.frame.type==="request"&&!this.canAcceptRequest()){this.send(_(e.id,I(T.overloaded,"MCode app-server admission is closed or this connection has too many active requests.",{retryable:!0})));return}try{this.transport.handleFrame(r.frame),this.send(z(e.id,{accepted:!0,requestId:r.frame.id}))}catch(n){this.send(_(e.id,mr(n)))}}canAcceptRequest(){return this.options.canAcceptDesktopServiceRequest?.()!==!1&&this.transport.inFlightCount()<(this.options.maxActiveRequests??64)}async initialize(e){if(this.initialized){this.send(_(e.id,I(T.alreadyInitialized,"The app-server connection is already initialized.")));return}let n=e.params??{},o=ir({clientProtocolVersion:n.protocolVersion,serverProtocolVersion:O,...n.clientInfo?.version?{clientVersion:n.clientInfo.version}:{},serverVersion:this.options.version});if(!o.compatible){this.send(_(e.id,I(T.unsupportedProtocol,ar(o.mismatch),o.mismatch)));return}let i=n.capabilities?.desktopService?.transportProtocolVersion,a=nr({clientTransportProtocolVersion:i,serverTransportProtocolVersion:G.transportProtocolVersion});if(!a.compatible){this.send(_(e.id,I(T.unsupportedTransport,or(a.mismatch),a.mismatch)));return}this.initialized=!0,this.binaryPayloadEncoding=this.options.sendBinaryFrame?Jt(n.capabilities?.desktopService?.binaryPayloadEncodings):"base64";let s={protocolVersion:O,serverInfo:{name:"mcode-app-server",title:"MCode SSH App Server",version:this.options.version},workspaceDir:this.options.workspaceDir,...this.options.environment?{environment:this.options.environment}:{},...this.options.hostIdentity?{hostIdentity:this.options.hostIdentity}:{},capabilities:{methods:[...this.options.onRuntimeAuthContext?[ve]:[],...this.options.remoteAuth?[ye,Se,re,ne]:[],...this.options.prepareRestart?[K]:[],V],clientNotifications:[...qe,...this.options.onRuntimeAuthContext?[ve]:[]],serverNotifications:this.options.remoteAuth?[...Je]:[V],transports:["stdio","unix-websocket"],desktopService:{...G,negotiatedBinaryPayloadEncoding:this.binaryPayloadEncoding},reconnect:{history:!0},auth:{deviceAuthorization:!!this.options.remoteAuth,credentialTransfer:!!this.options.onRuntimeAuthContext,mode:this.options.onRuntimeAuthContext?"desktop":"remote-oauth"}}};this.send(z(e.id,s))}async processAccountRead(e){if(!this.options.remoteAuth){this.sendUnsupportedAuth(e);return}try{this.send(z(e.id,await this.options.remoteAuth.read()))}catch(r){this.sendAuthError(e.id,r)}}async processAccountLoginStart(e){if(!this.options.remoteAuth){this.sendUnsupportedAuth(e);return}try{this.send(z(e.id,await this.options.remoteAuth.startLogin()))}catch(r){this.sendAuthError(e.id,r)}}sendUnsupportedAuth(e){this.send(_(e.id,I(T.methodNotFound,`Unknown app-server method: ${e.method}`)))}sendAuthError(e,r){let n=oe(r);this.send(_(e,I(T.authOperationFailed,n.message,n)))}requireInitialized(e){return this.initialized?this.initializedNotification?!0:(e!==void 0&&this.send(_(e,I(T.notInitialized,"Send the initialized notification before app-server requests."))),!1):(e!==void 0&&this.send(_(e,I(T.notInitialized,"The app-server connection must be initialized first."))),!1)}sendDesktopServiceFrame(e){if(this.closed)return;this.notificationsSent+=1;let r=this.options.sendBinaryFrame;if(this.binaryPayloadEncoding==="binaryFrame"&&r&&e.type==="stream-chunk"&&e.payload instanceof Uint8Array){r(Yt({type:"stream-chunk",id:e.id,seq:e.seq},e.payload));return}this.send({method:V,params:{frame:et(e)}})}send(e){this.closed||this.options.send(e)}};function hr(t){return I(T.invalidParams,t)}function mr(t){return I(T.internalError,t instanceof Error?t.message:String(t))}import{createServer as fn}from"node:http";import{chmod as vn,lstat as Sr,unlink as gr}from"node:fs/promises";import{connect as yn}from"node:net";import{randomUUID as Sn}from"node:crypto";import{dirname as gn}from"node:path";import{URL as Ar}from"node:url";import{chmod as hn,lstat as fr,mkdir as mn}from"node:fs/promises";async function Y(t,e={}){await mn(t,{recursive:!0,mode:448});let r=await fr(t),n=process.getuid?.();if(!r.isDirectory()||n===void 0||r.uid!==n)throw new Error(`App-server control directory must be a real directory owned by the current user: ${t}`);if((r.mode&4095)!==448&&e.repairPermissions&&(await hn(t,448),r=await fr(t)),!r.isDirectory()||r.uid!==n||(r.mode&4095)!==448)throw new Error(`App-server control directory requires effective 0700 permissions; use a private directory on a filesystem supporting Unix permissions: ${t}`)}var An=128*1024*1024,vr=50,Pn=10;async function rt(t){if((t.platform??process.platform)==="win32")throw new Error("The app-server Unix transport requires a Unix-like remote host.");if(!t.socketPath.trim())throw new Error("A non-empty app-server socket path is required.");let e=(t.platform??process.platform)==="linux"?107:103,r=Buffer.byteLength(t.socketPath,"utf8");if(r>e)throw new Error(`App-server socket path is ${r} bytes; Unix sockets allow at most ${e} on this platform. Use a shorter data directory: ${t.socketPath}`);let n=t.maxMessageBytes??W;if(!Number.isSafeInteger(n)||n<=0)throw new Error("App-server message limit must be a positive safe integer.");let o=Math.min(Math.min(n,W)*8,An),i=t.maxBufferedBytes??o;if(!Number.isSafeInteger(i)||i<=0)throw new Error("App-server buffered-byte limit must be a positive safe integer.");let a=t.maxConnections??16,s=t.handshakeTimeoutMs??1e4;if(!Number.isSafeInteger(a)||a<=0||!Number.isSafeInteger(s)||s<=0)throw new Error("App-server connection limits must be positive safe integers.");await Y(gn(t.socketPath)),await En(t.socketPath);let p=fn((d,m)=>wn(d,m,t.serverIdentity)),c=new Vt.default({noServer:!0,maxPayload:n}),l=new Set,u=0,h=!0,f=null,v,y,E,S=new Promise((d,m)=>{v=d,y=m}),g=new Promise(d=>{E=d}),w=!1,C,M=t.prepareRestart?()=>{if(f)return f;let d=b();return f=d,d.then(m=>{!m.ready&&f===d&&(f=null)},()=>{f===d&&(f=null)}),d}:void 0;async function b(){h=!1;let d=[...l].reduce((m,A)=>m+A.snapshot().blockingRequests,u);if(d>0)return h=!0,{ready:!1,activeRequestCount:d,activeTurnCount:0,pendingAdmissionCount:0};try{let m=await t.prepareRestart();return m.ready||(h=!0),{...m,activeRequestCount:0}}catch(m){throw h=!0,m}}p.on("upgrade",(d,m,A)=>{if(w||c.clients.size>=a){m.write(`HTTP/1.1 503 Service Unavailable\r
|
|
4
|
+
Connection: close\r
|
|
5
|
+
\r
|
|
6
|
+
`),m.destroy();return}if(d.headers.origin){m.write(`HTTP/1.1 403 Forbidden\r
|
|
7
|
+
Connection: close\r
|
|
8
|
+
\r
|
|
9
|
+
`),m.destroy();return}if((d.url?new Ar(d.url,"http://mcode.local").pathname:"/")!=="/"){m.write(`HTTP/1.1 404 Not Found\r
|
|
10
|
+
Connection: close\r
|
|
11
|
+
\r
|
|
12
|
+
`),m.destroy();return}c.handleUpgrade(d,m,A,P=>{c.emit("connection",P,d)})}),c.on("connection",d=>{let m,A=0,k=!1,P=D=>{if(d.readyState===j.default.OPEN){let ue=Ce(D).trimEnd();if(d.bufferedAmount+Buffer.byteLength(ue)>i){m?.close(),d.terminate();return}d.send(ue)}};m=new J({handleRequest:async D=>{A+=1;try{return await t.handleRequest(D)}finally{A-=1,k&&(u-=1)}},version:t.version,workspaceDir:t.workspaceDir,...t.serverIdentity?{hostIdentity:t.serverIdentity}:{},...t.environment?{environment:t.environment}:{},...t.remoteAuth?{remoteAuth:t.remoteAuth}:{},...M?{prepareRestart:M}:{},canAcceptDesktopServiceRequest:()=>h,send:P,sendBinaryFrame:D=>{if(d.readyState===j.default.OPEN){if(d.bufferedAmount+D.byteLength>i){m?.close(),d.terminate();return}d.send(D,{binary:!0})}},streamScope:Sn(),...t.maxMessageBytes!==void 0?{maxMessageBytes:t.maxMessageBytes}:{},...t.onWarning?{onWarning:t.onWarning}:{},...t.onRuntimeAuthContext?{onRuntimeAuthContext:t.onRuntimeAuthContext}:{},onClose:()=>{k=!0,u+=A,m&&l.delete(m),yr(d)}}),l.add(m);let U=setTimeout(()=>{m.snapshot().initializedNotification||m.close()},s);U.unref?.(),d.on("message",D=>{m.receive(Rn(D)).catch(()=>{})}),d.once("close",()=>{clearTimeout(U),m.close()}),d.once("error",()=>m.close())}),p.once("error",d=>{w||(y(d),R().catch(()=>{}))});let te=process.umask(63);try{p.listen(t.socketPath,()=>{(async()=>{await bn(t.socketPath),await t.onReady?.(),v()})().catch(d=>{y(d),R()})})}finally{process.umask(te)}let H={socketPath:t.socketPath,ready:S,closed:g,close:()=>(C??=R(),C)};return await S,H;async function R(){if(!w){w=!0;for(let d of l)d.close();for(let d of c.clients)yr(d);await new Promise(d=>c.close(()=>d())),await new Promise(d=>{if(!p.listening){d();return}p.close(()=>d())}),await gr(t.socketPath).catch(()=>{}),E()}}}function yr(t){if(t.readyState===j.default.CLOSED)return;t.readyState===j.default.OPEN&&t.close(1001,"Runtime connection closed");let e=setTimeout(()=>t.terminate(),500);e.unref(),t.once("close",()=>clearTimeout(e))}function wn(t,e,r){if(t.headers.origin){e.writeHead(403,{"content-type":"text/plain; charset=utf-8"}),e.end("Origin is not allowed.");return}let n=t.url?new Ar(t.url,"http://mcode.local").pathname:"/";if(t.method==="GET"&&(n==="/readyz"||n==="/healthz")){let o=JSON.stringify({ok:!0,...r??{}});e.writeHead(200,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(o,"utf8")}),e.end(o);return}e.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),e.end("Not found.")}function Rn(t){return typeof t=="string"||t instanceof ArrayBuffer?Buffer.from(t):Array.isArray(t)?Buffer.concat(t):t}async function En(t){let e;try{e=await Sr(t)}catch(r){if(tt(r))return;throw r}if(!e.isSocket())throw new Error(`Refusing to replace non-socket app-server path: ${t}`);if(await Tn(t)){let r=new Error(`App-server socket is already in use: ${t}`);throw Object.assign(r,{code:"EADDRINUSE"}),r}await gr(t).catch(r=>{if(!tt(r))throw r})}async function bn(t){for(let e=0;e<vr;e+=1)try{await vn(t,384);let r=await Sr(t);if(!r.isSocket()||r.uid!==process.getuid?.()||(r.mode&4095)!==384)throw new Error(`App-server socket requires current-user ownership and effective 0600 permissions: ${t}`);return}catch(r){if(!tt(r)||e===vr-1)throw r;await new Promise(n=>{setTimeout(n,Pn)})}}function Tn(t){return new Promise((e,r)=>{let n=yn(t),o=!1,i=(s,p)=>{o||(o=!0,n.destroy(),p?r(p):e(s))},a=setTimeout(()=>i(!1,new Error(`Timed out probing app-server socket: ${t}`)),1e3);a.unref?.(),n.once("connect",()=>{clearTimeout(a),i(!0)}),n.once("error",s=>{clearTimeout(a),xn(s)?i(!1):i(!1,s)})})}function tt(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}function xn(t){return typeof t=="object"&&t!==null&&"code"in t&&(t.code==="ENOENT"||t.code==="ECONNREFUSED")}import{randomUUID as Mn}from"node:crypto";var kn=128*1024*1024,_n=500;async function nt(t){if(t.signal?.aborted)return;let e=t.input??process.stdin,r=t.output??process.stdout,n=t.maxPendingMessages??128;if(!Number.isSafeInteger(n)||n<=0)throw new Error("App-server pending-message limit must be a positive safe integer.");let o=t.maxPendingBytes??kn;if(!Number.isSafeInteger(o)||o<=0)throw new Error("App-server pending-byte limit must be a positive safe integer.");let i=Promise.resolve(),a=0,s=0,p=!1,c,l=new Promise(d=>{c=d}),u={},h=d=>{let m=Ce(d),A=Buffer.byteLength(m,"utf8");if(a>=n||s+A>o){b();return}a+=1,s+=A,i=i.then(()=>{if(!p)return new Promise((k,P)=>{r.write(m,U=>{U?P(U):k()})})}).catch(()=>b()).finally(()=>{a-=1,s-=A})},f=d=>{if(a>=n||s+d.byteLength>o){b();return}a+=1,s+=d.byteLength,i=i.then(()=>{if(!p)return new Promise((m,A)=>{try{r.write(d,k=>{k?A(k):m()})}catch(k){A(k)}})}).catch(()=>{b()}).finally(()=>{a-=1,s-=d.byteLength})},v=new J({handleRequest:t.handleRequest,version:t.version,workspaceDir:t.workspaceDir,...t.hostIdentity?{hostIdentity:t.hostIdentity}:{},...t.environment?{environment:t.environment}:{},...t.remoteAuth?{remoteAuth:t.remoteAuth}:{},...t.prepareRestart?{prepareRestart:t.prepareRestart}:{},send:h,sendBinaryFrame:f,...t.maxMessageBytes!==void 0?{maxMessageBytes:t.maxMessageBytes}:{},streamScope:t.streamScope??Mn(),...t.onWarning?{onWarning:t.onWarning}:{},...t.onRuntimeAuthContext?{onRuntimeAuthContext:t.onRuntimeAuthContext}:{},onClose:()=>M()});u.current=v;let y=t.maxMessageBytes??W,E=[],S=0,g=!1,w,C=new Promise(d=>{w=d}),M=()=>{g||(g=!0,e.off("data",te),e.pause(),u.current?.close(),w())},b=()=>{p=!0,c(),r.destroy(),M()};function te(d){if(g)return;let m=typeof d=="string"?Buffer.from(d):d,A=0;for(;A<=m.length;){let P=m.indexOf(10,A);if(P===-1)break;let U=m.subarray(A,P),D=Buffer.concat([...E,U]).toString("utf8").replace(/\r$/u,"");E=[],S=0,A=P+1,D.trim().length!==0&&v.receive(D).catch(()=>{})}let k=m.subarray(A);if(k.length>0){if(S+=k.length,S>y){b();return}E.push(Buffer.from(k))}}let H=()=>{e.readableEnded||b()};t.signal?.addEventListener("abort",b,{once:!0}),e.on("data",te),e.once("end",M),e.once("close",H),e.once("error",b),r.once("error",b),r.once("close",b);let R;try{await C,R=setTimeout(b,_n),await Promise.race([i,l])}finally{R&&clearTimeout(R),t.signal?.removeEventListener("abort",b),e.off("end",M),e.off("close",H),e.off("error",b),r.off("error",b),r.off("close",b),v.close()}}import{connect as Dn}from"node:net";function ot(t){let e=t.input??process.stdin,r=t.output??process.stdout,n=t.connectTimeoutMs??1e4;return!Number.isFinite(n)||n<=0?Promise.reject(new Error("App-server proxy connect timeout must be positive.")):new Promise((o,i)=>{let a=!1,s=!1,p,c,l=h=>{a||(a=!0,p&&clearTimeout(p),t.signal?.removeEventListener("abort",u),c&&(e.unpipe(c),c.unpipe(r)),e.pause?.(),c?.destroy(),h?i(h):o())},u=()=>l(new Error("App-server proxy was cancelled."));if(t.signal?.addEventListener("abort",u,{once:!0}),t.signal?.aborted){u();return}p=setTimeout(()=>l(new Error(`Timed out connecting to ${t.socketPath}.`)),n),p.unref?.(),c=Dn(t.socketPath),c.once("connect",()=>{s=!0,p&&clearTimeout(p);let h=c;if(!h){l(new Error("Proxy socket disappeared before connect."));return}e.pipe(h),h.pipe(r,{end:!1})}),c.once("error",h=>{s?l():l(h)}),c.once("close",()=>l()),e.once("error",h=>l(h)),r.once("error",h=>l(h)),e.once("end",()=>c?.end())})}import{connect as In}from"node:net";import{get as Cn}from"node:http";async function it(t,e){return new Promise((r,n)=>{let o=Cn({socketPath:t,path:"/readyz",agent:!1},a=>{let s=[],p=0;a.on("data",c=>{p+=c.length,p>16384?o.destroy(new Error("App-server health response exceeded its size limit.")):s.push(c)}),a.once("error",n),a.once("end",()=>{try{let c=JSON.parse(Buffer.concat(s).toString("utf8"));if(a.statusCode!==200||!c||typeof c!="object"||!("ok"in c)||c.ok!==!0)throw new Error("App-server readiness response was invalid.");r(c)}catch(c){n(c)}})}),i=setTimeout(()=>{o.destroy(new Error(`Timed out probing app-server at ${t}.`))},Math.max(1,e));o.once("error",n),o.once("close",()=>clearTimeout(i))})}async function we(t,e){return On(t,e,async({call:r,initialize:n})=>{if(!n.capabilities.methods.includes(K))throw new Error("The running MCode app-server does not support managed restart.");let o=await r(K);if(!Nn(o))throw new Error("The app-server returned an invalid managed-restart response.");return o})}async function On(t,e,r){let n=new j.default("ws://mcode.local/",{createConnection:()=>In(t)}),o=new Map,i=0,a,s,p=(l,u)=>{let h=`lifecycle-${++i}`;return new Promise((f,v)=>{o.set(h,{resolve:f,reject:v}),n.send(JSON.stringify({id:h,method:l,...u?{params:u}:{}}))})};n.on("message",l=>{try{let u=JSON.parse(l.toString());if(typeof u.id!="string")return;let h=o.get(u.id);if(!h)return;o.delete(u.id),u.error?h.reject(new Error(typeof u.error.message=="string"?u.error.message:"App-server lifecycle request failed.")):h.resolve(u.result)}catch(u){c(u)}}),n.once("error",l=>c(l)),n.once("close",()=>{s??=new Error("App-server closed the lifecycle connection."),c(s)});try{await new Promise((u,h)=>{a=setTimeout(()=>h(new Error(`Timed out connecting to app-server at ${t}.`)),Math.max(1,e)),n.once("open",u),n.once("error",h)}),a&&clearTimeout(a),a=setTimeout(()=>{s=new Error(`Timed out calling app-server at ${t}.`),c(s),n.terminate()},Math.max(1,e));let l=await p("initialize",{protocolVersion:O,clientInfo:{name:"mcode-daemon-lifecycle"},capabilities:{desktopService:{transportProtocolVersion:G.transportProtocolVersion}}});if(!Ln(l))throw new Error("App-server initialize response was invalid.");return n.send(JSON.stringify({method:"initialized"})),await r({initialize:l,call:p})}finally{a&&clearTimeout(a),n.terminate(),c(s??new Error("App-server lifecycle connection closed."))}function c(l){for(let u of o.values())u.reject(l);o.clear()}}function Ln(t){if(!t||typeof t!="object")return!1;let e=t;return e.protocolVersion===O&&e.serverInfo?.name==="mcode-app-server"&&typeof e.serverInfo.version=="string"&&Array.isArray(e.capabilities?.methods)}function Nn(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.ready=="boolean"&&(e.activeRequestCount===void 0||Number.isSafeInteger(e.activeRequestCount))&&Number.isSafeInteger(e.activeTurnCount)&&Number.isSafeInteger(e.pendingAdmissionCount)}import{chmod as lt,mkdir as Tr,open as xr,readFile as jn,rename as Mr,stat as Wn,unlink as le,writeFile as kr}from"node:fs/promises";import{dirname as Gn,join as pe,resolve as $}from"node:path";import{spawn as qn}from"node:child_process";import{randomUUID as Jn}from"node:crypto";import{randomUUID as Un}from"node:crypto";import{open as Vn,readFile as Fn,stat as Bn,unlink as Pr}from"node:fs/promises";var st=12e4;async function ae(t,e){await Y(t.controlDir,{repairPermissions:!0});let r=Date.now()+Math.max(0,t.timeoutMs),n=t.staleAfterMs??st,o,i=Un();for(;!o;)try{o=await Vn(t.lockPath,"wx",384)}catch(s){if(!Rr(s,"EEXIST"))throw s;let p=await at(t.lockPath),c=p?.pid,l=c!==void 0&&t.isProcessAlive(c);if(c!==void 0&&!l||await wr(t.lockPath,n,t.now??Date.now)){let h=await at(t.lockPath);h?.pid===p?.pid&&h?.token===p?.token&&(h?.pid!==void 0&&!t.isProcessAlive(h.pid)||await wr(t.lockPath,n,t.now??Date.now))&&await Pr(t.lockPath).catch(y=>{if(!Rr(y,"ENOENT"))throw y});continue}if(Date.now()>=r)throw new Error(t.busyMessage);await Hn(50)}await o.writeFile(`${JSON.stringify({pid:process.pid,token:i})}
|
|
13
|
+
`,"utf8");let a=setInterval(()=>{let s=new Date;o?.utimes(s,s).catch(()=>{})},Math.max(1e3,Math.floor(n/3)));a.unref();try{return await e()}finally{clearInterval(a),await o.close().catch(()=>{}),(await at(t.lockPath))?.token===i&&await Pr(t.lockPath).catch(()=>{})}}async function at(t){try{let e=(await Fn(t,"utf8")).trim();try{let r=JSON.parse(e);if(!r||typeof r!="object")throw new TypeError("Legacy lock owner.");let n=r;return!Number.isSafeInteger(n.pid)||n.pid<=0?void 0:{pid:n.pid,...typeof n.token=="string"?{token:n.token}:{}}}catch{let r=Number.parseInt(e,10);return Number.isSafeInteger(r)&&r>0?{pid:r}:void 0}}catch{return}}async function wr(t,e,r){try{return r()-(await Bn(t)).mtimeMs>e}catch{return!1}}function Rr(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}function Hn(t){return new Promise(e=>setTimeout(e,t))}import{execFile as $n}from"node:child_process";import{readFile as Kn}from"node:fs/promises";function se(t){try{return process.kill(t,0),!0}catch(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EPERM"}}function L(t){return t instanceof Error?t.message:String(t)}async function Ne(t,e=process.platform){if(e!=="win32"){if(e==="linux")try{return(await Kn(`/proc/${t}/cmdline`)).toString("utf8").split("\0").filter(Boolean).join(" ")}catch{return}try{return await zn("ps",["-p",String(t),"-o","command="])}catch{return}}}function zn(t,e){return new Promise((r,n)=>{$n(t,[...e],{encoding:"utf8"},(o,i)=>{o?n(o):r(i)})})}var Er=6e4,ce=1e4,pt=1e3,Yn=4096,Xn=8*1024*1024,Qn=3,ct=1e3;function Q(t,e){let r=$(t),n=pe(r,"app-server-control"),o=$(e??pe(n,"app-server.sock"));return{controlDir:n,socketPath:o,statePath:pe(n,"app-server.state.json"),pidPath:pe(n,"app-server.pid"),lockPath:pe(n,"app-server.lock"),stderrLogPath:pe(n,"app-server.stderr.log")}}var N=class extends Error{constructor(r,n){super(r);this.field=n;this.name="AppServerDaemonProfileMismatchError"}code="appServerProfileMismatch"};function _r(t){let e=[];for(let r=0;r<t.length;r+=1){let n=t[r];if(n!==void 0){if(n==="--input-type"||n==="--eval"||n==="-e"||n==="--print"||n==="-p"){r+=1;continue}n==="--check"||n==="-c"||n.startsWith("--input-type=")||n.startsWith("--eval=")||n.startsWith("--print=")||n.startsWith("--check=")||n.startsWith("-e=")||n.startsWith("-p=")||e.push(n)}}return e}var X=class{constructor(e){this.options=e;let r=$(e.dataDir),n=Q(r,e.socketPath);this.paths=e.statePath?{...n,statePath:$(e.statePath)}:n,this.now=e.now??Date.now,this.spawn=e.spawn??((o,i,a)=>qn(o,i,a)),this.execArgv=_r(e.execArgv??process.execArgv),this.isProcessAlive=e.isProcessAlive??se,this.signalProcess=e.sendSignal??eo,this.waitForReady=e.waitForReady??to,this.createInstanceId=e.createInstanceId??Jn}paths;now;spawn;execArgv;isProcessAlive;signalProcess;waitForReady;createInstanceId;async bootstrap(){let e=await this.readState();return(this.options.authMode??"remote-oauth")==="remote-oauth"&&e.authMode==="desktop"&&de(e,this.isProcessAlive)&&await this.withLock(async()=>{let r=await this.readState();if(r.authMode!=="desktop"||!de(r,this.isProcessAlive))return;if(br({...r,authMode:"remote-oauth"},this.options),await this.waitForReady(r.socketPath,ce,Re(r)),!(await(this.options.prepareRestart??we)(r.socketPath,ce)).ready)throw new N("The remote MCode service is finishing active tasks. Reconnect after they finish to enable remote sign-in.","authMode");if(r.pid&&!await Ee(r.pid,this.isProcessAlive,ce))throw new Error("The idle remote MCode service has not exited yet. Retry the connection.")}),this.start()}async start(){if((this.options.platform??process.platform)==="win32")throw new Error("The app-server daemon requires a Unix-like remote host.");return this.withLock(async()=>{let e=await this.readState();if(de(e,this.isProcessAlive)){br(e,this.options),Zn(e,this.options.launcherPath);let g=!1;try{await this.waitForReady(e.socketPath,this.options.startTimeoutMs??ce,Re(e)),g=!0}catch(w){let C=await this.processOwnership(e),M={...e,status:"failed",error:`App-server readiness could not be verified: ${L(w)}`};if(await x(this.paths.statePath,M),C!=="other"&&e.pid!==void 0&&this.isProcessAlive(e.pid))throw new Error(`${M.error} Retained pid ${e.pid}; stop it before retrying.`);await le(this.paths.pidPath).catch(()=>{})}if(g){let w=this.readyState(e);return await x(this.paths.statePath,w),w}}await Tr(this.paths.controlDir,{recursive:!0,mode:448});let r=this.options.launcherPath?$(this.options.launcherPath):void 0,n=this.options.entryPath??process.argv[1],o=[];if(!r){if(!n)throw new Error("Cannot start the app-server daemon without a formal launcher.");o=[...this.execArgv,$(n)]}let i=this.paths.socketPath,a=$(this.options.workspaceDir??e.workspaceDir??this.paths.controlDir),s=this.createInstanceId(),p=this.now(),c=r??this.options.execPath??process.execPath,l=[...o,...this.options.lane?["--lane",this.options.lane]:[],"app-server","--auth-mode",this.options.authMode??"remote-oauth","--listen",`unix://${i}`,"--data-dir",$(this.options.dataDir),"--workspace",a,...this.options.region?["--region",this.options.region==="cn"?"cn":"global"]:[],"--instance-id",s,"--foreground","--state-file",this.paths.statePath],u={authMode:this.options.authMode??"remote-oauth",schemaVersion:ge,socketPath:i,stderrLogPath:this.paths.stderrLogPath,...r?{launcherPath:r}:{},...this.options.releaseKey?{releaseKey:this.options.releaseKey}:{},...r?{distributionChannel:this.options.distributionChannel??"latest"}:{},instanceId:s,protocolVersion:O,...this.options.region?{region:this.options.region}:{},...this.options.buildEnv?{buildEnv:this.options.buildEnv}:{},...this.options.lane?{lane:this.options.lane}:{},workspaceDir:a,version:this.options.version,startedAtMs:p};await oo(this.paths.stderrLogPath,Xn,Qn);let h=await xr(this.paths.stderrLogPath,"a",384);await lt(this.paths.stderrLogPath,384).catch(()=>{});let f;try{f=this.spawn(c,l,{cwd:this.paths.controlDir,detached:!0,stdio:["ignore","ignore",h.fd],windowsHide:!0})}catch(g){let w=await dt(`Failed to spawn the app-server daemon: ${L(g)}`,this.paths.stderrLogPath);throw await x(this.paths.statePath,{...u,status:"failed",error:w}).catch(()=>{}),new Error(w,g instanceof Error?{cause:g}:void 0)}finally{await h.close().catch(()=>{})}let v=f.pid;if(!v){let g=await dt("App-server daemon did not expose a child pid.",this.paths.stderrLogPath);throw await x(this.paths.statePath,{...u,status:"failed",error:g}).catch(()=>{}),new Error(g)}let y={...u,status:"starting",pid:v};await x(this.paths.statePath,y),await kr(this.paths.pidPath,`${v}
|
|
14
|
+
`,{encoding:"utf8",mode:384}),await lt(this.paths.pidPath,384).catch(()=>{}),f.once("error",g=>{x(this.paths.statePath,{...y,status:"failed",error:`${L(g)} See app-server stderr at ${this.paths.stderrLogPath}.`}).catch(()=>{})}),f.unref?.();try{await this.waitForReady(i,this.options.startTimeoutMs??ce,Re(y))}catch(g){let w=await this.cleanupFailedStart(v),C=await dt(`${L(g)}${w?"":` Child pid ${v} is still alive after cleanup; its state has been retained.`}`,this.paths.stderrLogPath),M={...y,status:"failed",error:C};throw await x(this.paths.statePath,M).catch(()=>{}),w&&await le(this.paths.pidPath).catch(()=>{}),new Error(C,g instanceof Error?{cause:g}:void 0)}let E=await this.readState(),S=this.readyState({...y,...E.pid===v?E:{},stderrLogPath:this.paths.stderrLogPath});return await x(this.paths.statePath,S),S})}async cleanupFailedStart(e){if(!this.isProcessAlive(e))return!0;try{this.signalProcess(e,"SIGTERM")}catch{}let r=this.options.stopTimeoutMs,n=Math.min(ct,r===void 0||!Number.isFinite(r)?ct:Math.max(0,r));if(await Ee(e,this.isProcessAlive,n))return!0;try{this.signalProcess(e,"SIGKILL")}catch{}return Ee(e,this.isProcessAlive,pt)}async status(){let e=await this.readState();if(e.pid&&de(e,this.isProcessAlive)){let r;try{await this.waitForReady(e.socketPath,250,Re(e)),r=this.readyState(e)}catch(o){r=e.status!=="ready"?e:{...e,status:"failed",error:`Daemon process is alive but app-server is unavailable: ${o instanceof Error?o.message:String(o)}`}}let n=await this.readState();return JSON.stringify(n)===JSON.stringify(e)?r:n}return!e.pid||!de(e,this.isProcessAlive)?e.status==="stopped"||e.status==="failed"?e:{...e,status:"stopped",stoppedAtMs:this.now()}:e}async stop(){return this.withLock(async()=>this.stopLocked(await this.readState()))}async stopLocked(e){if(!e.pid||!de(e,this.isProcessAlive)){let a={...e,status:"stopped",pid:void 0,stoppedAtMs:this.now()};return await x(this.paths.statePath,a),await le(this.paths.pidPath).catch(()=>{}),a}try{await this.waitForReady(e.socketPath,1e3,Re(e))}catch(a){let s=await this.processOwnership(e);if(s==="other"||!this.isProcessAlive(e.pid)){let p={...e,status:"stopped",pid:void 0,stoppedAtMs:this.now(),error:`Cleared stale app-server state without signaling pid ${e.pid}: ${L(a)}`};return await x(this.paths.statePath,p),await le(this.paths.pidPath).catch(()=>{}),p}if(s==="unknown"){let p={...e,status:"failed",error:`Cannot verify ownership of live pid ${e.pid}; retained lifecycle state: ${L(a)}`};return await x(this.paths.statePath,p),p}}let r={...e,status:"stopping"};await x(this.paths.statePath,r);try{this.signalProcess(e.pid,"SIGTERM")}catch(a){let s={...r,status:"failed",error:L(a)};return await x(this.paths.statePath,s),s}let n=this.options.stopTimeoutMs??Er,o=await Ee(e.pid,this.isProcessAlive,n);if(!o){try{this.signalProcess(e.pid,"SIGKILL")}catch{}o=await Ee(e.pid,this.isProcessAlive,Math.min(pt,Math.max(0,n)))}if(!o){let a={...r,status:"failed",error:`Daemon did not stop after SIGTERM and SIGKILL within ${n+Math.min(pt,Math.max(0,n))}ms`};return await x(this.paths.statePath,a),a}let i={...r,status:"stopped",pid:void 0,stoppedAtMs:this.now()};return await x(this.paths.statePath,i),await le(this.paths.pidPath).catch(()=>{}),i}async processOwnership(e){if(!e.pid||!e.instanceId)return"unknown";let r=await(this.options.readProcessCommandLine??(i=>Ne(i,this.options.platform??process.platform)))(e.pid).catch(()=>{});if(!r?.trim())return"unknown";let n=r.trim().split(/\s+/u),o=n.indexOf("--instance-id");return n.length===1&&!n[0]?.includes("/")||n.includes("app-server")&&o<0?"unknown":n.includes("app-server")&&n[o+1]===e.instanceId&&o>=0?"owned":"other"}async restart(){let e=await this.stop();if(e.status!=="stopped")throw new Error(`Cannot restart app-server while daemon is ${e.status}: ${e.error??"stop did not complete."}`);return this.start()}async readState(){try{let e=await jn(this.paths.statePath,"utf8"),r=JSON.parse(e);if(no(r))return{...r,stderrLogPath:r.stderrLogPath??this.paths.stderrLogPath};throw new Error("Invalid or unsupported app-server state schema.")}catch(e){if(!Ue(e))throw new Error(`Cannot read app-server state at ${this.paths.statePath}: ${L(e)}`)}return{schemaVersion:ge,status:"stopped",socketPath:this.paths.socketPath,stderrLogPath:this.paths.stderrLogPath,protocolVersion:O,version:this.options.version,startedAtMs:0}}readyState(e){return{...e,status:"ready",readyAtMs:e.readyAtMs??this.now(),error:void 0}}async withLock(e){let r=Math.max(this.options.startTimeoutMs??ce,this.options.stopTimeoutMs??Er)+ct+1e3;return ae({controlDir:this.paths.controlDir,lockPath:this.paths.lockPath,timeoutMs:this.options.lockTimeoutMs??r,staleAfterMs:st,isProcessAlive:this.isProcessAlive,now:this.now,busyMessage:"Another app-server daemon lifecycle operation is in progress."},e)}};function br(t,e){if((e.authMode??"remote-oauth")!==(t.authMode??"remote-oauth"))throw new N("The running app-server uses another credential authority. Use its existing auth mode or explicitly stop it before switching.","authMode");if(e.region&&e.region!==t.region)throw new N(t.region?`App-server daemon is already running for region ${t.region}; requested ${e.region}.`:`App-server daemon state is missing its region; requested ${e.region}. Stop it before reusing this profile.`,"region");if(e.buildEnv&&e.buildEnv!==t.buildEnv)throw new N(t.buildEnv?`App-server daemon is already running for ${t.buildEnv}; requested ${e.buildEnv}.`:`App-server daemon state is missing its build environment; requested ${e.buildEnv}. Stop it before reusing this profile.`,"buildEnv");if(e.lane!==t.lane)throw new N(`App-server daemon is already running for lane ${t.lane??"default"}; requested ${e.lane??"default"}. Stop it before switching lanes.`,"lane")}function Zn(t,e){if(e&&(!t.launcherPath||$(t.launcherPath)!==$(e)))throw new N("App-server is running from another installation. Stop it before starting the dedicated package.","installation")}function Re(t){return{...t.authMode?{authMode:t.authMode}:{},...t.instanceId?{instanceId:t.instanceId}:{},...t.protocolVersion===void 0?{}:{protocolVersion:t.protocolVersion},version:t.version,...t.region?{region:t.region}:{},...t.buildEnv?{buildEnv:t.buildEnv}:{},...t.lane?{lane:t.lane}:{}}}async function x(t,e){await Tr(Gn(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;await kr(r,`${JSON.stringify(e)}
|
|
15
|
+
`,{encoding:"utf8",mode:384}),await lt(r,384).catch(()=>{}),await Mr(r,t)}function de(t,e){return t.status==="stopped"?!1:!!(t.pid&&e(t.pid))}function eo(t,e){try{process.kill(t,e)}catch(r){if(!so(r))throw r}}async function to(t,e,r={}){let n=Date.now()+Math.max(1,e),o;for(;Date.now()<n;){try{let i=await it(t,Math.min(500,Math.max(1,n-Date.now())));ro(i,r);return}catch(i){o=i}await new Promise(i=>{setTimeout(i,50)})}throw new Error(`App-server did not become ready at ${t} within ${e}ms.`,o===void 0?void 0:{cause:o})}function ro(t,e){for(let r of["authMode","instanceId","protocolVersion","version","region","buildEnv","lane"])if(e[r]!==void 0&&t[r]!==e[r])throw new Error(`App-server health identity mismatch for ${r}: expected ${String(e[r])}, got ${String(t[r])}.`)}async function Ee(t,e,r){let n=Date.now()+Math.max(0,r);for(;e(t)&&Date.now()<n;)await new Promise(o=>{setTimeout(o,50)});return!e(t)}function no(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return e.schemaVersion===ge&&ao(e.status)&&typeof e.socketPath=="string"&&(e.stderrLogPath===void 0||typeof e.stderrLogPath=="string")&&(e.launcherPath===void 0||typeof e.launcherPath=="string")&&(e.releaseKey===void 0||typeof e.releaseKey=="string")&&(e.distributionChannel===void 0||e.distributionChannel==="latest"||e.distributionChannel==="test"||e.distributionChannel==="preview")&&(e.instanceId===void 0||typeof e.instanceId=="string"&&e.instanceId.length>0)&&(e.protocolVersion===void 0||typeof e.protocolVersion=="number"&&Number.isSafeInteger(e.protocolVersion)&&e.protocolVersion>0)&&(e.region===void 0||e.region==="cn"||e.region==="en")&&(e.authMode===void 0||e.authMode==="remote-oauth"||e.authMode==="desktop")&&(e.buildEnv===void 0||e.buildEnv==="dev"||e.buildEnv==="test"||e.buildEnv==="staging"||e.buildEnv==="prod")&&(e.lane===void 0||typeof e.lane=="string"&&e.lane.trim().length>0)&&(e.workspaceDir===void 0||typeof e.workspaceDir=="string"&&e.workspaceDir.trim().length>0)&&typeof e.version=="string"&&typeof e.startedAtMs=="number"&&(e.pid===void 0||typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0)}async function dt(t,e){let r=await io(e);return r?`${t}
|
|
16
|
+
App-server stderr (${e}):
|
|
17
|
+
${r}`:`${t} See app-server stderr at ${e}.`}async function oo(t,e,r){let n=0;try{n=(await Wn(t)).size}catch(o){if(!Ue(o))throw o;return}if(!(n<e))for(let o=r;o>=1;o-=1){let i=o===1?t:`${t}.${o-1}`,a=`${t}.${o}`;await le(a).catch(s=>{if(!Ue(s))throw s}),await Mr(i,a).catch(s=>{if(!Ue(s))throw s})}}async function io(t){let e;try{e=await xr(t,"r");let r=await e.stat();if(r.size<=0)return;let n=Math.min(r.size,Yn),o=Buffer.alloc(n),{bytesRead:i}=await e.read(o,0,n,r.size-n);return o.subarray(0,i).toString("utf8").trim()||void 0}catch{return}finally{await e?.close().catch(()=>{})}}function ao(t){return t==="starting"||t==="ready"||t==="stopping"||t==="stopped"||t==="failed"}function so(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ESRCH"}function Ue(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}import{randomUUID as zr}from"node:crypto";import{realpathSync as Br}from"node:fs";import{spawn as mo}from"node:child_process";import{chmod as fo,mkdir as jr,open as vo,readFile as Hr,rename as Wr,stat as yo,unlink as Te,writeFile as vt}from"node:fs/promises";import{dirname as So,join as ee,resolve as be}from"node:path";import{lstatSync as ht}from"node:fs";import{cp as lo,realpath as Lr,rm as uo}from"node:fs/promises";import F from"node:path";import{existsSync as po,readFileSync as Ir,realpathSync as Dr}from"node:fs";import Ve from"node:path";var co=/^[0-9A-Za-z][0-9A-Za-z._-]*$/u;function ut(t=process.argv[1],e=process.platform){let r=Ot(t,e,process.execPath,{requireVersionedLayout:!0});if(!r)return;let n=e==="win32"?Ve.win32:Ve.posix,o=n.join(r.prefix,"current"),i=Or(o);if(!i)return;let a=n.join(r.prefix,"releases",i),s=e==="win32"?n.join(r.prefix,"mcode.cmd"):n.join(r.prefix,"bin","mcode");if(!po(s))return;let p;try{p=he(a,r.packageName,e)}catch{return}return{prefix:r.prefix,launcherPath:s,currentFile:o,releaseKey:i,releasePrefix:a,entryFile:n.join(p.packageRoot,p.binEntry),packageName:r.packageName,version:p.version,npmExecutable:r.executable,runtimeExecutable:r.nodeExecutable??process.execPath,registry:r.registry,distTag:r.distTag??"latest"}}function Cr(t,e=process.platform){let r=e==="win32"?Ve.win32:Ve.posix;try{let n=JSON.parse(Ir(r.join(t,"install.json"),"utf8"));if(n.packageName!=="@minimax-ai/code"&&n.packageName!=="@minimax-ai/code")return;let o=Or(r.join(t,"current"));if(!o)return;let i=he(r.join(t,"releases",o),n.packageName,e),a=ut(r.join(i.packageRoot,i.binEntry),e);return a&&Dr(a.prefix)===Dr(t)?a:void 0}catch{return}}function Or(t){try{let e=Ir(t,"utf8").trim();return co.test(e)?e:void 0}catch{return}}function Fe(t){return F.join(F.resolve(t),"packages","app-server-daemon")}function Z(t,e=process.platform){let r=Fe(t);if(Nr(F.dirname(r)),Nr(r),!ht(F.join(r,"current"),{throwIfNoEntry:!1})){if(ht(F.join(r,"install.json"),{throwIfNoEntry:!1}))throw new Error("The app-server package selection is missing; repair its installation.");return}let n=Cr(r,e);if(!n)throw new Error("The app-server package is incomplete; repair its installation.");return Kt({...n,activePrefix:r},n.releaseKey,e),n}async function Vr(t,e,r=process.platform){if(r==="win32")throw new Error("The app-server daemon requires a Unix-like remote host.");let n=Fe(t),o=Z(t,r);return o||!e?o:(Fr(F.resolve(e.prefix),n),await Y(F.dirname(n),{repairPermissions:!0}),await Y(n,{repairPermissions:!0}),ae({controlDir:n,lockPath:F.join(n,"prepare.lock"),timeoutMs:6e4,isProcessAlive:se,busyMessage:"Another app-server package installation is in progress."},async()=>{let i=Z(t,r);return i||ho(t,n,e,r)}))}async function ho(t,e,r,n){let[o,i]=await Promise.all([Lr(e),Lr(r.prefix)]);Fr(i,o);let a=Bt(e,r.version,n),s=ke(e);try{await lo(r.releasePrefix,a,{recursive:!0,dereference:!0});let p=he(a,r.packageName,n);await Me(a,p,r.runtimeExecutable,r.version),Ht({...r,stagingPrefix:a,activePrefix:e,expectedVersion:r.version},n);let c=Z(t,n);if(!c)throw new Error("The app-server package could not be activated.");return c}finally{try{await uo(a,{recursive:!0,force:!0})}finally{s()}}}function Nr(t){let e=ht(t,{throwIfNoEntry:!1});if(e&&!e.isDirectory())throw new Error(`App-server package directory must be a real directory: ${t}`)}function Ur(t,e){let r=F.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${F.sep}`)&&!F.isAbsolute(r)}function Fr(t,e){if(Ur(t,e)||Ur(e,t))throw new Error("The app-server package directory must be separate from the CLI installation.")}var go=5*6e4,mt=60*6e4,ft=5e3,$r=1e4,Ao=1e4,Po=6e4,wo=8*1024*1024,Ro=3,Eo=1440*6e4,bo=2*6e4,To=30*6e4;function Gr(t){let e=Q(t).controlDir;return{controlDir:e,statePath:ee(e,"app-server-updater.state.json"),pidPath:ee(e,"app-server-updater.pid"),stopRequestPath:ee(e,"app-server-updater.stop.json"),lockPath:ee(e,"app-server-updater.lock"),stderrLogPath:ee(e,"app-server-updater.stderr.log")}}var xe=class{constructor(e){this.options=e;this.paths=Gr(e.dataDir),this.now=e.now??Date.now,this.spawn=e.spawn??((r,n,o)=>mo(r,n,o)),this.isProcessAlive=e.isProcessAlive??se,this.isUpdaterProcess=e.isUpdaterProcess??((r,n,o)=>Io(r,n,e.platform??process.platform,o)),this.resolveInstallation=e.resolveInstallation??Z,this.prepareRestart=e.prepareRestart??we}paths;now;spawn;isProcessAlive;isUpdaterProcess;resolveInstallation;prepareRestart;async start(){let e=this.options.installation;if(!e||!this.isDedicatedInstallation(e))throw new Error("The updater requires the dedicated app-server installation.");return this.withLifecycleLock(async()=>{let r=await this.readState();if(await this.hasLiveUpdaterOwner(r)){if(!r.pid||!await this.isUpdaterProcess(r.pid,r.generation,e.prefix))throw new N("App-server updater is running from another installation. Stop it before starting the dedicated package.","installation");return r}return this.spawnGeneration(e)})}async stop(){return this.withLifecycleLock(()=>this.stopUnlocked())}async stopUnlocked(){let e=await this.readState(),r=e.pid;if(!r||!await this.hasLiveUpdaterOwner(e)){let i={...e,status:"stopped",pid:void 0};return await this.writeState(i),await Te(this.paths.pidPath).catch(()=>{}),i}await Kr(this.paths.stopRequestPath,{generation:e.generation});let n=Date.now()+Ao;for(;Date.now()<n&&this.isProcessAlive(r);){let i=await this.readState();if(i.generation===e.generation&&i.status==="stopped")return i;await yt(100)}if(!this.isProcessAlive(r)){let i={...e,status:"stopped",pid:void 0};return await this.writeState(i),await Te(this.paths.pidPath).catch(()=>{}),i}let o={...e,status:"failed",error:"Updater did not acknowledge its generation-scoped stop request."};return await this.writeState(o),o}async status(){let e=await this.readState(),r=e.status!=="stopped"&&!await this.hasLiveUpdaterOwner(e)?{...e,status:"stopped",pid:void 0}:e,n=await this.readState();return JSON.stringify(n)===JSON.stringify(e)?r:n}async runLoop(e,r){let n=await this.readState();if(n.generation!==e)throw new Error("Updater generation does not own the current state file.");n={...n,status:"running",pid:process.pid,heartbeatAtMs:this.now(),error:void 0},await this.writeState(n),await vt(this.paths.pidPath,`${process.pid}
|
|
18
|
+
`,{encoding:"utf8",mode:384}),await fo(this.paths.pidPath,384).catch(()=>{});let o=new AbortController,i=r?AbortSignal.any([r,o.signal]):o.signal,a=this.options.initialDelayMs??go;try{for(;;){if(await this.waitOrStop(e,a,i))return;let p=setInterval(()=>{this.stopRequested(e).then(l=>{l&&o.abort()})},250),c;try{c=await this.updateOnce(e,i)}finally{clearInterval(p)}if(i.aborted||c==="replaced")return;a=c==="retry"?this.options.retryMs??ft:this.options.intervalMs??mt}}finally{let s=await this.readState();s.generation===e&&(await this.writeState({...s,status:"stopped",pid:void 0,heartbeatAtMs:this.now()}),await Te(this.paths.pidPath).catch(()=>{}),await Te(this.paths.stopRequestPath).catch(()=>{}))}}async updateOnce(e,r){let n=this.now(),o;try{o=this.resolveCurrentInstallation()}catch(a){return await this.recordFailure(e,n,L(a)),"continue"}if(!o)return await this.recordFailure(e,n,"Formal MCode installation is unavailable."),"continue";await this.patchOwnedState(e,{status:"checking",heartbeatAtMs:n,lastCheckAtMs:n,activeVersion:o.version,activeReleaseKey:o.releaseKey,channel:o.distTag,failure:void 0,error:void 0});let i=!1;try{let a=this.options.createUpdateApplication?.(o)??new zt({currentVersion:o.version,packageTag:o.distTag,packageName:o.packageName,entryFile:o.entryFile,platform:this.options.platform??process.platform,prefixInstall:{executable:o.npmExecutable,packageName:o.packageName,prefix:o.prefix,registry:o.registry,distTag:o.distTag,nodeExecutable:o.runtimeExecutable}},{validatePrefixPackage:async(f,v,y,E)=>{await Me(f,v,o.runtimeExecutable,y,E),await Lt(f,o.runtimeExecutable,[ee(v.packageRoot,v.binEntry),"app-server","--help"],"app-server",S=>/^Usage: \S+ app-server\b/mu.test(S)&&S.includes("--listen")&&S.includes("--auth-mode"),E)}}),s=await a.inspect({signal:r});if(He(r),s.kind==="package-manager")await a.apply(s,{signal:r});else if(s.kind==="available")await a.apply(s,{signal:r});else if(s.kind==="manual")throw new Error("Formal install was classified as unmanaged.");He(r);let p=this.resolveCurrentInstallation();if(!p)throw new Error("Updated formal MCode installation could not be validated.");let c=await this.readState(),l=p.releaseKey!==o.releaseKey?o.releaseKey:c.previousReleaseKey;i=!0;let u=await this.refreshRunningServer(o,p,l,async()=>r?.aborted===!0||await this.stopRequested(e));if(u.status==="busy"){let f=await this.daemonFor(p).status(),v=c.targetReleaseKey===p.releaseKey&&c.blockedSinceMs?c.blockedSinceMs:this.now();return await this.patchOwnedState(e,{status:"pending-restart",heartbeatAtMs:this.now(),activeVersion:p.version,activeReleaseKey:p.releaseKey,previousReleaseKey:l,targetVersion:p.version,targetReleaseKey:p.releaseKey,runningServerVersion:f.version,activeRequestCount:u.activeRequestCount,activeTurnCount:u.activeTurnCount,pendingAdmissionCount:u.pendingAdmissionCount,blockedSinceMs:v,...this.now()-v>=Eo?{warning:"MCode update has remained blocked by active client or Runtime work for more than 24 hours."}:{warning:void 0},nextCheckAtMs:this.now()+(this.options.retryMs??ft)}),"retry"}let h=this.now();return await this.patchOwnedState(e,{status:"running",heartbeatAtMs:h,lastSuccessAtMs:h,activeVersion:p.version,activeReleaseKey:p.releaseKey,previousReleaseKey:l,targetVersion:void 0,targetReleaseKey:void 0,runningServerVersion:u.status==="stopped"?void 0:p.version,nextCheckAtMs:h+(this.options.intervalMs??mt),blockedSinceMs:void 0,activeRequestCount:void 0,activeTurnCount:void 0,pendingAdmissionCount:void 0,warning:void 0,failure:void 0,error:void 0}),r?.aborted||await this.stopRequested(e)?"continue":p.releaseKey!==this.options.installation?.releaseKey?(await this.spawnGeneration(p),"replaced"):"continue"}catch(a){return Ct(a)&&r?.aborted?"continue":(await this.recordFailure(e,n,L(a),i),i?"retry":"continue")}}async refreshRunningServer(e,r,n,o){let i=this.daemonFor(r),a=await i.status();if(a.status==="stopped")return{status:"stopped"};if(a.status==="failed")return await o()?{status:"stopped"}:{status:"restarted",runningReleaseKey:(await i.start()).releaseKey??r.releaseKey};if(a.status!=="ready")throw new Error(a.error??`App-server is ${a.status}.`);if(a.version===r.version)return{status:"current",runningReleaseKey:a.releaseKey??r.releaseKey};if(await o())return{status:"stopped"};let s=await this.prepareRestart(a.socketPath,$r);if(!s.ready)return{status:"busy",activeRequestCount:s.activeRequestCount,activeTurnCount:s.activeTurnCount,pendingAdmissionCount:s.pendingAdmissionCount};if(!await Mo(i,Po))throw new Error("App-server accepted restart but did not exit within the grace period.");if(await o())return{status:"stopped"};try{return{status:"restarted",runningReleaseKey:(await i.start()).releaseKey??r.releaseKey}}catch(c){let l=a.releaseKey??n??(e.releaseKey!==r.releaseKey?e.releaseKey:void 0);if(!l||l===r.releaseKey)throw c;let u=this.activateRollbackRelease(r,l);if(u&&!await o())try{await this.daemonFor(u).start()}catch(h){throw new Error(`Failed to start MCode ${r.version}; restored ${u.version}, but failed to restart it: ${L(h)}.`,{cause:new AggregateError([c,h])})}throw new Error(`Failed to start MCode ${r.version}; restored ${u?.version??l}.`,{cause:c})}}daemonFor(e){return this.options.createDaemonController?this.options.createDaemonController(e):new X({authMode:this.options.authMode??"remote-oauth",dataDir:this.options.dataDir,version:e.version,launcherPath:e.launcherPath,releaseKey:e.releaseKey,distributionChannel:e.distTag,...this.options.workspaceDir?{workspaceDir:this.options.workspaceDir}:{},...this.options.socketPath?{socketPath:this.options.socketPath}:{},...this.options.daemonStatePath?{statePath:this.options.daemonStatePath}:{},...this.options.region?{region:this.options.region}:{},...this.options.buildEnv?{buildEnv:this.options.buildEnv}:{},...this.options.lane?{lane:this.options.lane}:{},platform:this.options.platform??process.platform})}activateRollbackRelease(e,r){let n=ke(e.prefix);try{let o=this.resolveCurrentInstallation();if(!o||o.prefix!==e.prefix)throw new Error("Formal MCode installation changed before rollback.");if(o.releaseKey!==e.releaseKey)throw new Error(`MCode current release changed from ${e.releaseKey} to ${o.releaseKey}; refusing to overwrite a concurrent update.`);return $t(xo(o),r,this.options.platform??process.platform),this.resolveCurrentInstallation()}finally{n()}}isDedicatedInstallation(e){let r=Fe(this.options.dataDir);return be(e.prefix)===r?!0:Br(e.prefix)===Br(r)}resolveCurrentInstallation(){let e=this.resolveInstallation(this.options.dataDir,this.options.platform??process.platform);if(e&&!this.isDedicatedInstallation(e))throw new Error("The updater cannot modify an installation outside its app-server profile.");return e}async hasLiveUpdaterOwner(e){if(!e.pid||!Do(e.status)||!this.isProcessAlive(e.pid))return!1;let r=e.status==="checking"?To:bo;return this.now()-e.heartbeatAtMs>r?!1:this.isUpdaterProcess(e.pid,e.generation)}async spawnGeneration(e){await jr(this.paths.controlDir,{recursive:!0,mode:448}),await ko(this.paths.stderrLogPath);let r=zr(),n=this.now(),o=await this.readState(),i=[...this.options.lane?["--lane",this.options.lane]:[],"app-server","daemon","update-loop","--data-dir",be(this.options.dataDir),...this.options.workspaceDir?["--workspace",be(this.options.workspaceDir)]:[],...this.options.region?["--region",this.options.region==="cn"?"cn":"global"]:[],"--auth-mode",this.options.authMode??"remote-oauth",...this.options.socketPath?["--sock",be(this.options.socketPath)]:[],...this.options.daemonStatePath?["--state-file",be(this.options.daemonStatePath)]:[],"--updater-generation",r],a={schemaVersion:1,status:"starting",generation:r,activeVersion:e.version,activeReleaseKey:e.releaseKey,...o.previousReleaseKey?{previousReleaseKey:o.previousReleaseKey}:{},channel:e.distTag,startedAtMs:n,heartbeatAtMs:n};await this.writeState(a);let s=await vo(this.paths.stderrLogPath,"a",384),p;try{p=this.spawn(e.launcherPath,i,{cwd:this.paths.controlDir,detached:!0,stdio:["ignore","ignore",s.fd],windowsHide:!0})}finally{await s.close().catch(()=>{})}if(!p.pid)throw new Error("App-server updater did not expose a child pid.");let c=await this.readState(),l={...a,pid:p.pid};return c.generation===r&&(l={...c,pid:p.pid},await this.writeState(l)),await vt(this.paths.pidPath,`${p.pid}
|
|
19
|
+
`,{encoding:"utf8",mode:384}),p.unref?.(),l}async withLifecycleLock(e){return ae({controlDir:this.paths.controlDir,lockPath:this.paths.lockPath,timeoutMs:$r,isProcessAlive:this.isProcessAlive,now:this.now,busyMessage:"Another app-server updater lifecycle operation is in progress."},e)}async waitOrStop(e,r,n){let o=Date.now()+Math.max(0,r),i=Date.now();for(;Date.now()<o;){if(n?.aborted||await this.stopRequested(e)||(await this.readState()).generation!==e)return!0;Date.now()>=i&&(await this.patchOwnedState(e,{heartbeatAtMs:this.now()}),i=Date.now()+3e4),await yt(Math.min(1e3,Math.max(1,o-Date.now())))}return n?.aborted===!0||await this.stopRequested(e)}async stopRequested(e){try{return JSON.parse(await Hr(this.paths.stopRequestPath,"utf8")).generation===e}catch{return!1}}async recordFailure(e,r,n,o=!1){let i=Co(n),a;try{a=this.resolveCurrentInstallation()}catch{}await this.patchOwnedState(e,{status:"failed",heartbeatAtMs:this.now(),lastCheckAtMs:r,nextCheckAtMs:this.now()+(o?this.options.retryMs??ft:this.options.intervalMs??mt),...a?{activeVersion:a.version,activeReleaseKey:a.releaseKey}:{},failure:i,error:n})}async patchOwnedState(e,r){let n=await this.readState();n.generation===e&&await this.writeState({...n,...r})}async readState(){try{let r=JSON.parse(await Hr(this.paths.statePath,"utf8"));if(_o(r))return r}catch{}let e=this.now();return{schemaVersion:1,status:"stopped",generation:"none",activeVersion:this.options.installation?.version??"unknown",activeReleaseKey:this.options.installation?.releaseKey??"unknown",channel:this.options.installation?.distTag??"latest",startedAtMs:0,heartbeatAtMs:e}}writeState(e){return Kr(this.paths.statePath,e)}};function xo(t){return{activePrefix:t.prefix,packageName:t.packageName,runtimeExecutable:t.runtimeExecutable,npmExecutable:t.npmExecutable,registry:t.registry,distTag:t.distTag}}async function Mo(t,e){let r=Date.now()+e;for(;Date.now()<r;){if((await t.status()).status==="stopped")return!0;await yt(100)}return(await t.status()).status==="stopped"}async function Kr(t,e){await jr(So(t),{recursive:!0,mode:448});let r=`${t}.${process.pid}.${zr()}.tmp`;await vt(r,`${JSON.stringify(e)}
|
|
20
|
+
`,{encoding:"utf8",mode:384}),await Wr(r,t)}async function ko(t){let e=0;try{e=(await yo(t)).size}catch{return}if(!(e<wo))for(let r=Ro;r>=1;r-=1){let n=r===1?t:`${t}.${r-1}`,o=`${t}.${r}`;await Te(o).catch(()=>{}),await Wr(n,o).catch(()=>{})}}function _o(t){if(!t||typeof t!="object")return!1;let e=t;return e.schemaVersion===1&&typeof e.generation=="string"&&typeof e.activeVersion=="string"&&typeof e.activeReleaseKey=="string"&&(e.channel==="latest"||e.channel==="test"||e.channel==="preview")&&typeof e.startedAtMs=="number"&&typeof e.heartbeatAtMs=="number"&&typeof e.status=="string"}function Do(t){return t!=="stopped"}async function Io(t,e,r,n){let o=await Ne(t,r);return o!==void 0&&o.includes(`--updater-generation ${e}`)&&(!n||o.includes(` ${ee(n,"releases")}/`))}function yt(t){return new Promise(e=>setTimeout(e,t))}function Co(t){let e=t.toLocaleLowerCase();return{code:"managedUpdateUnavailable",reason:e.includes("enospc")||e.includes("no space left")?"diskFull":e.includes("enoent")&&e.includes("npm")?"noNpm":/\b(econnreset|econnrefused|enotfound|etimedout|network|fetch failed)\b/u.test(e)?"network":"unknown",message:t}}import{realpath as Oo}from"node:fs/promises";import{arch as Lo,homedir as No,release as Uo,userInfo as Vo}from"node:os";async function qr(t,e){let r;try{r=Vo().username}catch{}let n=Uo(),o=process.env.WSL_DISTRO_NAME,i=e==="linux"&&(!!o||/microsoft/i.test(n));return{platformFamily:e==="win32"?"windows":"unix",platformOs:e,arch:Lo(),...r?{userName:r}:{},homeDir:No(),dataDir:await Oo(t),...i?{wsl:{...o?{distribution:o}:{},kernelRelease:n}}:{}}}import{randomUUID as Jr}from"node:crypto";var Be=class{constructor(e=Date.now){this.now=e}context;userID;rejectedAccessToken;generation=0;loginEpoch=Jr();listeners=new Set;apply(e){if(e.authState==="authenticated"){if(this.userID&&this.userID!==e.realUserID)throw new Error("This app-server is bound to another Desktop account. Use a separate profile or explicitly restart it.");this.userID=e.realUserID}e.authState==="logged_out"&&this.context?.authState!=="logged_out"&&(this.loginEpoch=Jr());let r=Fo(e);this.context={...e,expiresAtMs:r},this.generation+=1,this.publish()}getAuthContext(){if(!this.context||this.isRejected())return;let e={...this.context,loginEpoch:this.loginEpoch};return delete e.expiresAtMs,e}invalidate(e,r){if(r!==void 0&&r!==this.loginEpoch)return;let n=e?.trim();n&&this.context?.accessToken!==n||(this.rejectedAccessToken=this.context?.accessToken??this.rejectedAccessToken,this.context=void 0,this.generation+=1,this.publish())}async getStatus(){return this.snapshot()}async getAccessToken(e){let r=this.context;if(this.snapshot().status!=="authenticated"||!r?.accessToken||!r.expiresAtMs||r.expiresAtMs-this.now()<=e)throw new Gt("AUTH_REQUIRED");return{accessToken:r.accessToken,expiresAtMs:r.expiresAtMs,generation:this.generation,scopes:["agent.default"],audience:"agent-backend"}}async handleUnauthorized(e){return e<this.generation&&this.snapshot().status==="authenticated"?"retry":(e===this.generation&&this.invalidate(),"logout")}watch(e){return this.listeners.add(e),e(this.snapshot()),()=>this.listeners.delete(e)}isRejected(){return!!(this.context?.accessToken&&this.context.accessToken===this.rejectedAccessToken)}snapshot(){let e=this.context;return!e||e.authState==="logged_out"||this.isRejected()?{status:"anonymous",generation:this.generation}:e.authState==="pending"?{status:"authorizing",generation:this.generation}:{status:e.expiresAtMs&&e.expiresAtMs>this.now()?"authenticated":"expired",generation:this.generation,...e.expiresAtMs?{expiresAtMs:e.expiresAtMs}:{}}}publish(){let e=this.snapshot();for(let r of this.listeners)r(e)}};function Fo(t){let e=Yr(t.expiresAtMs),r,n=t.accessToken?.split(".");if(n?.length===3&&n[1])try{let o=JSON.parse(Buffer.from(n[1],"base64url").toString("utf8"));o&&typeof o=="object"&&"exp"in o&&typeof o.exp=="number"&&(r=Yr(o.exp*1e3))}catch{}return e&&r?Math.min(e,r):e??r}function Yr(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?t:void 0}async function Hs(t,e,r={}){let n=r.processRef??Yo();if(t.mode==="proxy"){let s=t.dataDir?B(t.dataDir):Nt(),p=Q(s,t.socketPath?B(t.socketPath):void 0);await(r.runProxy??ot)({socketPath:p.socketPath,input:n.stdin,output:n.stdout});return}let o=t.dataDir?B(t.dataDir):await(r.prepareDataDir??Ut)(),i;if((t.dataDir||t.region)&&(i=(r.configureRuntimeEnvironment??It)({dataDir:o,...t.region?{runtimeRegion:t.region}:{}}),(r.resetRuntimeConfig??_t)()),i??=Dt({runtimeRegion:Mt(),runtimeBuildEnv:kt()}),t.mode==="daemon"){try{await zo(t,e,o,t.workspaceDir?B(t.workspaceDir):void 0,i,n,r)}catch(s){if(s instanceof me)throw s;let p=t.daemonAction??"status";throw p==="update-loop"?s:jo(p,s)}return}let a=B(t.workspaceDir??process.cwd());await Ko(t,e,o,a,i,n,r)}async function Ko(t,e,r,n,o,i,a){await $o(r,{recursive:!0});let s=Go(t.listen,r);if(s.kind==="unix"&&i.platform==="win32")throw new Error("The app-server Unix transport requires a Unix-like remote host.");let p=qo(i.stderr),c=new AbortController,l,u,h=()=>{if(l){c.abort(new Error("App-server process stop was forced."));return}l=(async()=>{let R=u?.host.cliService?.beginProcessDrain();R?.accepted&&await R.idle,c.abort(new Error("App-server process is stopping."))})().catch(R=>c.abort(R))};i.once("SIGINT",h),i.once("SIGTERM",h),i.once("SIGHUP",h);let f=t.authMode==="desktop",v=f?new Be:void 0,y=async R=>{if(!v)throw new Error("This profile uses remote OAuth.");v.apply(R);let d=await v.getStatus();i.stderr.write(`[app-server] Desktop auth projected status=${d.status} generation=${d.generation}
|
|
21
|
+
`),R.authState==="authenticated"&&!d.expiresAtMs&&console.warn("[app-server] Desktop token expiry unavailable; update Desktop to enable mcode-tools OAuth leases."),await u?.host.notifyAuthContextChanged?.(R.authState)},E,S,g,w=Promise.resolve(),C=0,M=t.statePath?B(t.statePath):void 0,b=Date.now(),te=t.instanceId??Ho(),H={authMode:t.authMode??"remote-oauth",instanceId:te,protocolVersion:O,version:e,region:o.region,buildEnv:o.buildEnv,...t.lane?{lane:t.lane}:{}};try{let R=await qr(r,i.platform),d=a.createRuntime&&a.shutdownRuntime?{createTuiRuntime:a.createRuntime,shutdownTuiRuntime:a.shutdownRuntime}:await(a.loadRuntimeLifecycle??(()=>import("./lifecycle-VXPE5MII.js")))(),m=f?void 0:(a.createSharedAuthSession??Ft)({dataDir:r,region:o.region,buildEnv:o.buildEnv,oauthEndpoints:Rt(process.env,o)});if(S=m?(a.createRemoteAuthModule??(P=>new Pe(P)))({auth:bt(m),region:o.region,buildEnv:o.buildEnv}):void 0,u=await(a.createRuntime??d.createTuiRuntime)({dataDir:r,workspaceDir:n,version:e,surface:"app-server",runtimeOwnerKind:"app-server",...t.lane?{lane:t.lane}:{},startupExecutionPolicy:s.kind==="unix"?"enabled":"quarantined",...v?{authContextGetter:()=>v.getAuthContext(),authContextInvalidator:(P,U)=>v.invalidate(P,U),mcodeToolsAuthSession:v}:{}},m?{sharedAuthCore:m}:{}),S){let P;g=S.subscribe(U=>{if(U.method!=="account/updated")return;let{state:D,generation:ue}=U.params;if(!["authenticated","login_required","reauthentication_required"].includes(D))return;let gt=`${D}:${ue}`;if(P===gt)return;P=gt;let At=++C,Pt=D==="authenticated"?"authenticated":"logged_out";w=w.then(async()=>{At!==C||!u||(await u.synchronizeAuthContext(Pt),At===C&&(await u.host.notifyAuthContextChanged?.(Pt),i.stderr.write(`[app-server] Remote auth status=${D} generation=${ue}
|
|
22
|
+
`)))}).catch(()=>{P=void 0,i.stderr.write(`[app-server] Remote auth context update failed; credentials remain managed by OAuth Core.
|
|
23
|
+
`)})})}let A=u.host.apiHost.handleRequest.bind(u.host.apiHost),k=async()=>{let P=u?.host.cliService?.tryBeginProcessDrainIfIdle();return P?(P.accepted&&setImmediate(()=>c.abort(new Error("App-server accepted a managed restart."))),{ready:P.accepted,activeTurnCount:P.activeTurnCount,pendingAdmissionCount:P.pendingAdmissionCount}):{ready:!1,activeTurnCount:0,pendingAdmissionCount:0}};if(s.kind==="stdio"){await(a.serveStdio??nt)({handleRequest:A,version:e,workspaceDir:n,hostIdentity:H,environment:R,remoteAuth:S,prepareRestart:k,input:i.stdin,output:i.stdout,signal:c.signal,...f?{onRuntimeAuthContext:y}:{}});return}M&&await St(a.writeState??x,M,{schemaVersion:1,status:"starting",pid:process.pid,socketPath:s.socketPath,...H,workspaceDir:n,version:e,startedAtMs:b}),E=await(a.createUnixServer??rt)({socketPath:s.socketPath,handleRequest:A,version:e,workspaceDir:n,remoteAuth:S,serverIdentity:H,environment:R,prepareRestart:k,platform:i.platform,...f?{onRuntimeAuthContext:y}:{},onReady:async()=>{M&&await St(a.writeState??x,M,{schemaVersion:1,status:"ready",pid:process.pid,socketPath:s.socketPath,...H,workspaceDir:n,version:e,startedAtMs:b,readyAtMs:Date.now()})}}),await Wo(E,c.signal)}finally{if(g?.(),C+=1,await w,E&&await E.close().catch(()=>{}),S)try{await S.close()}catch(R){console.error("Failed to close app-server authentication cleanly.",R)}u&&await(a.shutdownRuntime??qt)(u),M&&await St(a.writeState??x,M,{schemaVersion:1,status:"stopped",socketPath:E?.socketPath??(s.kind==="unix"?s.socketPath:""),...H,workspaceDir:n,version:e,startedAtMs:b,stoppedAtMs:Date.now()}).catch(()=>{}),i.off("SIGINT",h),i.off("SIGTERM",h),i.off("SIGHUP",h),p()}}async function zo(t,e,r,n,o,i,a){let s=t.daemonAction??"status",p=s==="bootstrap"||s==="start"||s==="restart",c=a.resolveOfficialInstallation??ut,l;if(p?l=await(a.prepareServerInstallation??Vr)(r,c(i.argv[1],i.platform),i.platform):s!=="stop"&&(l=(a.resolveServerInstallation??Z)(r,i.platform)),(s==="bootstrap"||s==="start"||s==="restart"||s==="update-loop")&&!l)throw s==="update-loop"?new Error("The internal updater loop requires a formal installation."):new me({action:s,code:"appServerInstallationRequired",message:"A complete schema-v2 MCode installation is required to initialize the app-server package. Install MCode with the official installer, then retry.",recommendedAction:"installRemoteCli"});let u=new X({authMode:t.authMode??"remote-oauth",dataDir:r,version:l?.version??e,region:o.region,buildEnv:o.buildEnv,...t.lane?{lane:t.lane}:{},...n?{workspaceDir:n}:{},...t.socketPath?{socketPath:B(t.socketPath)}:{},...t.statePath?{statePath:t.statePath}:{},...l?{launcherPath:l.launcherPath,releaseKey:l.releaseKey,distributionChannel:l.distTag}:{},...i.execArgv?{execArgv:i.execArgv}:{},platform:i.platform}),h=a.managedUpdaterEnabled??!0,f=new xe({authMode:t.authMode??"remote-oauth",dataDir:r,installation:l,...n?{workspaceDir:n}:{},...t.socketPath?{socketPath:B(t.socketPath)}:{},...t.statePath?{daemonStatePath:B(t.statePath)}:{},region:o.region,buildEnv:o.buildEnv,...t.lane?{lane:t.lane}:{},platform:i.platform});if(s==="update-loop"){if(!l||!t.updaterGeneration)throw new Error("The internal updater loop requires a formal install and generation.");let E=new AbortController,S=()=>E.abort();i.once("SIGINT",S),i.once("SIGTERM",S),i.once("SIGHUP",S);try{await f.runLoop(t.updaterGeneration,E.signal)}finally{i.off("SIGINT",S),i.off("SIGTERM",S),i.off("SIGHUP",S)}return}let v,y;switch(s){case"bootstrap":v=await u.bootstrap(),y=h?await f.start():await f.status();break;case"start":v=await u.start(),y=h?await f.start():await f.status();break;case"stop":y=await Xr(f),v=await u.stop();break;case"restart":await Xr(f),v=await u.restart(),y=h?await f.start():await f.status();break;case"status":v=await u.status(),y=await f.status();break;case"version":v={schemaVersion:1,status:"stopped",socketPath:u.paths.socketPath,stderrLogPath:u.paths.stderrLogPath,...l?{launcherPath:l.launcherPath,releaseKey:l.releaseKey,distributionChannel:l.distTag}:{},protocolVersion:O,region:o.region,buildEnv:o.buildEnv,...t.lane?{lane:t.lane}:{},version:l?.version??e,startedAtMs:0},y=await f.status();break}(a.output??Jo)(i,`${JSON.stringify({action:s,state:v,...y?{updater:y}:{}})}
|
|
24
|
+
`)}async function Xr(t){let e=await t.stop();if(e.status!=="stopped")throw new Error(e.error??"The updater has not stopped; retry before changing the server process.");return e}function jo(t,e){let r=e instanceof Error?e.message:String(e);return e instanceof N?new me({action:t,code:"appServerProfileMismatch",message:r,recommendedAction:"stopRemoteDaemon",cause:e}):new me({action:t,code:"appServerDaemonCommandFailed",message:r,recommendedAction:"inspectRemoteLogs",cause:e})}async function Wo(t,e){e.aborted||await new Promise(r=>{let n=()=>{e.removeEventListener("abort",n),r()};e.addEventListener("abort",n,{once:!0}),t.closed.then(n)})}async function St(t,e,r){await t(e,r)}function Go(t,e){if(!t||t==="stdio"||t==="stdio://")return{kind:"stdio"};if(!t.startsWith("unix://"))throw new Error(`Unsupported app-server listen URI: ${t}. Use stdio:// or unix:///path.`);let r=decodeURIComponent(t.slice(7));if(!r){if(!e)throw new Error("unix:// requires a socket path or data directory.");return{kind:"unix",socketPath:Q(B(e)).socketPath}}return{kind:"unix",socketPath:B(r)}}function qo(t){let e=globalThis.console;return globalThis.console=new Bo({stdout:t,stderr:t}),()=>{globalThis.console=e}}function Jo(t,e){t.stdout.write(e)}function Yo(){return process}export{Hs as runAppServerCommand};
|
|
@@ -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 Je,
|
|
2
|
+
import{a as Je,h as ze,i as Xe}from"./chunk-5ADYFF2U.js";import"./chunk-4ESEMCSG.js";import"./chunk-EFVDRFCG.js";import{a as je,b as Ne,d as $e,e as ae,f as Ue,g as Le,h as q}from"./chunk-I7MLO7YD.js";import{b as qe,c as ce,d as He,e as Ve,h as We,k as Be}from"./chunk-KGAIRLNO.js";import{a as j,b as y,c as ke,d as L,f as Me,k as Ae}from"./chunk-NJVLEZ3I.js";import"./chunk-25R53L7J.js";import{r as At}from"./chunk-47KWM23C.js";import{c as Fe,q as ue}from"./chunk-2BNOPHYG.js";import"./chunk-I5CQQ3J6.js";import{e as Oe,f as Ce,g as ie,h as O,i as _e}from"./chunk-52LBQEEC.js";import{a as Pe}from"./chunk-PRXIML4F.js";import"./chunk-PPIEC7ZM.js";import"./chunk-FKQFVOLR.js";import"./chunk-G3BYCHZS.js";import"./chunk-75PL5LYJ.js";import"./chunk-VYI2WX6B.js";import"./chunk-ONRKFD6S.js";import"./chunk-ZPSMBMGA.js";import{a as De}from"./chunk-OHWTK4KK.js";import{a as Ge}from"./chunk-SLFKHVQC.js";import"./chunk-U5SHMJ7Y.js";import"./chunk-LOQ4VVEN.js";import"./chunk-76MC32T2.js";import"./chunk-PWQHCWDV.js";import"./chunk-SHXPTUWI.js";import"./chunk-IIHJNKC3.js";import"./chunk-II4JKPH5.js";import"./chunk-UOE7W4PK.js";import"./chunk-6UEFDGWN.js";import"./chunk-WFWSBUYD.js";import"./chunk-4Y64C4JT.js";import"./chunk-GMLXHJYG.js";import"./chunk-HQ2U4QVQ.js";import{d as be}from"./chunk-IO46JRII.js";import"./chunk-QJ2FEPC2.js";import{qb as Re,rb as Ie}from"./chunk-X3PES5WL.js";import"./chunk-I2T4QMR7.js";import"./chunk-CWWDVX6C.js";import"./chunk-ZITT4GJK.js";import"./chunk-KTNHM6NK.js";import{e as Mt}from"./chunk-D76SO2ME.js";async function Ye(e,t){try{return Ie(e,t)}catch(r){let n=r instanceof Re?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new y("config",n,{cause:r})}}var Ke=`${Ce} Lower the effort level, then retry.`;function H(e){return e.cause instanceof Je?O(e.cause):e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"?O(e):e.kind==="runtime"?ie(e.message)?Ke:`The run failed: ${O(e)}. Retry after the connection recovers.`:`MCode encountered an internal error: ${O(e)}. Retry; if it keeps happening, report it through an available support channel.`}function Qe(e){return e.status==="timeout"?"The run timed out. Increase --timeout or retry.":e.status==="limit_exceeded"?"The run reached its step limit. Increase --max-steps or narrow the task.":e.status==="cancelled"?"The run was cancelled.":e.error?.category==="config"?`The run could not start with the current configuration${e.error.message?`: ${O(e.error.message)}`:""}. Open MCode and run /doctor.`:e.error?.category==="internal"?`MCode encountered an internal error${e.error.message?`: ${O(e.error.message)}`:""}. Retry; if it keeps happening, report it through an available support channel.`:ie(e.error?.message)?Ke:`The run failed${e.error?.message?`: ${O(e.error.message)}`:""}. Retry after the connection recovers.`}import{readFile as Yt,realpath as fe,stat as Q}from"node:fs/promises";import{homedir as at}from"node:os";import{basename as ct,dirname as Kt,extname as Qt,isAbsolute as Zt,resolve as K}from"node:path";var de=Mt(At(),1);function le(e,t){if(!t)return{ok:!0,value:e??null};if(!e?.trim())return{ok:!1,kind:"empty",message:"Structured output was empty."};let r;try{r=JSON.parse(e)}catch{return{ok:!1,kind:"invalid_json",message:"Structured output was not valid JSON."}}let n=new de.Ajv({allErrors:!0,strict:!1}),s=n.compile(t);return s(r)?{ok:!0,value:r}:{ok:!1,kind:"schema_mismatch",message:`Structured output did not match --output-schema: ${n.errorsText(s.errors,{separator:"; "})}`}}function Ze(e,t){let r=e.status==="succeeded"?t.validation??le(e.answer,t.outputSchema):void 0,n=Ot(e,r);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:n.sessionId,turnId:n.turnId,status:n.status==="awaiting-user-continuation"?"failed":n.status,...n.status==="succeeded"&&r?.ok?{output:r.value}:{},...n.error?{error:{...n.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},...t.usageSource!==void 0?{usageSource:t.usageSource}:{},...t.usageIncomplete!==void 0?{usageIncomplete:t.usageIncomplete}:{},durationMs:n.durationMs}}function et(e){return z(e)?e.schemaVersion===1&&e.type==="exec.result"&&typeof e.runId=="string"&&typeof e.sessionId=="string"&&typeof e.turnId=="string"&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&Ct(e.status)&&_t(e.model)&&Dt(e.usage)&&(e.usageSource===void 0||e.usageSource==="completed_responses"||e.usageSource==="analytics_fallback"||e.usageSource==="unavailable")&&(e.usageIncomplete===void 0||typeof e.usageIncomplete=="boolean")&&jt(e.error):!1}function Ot(e,t){return e.status==="awaiting-user-continuation"?{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:!1}}:e.status!=="succeeded"||!t||t.ok?e:{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:t.message,retryable:!0}}}function tt(e){new de.Ajv({allErrors:!0,strict:!1}).compile(e)}function Ct(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function _t(e){return e===void 0?!0:z(e)?typeof e.providerId=="string"&&typeof e.modelId=="string"&&V(e.variant)&&V(e.providerSource)&&V(e.providerKind)&&V(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict"):!1}function Dt(e){return e===void 0?!0:z(e)?Object.values(e).every(t=>t===void 0||typeof t=="number"&&Number.isFinite(t)):!1}function jt(e){return e===void 0?!0:z(e)?(e.category==="config"||e.category==="runtime"||e.category==="internal")&&V(e.code)&&typeof e.message=="string"&&(e.retryable===void 0||typeof e.retryable=="boolean"):!1}function V(e){return e===void 0||typeof e=="string"}function z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHash as Ft,randomUUID as Nt}from"node:crypto";import{access as $t,constants as Ut,lstat as rt,mkdir as Lt,open as qt,readdir as nt,rename as Ht,unlink as Vt,writeFile as Wt}from"node:fs/promises";import{join as X,resolve as Bt}from"node:path";var me=256*1024,Gt=4*1024*1024,Jt=5e3;function st(e){return _e(e.replace(/("(?:authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"(?:\\.|[^"\\])*"/giu,'$1"[redacted]"'))}function zt(e){if(e.length<=me)return e;let t=Buffer.from(`
|
|
3
3
|
[diagnostic answer truncated: middle omitted]
|
|
4
4
|
`),r=Math.floor((me-t.length)/2),n=r,s=e.length-r;for(;((e[n]??0)&192)===128;)n-=1;for(;((e[s]??0)&192)===128;)s+=1;return Buffer.concat([e.subarray(0,n),t,e.subarray(s)])}async function ot(e,t){let r=Bt(t,e);if(await Lt(r,{recursive:!0,mode:448}),!(await rt(r)).isDirectory())throw new Error("Diagnostics path must be a real directory.");if(await $t(r,Ut.W_OK),(await nt(r)).length>0)throw new Error("Diagnostics directory must be empty.");return r}function it(e){return e?Ft("sha256").update(JSON.stringify(e)).digest("hex"):void 0}function W(e){return typeof e=="string"?st(e):Array.isArray(e)?e.map(W):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,/^(authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)$/iu.test(t)?"[redacted]":W(r)])):e}var Y=class e{constructor(t,r,n){this.directory=t;this.warn=r;this.progressFile=n}pending=Promise.resolve();bytes=0;droppedEvents=0;closed=!1;failed=!1;static async create(t,r){if((await nt(t)).length>0)throw Object.assign(new Error("Diagnostics directory must be empty."),{code:"EEXIST"});let n=await qt(X(t,"progress.jsonl"),"wx",384);return new e(t,r,n)}record(t){if(this.closed)return;let r=`${JSON.stringify(W({timestampMs:Date.now(),...t}))}
|
|
5
5
|
`,n=Buffer.byteLength(r);if(this.bytes+n>Gt){this.droppedEvents+=1;return}this.bytes+=n,this.enqueue(()=>this.progressFile.appendFile(r))}execution(t){this.json("execution.json",{schemaVersion:1,...t})}failure(t,r){let n=Buffer.from(st(t??"")),s=n.length>me,i=zt(n);this.json("failure.json",{schemaVersion:1,...r,answerBytes:Buffer.byteLength(t??""),savedBytes:i.length,truncated:s,redacted:!0}),this.enqueue(()=>this.replaceFile("failure-answer.txt",i))}async flush(t={}){this.enqueue(async()=>{let[s,i]=await Promise.all([rt(X(this.directory,"progress.jsonl")),this.progressFile.stat()]);if(!s.isFile()||s.ino!==i.ino||s.dev!==i.dev)throw new Error("Diagnostics progress file was replaced.")}),this.enqueue(()=>this.progressFile.close()),this.enqueue(()=>this.replaceFile("diagnostics-status.json",`${JSON.stringify(W({...t,recoveryReady:t.recoveryReady===!0&&!this.failed,diagnosticsComplete:!this.failed,droppedEventCount:this.droppedEvents}),null,2)}
|
|
@@ -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{A as n,B as o,C as p,D as q,E as r,F as s,G as t,H as u,I as v,J as w,K as x,L as y,M as z,N as A,O as B,P as C,Q as D,R as E,S as F,k as a,l as b,m as c,n as d,o as e,p as f,q as g,r as h,s as i,t as j,x as k,y as l,z as m}from"./chunk-
|
|
2
|
+
import{A as n,B as o,C as p,D as q,E as r,F as s,G as t,H as u,I as v,J as w,K as x,L as y,M as z,N as A,O as B,P as C,Q as D,R as E,S as F,k as a,l as b,m as c,n as d,o as e,p as f,q as g,r as h,s as i,t as j,x as k,y as l,z as m}from"./chunk-ZPSMBMGA.js";import"./chunk-GMLXHJYG.js";import"./chunk-HQ2U4QVQ.js";import"./chunk-D76SO2ME.js";export{g as BashExecutionError,b as DEFAULT_MAX_BYTES,a as DEFAULT_MAX_LINES,x as allToolNames,C as createAllToolDefinitions,F as createAllTools,j as createBashTool,i as createBashToolDefinition,A as createCodingToolDefinitions,D as createCodingTools,m as createEditTool,l as createEditToolDefinition,o as createFindTool,n as createFindToolDefinition,q as createGrepTool,p as createGrepToolDefinition,h as createLocalBashOperations,s as createLsTool,r as createLsToolDefinition,B as createReadOnlyToolDefinitions,E as createReadOnlyTools,u as createReadTool,t as createReadToolDefinition,z as createTool,y as createToolDefinition,w as createWriteTool,v as createWriteToolDefinition,c as formatSize,d as truncateHead,f as truncateLine,e as truncateTail,k as withFileMutationQueue};
|
|
@@ -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 h,b as f,
|
|
2
|
+
import{a as h,b as f,h as g}from"./chunk-X7FQ5SBJ.js";import"./chunk-FKQFVOLR.js";import{e as m}from"./chunk-DCFP5ZHZ.js";import"./chunk-334CV6RF.js";import"./chunk-HQ2U4QVQ.js";import"./chunk-I2T4QMR7.js";import"./chunk-CWWDVX6C.js";import"./chunk-D76SO2ME.js";import{createInterface as M}from"node:readline/promises";import{stripVTControlCharacters as w}from"node:util";var $=80,T=15e3,l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],v=72;async function V(t,e={}){let n=e.application??new g({currentVersion:t}),r=e.interactive??!!(process.stdin.isTTY&&process.stdout.isTTY),a=e.write??(s=>process.stdout.write(s)),c=e.schedulePendingPrefixUpdate??(()=>m());if(await c()){a(`${h()}
|
|
3
3
|
`);return}let i=await n.inspect();if(i.kind==="current"){a(i.source==="managed-installer"?`MCode ${i.currentVersion} is current on ${i.channel}.
|
|
4
4
|
`:`MCode ${i.currentVersion} is current on @${i.packageTag}.
|
|
5
5
|
`);return}if(i.kind==="ahead"){a(`MCode ${i.currentVersion} is newer than ${i.source==="managed-installer"?i.channel:`@${i.packageTag}`} ${i.latestVersion}; no update was applied.
|
package/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
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;
|
|
3
|
-
import{
|
|
4
|
-
`),process.exitCode=1;return}let{getTuiDataDirPath:m}=await import("./chunks/data-dir-
|
|
3
|
+
import{h as s}from"./chunks/chunk-DCFP5ZHZ.js";import{A as n,B as a}from"./chunks/chunk-334CV6RF.js";import"./chunks/chunk-HQ2U4QVQ.js";import{r as o,t as i}from"./chunks/chunk-QJ2FEPC2.js";import"./chunks/chunk-X3PES5WL.js";import"./chunks/chunk-I2T4QMR7.js";import"./chunks/chunk-CWWDVX6C.js";import"./chunks/chunk-ZITT4GJK.js";import"./chunks/chunk-D76SO2ME.js";import{fileURLToPath as u}from"node:url";async function l(){let c=n(u(__mavis_tuiPackageEntryUrl)),t=a(c),r;try{r=i(process.argv.slice(2),t)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
4
|
+
`),process.exitCode=1;return}let{getTuiDataDirPath:m}=await import("./chunks/data-dir-C6MQE6W2.js");o({dataDir:m(),...r?{startupBuildEnvironment:r}:{}});let p=await s();try{let{runTuiCli:e}=await import("./chunks/main-JXKRTY5N.js");await e({allowStartupEnvironmentSelection:t})}finally{p.remove()}}await l();
|
package/package.json
CHANGED
package/chunks/chunk-5JU6ZMXS.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
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-52LBQEEC.js";import{a as G}from"./chunk-PRXIML4F.js";import{a as w,c as C,e as le}from"./chunk-D76SO2ME.js";var E=C(V=>{var x=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},H=class extends x{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};V.CommanderError=x;V.InvalidArgumentError=H});var $=C(P=>{var{InvalidArgumentError:pe}=E(),k=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new pe(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function fe(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}P.Argument=k;P.humanReadableArgName=fe});var T=C(K=>{var{humanReadableArgName:ge}=$(),I=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,r)=>n.name().localeCompare(r.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);!n&&!r?t.push(i):i.long&&!r?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>ge(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth||80,r=2,s=2;function l(m,O){if(O){let S=`${m.padEnd(i+s)}${O}`;return t.wrap(S,n-r,i+s)}return m}function a(m){return m.join(`
|
|
3
|
-
`).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};
|