@niwa-labs/ncode 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/CHANGELOG.zh-CN.md +5 -0
  3. package/README.md +2 -2
  4. package/chunks/{application-A3S2LMBY.js → application-6B6N6MDM.js} +1 -1
  5. package/chunks/{auth-command-QNQ32TBI.js → auth-command-L57HWPOO.js} +1 -1
  6. package/chunks/{chunk-6LDRLO4Y.js → chunk-3LRARE6Z.js} +1 -1
  7. package/chunks/{chunk-5R2PGOIA.js → chunk-3MLT4F77.js} +1 -1
  8. package/chunks/{chunk-NOGL6Y6L.js → chunk-7F3QKGB7.js} +1 -1
  9. package/chunks/{chunk-LFGHL5A2.js → chunk-ALZZ3WAV.js} +1 -1
  10. package/chunks/{chunk-RD7XROJD.js → chunk-CUPCI2YC.js} +1 -1
  11. package/chunks/{chunk-OOBSLGMR.js → chunk-DBSRTVJC.js} +1 -1
  12. package/chunks/{chunk-XSWWOH4F.js → chunk-GS7TCNDK.js} +1 -1
  13. package/chunks/{chunk-36COWQLE.js → chunk-GZPVFWYD.js} +1 -1
  14. package/chunks/{chunk-CAY2BP2G.js → chunk-JEHPL5Z6.js} +1 -1
  15. package/chunks/{chunk-R7NDEPS3.js → chunk-LC7ZI6EV.js} +1 -1
  16. package/chunks/{chunk-ELHMZ5OD.js → chunk-NWMN2FDO.js} +1 -1
  17. package/chunks/{chunk-MVI24MQ2.js → chunk-O5EROATK.js} +664 -664
  18. package/chunks/{chunk-UMGGEC4N.js → chunk-QIYZZJVO.js} +1 -1
  19. package/chunks/{chunk-PBGCNSGZ.js → chunk-QMBFFQPV.js} +1 -1
  20. package/chunks/{chunk-JLFN6WSO.js → chunk-RZDVNG5Z.js} +1 -1
  21. package/chunks/{chunk-MI4YWYJF.js → chunk-UEPKZSE6.js} +1 -1
  22. package/chunks/{chunk-V4IDVAIA.js → chunk-WHBWI5OQ.js} +1 -1
  23. package/chunks/{chunk-ZPIJSTUE.js → chunk-WUORF7YS.js} +1 -1
  24. package/chunks/{chunk-UNEPZJKK.js → chunk-XWNCITOR.js} +5 -5
  25. package/chunks/{data-dir-OKWMOLNQ.js → data-dir-6RWVCAMB.js} +1 -1
  26. package/chunks/{launcher-4QSNU24J.js → launcher-B3C4PQ6Q.js} +3 -3
  27. package/chunks/{lifecycle-ELQ2EYO3.js → lifecycle-56K655PJ.js} +1 -1
  28. package/chunks/main-W3SJ2POE.js +14 -0
  29. package/chunks/{plugin-command-NGTATXBX.js → plugin-command-EBSKJLM3.js} +1 -1
  30. package/chunks/{profile-command-ZHVREBWO.js → profile-command-HIJDJDEL.js} +1 -1
  31. package/chunks/{provider-command-BGKOLCUG.js → provider-command-VCCPLOXR.js} +1 -1
  32. package/chunks/{run-acp-command-2CJQDXHQ.js → run-acp-command-FBV27QBE.js} +13 -13
  33. package/chunks/run-daemon-command-PZ2TU524.js +2 -0
  34. package/chunks/run-exec-command-K7BC2HEI.js +16 -0
  35. package/chunks/src-7ZMHMWLX.js +2 -0
  36. package/chunks/{telemetry-command-6FE4WQ4Q.js → telemetry-command-ZYOF64Y4.js} +1 -1
  37. package/chunks/{update-4VPIX7FP.js → update-ZKUCGIOR.js} +1 -1
  38. package/cli.js +3 -3
  39. package/matrix-mcp-stdio.js +1 -1
  40. package/mcoded.js +1 -1
  41. package/package.json +1 -1
  42. package/release.json +4 -4
  43. package/chunks/main-TXP74KHK.js +0 -14
  44. package/chunks/run-daemon-command-NDOIPTKF.js +0 -2
  45. package/chunks/run-exec-command-VNT4IKOJ.js +0 -16
  46. package/chunks/src-ED5HBSWE.js +0 -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 p,c as b}from"./chunk-6LDRLO4Y.js";import{b as d}from"./chunk-V4IDVAIA.js";import{D as c}from"./chunk-MVI24MQ2.js";import{R as s,S as u,ka as l}from"./chunk-UNEPZJKK.js";import{dirname as w,resolve as y}from"node:path";import{fileURLToPath as E}from"node:url";function f(){const e=w(E(__mavis_tuiPackageEntryUrl));return true?y(e,"assets/prompts/code-review"):y(e,"../../../local-runtime/assets/prompts/code-review")}function _(e,r=d(),n=false){return{...e,review:{...e.review,mode:!e.review||e.review.modeSource==="default"?"inline":e.review.mode},beta:{...e.beta,codexOAuth:r.isInternalBuild,mcodeTools:n&&e.beta?.mcodeTools===true},memory:{...e.memory,enabled:false}}}async function I(e,r=c){if(process.env.MAVIS_LOCAL_RUNTIME_V2_FORCE_LEGACY==="1"){throw new Error("Minimax Code embedded Runtime requires the local-runtime-v2 front door; legacy fallback is disabled.")}const{productCapabilities:n,...i}=e;const R=i.configGetter??l;const v=new p({authContextGetter:e.authContextGetter??(()=>void 0),region:s(),buildEnv:u(),...e.routingContextGetter?{routingContextGetter:e.routingContextGetter}:{}});const t=await r({...i,subscriptionQuota:e.subscriptionQuota??(async({provider:o,signal:a})=>{if(o!=="minimax")return void 0;const C=await v.getTokenPlanAccountStatus(a,{forceRefresh:true});const m=b(C.quota);return m!==void 0?{resetAtMs:m}:{}}),reviewPromptDir:i.reviewPromptDir??f(),configGetter:()=>_(R(),d(),n?.mcodeTools===true),runtimeOwnerKind:"tui",runtimeMode:"clean",legacyOpencodeEnabled:false,enableLiveMcp:true,capabilityProfile:"cli",isContextWindowUsageEnabled:()=>true,capabilities:{...i.capabilities,cliEmbedded:true}});try{await t.ready;if(!t.cliService){throw new Error("Minimax Code embedded Runtime does not expose CliService.")}await t.apiHost.ensureBuiltinAgents();return t}catch(o){try{await t.apiHost.close()}catch(a){throw new AggregateError([o,a],"Embedded Runtime startup cleanup failed.")}throw o}}export{I as a};
2
+ import{a as p,c as b}from"./chunk-3LRARE6Z.js";import{b as d}from"./chunk-WHBWI5OQ.js";import{D as c}from"./chunk-O5EROATK.js";import{V as s,W as u,oa as l}from"./chunk-XWNCITOR.js";import{dirname as w,resolve as y}from"node:path";import{fileURLToPath as E}from"node:url";function f(){const e=w(E(__mavis_tuiPackageEntryUrl));return true?y(e,"assets/prompts/code-review"):y(e,"../../../local-runtime/assets/prompts/code-review")}function _(e,r=d(),n=false){return{...e,review:{...e.review,mode:!e.review||e.review.modeSource==="default"?"inline":e.review.mode},beta:{...e.beta,codexOAuth:r.isInternalBuild,mcodeTools:n&&e.beta?.mcodeTools===true},memory:{...e.memory,enabled:false}}}async function I(e,r=c){if(process.env.MAVIS_LOCAL_RUNTIME_V2_FORCE_LEGACY==="1"){throw new Error("Minimax Code embedded Runtime requires the local-runtime-v2 front door; legacy fallback is disabled.")}const{productCapabilities:n,...i}=e;const R=i.configGetter??l;const v=new p({authContextGetter:e.authContextGetter??(()=>void 0),region:s(),buildEnv:u(),...e.routingContextGetter?{routingContextGetter:e.routingContextGetter}:{}});const t=await r({...i,subscriptionQuota:e.subscriptionQuota??(async({provider:o,signal:a})=>{if(o!=="minimax")return void 0;const C=await v.getTokenPlanAccountStatus(a,{forceRefresh:true});const m=b(C.quota);return m!==void 0?{resetAtMs:m}:{}}),reviewPromptDir:i.reviewPromptDir??f(),configGetter:()=>_(R(),d(),n?.mcodeTools===true),runtimeOwnerKind:"tui",runtimeMode:"clean",legacyOpencodeEnabled:false,enableLiveMcp:true,capabilityProfile:"cli",isContextWindowUsageEnabled:()=>true,capabilities:{...i.capabilities,cliEmbedded:true}});try{await t.ready;if(!t.cliService){throw new Error("Minimax Code embedded Runtime does not expose CliService.")}await t.apiHost.ensureBuiltinAgents();return t}catch(o){try{await t.apiHost.close()}catch(a){throw new AggregateError([o,a],"Embedded Runtime startup cleanup failed.")}throw o}}export{I as a};
@@ -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{b,c as L,d as w,h as P,i as I}from"./chunk-TRX2HFTB.js";import{rb as s,tb as d,ub as S,vb as C}from"./chunk-UNEPZJKK.js";import{n as a}from"./chunk-5R2PGOIA.js";function se(e){const t=b({dataDir:e.dataDir,buildEnv:e.buildEnv,region:e.region});const n=e.oauthClient??X(e.oauthEndpoints);const i=I({authHome:t.namespaceHome});return new P({namespace:t,oauthClient:n,credentialStore:i,initialize:()=>L(t)})}function X(e){if(!e){throw new TypeError("Shared MCode OAuth requires explicit device authorization, token, and revocation endpoints.")}return new w(e)}import{createHash as G}from"node:crypto";import h from"node:fs";import O from"node:path";var K="account-identity.json";function g(e,t){return O.join(e,"cli-auth",t.buildEnv,t.region,K)}function M(e,t,n){const i=k(e,t,n);const r=s(i);const o=r.realUserID;if(i?.status!=="verified"||!o)return void 0;return{realUserID:o,...r.userEmail?{userEmail:r.userEmail}:{},...r.userName?{userName:r.userName}:{},...r.subUserName?{subUserName:r.subUserName}:{},verifiedAtMs:i.updatedAtMs}}function f(e,t,n){return k(e,t,n)?.status==="rejected"}function fe(e,t,n,i,r=Date.now()){const o=s(typeof i==="string"?{realUserID:i}:i);if(!o.realUserID)throw new Error("MiniMax account identity is missing a user ID.");T(e,t,{version:1,...t,status:"verified",tokenFingerprint:y(n),realUserID:o.realUserID,...o.userEmail?{userEmail:o.userEmail}:{},...o.userName?{userName:o.userName}:{},...o.subUserName?{subUserName:o.subUserName}:{},updatedAtMs:r})}function Ae(e,t,n,i=Date.now()){T(e,t,{version:1,...t,status:"rejected",tokenFingerprint:y(n),updatedAtMs:i})}function N(e,t){h.rmSync(g(e,t),{force:true})}function k(e,t,n){const i=n.trim();if(!i)return void 0;try{const r=JSON.parse(h.readFileSync(g(e,t),"utf8"));if(r.version!==1||r.region!==t.region||r.buildEnv!==t.buildEnv||r.status!=="verified"&&r.status!=="rejected"||r.tokenFingerprint!==y(i)||typeof r.updatedAtMs!=="number"){return void 0}return r}catch{return void 0}}function T(e,t,n){const i=g(e,t);const r=O.dirname(i);h.mkdirSync(r,{recursive:true,mode:448});const o=`${i}.${process.pid}.${Date.now()}.tmp`;h.writeFileSync(o,`${JSON.stringify(n,null,2)}
2
+ import{b,c as L,d as w,h as P,i as I}from"./chunk-TRX2HFTB.js";import{vb as s,xb as d,yb as S,zb as C}from"./chunk-XWNCITOR.js";import{n as a}from"./chunk-3MLT4F77.js";function se(e){const t=b({dataDir:e.dataDir,buildEnv:e.buildEnv,region:e.region});const n=e.oauthClient??X(e.oauthEndpoints);const i=I({authHome:t.namespaceHome});return new P({namespace:t,oauthClient:n,credentialStore:i,initialize:()=>L(t)})}function X(e){if(!e){throw new TypeError("Shared MCode OAuth requires explicit device authorization, token, and revocation endpoints.")}return new w(e)}import{createHash as G}from"node:crypto";import h from"node:fs";import O from"node:path";var K="account-identity.json";function g(e,t){return O.join(e,"cli-auth",t.buildEnv,t.region,K)}function M(e,t,n){const i=k(e,t,n);const r=s(i);const o=r.realUserID;if(i?.status!=="verified"||!o)return void 0;return{realUserID:o,...r.userEmail?{userEmail:r.userEmail}:{},...r.userName?{userName:r.userName}:{},...r.subUserName?{subUserName:r.subUserName}:{},verifiedAtMs:i.updatedAtMs}}function f(e,t,n){return k(e,t,n)?.status==="rejected"}function fe(e,t,n,i,r=Date.now()){const o=s(typeof i==="string"?{realUserID:i}:i);if(!o.realUserID)throw new Error("MiniMax account identity is missing a user ID.");T(e,t,{version:1,...t,status:"verified",tokenFingerprint:y(n),realUserID:o.realUserID,...o.userEmail?{userEmail:o.userEmail}:{},...o.userName?{userName:o.userName}:{},...o.subUserName?{subUserName:o.subUserName}:{},updatedAtMs:r})}function Ae(e,t,n,i=Date.now()){T(e,t,{version:1,...t,status:"rejected",tokenFingerprint:y(n),updatedAtMs:i})}function N(e,t){h.rmSync(g(e,t),{force:true})}function k(e,t,n){const i=n.trim();if(!i)return void 0;try{const r=JSON.parse(h.readFileSync(g(e,t),"utf8"));if(r.version!==1||r.region!==t.region||r.buildEnv!==t.buildEnv||r.status!=="verified"&&r.status!=="rejected"||r.tokenFingerprint!==y(i)||typeof r.updatedAtMs!=="number"){return void 0}return r}catch{return void 0}}function T(e,t,n){const i=g(e,t);const r=O.dirname(i);h.mkdirSync(r,{recursive:true,mode:448});const o=`${i}.${process.pid}.${Date.now()}.tmp`;h.writeFileSync(o,`${JSON.stringify(n,null,2)}
3
3
  `,{encoding:"utf8",mode:384});a(()=>h.renameSync(o,i));a(()=>h.chmodSync(i,384))}function y(e){return`sha256:${G("sha256").update(e.trim()).digest("hex")}`}import{createHash as Q}from"node:crypto";import u from"node:fs";import l from"node:path";var m="cli-auth";var v="cli-auth.scope.json";var Z="shared-projection.json";function p(e,t){return l.join(e,m,t.buildEnv,t.region)}function D(e,t){return l.join(e,m,t)}function Ee(e,t){const n=ee(e,t);if(!n)return F(e,t);const i=d(e);if(!i||$(n,i)||H(e,i)){return n}return F(e,t)}function ee(e,t){const n=W(e,t)??z(e,t);return U(e,t,n)}function je(e,t,n,i={}){const r=s(t);const o=R(e,r,n);const c=d(e);if(i.expectedSharedAuth&&c&&!$(c,i.expectedSharedAuth)&&!H(e,c)){return o}const Y=S(e,r,{retryWindowsFileSystem:true});if(Y.written)J(e,n,r);else B(e);return o}function be(e,t){const n=ne(e,t)??te(e,t);ie(e,t);N(e,t);if(n)re(e,n)}function te(e,t){const n=d(e);const i=n?.accessToken?.trim();return i&&f(e,t,i)?n:void 0}function ne(e,t){return W(e,t)??z(e,t)}function ie(e,t){C(p(e,t));q(e,t)}function F(e,t,n){const i=d(e);const r=i?.accessToken?.trim();const o=i?_(e,i):void 0;if(!i||!r||o&&!j(o,t)||r===n?.trim()||f(e,t,r)){return void 0}const c=s(i);R(e,c,t);J(e,t,c);return U(e,t,c)}function re(e,t){const n=t.accessToken?.trim();const i=d(e)?.accessToken?.trim();if(!n||i!==n)return false;C(e);B(e);return true}function U(e,t,n){const i=n?.accessToken?.trim();if(!i||f(e,t,i))return void 0;const r=M(e,t,i);if(!r)return s(n);const{verifiedAtMs:o,...c}=r;void o;return{...c,...s(n),accessToken:i}}function $(e,t){return A(e)===A(t)}function A(e){return`sha256:${Q("sha256").update(JSON.stringify(s(e))).digest("hex")}`}function x(e){return l.join(e,m,Z)}function H(e,t){return Boolean(_(e,t))}function _(e,t=d(e)){if(!t)return void 0;try{const n=JSON.parse(u.readFileSync(x(e),"utf8"));return n.version===1&&(n.region==="cn"||n.region==="en")&&(n.buildEnv==="dev"||n.buildEnv==="test"||n.buildEnv==="staging"||n.buildEnv==="prod")&&typeof n.authFingerprint==="string"&&n.authFingerprint===A(t)?n:void 0}catch{return void 0}}function J(e,t,n){const i=l.join(e,m);u.mkdirSync(i,{recursive:true,mode:448});const r=x(e);const o=`${r}.${process.pid}.${Date.now()}.tmp`;const c={version:1,...t,authFingerprint:A(n),updatedAtMs:Date.now()};u.writeFileSync(o,`${JSON.stringify(c,null,2)}
4
4
  `,{encoding:"utf8",mode:384});a(()=>u.renameSync(o,r));a(()=>u.chmodSync(r,384))}function B(e){u.rmSync(x(e),{force:true})}function R(e,t,n){const i=S(p(e,n),t,{retryWindowsFileSystem:true});if(i.written)ue(e,n);else q(e,n);return i}function W(e,t){if(!j(oe(e,t),t))return void 0;return d(p(e,t))}function z(e,t){const n=D(e,t.buildEnv);const i=V(l.join(n,v));if(!j(i,t))return void 0;const r=d(n);if(!r?.accessToken)return void 0;R(e,r,t);C(n);u.rmSync(l.join(n,v),{force:true});return r}function E(e,t){return l.join(p(e,t),v)}function oe(e,t){return V(E(e,t))}function V(e){try{const t=JSON.parse(u.readFileSync(e,"utf8"));if(t.version!==1||t.region!=="cn"&&t.region!=="en"||t.buildEnv!=="dev"&&t.buildEnv!=="test"&&t.buildEnv!=="staging"&&t.buildEnv!=="prod"||typeof t.updatedAtMs!=="number"){return void 0}return t}catch{return void 0}}function ue(e,t){const n=p(e,t);u.mkdirSync(n,{recursive:true,mode:448});const i=E(e,t);const r=`${i}.${process.pid}.${Date.now()}.tmp`;const o={version:1,updatedAtMs:Date.now(),...t};u.writeFileSync(r,`${JSON.stringify(o,null,2)}
5
5
  `,{encoding:"utf8",mode:384});a(()=>u.renameSync(r,i));a(()=>u.chmodSync(i,384))}function q(e,t){u.rmSync(E(e,t),{force:true})}function j(e,t){return e?.region===t.region&&e.buildEnv===t.buildEnv}export{se as a,M as b,fe as c,Ae as d,Ee as e,je as f,be as g,ie as h,F as i};
@@ -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 d,b as y,c as f,d as M,e as l,f as m}from"./chunk-MVI24MQ2.js";import{a as k}from"./chunk-VAARXN34.js";import _ from"node:net";var P=5e3;async function I(i,e={}){try{return await w(i,e.timeoutMs,async t=>{p(t,l({type:"hello",version:d,...e.token!==void 0?{token:e.token}:{},...e.dataDir!==void 0?{dataDir:e.dataDir}:{},...e.env!==void 0?{env:e.env}:{}}));const r=await h(t,e.timeoutMs);if(r.type!=="response"||r.command!=="hello"){return{ok:false,error:`unexpected frame in reply to hello: ${JSON.stringify(r).slice(0,120)}`}}if(!r.success){return{ok:false,error:r.error,...r.errorCode?{errorCode:r.errorCode}:{}}}return{ok:true,data:r.data}})}catch(t){return g(t)}}async function F(i,e={}){try{return await w(i,e.timeoutMs,async t=>{p(t,l({type:"hello",version:d,...e.token!==void 0?{token:e.token}:{},...e.dataDir!==void 0?{dataDir:e.dataDir}:{},...e.env!==void 0?{env:e.env}:{}}));const r=await h(t,e.timeoutMs);if(r.type!=="response"||r.command!=="hello"){return{ok:false,error:"unexpected handshake reply"}}if(!r.success){return{ok:false,error:r.error,...r.errorCode?{errorCode:r.errorCode}:{}}}p(t,l({type:"shutdown"}));for(;;){const s=await h(t,e.timeoutMs);if(s.type==="response"&&s.command==="shutdown"&&!s.success){return{ok:false,error:s.error,...s.errorCode?{errorCode:s.errorCode}:{}}}if(s.type==="bye"||s.type==="response")break}return{ok:true,data:{accepted:true}}})}catch(t){return g(t)}}async function H(i,e={}){try{return await w(i,e.timeoutMs,async t=>{p(t,l({type:"hello",version:d,...e.token!==void 0?{token:e.token}:{},...e.dataDir!==void 0?{dataDir:e.dataDir}:{},...e.env!==void 0?{env:e.env}:{}}));const r=await h(t,e.timeoutMs);if(r.type!=="response"||r.command!=="hello"){return{ok:false,error:"unexpected handshake reply"}}if(!r.success){return{ok:false,error:r.error,...r.errorCode?{errorCode:r.errorCode}:{}}}p(t,l({type:"daemon.status",id:"active-runs"}));const s=await h(t,e.timeoutMs);if(s.type!=="response"||s.command!=="daemon.status"){return{ok:false,error:`unexpected frame in reply to daemon.status: ${JSON.stringify(s).slice(0,120)}`}}if(!s.success){return{ok:false,error:s.error,...s.errorCode?{errorCode:s.errorCode}:{}}}const o=s.data??{};return{ok:true,data:{runs:Array.isArray(o.activeRuns)?o.activeRuns:[],activeRunsReported:Array.isArray(o.activeRuns),...typeof o.activeTurns==="number"?{activeTurns:o.activeTurns}:{}}}})}catch(t){return g(t)}}function g(i){const e=i.code;return{ok:false,error:i instanceof Error?i.message:String(i),...typeof e==="string"?{errno:e}:{}}}async function w(i,e,t){const r=e??P;const s=await G(i,r);try{return await t(s)}finally{s.end()}}function G(i,e){return new Promise((t,r)=>{const s=_.connect(i);const o=setTimeout(()=>{s.destroy();r(new Error(`connect ${i} timed out after ${e} ms`))},e);o.unref?.();s.once("connect",()=>{clearTimeout(o);t(new m(s))});s.once("error",n=>{clearTimeout(o);r(n)})})}function p(i,e){i.write(e)}async function h(i,e){const t=i.lines();const r=e??P;let s;const o=new Promise((n,O)=>{s=setTimeout(()=>{O(new Error(`daemon reply timed out after ${r} ms`))},r);s.unref?.()});try{const n=await Promise.race([t.next(),o]);if(n.done)throw new Error("daemon closed the connection before replying");return JSON.parse(n.value)}finally{if(s)clearTimeout(s)}}import N from"node:net";import{setTimeout as x}from"node:timers/promises";var E=6e4;var b=3;var D=6e4;var v=class extends Error{name="McodedCrashLoopError";crashes;windowMs;retryAfterMs;constructor(e,t){super(`mcoded crash-loop: ${e.crashes} daemon starts failed within ${Math.round(e.windowMs/1e3)}s; auto-spawn stopped. See the daemon log${t?` (${t} and .1\u2026)`:""} for the cause, or set MCODE_SERVER_MODE=off to run without the daemon. Respawning resumes after ${Math.ceil(e.retryAfterMs/1e3)}s of quiet.`);this.crashes=e.crashes;this.windowMs=e.windowMs;this.retryAfterMs=e.retryAfterMs}};var R=class{windowMs;maxCrashes;cooldownMs;logPath;now;crashes=[];trippedAt;constructor(e={}){this.windowMs=e.windowMs??E;this.maxCrashes=e.maxCrashes??b;this.cooldownMs=e.cooldownMs??D;this.logPath=e.logPath;this.now=e.now??Date.now}recordCrash(){const e=this.now();this.prune(e);this.crashes.push(e);if(this.trippedAt!==void 0){if(e-this.trippedAt>=this.cooldownMs&&this.crashes.length===0){this.trippedAt=void 0}}if(this.trippedAt!==void 0||this.crashes.length>=this.maxCrashes){this.trippedAt??=e;return{allowSpawn:false,crashes:this.crashes.length,windowMs:this.windowMs,retryAfterMs:Math.max(0,this.trippedAt+this.cooldownMs-e)}}return{allowSpawn:true}}canSpawn(){if(this.trippedAt===void 0)return true;const e=this.now();this.prune(e);if(e-this.trippedAt>=this.cooldownMs&&this.crashes.length===0){this.trippedAt=void 0;return true}return false}requireSpawn(){if(this.canSpawn())return;throw new v({allowSpawn:false,crashes:this.maxCrashes,windowMs:this.windowMs,retryAfterMs:Math.max(0,this.trippedAt+this.cooldownMs-this.now())},this.logPath)}tripMessage(e){return new v(e,this.logPath).message}prune(e){while(this.crashes.length>0&&e-this.crashes[0]>this.windowMs){this.crashes.shift()}}};var c=k("mcode:rpc");var u=class extends Error{code;errorName;data;constructor(e,t={}){super(e);this.name="McodedRemoteError";this.code=t.code;this.errorName=t.errorName;this.data=t.data}};var a=class extends Error{constructor(e){super(e);this.name="McodedConnectionError"}};function U(i,e){const t={scope:i,lastCursor:e,queue:[],waiters:[],stopped:false,gapped:Promise.resolve(void 0),settleGap:()=>void 0};t.gapped=new Promise(r=>{t.settleGap=r});return t}var A=class{socketPath;handshakePayload;connectOverride;spawnHook;crashLoop;readyTimeoutMs;backoffMinMs;backoffMaxMs;creditStep;initialStreamCredit;stateListeners=[];reconnectedListeners=[];transport;readerTask;reconnectTask;state="disconnected";pending=new Map;streams=new Map;orphanFrames=new Map;subscriptions=new Set;attachments=new Map;requestSeq=0;welcome;reconnectAttempts=0;userClosed=false;helloWaiters=[];constructor(e){this.socketPath=e.socketPath;this.handshakePayload=e.handshake;this.connectOverride=e.connect;this.spawnHook=e.spawn;this.crashLoop=e.crashLoop;this.readyTimeoutMs=e.readyTimeoutMs??2e4;this.backoffMinMs=e.backoffMinMs??100;this.backoffMaxMs=e.backoffMaxMs??2e3;this.creditStep=e.creditStep??1;this.initialStreamCredit=e.initialStreamCredit??M;if(e.onStateChange)this.stateListeners.push(e.onStateChange);if(e.onReconnected)this.reconnectedListeners.push(e.onReconnected)}onStateChange(e){this.stateListeners.push(e);return()=>{const t=this.stateListeners.indexOf(e);if(t>=0)this.stateListeners.splice(t,1)}}onReconnected(e){this.reconnectedListeners.push(e);return()=>{const t=this.reconnectedListeners.indexOf(e);if(t>=0)this.reconnectedListeners.splice(t,1)}}get connectionState(){return this.state}get hello(){return this.welcome}hasFeature(e){return this.welcome?.features?.includes(e)??false}requireFeature(e){const t=this.welcome?.features;if(t===void 0||t.includes(e))return;throw new a(`the daemon does not advertise feature "${e}" (it is older than this client); run "mcode daemon restart" to bring it to the current build`)}async connect(){if(this.state==="ready"&&this.welcome)return this.welcome;if(this.state==="closed")throw new a("client is closed");this.userClosed=false;this.setState("connecting");const e=Date.now()+this.readyTimeoutMs*4;let t=Date.now()+this.readyTimeoutMs;let r;for(;;){try{return await this.connectOnce()}catch(s){if(this.userClosed)throw new a("client closed during connect");if(!(s instanceof S))throw s;if(this.spawnHook){this.crashLoop?.requireSpawn();let o=false;try{o=await this.spawnHook()===true;r=void 0}catch(n){c.warn("client-spawn-failed",{err:n});r=n}if(this.crashLoop&&o)this.crashLoop.recordCrash();this.crashLoop?.requireSpawn();if(o||r===void 0){t=Math.min(Date.now()+this.readyTimeoutMs,e)}}if(Date.now()>=t){if(r!==void 0){throw new a(`daemon socket is not answering and auto-spawn failed: ${r instanceof Error?r.message:String(r)}`)}throw s}await x(Math.min(this.backoffMinMs*2**this.reconnectAttempts,this.backoffMaxMs))}}}async call(e,...t){this.assertReady();this.requireFeature("call");const r=await this.request(this.nextId(),{type:"call",id:"pending",method:e,params:t});return r}async callIdempotent(e,t,...r){this.assertReady();this.requireFeature("call");const s=await this.request(e,{type:"call",id:e,method:t,params:r});return s}async openStream(e,t,r){this.assertReady();this.requireFeature("stream");const s={type:"stream.open",id:this.nextId(),method:e,params:t,...r!==void 0?{credit:r}:{credit:this.initialStreamCredit}};const o=await this.request(s.id,s);return this.makeStream(o.streamId)}async sessionAttach(e,t="owner",r){this.assertReady();this.requireFeature("attach");const s=this.nextId();await this.request(s,{type:"session.attach",id:s,sessionId:e,role:t,...r!==void 0?{toolEnv:r}:{}});this.attachments.set(e,{role:t,...r!==void 0?{toolEnv:r}:{}})}async sessionDetach(e){this.assertReady();this.requireFeature("attach");const t=this.nextId();await this.request(t,{type:"session.detach",id:t,sessionId:e});this.attachments.delete(e)}subscribe(e={}){this.assertReady();this.requireFeature("subscribe");const t=U(e.scope??"catalog+attached",e.after??null);this.subscriptions.add(t);void this.sendSubscribe(t);return{events:W(t),gapped:t.gapped,stop:()=>{t.stopped=true;this.subscriptions.delete(t);for(const r of t.waiters.splice(0)){r({done:true,value:void 0})}}}}async ping(){this.assertReady();const e=this.nextId();await this.request(e,{type:"ping",id:e})}async daemonStatus(){this.assertReady();const e=this.nextId();return await this.request(e,{type:"daemon.status",id:e})}async daemonRestart(e){this.assertReady();if(e==="idle")this.requireFeature("restart-when-idle");const t=this.nextId();await this.request(t,{type:"daemon.restart",id:t,when:e})}async daemonAuthSync(){this.assertReady();const e=this.nextId();await this.request(e,{type:"daemon.authSync",id:e})}async shutdown(){this.assertReady();const e=this.nextId();await this.request(e,{type:"shutdown",id:e})}close(){this.userClosed=true;this.teardown("client closed");this.setState("closed")}nextId(){this.requestSeq+=1;return`c${this.requestSeq}`}assertReady(){if(this.state!=="ready"||!this.transport){throw new a(`client is ${this.state}, not ready`)}}async request(e,t){const r=this.transport;if(!r||this.state!=="ready"){throw new a(`client is ${this.state}, not ready`)}const s=new Promise((o,n)=>{this.pending.set(e,{resolve:o,reject:n})});r.write(l({...t,id:e}));return s}async connectOnce(){const e=await this.connectOverride?.()??await this.connectSocket(this.socketPath);this.transport=e;this.readerTask=this.readLoop(e);let t;try{t=await this.handshake(e)}catch(r){e.end();this.transport=void 0;throw r}this.welcome=t;this.reconnectAttempts=0;this.setState("ready");for(const[r,s]of this.attachments){e.write(l({type:"session.attach",id:this.nextId(),sessionId:r,role:s.role,...s.toolEnv!==void 0?{toolEnv:s.toolEnv}:{}}))}for(const r of this.subscriptions){void this.sendSubscribe(r)}if(this.reconnectAttempts>0){const r=this.reconnectAttempts;this.reconnectAttempts=0;for(const s of this.reconnectedListeners)s({attempts:r})}return t}async connectSocket(e){return await new Promise((t,r)=>{const s=N.connect(e);const o=n=>{s.destroy();r(new S(n.message,n.code))};s.once("error",o);s.once("connect",()=>{s.removeListener("error",o);t(new m(s))})})}handshake(e){const t=this.handshakePayload;const r=t.tokenGetter?.();e.write(l({type:"hello",version:d,minor:y,features:[...f],...r!==void 0?{token:r}:t.token!==void 0?{token:t.token}:{},...t.dataDir!==void 0?{dataDir:t.dataDir}:{},...t.env!==void 0?{env:t.env}:{},...t.clientInstanceId!==void 0?{clientInstanceId:t.clientInstanceId}:{},...t.client!==void 0?{client:t.client}:{},...t.promptMode!==void 0?{promptMode:t.promptMode}:{}}));return new Promise((s,o)=>{this.helloWaiters.push({resolve:s,reject:o})})}async readLoop(e){try{const t=e.lines();for(;;){const r=await t.next();if(r.done)break;this.handleFrame(JSON.parse(r.value))}}catch(t){c.warn("client-read-failed",{err:t})}finally{if(this.transport===e){this.transport=void 0;this.onConnectionLost()}}}handleFrame(e){switch(e.type){case"response":{if(e.command==="hello"){const s=this.helloWaiters.shift();if(!s)return;if(e.success)s.resolve(e.data);else s.reject(new u(e.error,{code:e.errorCode}));return}const t=e.id;if(t===void 0)return;const r=this.pending.get(t);if(!r)return;this.pending.delete(t);if(e.success)r.resolve(e.data);else r.reject(new u(e.error,{code:e.errorCode,errorName:e.errorName,data:e.errorData}));return}case"event":{for(const t of this.subscriptions){if(t.stopped)continue;if(t.lastCursor!==null&&Number(e.cursor)<=Number(t.lastCursor)){continue}t.lastCursor=e.cursor;q(t,{cursor:e.cursor,event:e.event})}return}case"replay_gap":{for(const t of this.subscriptions){const r=t.lastCursor!==null;t.lastCursor=null;t.settleGap({after:e.after,head:e.head});if(r)void this.sendSubscribe(t)}return}case"stream.frame":{const t=this.streams.get(e.streamId);if(!t){this.orphan(e.streamId,{frame:e.frame});return}if(t.finished)return;L(t,e.frame);return}case"stream.end":{const t=this.streams.get(e.streamId);const r={reason:e.reason,resumable:e.resumable,error:e.error};if(!t){this.orphan(e.streamId,{end:r});return}if(t.finished)return;C(t,r);return}case"pong":case"bye":case"notice":return}}orphan(e,t){let r=this.orphanFrames.get(e);if(!r){r=[];this.orphanFrames.set(e,r)}r.push(t);if(r.length>4096)this.orphanFrames.delete(e)}makeStream(e){const t={streamId:e,queue:[],waiters:[],ended:void 0,settleEnd:()=>void 0,finished:false};t.ended=new Promise(s=>{t.settleEnd=s});this.streams.set(e,t);const r=this.orphanFrames.get(e);this.orphanFrames.delete(e);if(r){for(const s of r){if(s.end!==void 0){C(t,s.end);break}L(t,s.frame)}}return{streamId:e,frames:this.iterateStream(t),ended:t.ended,detach:()=>{void this.request(this.nextId(),{type:"stream.cancel",streamId:e,mode:"detach"}).catch(()=>void 0)},abort:async()=>{await this.request(this.nextId(),{type:"stream.cancel",streamId:e,mode:"abort"})}}}iterateStream(e){const t=this.creditStep;const r={[Symbol.asyncIterator]:()=>r,next:()=>{const s=e.queue.shift();if(s!==void 0){this.refill(e.streamId,t);return Promise.resolve({done:false,value:s})}if(e.finished)return Promise.resolve({done:true,value:void 0});return new Promise(o=>e.waiters.push(n=>{if(!n.done)this.refill(e.streamId,t);o(n)}))}};return r}refill(e,t){if(this.state!=="ready"||!this.transport)return;this.transport.write(l({type:"stream.credit",streamId:e,frames:t}))}async sendSubscribe(e){if(this.state!=="ready"||!this.transport)return;const t={type:"subscribe",id:this.nextId(),scope:e.scope,...e.lastCursor!==null?{after:e.lastCursor}:{}};try{await this.request(t.id,t)}catch(r){if(this.userClosed||this.connectionState==="closed"){c.debug("subscribe-failed",{err:r});return}c.warn("subscribe-failed",{err:r})}}onConnectionLost(){for(const[e,t]of this.pending){this.pending.delete(e);t.reject(new a("connection lost"))}for(const e of[...this.streams.values()]){C(e,{reason:"error",error:"connection lost",resumable:true})}for(const e of this.helloWaiters.splice(0)){e.reject(new a("connection lost"))}if(this.userClosed)return;this.setState("reconnecting");this.reconnectTask??=this.reconnectLoop()}async reconnectLoop(){try{for(;;){if(this.userClosed)return;const e=Math.min(this.backoffMinMs*2**this.reconnectAttempts,this.backoffMaxMs);this.reconnectAttempts+=1;await x(e);if(this.userClosed)return;try{await this.connectOnce();return}catch(t){c.warn("reconnect-failed",{err:t,attempts:this.reconnectAttempts});if(this.spawnHook&&t instanceof S){try{await this.spawnHook()}catch(r){c.warn("client-spawn-failed",{err:r})}}}}}finally{this.reconnectTask=void 0}}teardown(e){for(const[t,r]of this.pending){this.pending.delete(t);r.reject(new a(e))}for(const t of[...this.streams.values()]){C(t,{reason:"error",error:e})}for(const t of this.helloWaiters.splice(0)){t.reject(new a(e))}this.transport?.end();this.transport=void 0}setState(e){if(this.state===e)return;this.state=e;for(const t of this.stateListeners)t(e)}};function q(i,e){const t=i.waiters.shift();if(t){t({done:false,value:e});return}i.queue.push(e)}function W(i){const e={[Symbol.asyncIterator]:()=>e,next:()=>{const t=i.queue.shift();if(t!==void 0)return Promise.resolve({done:false,value:t});if(i.stopped)return Promise.resolve({done:true,value:void 0});return new Promise(r=>i.waiters.push(r))}};return e}function L(i,e){const t=i.waiters.shift();if(t){t({done:false,value:e});return}i.queue.push(e)}function C(i,e){if(i.finished)return;i.finished=true;for(const t of i.waiters.splice(0))t({done:true,value:void 0});i.settleEnd(e)}var S=class extends Error{errno;constructor(e,t){super(e);this.name="SocketConnectError";this.errno=t}};var T=class{constructor(e){this.client=e}client;sendMessage(e,t){return this.openConversationStream("sendMessage",t?[e,t]:[e])}async resumeSession(e){return this.openConversationStream("resumeSession",[e])}watchSessionUsageCommits(){const e=()=>this.client.openStream("watchSessionUsageCommits",[]);const t=(async function*(){const r=await e();for await(const s of r.frames){if(typeof s==="string")yield s}})();return t}watchEvents(){const e=this.client.subscribe({scope:"all"});const t=(async function*(){for await(const r of e.events)yield r.event})();return{events:t,gapped:e.gapped,stop:e.stop}}async invoke(e,...t){return await this.client.call(e,...t)}async openConversationStream(e,t){try{const r=await this.client.openStream(e,t);return{ok:true,source:r.frames}}catch(r){if(r instanceof u&&r.data!==void 0){const s=r.data;if(typeof s.status==="number"){return{ok:false,status:s.status,body:s.body}}}throw r}}listSessions(...e){return this.invoke("listSessions",...e)}createSession(...e){return this.invoke("createSession",...e)}getSession(...e){return this.invoke("getSession",...e)}getSessionTree(...e){return this.invoke("getSessionTree",...e)}getMessages(...e){return this.invoke("getMessages",...e)}updateSession(...e){return this.invoke("updateSession",...e)}archiveSession(...e){return this.invoke("archiveSession",...e)}deleteSession(...e){return this.invoke("deleteSession",...e)}listSessionInputSummaries(...e){return this.invoke("listSessionInputSummaries",...e)}getSessionRewindPreview(...e){return this.invoke("getSessionRewindPreview",...e)}rewindSession(...e){return this.invoke("rewindSession",...e)}editSessionMessage(...e){return this.invoke("editSessionMessage",...e)}configureSessionMcpServers(...e){return this.invoke("configureSessionMcpServers",...e)}clearSessionMcpServers(...e){return this.invoke("clearSessionMcpServers",...e)}forkSession(...e){return this.invoke("forkSession",...e)}getSessionForkOptions(...e){return this.invoke("getSessionForkOptions",...e)}abortSession(...e){return this.invoke("abortSession",...e)}steerSession(...e){return this.invoke("steerSession",...e)}steer(...e){return this.invoke("steer",...e)}enqueueMessage(...e){return this.invoke("enqueueMessage",...e)}getPendingQuestionnaire(...e){return this.invoke("getPendingQuestionnaire",...e)}replyQuestionnaire(...e){return this.invoke("replyQuestionnaire",...e)}dismissQuestionnaire(...e){return this.invoke("dismissQuestionnaire",...e)}getLatestPlanReview(...e){return this.invoke("getLatestPlanReview",...e)}getPlanModeCapabilities(...e){return this.invoke("getPlanModeCapabilities",...e)}listPendingPermissions(...e){return this.invoke("listPendingPermissions",...e)}replyPermission(...e){return this.invoke("replyPermission",...e)}listQueueMessages(...e){return this.invoke("listQueueMessages",...e)}getQueueItem(...e){return this.invoke("getQueueItem",...e)}updateQueueItem(...e){return this.invoke("updateQueueItem",...e)}reorderQueue(...e){return this.invoke("reorderQueue",...e)}deleteQueueItem(...e){return this.invoke("deleteQueueItem",...e)}getSessionUsage(...e){return this.invoke("getSessionUsage",...e)}getSessionUsageSummary(...e){return this.invoke("getSessionUsageSummary",...e)}getSessionCacheWarmingStatus(...e){return this.invoke("getSessionCacheWarmingStatus",...e)}requestCompaction(...e){return this.invoke("requestCompaction",...e)}listSkills(...e){return this.invoke("listSkills",...e)}listRuntimeSkills(...e){return this.invoke("listRuntimeSkills",...e)}collectSessionReport(...e){return this.invoke("collectSessionReport",...e)}getPermissionMode(...e){return this.invoke("getPermissionMode",...e)}setPermissionMode(...e){return this.invoke("setPermissionMode",...e)}bindSessionPermissionMode(...e){return this.invoke("bindSessionPermissionMode",...e)}setSessionPermissionMode(...e){return this.invoke("setSessionPermissionMode",...e)}getSessionPermissionMode(...e){return this.invoke("getSessionPermissionMode",...e)}getDangerousCommandGateEnabled(...e){return this.invoke("getDangerousCommandGateEnabled",...e)}setDangerousCommandGateEnabled(...e){return this.invoke("setDangerousCommandGateEnabled",...e)}getSandboxFilesystemMode(...e){return this.invoke("getSandboxFilesystemMode",...e)}setSandboxFilesystemMode(...e){return this.invoke("setSandboxFilesystemMode",...e)}listModels(...e){return this.invoke("listModels",...e)}selectModel(...e){return this.invoke("selectModel",...e)}setModelFavorite(...e){return this.invoke("setModelFavorite",...e)}getRuntimeDiagnostics(...e){return this.invoke("getRuntimeDiagnostics",...e)}getAccountStatus(...e){return this.invoke("getAccountStatus",...e)}getInstructionSources(...e){return this.invoke("getInstructionSources",...e)}isGoalEnabled(...e){return this.invoke("isGoalEnabled",...e)}getGoal(...e){return this.invoke("getGoal",...e)}createGoal(...e){return this.invoke("createGoal",...e)}patchGoal(...e){return this.invoke("patchGoal",...e)}clearGoal(...e){return this.invoke("clearGoal",...e)}listBackgroundTasks(...e){return this.invoke("listBackgroundTasks",...e)}getActiveTurn(...e){return this.invoke("getActiveTurn",...e)}getTurnStatus(...e){return this.invoke("getTurnStatus",...e)}refreshPlugins(...e){return this.invoke("refreshPlugins",...e)}listMarketplacePlugins(...e){return this.invoke("listMarketplacePlugins",...e)}listInstalledPlugins(...e){return this.invoke("listInstalledPlugins",...e)}installPlugin(...e){return this.invoke("installPlugin",...e)}enablePlugin(...e){return this.invoke("enablePlugin",...e)}disablePlugin(...e){return this.invoke("disablePlugin",...e)}uninstallPlugin(...e){return this.invoke("uninstallPlugin",...e)}getWorkspaceGitMetadata(...e){return this.invoke("getWorkspaceGitMetadata",...e)}getWorkspaceReviewLink(...e){return this.invoke("getWorkspaceReviewLink",...e)}listWorkspaceFileTree(...e){return this.invoke("listWorkspaceFileTree",...e)}searchWorkspaceFiles(...e){return this.invoke("searchWorkspaceFiles",...e)}listMcpServers(...e){return this.invoke("listMcpServers",...e)}inspectProjectMcp(...e){return this.invoke("inspectProjectMcp",...e)}listUserModelProviders(...e){return this.invoke("listUserModelProviders",...e)}listProviderPresets(...e){return this.invoke("listProviderPresets",...e)}getCodexOAuthStatus(...e){return this.invoke("getCodexOAuthStatus",...e)}startCodexOAuthLogin(...e){return this.invoke("startCodexOAuthLogin",...e)}cancelCodexOAuthLogin(...e){return this.invoke("cancelCodexOAuthLogin",...e)}getMiniMaxApiKeyStatus(...e){return this.invoke("getMiniMaxApiKeyStatus",...e)}getMiniMaxModelSource(...e){return this.invoke("getMiniMaxModelSource",...e)}setMiniMaxModelSource(...e){return this.invoke("setMiniMaxModelSource",...e)}upsertMiniMaxApiKey(...e){return this.invoke("upsertMiniMaxApiKey",...e)}createUserModelProvider(...e){return this.invoke("createUserModelProvider",...e)}discoverUserModelsCandidate(...e){return this.invoke("discoverUserModelsCandidate",...e)}saveUserModelProviderCandidate(...e){return this.invoke("saveUserModelProviderCandidate",...e)}updateUserModelProvider(...e){return this.invoke("updateUserModelProvider",...e)}deleteUserModelProvider(...e){return this.invoke("deleteUserModelProvider",...e)}testUserModelProvider(...e){return this.invoke("testUserModelProvider",...e)}testUserModel(...e){return this.invoke("testUserModel",...e)}};export{R as a,u as b,A as c,T as d,I as e,F as f,H as g};
2
+ import{a as d,b as y,c as f,d as M,e as l,f as m}from"./chunk-O5EROATK.js";import{a as k}from"./chunk-VAARXN34.js";import _ from"node:net";var P=5e3;async function I(i,e={}){try{return await w(i,e.timeoutMs,async t=>{p(t,l({type:"hello",version:d,...e.token!==void 0?{token:e.token}:{},...e.dataDir!==void 0?{dataDir:e.dataDir}:{},...e.env!==void 0?{env:e.env}:{}}));const r=await h(t,e.timeoutMs);if(r.type!=="response"||r.command!=="hello"){return{ok:false,error:`unexpected frame in reply to hello: ${JSON.stringify(r).slice(0,120)}`}}if(!r.success){return{ok:false,error:r.error,...r.errorCode?{errorCode:r.errorCode}:{}}}return{ok:true,data:r.data}})}catch(t){return g(t)}}async function F(i,e={}){try{return await w(i,e.timeoutMs,async t=>{p(t,l({type:"hello",version:d,...e.token!==void 0?{token:e.token}:{},...e.dataDir!==void 0?{dataDir:e.dataDir}:{},...e.env!==void 0?{env:e.env}:{}}));const r=await h(t,e.timeoutMs);if(r.type!=="response"||r.command!=="hello"){return{ok:false,error:"unexpected handshake reply"}}if(!r.success){return{ok:false,error:r.error,...r.errorCode?{errorCode:r.errorCode}:{}}}p(t,l({type:"shutdown"}));for(;;){const s=await h(t,e.timeoutMs);if(s.type==="response"&&s.command==="shutdown"&&!s.success){return{ok:false,error:s.error,...s.errorCode?{errorCode:s.errorCode}:{}}}if(s.type==="bye"||s.type==="response")break}return{ok:true,data:{accepted:true}}})}catch(t){return g(t)}}async function H(i,e={}){try{return await w(i,e.timeoutMs,async t=>{p(t,l({type:"hello",version:d,...e.token!==void 0?{token:e.token}:{},...e.dataDir!==void 0?{dataDir:e.dataDir}:{},...e.env!==void 0?{env:e.env}:{}}));const r=await h(t,e.timeoutMs);if(r.type!=="response"||r.command!=="hello"){return{ok:false,error:"unexpected handshake reply"}}if(!r.success){return{ok:false,error:r.error,...r.errorCode?{errorCode:r.errorCode}:{}}}p(t,l({type:"daemon.status",id:"active-runs"}));const s=await h(t,e.timeoutMs);if(s.type!=="response"||s.command!=="daemon.status"){return{ok:false,error:`unexpected frame in reply to daemon.status: ${JSON.stringify(s).slice(0,120)}`}}if(!s.success){return{ok:false,error:s.error,...s.errorCode?{errorCode:s.errorCode}:{}}}const o=s.data??{};return{ok:true,data:{runs:Array.isArray(o.activeRuns)?o.activeRuns:[],activeRunsReported:Array.isArray(o.activeRuns),...typeof o.activeTurns==="number"?{activeTurns:o.activeTurns}:{}}}})}catch(t){return g(t)}}function g(i){const e=i.code;return{ok:false,error:i instanceof Error?i.message:String(i),...typeof e==="string"?{errno:e}:{}}}async function w(i,e,t){const r=e??P;const s=await G(i,r);try{return await t(s)}finally{s.end()}}function G(i,e){return new Promise((t,r)=>{const s=_.connect(i);const o=setTimeout(()=>{s.destroy();r(new Error(`connect ${i} timed out after ${e} ms`))},e);o.unref?.();s.once("connect",()=>{clearTimeout(o);t(new m(s))});s.once("error",n=>{clearTimeout(o);r(n)})})}function p(i,e){i.write(e)}async function h(i,e){const t=i.lines();const r=e??P;let s;const o=new Promise((n,O)=>{s=setTimeout(()=>{O(new Error(`daemon reply timed out after ${r} ms`))},r);s.unref?.()});try{const n=await Promise.race([t.next(),o]);if(n.done)throw new Error("daemon closed the connection before replying");return JSON.parse(n.value)}finally{if(s)clearTimeout(s)}}import N from"node:net";import{setTimeout as x}from"node:timers/promises";var E=6e4;var b=3;var D=6e4;var v=class extends Error{name="McodedCrashLoopError";crashes;windowMs;retryAfterMs;constructor(e,t){super(`mcoded crash-loop: ${e.crashes} daemon starts failed within ${Math.round(e.windowMs/1e3)}s; auto-spawn stopped. See the daemon log${t?` (${t} and .1\u2026)`:""} for the cause, or set MCODE_SERVER_MODE=off to run without the daemon. Respawning resumes after ${Math.ceil(e.retryAfterMs/1e3)}s of quiet.`);this.crashes=e.crashes;this.windowMs=e.windowMs;this.retryAfterMs=e.retryAfterMs}};var R=class{windowMs;maxCrashes;cooldownMs;logPath;now;crashes=[];trippedAt;constructor(e={}){this.windowMs=e.windowMs??E;this.maxCrashes=e.maxCrashes??b;this.cooldownMs=e.cooldownMs??D;this.logPath=e.logPath;this.now=e.now??Date.now}recordCrash(){const e=this.now();this.prune(e);this.crashes.push(e);if(this.trippedAt!==void 0){if(e-this.trippedAt>=this.cooldownMs&&this.crashes.length===0){this.trippedAt=void 0}}if(this.trippedAt!==void 0||this.crashes.length>=this.maxCrashes){this.trippedAt??=e;return{allowSpawn:false,crashes:this.crashes.length,windowMs:this.windowMs,retryAfterMs:Math.max(0,this.trippedAt+this.cooldownMs-e)}}return{allowSpawn:true}}canSpawn(){if(this.trippedAt===void 0)return true;const e=this.now();this.prune(e);if(e-this.trippedAt>=this.cooldownMs&&this.crashes.length===0){this.trippedAt=void 0;return true}return false}requireSpawn(){if(this.canSpawn())return;throw new v({allowSpawn:false,crashes:this.maxCrashes,windowMs:this.windowMs,retryAfterMs:Math.max(0,this.trippedAt+this.cooldownMs-this.now())},this.logPath)}tripMessage(e){return new v(e,this.logPath).message}prune(e){while(this.crashes.length>0&&e-this.crashes[0]>this.windowMs){this.crashes.shift()}}};var c=k("mcode:rpc");var u=class extends Error{code;errorName;data;constructor(e,t={}){super(e);this.name="McodedRemoteError";this.code=t.code;this.errorName=t.errorName;this.data=t.data}};var a=class extends Error{constructor(e){super(e);this.name="McodedConnectionError"}};function U(i,e){const t={scope:i,lastCursor:e,queue:[],waiters:[],stopped:false,gapped:Promise.resolve(void 0),settleGap:()=>void 0};t.gapped=new Promise(r=>{t.settleGap=r});return t}var A=class{socketPath;handshakePayload;connectOverride;spawnHook;crashLoop;readyTimeoutMs;backoffMinMs;backoffMaxMs;creditStep;initialStreamCredit;stateListeners=[];reconnectedListeners=[];transport;readerTask;reconnectTask;state="disconnected";pending=new Map;streams=new Map;orphanFrames=new Map;subscriptions=new Set;attachments=new Map;requestSeq=0;welcome;reconnectAttempts=0;userClosed=false;helloWaiters=[];constructor(e){this.socketPath=e.socketPath;this.handshakePayload=e.handshake;this.connectOverride=e.connect;this.spawnHook=e.spawn;this.crashLoop=e.crashLoop;this.readyTimeoutMs=e.readyTimeoutMs??2e4;this.backoffMinMs=e.backoffMinMs??100;this.backoffMaxMs=e.backoffMaxMs??2e3;this.creditStep=e.creditStep??1;this.initialStreamCredit=e.initialStreamCredit??M;if(e.onStateChange)this.stateListeners.push(e.onStateChange);if(e.onReconnected)this.reconnectedListeners.push(e.onReconnected)}onStateChange(e){this.stateListeners.push(e);return()=>{const t=this.stateListeners.indexOf(e);if(t>=0)this.stateListeners.splice(t,1)}}onReconnected(e){this.reconnectedListeners.push(e);return()=>{const t=this.reconnectedListeners.indexOf(e);if(t>=0)this.reconnectedListeners.splice(t,1)}}get connectionState(){return this.state}get hello(){return this.welcome}hasFeature(e){return this.welcome?.features?.includes(e)??false}requireFeature(e){const t=this.welcome?.features;if(t===void 0||t.includes(e))return;throw new a(`the daemon does not advertise feature "${e}" (it is older than this client); run "mcode daemon restart" to bring it to the current build`)}async connect(){if(this.state==="ready"&&this.welcome)return this.welcome;if(this.state==="closed")throw new a("client is closed");this.userClosed=false;this.setState("connecting");const e=Date.now()+this.readyTimeoutMs*4;let t=Date.now()+this.readyTimeoutMs;let r;for(;;){try{return await this.connectOnce()}catch(s){if(this.userClosed)throw new a("client closed during connect");if(!(s instanceof S))throw s;if(this.spawnHook){this.crashLoop?.requireSpawn();let o=false;try{o=await this.spawnHook()===true;r=void 0}catch(n){c.warn("client-spawn-failed",{err:n});r=n}if(this.crashLoop&&o)this.crashLoop.recordCrash();this.crashLoop?.requireSpawn();if(o||r===void 0){t=Math.min(Date.now()+this.readyTimeoutMs,e)}}if(Date.now()>=t){if(r!==void 0){throw new a(`daemon socket is not answering and auto-spawn failed: ${r instanceof Error?r.message:String(r)}`)}throw s}await x(Math.min(this.backoffMinMs*2**this.reconnectAttempts,this.backoffMaxMs))}}}async call(e,...t){this.assertReady();this.requireFeature("call");const r=await this.request(this.nextId(),{type:"call",id:"pending",method:e,params:t});return r}async callIdempotent(e,t,...r){this.assertReady();this.requireFeature("call");const s=await this.request(e,{type:"call",id:e,method:t,params:r});return s}async openStream(e,t,r){this.assertReady();this.requireFeature("stream");const s={type:"stream.open",id:this.nextId(),method:e,params:t,...r!==void 0?{credit:r}:{credit:this.initialStreamCredit}};const o=await this.request(s.id,s);return this.makeStream(o.streamId)}async sessionAttach(e,t="owner",r){this.assertReady();this.requireFeature("attach");const s=this.nextId();await this.request(s,{type:"session.attach",id:s,sessionId:e,role:t,...r!==void 0?{toolEnv:r}:{}});this.attachments.set(e,{role:t,...r!==void 0?{toolEnv:r}:{}})}async sessionDetach(e){this.assertReady();this.requireFeature("attach");const t=this.nextId();await this.request(t,{type:"session.detach",id:t,sessionId:e});this.attachments.delete(e)}subscribe(e={}){this.assertReady();this.requireFeature("subscribe");const t=U(e.scope??"catalog+attached",e.after??null);this.subscriptions.add(t);void this.sendSubscribe(t);return{events:W(t),gapped:t.gapped,stop:()=>{t.stopped=true;this.subscriptions.delete(t);for(const r of t.waiters.splice(0)){r({done:true,value:void 0})}}}}async ping(){this.assertReady();const e=this.nextId();await this.request(e,{type:"ping",id:e})}async daemonStatus(){this.assertReady();const e=this.nextId();return await this.request(e,{type:"daemon.status",id:e})}async daemonRestart(e){this.assertReady();if(e==="idle")this.requireFeature("restart-when-idle");const t=this.nextId();await this.request(t,{type:"daemon.restart",id:t,when:e})}async daemonAuthSync(){this.assertReady();const e=this.nextId();await this.request(e,{type:"daemon.authSync",id:e})}async shutdown(){this.assertReady();const e=this.nextId();await this.request(e,{type:"shutdown",id:e})}close(){this.userClosed=true;this.teardown("client closed");this.setState("closed")}nextId(){this.requestSeq+=1;return`c${this.requestSeq}`}assertReady(){if(this.state!=="ready"||!this.transport){throw new a(`client is ${this.state}, not ready`)}}async request(e,t){const r=this.transport;if(!r||this.state!=="ready"){throw new a(`client is ${this.state}, not ready`)}const s=new Promise((o,n)=>{this.pending.set(e,{resolve:o,reject:n})});r.write(l({...t,id:e}));return s}async connectOnce(){const e=await this.connectOverride?.()??await this.connectSocket(this.socketPath);this.transport=e;this.readerTask=this.readLoop(e);let t;try{t=await this.handshake(e)}catch(r){e.end();this.transport=void 0;throw r}this.welcome=t;this.reconnectAttempts=0;this.setState("ready");for(const[r,s]of this.attachments){e.write(l({type:"session.attach",id:this.nextId(),sessionId:r,role:s.role,...s.toolEnv!==void 0?{toolEnv:s.toolEnv}:{}}))}for(const r of this.subscriptions){void this.sendSubscribe(r)}if(this.reconnectAttempts>0){const r=this.reconnectAttempts;this.reconnectAttempts=0;for(const s of this.reconnectedListeners)s({attempts:r})}return t}async connectSocket(e){return await new Promise((t,r)=>{const s=N.connect(e);const o=n=>{s.destroy();r(new S(n.message,n.code))};s.once("error",o);s.once("connect",()=>{s.removeListener("error",o);t(new m(s))})})}handshake(e){const t=this.handshakePayload;const r=t.tokenGetter?.();e.write(l({type:"hello",version:d,minor:y,features:[...f],...r!==void 0?{token:r}:t.token!==void 0?{token:t.token}:{},...t.dataDir!==void 0?{dataDir:t.dataDir}:{},...t.env!==void 0?{env:t.env}:{},...t.clientInstanceId!==void 0?{clientInstanceId:t.clientInstanceId}:{},...t.client!==void 0?{client:t.client}:{},...t.promptMode!==void 0?{promptMode:t.promptMode}:{}}));return new Promise((s,o)=>{this.helloWaiters.push({resolve:s,reject:o})})}async readLoop(e){try{const t=e.lines();for(;;){const r=await t.next();if(r.done)break;this.handleFrame(JSON.parse(r.value))}}catch(t){c.warn("client-read-failed",{err:t})}finally{if(this.transport===e){this.transport=void 0;this.onConnectionLost()}}}handleFrame(e){switch(e.type){case"response":{if(e.command==="hello"){const s=this.helloWaiters.shift();if(!s)return;if(e.success)s.resolve(e.data);else s.reject(new u(e.error,{code:e.errorCode}));return}const t=e.id;if(t===void 0)return;const r=this.pending.get(t);if(!r)return;this.pending.delete(t);if(e.success)r.resolve(e.data);else r.reject(new u(e.error,{code:e.errorCode,errorName:e.errorName,data:e.errorData}));return}case"event":{for(const t of this.subscriptions){if(t.stopped)continue;if(t.lastCursor!==null&&Number(e.cursor)<=Number(t.lastCursor)){continue}t.lastCursor=e.cursor;q(t,{cursor:e.cursor,event:e.event})}return}case"replay_gap":{for(const t of this.subscriptions){const r=t.lastCursor!==null;t.lastCursor=null;t.settleGap({after:e.after,head:e.head});if(r)void this.sendSubscribe(t)}return}case"stream.frame":{const t=this.streams.get(e.streamId);if(!t){this.orphan(e.streamId,{frame:e.frame});return}if(t.finished)return;L(t,e.frame);return}case"stream.end":{const t=this.streams.get(e.streamId);const r={reason:e.reason,resumable:e.resumable,error:e.error};if(!t){this.orphan(e.streamId,{end:r});return}if(t.finished)return;C(t,r);return}case"pong":case"bye":case"notice":return}}orphan(e,t){let r=this.orphanFrames.get(e);if(!r){r=[];this.orphanFrames.set(e,r)}r.push(t);if(r.length>4096)this.orphanFrames.delete(e)}makeStream(e){const t={streamId:e,queue:[],waiters:[],ended:void 0,settleEnd:()=>void 0,finished:false};t.ended=new Promise(s=>{t.settleEnd=s});this.streams.set(e,t);const r=this.orphanFrames.get(e);this.orphanFrames.delete(e);if(r){for(const s of r){if(s.end!==void 0){C(t,s.end);break}L(t,s.frame)}}return{streamId:e,frames:this.iterateStream(t),ended:t.ended,detach:()=>{void this.request(this.nextId(),{type:"stream.cancel",streamId:e,mode:"detach"}).catch(()=>void 0)},abort:async()=>{await this.request(this.nextId(),{type:"stream.cancel",streamId:e,mode:"abort"})}}}iterateStream(e){const t=this.creditStep;const r={[Symbol.asyncIterator]:()=>r,next:()=>{const s=e.queue.shift();if(s!==void 0){this.refill(e.streamId,t);return Promise.resolve({done:false,value:s})}if(e.finished)return Promise.resolve({done:true,value:void 0});return new Promise(o=>e.waiters.push(n=>{if(!n.done)this.refill(e.streamId,t);o(n)}))}};return r}refill(e,t){if(this.state!=="ready"||!this.transport)return;this.transport.write(l({type:"stream.credit",streamId:e,frames:t}))}async sendSubscribe(e){if(this.state!=="ready"||!this.transport)return;const t={type:"subscribe",id:this.nextId(),scope:e.scope,...e.lastCursor!==null?{after:e.lastCursor}:{}};try{await this.request(t.id,t)}catch(r){if(this.userClosed||this.connectionState==="closed"){c.debug("subscribe-failed",{err:r});return}c.warn("subscribe-failed",{err:r})}}onConnectionLost(){for(const[e,t]of this.pending){this.pending.delete(e);t.reject(new a("connection lost"))}for(const e of[...this.streams.values()]){C(e,{reason:"error",error:"connection lost",resumable:true})}for(const e of this.helloWaiters.splice(0)){e.reject(new a("connection lost"))}if(this.userClosed)return;this.setState("reconnecting");this.reconnectTask??=this.reconnectLoop()}async reconnectLoop(){try{for(;;){if(this.userClosed)return;const e=Math.min(this.backoffMinMs*2**this.reconnectAttempts,this.backoffMaxMs);this.reconnectAttempts+=1;await x(e);if(this.userClosed)return;try{await this.connectOnce();return}catch(t){c.warn("reconnect-failed",{err:t,attempts:this.reconnectAttempts});if(this.spawnHook&&t instanceof S){try{await this.spawnHook()}catch(r){c.warn("client-spawn-failed",{err:r})}}}}}finally{this.reconnectTask=void 0}}teardown(e){for(const[t,r]of this.pending){this.pending.delete(t);r.reject(new a(e))}for(const t of[...this.streams.values()]){C(t,{reason:"error",error:e})}for(const t of this.helloWaiters.splice(0)){t.reject(new a(e))}this.transport?.end();this.transport=void 0}setState(e){if(this.state===e)return;this.state=e;for(const t of this.stateListeners)t(e)}};function q(i,e){const t=i.waiters.shift();if(t){t({done:false,value:e});return}i.queue.push(e)}function W(i){const e={[Symbol.asyncIterator]:()=>e,next:()=>{const t=i.queue.shift();if(t!==void 0)return Promise.resolve({done:false,value:t});if(i.stopped)return Promise.resolve({done:true,value:void 0});return new Promise(r=>i.waiters.push(r))}};return e}function L(i,e){const t=i.waiters.shift();if(t){t({done:false,value:e});return}i.queue.push(e)}function C(i,e){if(i.finished)return;i.finished=true;for(const t of i.waiters.splice(0))t({done:true,value:void 0});i.settleEnd(e)}var S=class extends Error{errno;constructor(e,t){super(e);this.name="SocketConnectError";this.errno=t}};var T=class{constructor(e){this.client=e}client;sendMessage(e,t){return this.openConversationStream("sendMessage",t?[e,t]:[e])}async resumeSession(e){return this.openConversationStream("resumeSession",[e])}watchSessionUsageCommits(){const e=()=>this.client.openStream("watchSessionUsageCommits",[]);const t=(async function*(){const r=await e();for await(const s of r.frames){if(typeof s==="string")yield s}})();return t}watchEvents(){const e=this.client.subscribe({scope:"all"});const t=(async function*(){for await(const r of e.events)yield r.event})();return{events:t,gapped:e.gapped,stop:e.stop}}async invoke(e,...t){return await this.client.call(e,...t)}async openConversationStream(e,t){try{const r=await this.client.openStream(e,t);return{ok:true,source:r.frames}}catch(r){if(r instanceof u&&r.data!==void 0){const s=r.data;if(typeof s.status==="number"){return{ok:false,status:s.status,body:s.body}}}throw r}}listSessions(...e){return this.invoke("listSessions",...e)}createSession(...e){return this.invoke("createSession",...e)}getSession(...e){return this.invoke("getSession",...e)}getSessionTree(...e){return this.invoke("getSessionTree",...e)}getMessages(...e){return this.invoke("getMessages",...e)}updateSession(...e){return this.invoke("updateSession",...e)}archiveSession(...e){return this.invoke("archiveSession",...e)}deleteSession(...e){return this.invoke("deleteSession",...e)}listSessionInputSummaries(...e){return this.invoke("listSessionInputSummaries",...e)}getSessionRewindPreview(...e){return this.invoke("getSessionRewindPreview",...e)}rewindSession(...e){return this.invoke("rewindSession",...e)}editSessionMessage(...e){return this.invoke("editSessionMessage",...e)}configureSessionMcpServers(...e){return this.invoke("configureSessionMcpServers",...e)}clearSessionMcpServers(...e){return this.invoke("clearSessionMcpServers",...e)}forkSession(...e){return this.invoke("forkSession",...e)}getSessionForkOptions(...e){return this.invoke("getSessionForkOptions",...e)}abortSession(...e){return this.invoke("abortSession",...e)}steerSession(...e){return this.invoke("steerSession",...e)}steer(...e){return this.invoke("steer",...e)}enqueueMessage(...e){return this.invoke("enqueueMessage",...e)}getPendingQuestionnaire(...e){return this.invoke("getPendingQuestionnaire",...e)}replyQuestionnaire(...e){return this.invoke("replyQuestionnaire",...e)}dismissQuestionnaire(...e){return this.invoke("dismissQuestionnaire",...e)}getLatestPlanReview(...e){return this.invoke("getLatestPlanReview",...e)}getPlanModeCapabilities(...e){return this.invoke("getPlanModeCapabilities",...e)}listPendingPermissions(...e){return this.invoke("listPendingPermissions",...e)}replyPermission(...e){return this.invoke("replyPermission",...e)}listQueueMessages(...e){return this.invoke("listQueueMessages",...e)}getQueueItem(...e){return this.invoke("getQueueItem",...e)}updateQueueItem(...e){return this.invoke("updateQueueItem",...e)}reorderQueue(...e){return this.invoke("reorderQueue",...e)}deleteQueueItem(...e){return this.invoke("deleteQueueItem",...e)}getSessionUsage(...e){return this.invoke("getSessionUsage",...e)}getSessionUsageSummary(...e){return this.invoke("getSessionUsageSummary",...e)}getSessionCacheWarmingStatus(...e){return this.invoke("getSessionCacheWarmingStatus",...e)}requestCompaction(...e){return this.invoke("requestCompaction",...e)}listSkills(...e){return this.invoke("listSkills",...e)}listRuntimeSkills(...e){return this.invoke("listRuntimeSkills",...e)}collectSessionReport(...e){return this.invoke("collectSessionReport",...e)}getPermissionMode(...e){return this.invoke("getPermissionMode",...e)}setPermissionMode(...e){return this.invoke("setPermissionMode",...e)}bindSessionPermissionMode(...e){return this.invoke("bindSessionPermissionMode",...e)}setSessionPermissionMode(...e){return this.invoke("setSessionPermissionMode",...e)}getSessionPermissionMode(...e){return this.invoke("getSessionPermissionMode",...e)}getDangerousCommandGateEnabled(...e){return this.invoke("getDangerousCommandGateEnabled",...e)}setDangerousCommandGateEnabled(...e){return this.invoke("setDangerousCommandGateEnabled",...e)}getSandboxFilesystemMode(...e){return this.invoke("getSandboxFilesystemMode",...e)}setSandboxFilesystemMode(...e){return this.invoke("setSandboxFilesystemMode",...e)}listModels(...e){return this.invoke("listModels",...e)}selectModel(...e){return this.invoke("selectModel",...e)}setModelFavorite(...e){return this.invoke("setModelFavorite",...e)}getRuntimeDiagnostics(...e){return this.invoke("getRuntimeDiagnostics",...e)}getAccountStatus(...e){return this.invoke("getAccountStatus",...e)}getInstructionSources(...e){return this.invoke("getInstructionSources",...e)}isGoalEnabled(...e){return this.invoke("isGoalEnabled",...e)}getGoal(...e){return this.invoke("getGoal",...e)}createGoal(...e){return this.invoke("createGoal",...e)}patchGoal(...e){return this.invoke("patchGoal",...e)}clearGoal(...e){return this.invoke("clearGoal",...e)}listBackgroundTasks(...e){return this.invoke("listBackgroundTasks",...e)}getActiveTurn(...e){return this.invoke("getActiveTurn",...e)}getTurnStatus(...e){return this.invoke("getTurnStatus",...e)}refreshPlugins(...e){return this.invoke("refreshPlugins",...e)}listMarketplacePlugins(...e){return this.invoke("listMarketplacePlugins",...e)}listInstalledPlugins(...e){return this.invoke("listInstalledPlugins",...e)}installPlugin(...e){return this.invoke("installPlugin",...e)}enablePlugin(...e){return this.invoke("enablePlugin",...e)}disablePlugin(...e){return this.invoke("disablePlugin",...e)}uninstallPlugin(...e){return this.invoke("uninstallPlugin",...e)}getWorkspaceGitMetadata(...e){return this.invoke("getWorkspaceGitMetadata",...e)}getWorkspaceReviewLink(...e){return this.invoke("getWorkspaceReviewLink",...e)}listWorkspaceFileTree(...e){return this.invoke("listWorkspaceFileTree",...e)}searchWorkspaceFiles(...e){return this.invoke("searchWorkspaceFiles",...e)}listMcpServers(...e){return this.invoke("listMcpServers",...e)}inspectProjectMcp(...e){return this.invoke("inspectProjectMcp",...e)}listUserModelProviders(...e){return this.invoke("listUserModelProviders",...e)}listProviderPresets(...e){return this.invoke("listProviderPresets",...e)}getCodexOAuthStatus(...e){return this.invoke("getCodexOAuthStatus",...e)}startCodexOAuthLogin(...e){return this.invoke("startCodexOAuthLogin",...e)}cancelCodexOAuthLogin(...e){return this.invoke("cancelCodexOAuthLogin",...e)}getMiniMaxApiKeyStatus(...e){return this.invoke("getMiniMaxApiKeyStatus",...e)}getMiniMaxModelSource(...e){return this.invoke("getMiniMaxModelSource",...e)}setMiniMaxModelSource(...e){return this.invoke("setMiniMaxModelSource",...e)}upsertMiniMaxApiKey(...e){return this.invoke("upsertMiniMaxApiKey",...e)}createUserModelProvider(...e){return this.invoke("createUserModelProvider",...e)}discoverUserModelsCandidate(...e){return this.invoke("discoverUserModelsCandidate",...e)}saveUserModelProviderCandidate(...e){return this.invoke("saveUserModelProviderCandidate",...e)}updateUserModelProvider(...e){return this.invoke("updateUserModelProvider",...e)}deleteUserModelProvider(...e){return this.invoke("deleteUserModelProvider",...e)}testUserModelProvider(...e){return this.invoke("testUserModelProvider",...e)}testUserModel(...e){return this.invoke("testUserModel",...e)}};export{R as a,u as b,A as c,T as d,I as e,F as f,H as g};
@@ -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{i as m}from"./chunk-U6RWF7BC.js";import{oa as w}from"./chunk-UNEPZJKK.js";import{a as P}from"./chunk-NOGL6Y6L.js";import{appendFile as G,mkdir as Z,readdir as Q,rm as ee,stat as re}from"node:fs/promises";import{join as S}from"node:path";var ne=1;var te=16;var ie=3;var oe=120;var se=512;var ae=1e3;var de=32;var ce=7*24*60*60*1e3;var D="mcode-observability-";function ue(r){return S(r,"v2","observability","mcode")}function ir(r,e){return new T(r,e)}var or=Object.freeze({recordStartup:()=>void 0,recordAccess:()=>void 0,recordEventStream:()=>void 0,recordTerminal:()=>void 0,recordProcessStop:()=>void 0,recordTheme:()=>void 0,observeRender:()=>void 0,observeRenderWait:()=>void 0,recordTranscriptPerformance:()=>void 0,snapshot:()=>({filePath:"",eventCounts:{},accessSources:{},reconnects:0,render:{frames:0,averageDurationMs:0,maxDurationMs:0,p95DurationMs:0}}),flush:async()=>void 0});var T=class{surface;now;append;ready;pending=[];eventCounts=new Map;accessSources=new Map;renderDurations=[];writeChain=Promise.resolve();flushTimer;reconnects=0;renderFrames=0;renderDurationTotalMs=0;renderMaxDurationMs=0;lastRenderSummaryFrame=0;terminal;filePath;constructor(e,n){const t=n.startedAtMs??Date.now();const i=ue(e);this.surface=n.surface;this.now=n.now??Date.now;this.append=n.append??((d,a)=>G(d,a,{encoding:"utf8",mode:384}));this.filePath=S(i,`${D}${t}-${n.pid??process.pid}.jsonl`);const o=n.ensureDirectory??(d=>Z(d,{recursive:true}).then(()=>{}));const s=n.prune??le;this.ready=o(i).then(()=>s(i,t-ce)).catch(()=>void 0)}recordSideSessionFailure(e){const{error:n,...t}=e;this.record("session.side.failed",{...t,errors:me(n)})}recordClipboardRead(e){this.record("clipboard.read",e)}recordStopPolicy(e){this.record("stop.policy",e)}recordStartup(e){this.record("startup",e)}recordAccess(e){if(this.accessSources.get(e.operation)===e.source)return;this.accessSources.set(e.operation,e.source);this.record("runtime.access",e)}recordEventStream(e){if(e.state==="retry-scheduled")this.reconnects+=1;this.record("event.stream",e)}recordRunLifecycle(e){this.record("run.lifecycle",e)}recordTerminal(e){this.terminal=Object.freeze({...e});this.record("terminal.capability",e)}recordProcessStop(e){this.record("process.stop",e)}recordTheme(e){this.record("terminal.theme",e)}observeRender(e){const n=C(e.durationMs);this.renderFrames+=1;this.renderDurationTotalMs+=n;this.renderMaxDurationMs=Math.max(this.renderMaxDurationMs,n);this.renderDurations.push(n);if(this.renderDurations.length>se)this.renderDurations.shift();if(this.renderFrames<=ie||n>=te||this.renderFrames%oe===0){this.record("render.latency",{...e,durationMs:n,frame:this.renderFrames})}}observeRenderWait(e){this.record("render.wait",{...e,durationMs:C(e.durationMs)})}recordTranscriptPerformance(e){this.record("render.transcript",e)}snapshot(){return{filePath:this.filePath,eventCounts:{startup:this.eventCounts.get("startup")??0,runtimeAccess:this.eventCounts.get("runtime.access")??0,eventStream:this.eventCounts.get("event.stream")??0,terminal:this.eventCounts.get("terminal.capability")??0,processStop:this.eventCounts.get("process.stop")??0,renderLatency:this.eventCounts.get("render.latency")??0,renderWait:this.eventCounts.get("render.wait")??0,renderTranscript:this.eventCounts.get("render.transcript")??0,renderSummary:this.eventCounts.get("render.summary")??0},accessSources:Object.fromEntries(this.accessSources),reconnects:this.reconnects,render:this.renderSnapshot(),...this.terminal?{terminal:{...this.terminal}}:{}}}async flush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=void 0;if(this.renderFrames>this.lastRenderSummaryFrame){this.record("render.summary",this.renderSnapshot());this.lastRenderSummaryFrame=this.renderFrames}if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=void 0;this.queuePendingWrite();await this.writeChain}queuePendingWrite(){if(this.pending.length>0){const e=this.pending.splice(0);const n=`${e.map(t=>JSON.stringify(t)).join("\n")}
2
+ import{i as m}from"./chunk-U6RWF7BC.js";import{sa as w}from"./chunk-XWNCITOR.js";import{a as P}from"./chunk-7F3QKGB7.js";import{appendFile as G,mkdir as Z,readdir as Q,rm as ee,stat as re}from"node:fs/promises";import{join as S}from"node:path";var ne=1;var te=16;var ie=3;var oe=120;var se=512;var ae=1e3;var de=32;var ce=7*24*60*60*1e3;var D="mcode-observability-";function ue(r){return S(r,"v2","observability","mcode")}function ir(r,e){return new T(r,e)}var or=Object.freeze({recordStartup:()=>void 0,recordAccess:()=>void 0,recordEventStream:()=>void 0,recordTerminal:()=>void 0,recordProcessStop:()=>void 0,recordTheme:()=>void 0,observeRender:()=>void 0,observeRenderWait:()=>void 0,recordTranscriptPerformance:()=>void 0,snapshot:()=>({filePath:"",eventCounts:{},accessSources:{},reconnects:0,render:{frames:0,averageDurationMs:0,maxDurationMs:0,p95DurationMs:0}}),flush:async()=>void 0});var T=class{surface;now;append;ready;pending=[];eventCounts=new Map;accessSources=new Map;renderDurations=[];writeChain=Promise.resolve();flushTimer;reconnects=0;renderFrames=0;renderDurationTotalMs=0;renderMaxDurationMs=0;lastRenderSummaryFrame=0;terminal;filePath;constructor(e,n){const t=n.startedAtMs??Date.now();const i=ue(e);this.surface=n.surface;this.now=n.now??Date.now;this.append=n.append??((d,a)=>G(d,a,{encoding:"utf8",mode:384}));this.filePath=S(i,`${D}${t}-${n.pid??process.pid}.jsonl`);const o=n.ensureDirectory??(d=>Z(d,{recursive:true}).then(()=>{}));const s=n.prune??le;this.ready=o(i).then(()=>s(i,t-ce)).catch(()=>void 0)}recordSideSessionFailure(e){const{error:n,...t}=e;this.record("session.side.failed",{...t,errors:me(n)})}recordClipboardRead(e){this.record("clipboard.read",e)}recordStopPolicy(e){this.record("stop.policy",e)}recordStartup(e){this.record("startup",e)}recordAccess(e){if(this.accessSources.get(e.operation)===e.source)return;this.accessSources.set(e.operation,e.source);this.record("runtime.access",e)}recordEventStream(e){if(e.state==="retry-scheduled")this.reconnects+=1;this.record("event.stream",e)}recordRunLifecycle(e){this.record("run.lifecycle",e)}recordTerminal(e){this.terminal=Object.freeze({...e});this.record("terminal.capability",e)}recordProcessStop(e){this.record("process.stop",e)}recordTheme(e){this.record("terminal.theme",e)}observeRender(e){const n=C(e.durationMs);this.renderFrames+=1;this.renderDurationTotalMs+=n;this.renderMaxDurationMs=Math.max(this.renderMaxDurationMs,n);this.renderDurations.push(n);if(this.renderDurations.length>se)this.renderDurations.shift();if(this.renderFrames<=ie||n>=te||this.renderFrames%oe===0){this.record("render.latency",{...e,durationMs:n,frame:this.renderFrames})}}observeRenderWait(e){this.record("render.wait",{...e,durationMs:C(e.durationMs)})}recordTranscriptPerformance(e){this.record("render.transcript",e)}snapshot(){return{filePath:this.filePath,eventCounts:{startup:this.eventCounts.get("startup")??0,runtimeAccess:this.eventCounts.get("runtime.access")??0,eventStream:this.eventCounts.get("event.stream")??0,terminal:this.eventCounts.get("terminal.capability")??0,processStop:this.eventCounts.get("process.stop")??0,renderLatency:this.eventCounts.get("render.latency")??0,renderWait:this.eventCounts.get("render.wait")??0,renderTranscript:this.eventCounts.get("render.transcript")??0,renderSummary:this.eventCounts.get("render.summary")??0},accessSources:Object.fromEntries(this.accessSources),reconnects:this.reconnects,render:this.renderSnapshot(),...this.terminal?{terminal:{...this.terminal}}:{}}}async flush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=void 0;if(this.renderFrames>this.lastRenderSummaryFrame){this.record("render.summary",this.renderSnapshot());this.lastRenderSummaryFrame=this.renderFrames}if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=void 0;this.queuePendingWrite();await this.writeChain}queuePendingWrite(){if(this.pending.length>0){const e=this.pending.splice(0);const n=`${e.map(t=>JSON.stringify(t)).join("\n")}
3
3
  `;this.writeChain=this.writeChain.then(()=>this.ready).then(()=>this.append(this.filePath,n)).catch(()=>void 0)}}renderSnapshot(){return{frames:this.renderFrames,averageDurationMs:this.renderFrames===0?0:f(this.renderDurationTotalMs/this.renderFrames),maxDurationMs:f(this.renderMaxDurationMs),p95DurationMs:f(pe(this.renderDurations,.95))}}record(e,n){this.eventCounts.set(e,(this.eventCounts.get(e)??0)+1);this.pending.push({schemaVersion:ne,observedAtMs:Math.floor(this.now()),surface:this.surface,type:e,...n});if(this.pending.length>=de){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=void 0;this.queuePendingWrite();return}if(!this.flushTimer){this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;this.queuePendingWrite()},ae);this.flushTimer.unref?.()}}};async function le(r,e){const n=await Q(r,{withFileTypes:true});await Promise.all(n.filter(t=>t.isFile()&&t.name.startsWith(D)).map(async t=>{const i=S(r,t.name);const o=await re(i);if(o.mtimeMs<e)await ee(i,{force:true})}))}function C(r){return f(Math.max(0,Number.isFinite(r)?r:0))}function f(r){return Math.round(r*1e3)/1e3}function pe(r,e){if(r.length===0)return 0;const n=[...r].sort((i,o)=>i-o);const t=Math.max(0,Math.ceil(n.length*e)-1);return n[t]??0}function me(r){const e=[];let n=r;for(let t=0;n!==void 0&&t<3;t+=1){if(!(n instanceof Error)){e.push({message:m(String(n)).slice(0,1024)});break}const i=Reflect.get(n,"code");e.push({name:m(n.name).slice(0,128),message:m(n.message).slice(0,1024),...typeof i==="string"?{code:m(i).slice(0,128)}:{},...n.stack?{stack:m(n.stack).slice(0,2048)}:{}});n=n.cause}return e}import{createCipheriv as ye,createHash as he,hkdfSync as fe,randomBytes as be,randomUUID as _}from"node:crypto";import{chmodSync as F,mkdirSync as ve,readFileSync as A,readdirSync as ge,renameSync as L,rmSync as U,statSync as Te,writeFileSync as V}from"node:fs";import{arch as Se,platform as _e}from"node:os";import{basename as g,dirname as Ee,join as p}from"node:path";var Ie=["v2","observability","cli","incidents"];var y=2;var Me="v1";var Re="mcode-desktop-event-log-v1";var xe=200;var Ae=100;var B=20;var N=7*24*60*60*1e3;var Oe=6e4;var we=2e3;var Pe=1e4;var Ce=300;var k=20;var De={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimaxi.com"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};var Ne="/minimax-cloud/api/v1/observability/desktop-errors/batch";function ke(r){return p(r,...Ie)}function mr(r){try{return new E(r)}catch{return Fe}}var Fe=Object.freeze({runId:"",hasFatalIncident:false,capture:()=>void 0,breadcrumb:()=>void 0,setPhase:()=>void 0,drain:async()=>void 0,flush:async()=>void 0,completeRun:()=>void 0});function yr(r,e){try{return r?.capture(e)}catch{return void 0}}var E=class{constructor(e){this.options=e;this.directory=ke(e.dataDir);this.nowMs=e.nowMs??Date.now;this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis);this.pid=e.pid??process.pid;this.startedAtMs=this.nowMs();this.isProcessAlive=e.isProcessAlive??Je;this.markerPath=p(this.directory,`active-${this.runId}.json`);qe(this.directory);this.prune();this.recoverUncleanRuns();this.writeRunMarker();this.breadcrumb("cli.run.started",{phase:this.phase});void this.drain()}options;runId=_();directory;markerPath;nowMs;fetchImpl;pid;startedAtMs;isProcessAlive;breadcrumbs=[];recentFingerprints=new Map;activeRequestControllers=new Set;drainPromise;drainRequested=false;phase="startup";nonFatalIncidentCount=0;fatalIncidentCaptured=false;networkDrainStopped=false;completed=false;get hasFatalIncident(){return this.fatalIncidentCaptured}setPhase(e){if(this.completed||this.phase===e)return;this.phase=e;this.breadcrumb("cli.phase.changed",{phase:e});this.writeRunMarker()}breadcrumb(e,n){try{const t=u(e,$);if(!t)return;const i=u(n?.phase,I);this.breadcrumbs.push({occurredAtMs:Math.floor(this.nowMs()),name:t,...i?{details:{phase:i}}:{}});while(this.breadcrumbs.length>B)this.breadcrumbs.shift()}catch{}}capture(e){try{const n=u(e.eventType,W);if(!n)return void 0;const t=u(e.severity,j)??"error";if(t!=="fatal"&&this.nonFatalIncidentCount>=Ae){return void 0}const i=Math.floor(this.nowMs());const o=q(e.error);const s=J(n,o);const d=`${n}:${s}`;const a=this.recentFingerprints.get(d);const c=t==="fatal"?we:Oe;if(a!==void 0&&i-a<c){return void 0}this.recentFingerprints.set(d,i);if(t==="fatal")this.fatalIncidentCaptured=true;else this.nonFatalIncidentCount+=1;const h=_();const Y=z({incidentId:h,runId:this.runId,phase:e.phase??this.phase,severity:t,impact:e.impact??(t==="fatal"?"exit":"action_failed"),handled:e.handled??t!=="fatal",error:o,context:{appVersion:this.options.appVersion,platform:this.options.platform??_e(),arch:this.options.architecture??Se(),nodeVersion:this.options.nodeVersion??process.versions.node},breadcrumbs:this.breadcrumbs},n);const K={schemaVersion:y,incidentId:h,eventType:n,occurredAtMs:i,codeLocation:`tui.${n}`,eventLog:Y};X(this.directory,p(this.directory,`${this.uploadEnabled()?"pending":"local"}-${i}-${h}.json`),K);this.prune();void this.drain();return h}catch{return void 0}}drain(){this.drainRequested=true;if(this.drainPromise)return this.drainPromise;const e=this.runDrainLoop().finally(()=>{if(this.drainPromise===e)this.drainPromise=void 0});this.drainPromise=e;return e}async runDrainLoop(){do{this.drainRequested=false;await this.drainPending()}while(this.drainRequested)}async flush(e=Ce){const n=this.drain();if(!Number.isFinite(e)||e<0){await n.catch(()=>void 0);return}let t;try{await Promise.race([n.catch(()=>void 0),new Promise(i=>{t=setTimeout(()=>{this.networkDrainStopped=true;for(const o of this.activeRequestControllers)o.abort();i()},Math.max(0,e));t.unref?.()})])}finally{if(t)clearTimeout(t)}}completeRun(){if(this.completed)return;this.completed=true;try{U(this.markerPath,{force:true})}catch{}}async drainPending(){if(!this.uploadEnabled())return;const e=this.options.resolveAuthContext;if(!e)return;let n;try{n=await e()}catch{return}const t=n?.accessToken?.trim();const i=n?.realUserID?.trim();if(!t||!i)return;const o=We(this.directory);for(let s=0;s<o.length;s+=k){const d=o.slice(s,s+k);let a;try{a=d.map(({incident:c})=>({event_type:c.eventType,event_log:Be(c.eventLog,t,i,c),occurred_at_ms:c.occurredAtMs,code_location:c.codeLocation}))}catch{return}if(!await this.sendBatch(a,t,i))return;for(const c of d)$e(c.path)}}async sendBatch(e,n,t){if(this.networkDrainStopped||!this.uploadEnabled())return false;const i=new AbortController;const o=setTimeout(()=>i.abort(),this.options.requestTimeoutMs??Pe);o.unref?.();this.activeRequestControllers.add(i);try{const s=new URL(`${De[this.options.region][this.options.buildEnv]}${Ne}`);if(s.protocol!=="https:")return false;s.searchParams.set("user_id",t);const d=await this.fetchImpl(s,{method:"POST",headers:{"User-Agent":P("MiniMaxAgent"),"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({events:e}),signal:i.signal});return d.ok}catch{return false}finally{clearTimeout(o);this.activeRequestControllers.delete(i)}}recoverUncleanRuns(){for(const e of x(this.directory)){if(!e.startsWith("active-")||!e.endsWith(".json"))continue;const n=p(this.directory,e);const t=je(n);if(!t){l(n);continue}if(t.pid!==this.pid&&this.isProcessAlive(t.pid))continue;this.capture({eventType:"cli_unclean_exit",error:new Error(`Previous TUI run ended without completing ${t.phase}.`),component:"process",operation:"recover-unclean-run",codeLocation:"src/observability/incident-reporter.ts#recoverUncleanRuns",severity:"error",impact:"exit",handled:true,phase:t.phase,context:{previousRunId:t.runId,previousPid:t.pid,previousAppVersion:t.appVersion,previousStartedAtMs:t.startedAtMs,previousUpdatedAtMs:t.updatedAtMs}});l(n)}}writeRunMarker(){if(this.completed)return;const e={schemaVersion:1,runId:this.runId,pid:this.pid,startedAtMs:this.startedAtMs,updatedAtMs:Math.floor(this.nowMs()),phase:this.phase,appVersion:M(this.options.appVersion)??"unknown"};try{V(this.markerPath,`${JSON.stringify(e)}
4
4
  `,{encoding:"utf8",mode:384});O(this.markerPath)}catch{}}uploadEnabled(){return w("diagnostics",this.options.readTelemetryEnabled)}prune(){const e=this.nowMs();const n=x(this.directory).filter(o=>/^(?:pending|sent|local)-.*\.json$/u.test(o)).flatMap(o=>{const s=p(this.directory,o);try{return[{path:s,modifiedAtMs:Te(s).mtimeMs}]}catch{return[]}}).sort((o,s)=>o.modifiedAtMs-s.modifiedAtMs);for(const o of n){try{if(JSON.parse(A(o.path,"utf8")).schemaVersion!==y){l(o.path)}}catch{l(o.path)}if(e-o.modifiedAtMs>N)l(o.path)}const t=n.filter(o=>e-o.modifiedAtMs<=N);const i=[...t.filter(o=>g(o.path).startsWith("local-")),...t.filter(o=>g(o.path).startsWith("sent-")),...t.filter(o=>g(o.path).startsWith("pending-"))];for(const o of i.slice(0,Math.max(0,t.length-xe))){l(o.path)}}};var W=["cli_process_error","cli_startup_error","cli_render_error","cli_interaction_error","cli_runtime_bridge_error","cli_terminal_error","cli_persistence_error","cli_shutdown_error","cli_unclean_exit"];var I=["startup","runtime","shutdown"];var j=["fatal","error","warning"];var Le=["exit","screen_unavailable","action_failed","degraded"];var Ue=["Error","TypeError","RangeError","SyntaxError","ReferenceError","URIError","EvalError","AggregateError","AbortError"];var Ve=["ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","EAI_AGAIN","EPIPE","ENOENT","EACCES","EPERM","ENOSPC","ABORT_ERR"];var $=["cli.run.started","cli.phase.changed","cli.runtime.events.reconnected","cli.runtime.events.connected","cli.runtime.events.disconnected","cli.runtime.initialize.started","cli.runtime.initialize.succeeded","cli.auth.context.changed","cli.first-frame.rendered","cli.shutdown.started"];function u(r,e){return typeof r==="string"&&e.includes(r)?r:void 0}function b(r,e){if(!r||typeof r!=="object")return void 0;return Object.getOwnPropertyDescriptor(r,e)?.value}function q(r){const e=u(b(r,"name"),Ue)??([AggregateError,TypeError,RangeError,SyntaxError,ReferenceError,URIError,EvalError,Error].find(i=>r instanceof i)?.name??"unknown");const n=u(b(r,"code"),Ve);const t=b(r,"status")??b(r,"statusCode");return{name:e,...n?{code:n}:{},...typeof t==="number"&&Number.isInteger(t)&&t>=100&&t<=599?{status:t}:{}}}function M(r){return typeof r==="string"&&/^\d{1,4}\.\d{1,4}\.\d{1,4}$/u.test(r)?r:void 0}function J(r,e){return he("sha256").update(JSON.stringify([r,e])).digest("hex").slice(0,24)}function v(r){return r&&typeof r==="object"?r:{}}function R(r){return typeof r==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(r)?r:void 0}function H(r){return typeof r==="number"&&Number.isSafeInteger(r)&&r>=0}function z(r,e){const n=v(r);const t=v(n.context);const i=q(n.error);const o=(Array.isArray(n.breadcrumbs)?n.breadcrumbs:[]).slice(-B).flatMap(s=>{const d=v(s);const a=u(d.name,$);const c=u(v(d.details).phase,I);return a&&H(d.occurredAtMs)?[{name:a,occurredAtMs:d.occurredAtMs,...c?{details:{phase:c}}:{}}]:[]});return JSON.stringify({schemaVersion:y,incidentId:R(n.incidentId),runId:R(n.runId),source:"cli",phase:u(n.phase,I)??"runtime",severity:u(n.severity,j)??"error",impact:u(n.impact,Le)??"action_failed",handled:typeof n.handled==="boolean"?n.handled:true,fingerprint:J(e,i),error:i,context:{appVersion:M(t.appVersion),platform:u(t.platform,["darwin","linux","win32","freebsd","openbsd","aix","sunos"]),arch:u(t.arch,["arm64","x64","arm","ia32","riscv64","ppc64","s390x"]),nodeVersion:M(t.nodeVersion)},breadcrumbs:o})}function Be(r,e,n,t){const i=Buffer.from(fe("sha256",Buffer.from(e,"utf8"),Buffer.from(Re,"utf8"),Buffer.from(n,"utf8"),32));const o=be(12);const s=ye("aes-256-gcm",i,o);s.setAAD(Buffer.from(JSON.stringify({event_type:t.eventType,occurred_at_ms:t.occurredAtMs}),"utf8"));const d=Buffer.concat([s.update(r,"utf8"),s.final()]);const a=Buffer.concat([d,s.getAuthTag()]);return`${Me}.${o.toString("base64url")}.${a.toString("base64url")}`}function We(r){return x(r).filter(e=>e.startsWith("pending-")&&e.endsWith(".json")).sort().flatMap(e=>{const n=p(r,e);try{const t=JSON.parse(A(n,"utf8"));const i=u(t.eventType,W);if(t.schemaVersion!==y||!R(t.incidentId)||!i||!H(t.occurredAtMs)||typeof t.eventLog!=="string"){l(n);return[]}const o={schemaVersion:y,incidentId:t.incidentId,eventType:i,occurredAtMs:t.occurredAtMs,codeLocation:`tui.${i}`,eventLog:z(JSON.parse(t.eventLog),i)};X(r,n,o);return[{path:n,incident:o}]}catch{return[]}})}function je(r){try{const e=JSON.parse(A(r,"utf8"));if(e.schemaVersion!==1||typeof e.runId!=="string"||typeof e.pid!=="number"||typeof e.startedAtMs!=="number"||typeof e.updatedAtMs!=="number"||e.phase!=="startup"&&e.phase!=="runtime"&&e.phase!=="shutdown"||typeof e.appVersion!=="string"){return void 0}return e}catch{return void 0}}function X(r,e,n){const t=p(r,`.incident-${process.pid}-${_()}.tmp`);try{V(t,`${JSON.stringify(n)}
5
5
  `,{encoding:"utf8",mode:384,flag:"wx"});L(t,e);O(e)}catch(i){l(t);throw i}}function $e(r){const e=p(Ee(r),g(r).replace(/^pending-/u,"sent-"));try{L(r,e);O(e)}catch{}}function qe(r){ve(r,{recursive:true,mode:448});try{F(r,448)}catch{}}function O(r){try{F(r,384)}catch{}}function x(r){try{return ge(r)}catch{return[]}}function l(r){try{U(r,{force:true})}catch{}}function Je(r){if(!Number.isSafeInteger(r)||r<=0||r===process.pid)return false;try{process.kill(r,0);return true}catch(e){return e.code==="EPERM"}}var He=new Set([1,2,3,4]);var ze=new Set([1,2]);var Xe=new Set([0,1,2,3,4]);function gr(r){return Boolean(r?.days.some(e=>e.status===2))}function Tr(r){return Boolean(r?.days.some(e=>e.is_today&&e.status===3))}function Sr(r){const e=[...r].sort((s,d)=>s.day_no-d.day_no);const n=e.findIndex(s=>s.is_today);if(n<0)return 0;const t=e[n]?.status;let i=t===3?n:t===2?n-1:-1;if(i<0)return 0;let o=0;for(;i>=0;i-=1){if(e[i]?.status!==3)break;o+=1}return o}function Ye(r){const e=r;const n=e?.days;const t=new Set;let i=0;let o=0;const s=Array.isArray(n)&&n.length===7&&n.every(d=>{if(!d||typeof d!=="object")return false;const a=d;const c=a.day_no;if(typeof c!=="number"||!Number.isInteger(c)||c<1||c>7||t.has(c)){return false}if(typeof a.points!=="number"||!Number.isFinite(a.points)||a.points<0||a.bonus_points!==void 0&&(typeof a.bonus_points!=="number"||!Number.isFinite(a.bonus_points)||a.bonus_points<0)||typeof a.is_today!=="boolean"||!He.has(a.status)){return false}t.add(c);if(a.status===2)i+=1;if(a.is_today)o+=1;return true});if(e===null||typeof e!=="object"||!Xe.has(e.scene)||!s||i>1||o>1){throw new Error("Invalid sign-in panel")}return e}function _r(r){const e=r;const n=e!==null&&typeof e==="object"&&typeof e.claim_id==="string"&&e.claim_id.length>0&&ze.has(e.claim_result)&&Number.isInteger(e.day_no)&&(e.day_no??0)>=1&&(e.day_no??8)<=7&&typeof e.points==="number"&&Number.isFinite(e.points)&&e.points>=0&&typeof e.expire_at_ms==="number"&&Number.isFinite(e.expire_at_ms);if(!n){throw new Error("Invalid sign-in claim response")}return{...e,panel:Ye(e.panel)}}var Ke=["read_only","workspace_write","delete_guard","full_access"];var Ge={read_only:"Read only",workspace_write:"Workspace",delete_guard:"Delete guard",full_access:"Full access"};var Ze={read_only:"READ",workspace_write:"WORK",delete_guard:"GUARD",full_access:"FULL"};var Qe={read_only:"The agent can read files but cannot write or delete them",workspace_write:"Writes and deletes stay on the workspace surface",delete_guard:"Writes anywhere, deletes stay on the workspace surface",full_access:"No filesystem restriction, including deletes outside the workspace"};function er(r){return Ke.find(e=>e===r)}function Ir(r){return er(r.trim().toLocaleLowerCase())}function Mr(r){if(r===void 0)return"Managed by host";return Ge[r]}function Rr(r){return Ze[r]}function xr(r){return Qe[r]}function Ar(r){return r==="full_access"||r==="read_only"}export{ir as a,or as b,mr as c,Fe as d,yr as e,gr as f,Tr as g,Sr as h,Ye as i,_r as j,Ke as k,er as l,Ir as m,Mr as n,Rr as o,xr as p,Ar as q};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{S as d}from"./chunk-UNEPZJKK.js";import{b as t}from"./chunk-NOGL6Y6L.js";var i;function _(n){i=n}function l(n={}){const e=n.embeddedBuildEnvironment??u();const r=n.embeddedBuildVariant??a();const o=n.runtimeBuildEnv??d();return t({buildEnv:e??m(o),internalBuild:r==="internal"})}function c(n={}){const e=l(n);return{region:n.runtimeRegion??v(process.env.MAVIS_REGION)??"cn",buildEnv:i??e.buildEnv??"test"}}function v(n){return n==="cn"||n==="en"?n:void 0}function s(n=u()){return i??n??"dev"}function u(){if(false)return void 0;return"prod"}function a(){if(false)return void 0;return"standard"}function m(n){return n==="dev"?"test":n}export{_ as a,l as b,c,v as d,s as e};
2
+ import{W as d}from"./chunk-XWNCITOR.js";import{b as t}from"./chunk-7F3QKGB7.js";var i;function _(n){i=n}function l(n={}){const e=n.embeddedBuildEnvironment??u();const r=n.embeddedBuildVariant??a();const o=n.runtimeBuildEnv??d();return t({buildEnv:e??m(o),internalBuild:r==="internal"})}function c(n={}){const e=l(n);return{region:n.runtimeRegion??v(process.env.MAVIS_REGION)??"cn",buildEnv:i??e.buildEnv??"test"}}function v(n){return n==="cn"||n==="en"?n:void 0}function s(n=u()){return i??n??"dev"}function u(){if(false)return void 0;return"prod"}function a(){if(false)return void 0;return"standard"}function m(n){return n==="dev"?"test":n}export{_ as a,l as b,c,v as d,s as e};
@@ -1,3 +1,3 @@
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 m,c as d,d as l}from"./chunk-V4IDVAIA.js";import{b as p}from"./chunk-TRX2HFTB.js";import{ha as f,ia as g}from"./chunk-UNEPZJKK.js";import S from"node:fs";import u from"node:fs";import E from"node:path";var R="preferences";var T="mcode-region.json";function v(n,t){try{const e=JSON.parse(u.readFileSync(h(n),"utf8"));if(e.version!==1||!e.regions||typeof e.regions!=="object"){return void 0}const r=e.regions[t];return r==="cn"||r==="en"?r:void 0}catch{return void 0}}function D(n,t){const e=E.join(n,R);u.mkdirSync(e,{recursive:true,mode:448});const r=h(n);const i=M(r);const o={version:1,regions:{...i,[t.buildEnv]:t.region},updatedAtMs:Date.now()};const s=`${r}.${process.pid}.${Date.now()}.tmp`;u.writeFileSync(s,`${JSON.stringify(o,null,2)}
2
+ import{a as m,c as d,d as l}from"./chunk-WHBWI5OQ.js";import{b as p}from"./chunk-TRX2HFTB.js";import{la as f,ma as g}from"./chunk-XWNCITOR.js";import S from"node:fs";import u from"node:fs";import E from"node:path";var R="preferences";var T="mcode-region.json";function v(n,t){try{const e=JSON.parse(u.readFileSync(h(n),"utf8"));if(e.version!==1||!e.regions||typeof e.regions!=="object"){return void 0}const r=e.regions[t];return r==="cn"||r==="en"?r:void 0}catch{return void 0}}function D(n,t){const e=E.join(n,R);u.mkdirSync(e,{recursive:true,mode:448});const r=h(n);const i=M(r);const o={version:1,regions:{...i,[t.buildEnv]:t.region},updatedAtMs:Date.now()};const s=`${r}.${process.pid}.${Date.now()}.tmp`;u.writeFileSync(s,`${JSON.stringify(o,null,2)}
3
3
  `,{encoding:"utf8",mode:384});u.renameSync(s,r);return r}function h(n){return E.join(n,R,T)}function M(n){try{const t=JSON.parse(u.readFileSync(n,"utf8"));if(t.version!==1||!t.regions||typeof t.regions!=="object")return{};return Object.fromEntries(Object.entries(t.regions).filter(([e,r])=>(e==="dev"||e==="test"||e==="staging"||e==="prod")&&(r==="cn"||r==="en")))}catch{return{}}}var _=/^[A-Za-z0-9._-]+$/u;var c="--env";var P=new Set(["--lane","--profile","--resume","--tui-mode","-m","--model","--system-prompt","--system-prompt-file","--append-system-prompt","--append-system-prompt-file"]);var N=Object.freeze({test:"test",pre:"staging",staging:"staging",prod:"prod"});function L(n={}){f(false);g(false);const{target:t=process.env,dataDir:e,startupBuildEnvironment:r,...i}=n;if(r)m(r);const o=d(i);const s=e?v(e,o.buildEnv):void 0;const y=e?I(e,o.buildEnv):void 0;const A=l(t.MAVIS_REGION);const a=d({...i,runtimeRegion:i.runtimeRegion??A??s??y?.region??"cn"});if(e){t.MINIMAX_DATA_DIR=e;t.MAVIS_DATA_DIR=e}t.MAVIS_REGION=a.region;t.MAVIS_BUILD_ENV=a.buildEnv;t.__MAVIS_RUNTIME_MANAGED="1";return a}function O(n){const t=N[n.trim()];if(!t){throw new Error("--env must be test, staging, pre, or prod.")}return t}function U(n,t){const e=[];for(let r=0;r<n.length;r+=1){const i=n[r];if(i===void 0)continue;if(i==="--")break;if(i===c){const o=n[r+1];if(!o||o.startsWith("-"))throw new Error("--env requires a value.");e.push(o);r+=1;continue}if(i.startsWith(`${c}=`)){e.push(i.slice(c.length+1));continue}if(P.has(i)){r+=1;continue}if(i==="--session"&&n[r+1]&&!n[r+1]?.startsWith("-")){r+=1;continue}if(!i.startsWith("-"))break}if(e.length===0)return void 0;if(!t){throw new Error("--env is only available in the internal MCode package.")}if(e.length>1)throw new Error("--env may only be specified once.");return O(e[0]??"")}function G(n,t=d().buildEnv){if(n===void 0)return void 0;if(t!=="test"&&t!=="staging"){throw new Error("--lane is only supported in test or staging builds.")}const e=n.trim();if(!_.test(e)){throw new Error("--lane only accepts letters, numbers, dot, underscore, and hyphen.")}return e}function I(n,t){const e=["cn","en"].filter(i=>{try{const o=p({dataDir:n,buildEnv:t,region:i});const s=JSON.parse(S.readFileSync(o.statePath,"utf8"));return s.buildEnv===t&&s.region===i&&b(s.status)}catch{return false}});const r=e.length===1?e[0]:void 0;return r?{buildEnv:t,region:r}:void 0}function b(n){return n==="authorizing"||n==="authenticated"||n==="refreshing"||n==="scope_upgrade_required"||n==="expired"}export{D as a,L as b,O as c,U as d,G as e};