@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
@@ -0,0 +1,2 @@
1
+ import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
+ import{a as x}from"./chunk-QIYZZJVO.js";import{e as E,f as N,g as U}from"./chunk-RZDVNG5Z.js";import"./chunk-3LRARE6Z.js";import"./chunk-WHBWI5OQ.js";import{F as M,I as S,J as h,L as T,O as L,P as f,Q as p,R as q,S as j,T as F}from"./chunk-O5EROATK.js";import"./chunk-NJAER6QW.js";import"./chunk-PIADSVUZ.js";import"./chunk-ZJZBXSNG.js";import"./chunk-OLQR4XQZ.js";import"./chunk-ASRGXT22.js";import"./chunk-FJEP2EHP.js";import"./chunk-HMLSH6YL.js";import"./chunk-PIV6YF7B.js";import"./chunk-D2BEUF36.js";import"./chunk-2EBHD6KJ.js";import"./chunk-3KTXNSLL.js";import"./chunk-SKLKXOH4.js";import"./chunk-QASV4FRT.js";import"./chunk-W7O5Y6VY.js";import"./chunk-E3RI7IHR.js";import"./chunk-NT6GUYYJ.js";import"./chunk-3ZEDGMQ4.js";import"./chunk-TRX2HFTB.js";import{Sa as C,V as R,W as b,Wa as A,_a as P,jb as I}from"./chunk-XWNCITOR.js";import"./chunk-ISBSRM3S.js";import"./chunk-3MLT4F77.js";import"./chunk-UQL67NEA.js";import"./chunk-ZK7UCXBX.js";import"./chunk-2YX4JWQ4.js";import"./chunk-T4KXNSN3.js";import"./chunk-LVGBQ7NP.js";import"./chunk-SK4JBJDF.js";import"./chunk-YHXW6NMN.js";import"./chunk-NG2L523L.js";import"./chunk-UE7MODZO.js";import"./chunk-HVCY6M5J.js";import"./chunk-XWU4BV73.js";import"./chunk-NUHYT7HY.js";import"./chunk-FHJWUDED.js";import"./chunk-4QXF4OT5.js";import"./chunk-6MFNDZP7.js";import"./chunk-4GGSPZK3.js";import"./chunk-IONMKU5J.js";import"./chunk-AODHXPQF.js";import"./chunk-AUG3KCLV.js";import"./chunk-JEHPL5Z6.js";import"./chunk-DSIZQTS3.js";import"./chunk-7F3QKGB7.js";import"./chunk-OKOOSGFE.js";import"./chunk-INIZLM6Q.js";import"./chunk-ELQ5G4U6.js";import"./chunk-BF4U2LYQ.js";import"./chunk-GJ3NP2JO.js";import"./chunk-WXD24E23.js";import"./chunk-2PNC3MM4.js";import"./chunk-4QKCRKWB.js";import"./chunk-YNDFGYGN.js";import"./chunk-NEICESQ2.js";import"./chunk-TXWPPTYK.js";import"./chunk-5RFGU5IW.js";import"./chunk-QH5Z4N4A.js";import"./chunk-WTI4WCBV.js";import"./chunk-PTV7FFNF.js";import"./chunk-TAEC3WRM.js";import"./chunk-3XYKJXXO.js";import"./chunk-4A4KPPPE.js";import"./chunk-VAARXN34.js";import"./chunk-FK3SSGJE.js";import v from"node:fs";import B from"node:net";import g from"node:path";import _ from"node:process";import{spawn as G}from"node:child_process";var J=2e4;function O(){return{region:R(),buildEnv:b()}}function y(e){if(typeof e.region!=="string"||typeof e.buildEnv!=="string"){return O()}return{region:e.region,buildEnv:e.buildEnv}}var W=200;var X=100;var K=1e4;async function he(e){const r=e.environment??_.env;const n=e.homeDir??r["HOME"];const t=q({profile:e.request.profile,dataDir:e.request.dataDir,homeDir:n,env:r});switch(e.request.action){case"run":return z(e,r,n);case"status":return Q(t,e,r,n);case"stop":return ne(t,e);case"restart":return te(t,e,r);case"recover":return ee(t)}}async function z(e,r,n){let t=false;const o=await F({argv:[...e.request.profile?["--profile",e.request.profile]:[],...e.request.dataDir?["--data-dir",e.request.dataDir]:[]],env:r,...n!==void 0?{homeDir:n}:{},onMcodeToolsReadiness:i=>{t=i.ready},createHost:i=>x({...i,...t?{productCapabilities:{mcodeTools:true}}:{}})});await o.done;return`mcoded stopped (socket ${o.daemon.socketPath})`}async function Q(e,r,n,t){const o=f(e.controlRoot);const i=p(e.controlRoot);const s=o===void 0?void 0:y(o);const a=o===void 0||s===void 0?void 0:await E(o.socketPath,{...i!==void 0?{token:i}:{},dataDir:e.dataDir,env:s,timeoutMs:2e3});const $=C(e.profile,t??n["HOME"]);const l=ae($);const m=Y(e.controlRoot);const w={running:a?.ok===true,controlRoot:e.controlRoot,dataDir:e.dataDir,profile:e.profile,manifest:o??null,probeError:a&&!a.ok?a.error:null,holderAlive:o?h(o.pid):null,staleLock:m,legacyDataPath:l};if(r.request.json)return JSON.stringify(w,null,2);const d=m?Z(m.holderPid,e.profile):null;if(!o){return[`mcoded is not running`,` control root: ${e.controlRoot}`,` data dir: ${e.dataDir}`,...l?[` legacy daemon data present: ${l} (not used)`]:[],...d?[` ${d}`]:[]].join("\n")}if(a?.ok){const c=O();const u=s??c;const D=u.region===c.region&&u.buildEnv===c.buildEnv?"":` (your env: region=${c.region} buildEnv=${c.buildEnv})`;return[`mcoded is running (state: ${o.state})`,` pid: ${o.pid}`,` socket: ${o.socketPath}`,` data dir: ${o.dataDir}`,` profile: ${o.profile??"default"}`,` env: region=${o.region} buildEnv=${o.buildEnv}${D}`,` protocol: v${o.protocol}`,` started at: ${o.startedAt}`,...l?[` legacy daemon data present: ${l} (not used)`]:[]].join("\n")}return[`mcoded is not responding (manifest state: ${o.state})`,` pid: ${o.pid} (${h(o.pid)?"alive but not answering":"gone"})`,` socket: ${o.socketPath}`,` error: ${a&&!a.ok?a.error:"probe not attempted"}`,...d?[` ${d}`]:[]].join("\n")}function Y(e){const r=g.join(e,M);try{v.statSync(r)}catch{return null}const n=S(r);if(n!==void 0&&h(n))return null;return{holderPid:n??null}}function Z(e,r){const n=`mcode daemon recover${r?` --profile ${r}`:""}`;return e===null?`stale lock (unparsable record) \u2014 run \`${n}\``:`stale lock from dead pid ${e} \u2014 run \`${n}\``}async function ee(e){const r=g.join(e.controlRoot,M);const n=A(e.controlRoot);const t=[`control root: ${e.controlRoot}`];const o=S(r);const i=v.existsSync(r);if(i&&o!==void 0&&h(o)){return[`nothing recovered \u2014 mcoded.lock is held by LIVE pid ${o}`,...t,` a live daemon owns this root; use \`mcode daemon stop\` instead`].join("\n")}if(!i){t.push(`mcoded.lock: absent (nothing to recover)`)}else if(o===void 0){const a=T(r);t.push(a?`mcoded.lock: removed unparsable debris (torn record)`:`mcoded.lock: unparsable debris could NOT be removed (changed while recovering)`)}else{const a=T(r);t.push(a?`mcoded.lock: removed stale lock of dead pid ${o}`:`mcoded.lock: stale lock of dead pid ${o} could NOT be removed (changed while recovering)`)}let s;if(v.existsSync(n)){if(await oe(n)){s=`socket ${n}: still answers \u2014 left untouched (a daemon is serving)`}else{try{v.unlinkSync(n);s=`socket ${n}: removed stale socket file (nothing answered)`}catch(a){s=`socket ${n}: could not be removed (${a.message})`}}}else{s=`socket ${n}: absent (nothing to recover)`}t.push(` ${s}`);return[`mcoded recover report`,...t].join("\n")}function oe(e){return new Promise(r=>{const n=B.connect(e);n.once("connect",()=>{n.destroy();r(true)});n.once("error",()=>{n.destroy();r(false)})})}var k=class extends Error{constructor(n){super(n);this.report=n;this.name="DaemonDrainRefusalError"}report};async function ne(e,r){const n=f(e.controlRoot);if(!n){return`mcoded is not running (no daemon manifest in ${e.controlRoot})`}const t=await V(e,n,r.request.force,"stop");if(t)throw new k(t);const o=await N(n.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:y(n),timeoutMs:1e4});if(o.ok)return`mcoded stopped (pid ${n.pid})`;if(o.errno==="ENOENT"||o.errno==="ECONNREFUSED"){return`mcoded is not running (socket ${n.socketPath} does not answer)`}throw new Error(`Failed to stop mcoded: ${o.errorCode??""} ${o.error}`.trim())}async function V(e,r,n,t){if(n)return void 0;const o=await U(r.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:y(r),timeoutMs:2e3});if(!o.ok){if(o.errno==="ENOENT"||o.errno==="ECONNREFUSED")return void 0;return[`cannot verify mcoded (pid ${r.pid}) is idle; refusing to ${t} without --force`,` status probe failed: ${o.errorCode?`${o.errorCode}: `:""}${o.error}`,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs would be killed).`].join("\n")}if(o.data.runs.length>0){const i=o.data.runs.map(s=>` ${s.sessionId} running ${re(s.elapsedMs)} (${s.method})`);return[`mcoded has ${o.data.runs.length} active run${o.data.runs.length===1?"":"s"}; refusing to ${t} without --force`,...i,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs will be killed).`].join("\n")}if(!o.data.activeRunsReported){const i=o.data.activeTurns;if(i===void 0){return[`cannot verify mcoded (pid ${r.pid}) is idle; refusing to ${t} without --force`,` the daemon reported neither activeRuns nor activeTurns`,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs would be killed).`].join("\n")}if(i>0){return[`mcoded has ${i} active turn${i===1?"":"s"}; refusing to ${t} without --force`,` (the daemon did not report the per-run list)`,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs will be killed).`].join("\n")}}return void 0}function re(e){return`${Math.max(1,Math.round(e/1e3))}s`}async function te(e,r,n){const t=f(e.controlRoot);if(t){const d=await V(e,t,r.request.force,"restart");if(d)throw new k(d);const c=y(t);const u=await N(t.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:c,timeoutMs:1e4});if(!u.ok&&u.errno!=="ENOENT"&&u.errno!=="ECONNREFUSED"){throw new Error(`Failed to stop the previous mcoded: ${u.error}`)}await ie(t.socketPath,c,r)}const o=_.argv[1];if(!o){throw new Error("Cannot restart: this process has no entry script (process.argv[1]).")}const i={...n,MINIMAX_DATA_DIR:e.dataDir,MAVIS_REGION:R(),MAVIS_BUILD_ENV:b(),...e.profile?{MINIMAX_PROFILE:e.profile}:{}};const s=i[P]?.trim().toLowerCase();if(s===void 0||s===""||s==="off"){i[P]="auto"}const a=[_.execPath,o,"daemon","run","--data-dir",e.dataDir,...e.profile?["--profile",e.profile]:[]];I(e.controlRoot);const $=r.spawnDaemon??(({argv:d,env:c,logFd:u})=>{const D=G(d[0],d.slice(1),{detached:true,stdio:["ignore",u,u],env:c});D.unref();return D});const l=j(e.controlRoot,i);try{$({argv:a,env:l.childEnv,logFd:l.fd})}finally{v.closeSync(l.fd)}const m=await se(e,r);if(!m.ok){throw new Error(`mcoded did not become ready within ${r.request.waitTimeoutMs??J} ms: ${m.error}. See ${g.join(e.controlRoot,L,"mcoded.log")}`)}const w=f(e.controlRoot);return`mcoded restarted (pid ${w?.pid??"?"}, socket ${m.socketPath})`}async function ie(e,r,n){const t=n.sleep??H;const o=Date.now()+K;for(;;){const i=await E(e,{env:r,timeoutMs:1e3});if(!i.ok&&(i.errno==="ENOENT"||i.errno==="ECONNREFUSED"))return;if(Date.now()>o)return;await t(X)}}async function se(e,r){const n=r.sleep??H;const t=Date.now()+(r.request.waitTimeoutMs??J);let o="socket never appeared";for(;;){const i=f(e.controlRoot);if(i&&i.state.startsWith("failed:")){return{ok:false,error:`daemon start failed (${i.state})`}}if(i){const s=await E(i.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:O(),timeoutMs:1e3});if(s.ok)return{ok:true,socketPath:i.socketPath};o=s.error}if(Date.now()>t)return{ok:false,error:o};await n(W)}}function H(e){return new Promise(r=>{setTimeout(r,e)})}function ae(e){for(const r of["durable-history","workspace"]){const n=g.join(e,r);try{if(v.statSync(n).isDirectory())return n}catch{}}return null}export{k as DaemonDrainRefusalError,he as runMcodeDaemonCommand};
@@ -0,0 +1,16 @@
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 Be,b as He,d as We,e as ce,f as Ve,g as Ge,h as q}from"./chunk-NWMN2FDO.js";import{d as j,e as g,f as _e,g as B,h as De,i as Ce,n as Ne}from"./chunk-K6C7372U.js";import{c as ze,d as le,e as Xe,f as Ke,i as Ye,l as Qe}from"./chunk-GS7TCNDK.js";import{a as Le,b as Ze,d as et}from"./chunk-SRTYTXAC.js";import{a as tt,b as rt}from"./chunk-GZPVFWYD.js";import"./chunk-UEPKZSE6.js";import{e as Fe,f as $e,g as ue,h as D,i as Ue}from"./chunk-U6RWF7BC.js";import"./chunk-E25NCIC6.js";import{c as qe,s as de,w as Je}from"./chunk-CUPCI2YC.js";import{a as Oe}from"./chunk-ME57CPMB.js";import"./chunk-QMBFFQPV.js";import"./chunk-QIYZZJVO.js";import"./chunk-RZDVNG5Z.js";import"./chunk-3LRARE6Z.js";import{d as Ae}from"./chunk-LC7ZI6EV.js";import"./chunk-WUORF7YS.js";import"./chunk-WHBWI5OQ.js";import"./chunk-O5EROATK.js";import"./chunk-NJAER6QW.js";import"./chunk-PIADSVUZ.js";import"./chunk-ZJZBXSNG.js";import"./chunk-OLQR4XQZ.js";import"./chunk-ASRGXT22.js";import"./chunk-FJEP2EHP.js";import"./chunk-HMLSH6YL.js";import"./chunk-PIV6YF7B.js";import"./chunk-D2BEUF36.js";import"./chunk-2EBHD6KJ.js";import"./chunk-3KTXNSLL.js";import"./chunk-SKLKXOH4.js";import"./chunk-QASV4FRT.js";import"./chunk-W7O5Y6VY.js";import"./chunk-E3RI7IHR.js";import"./chunk-NT6GUYYJ.js";import"./chunk-3ZEDGMQ4.js";import"./chunk-TRX2HFTB.js";import{Gb as Pe,Hb as Me,r as be,s as z,u as ke}from"./chunk-XWNCITOR.js";import"./chunk-ISBSRM3S.js";import"./chunk-3MLT4F77.js";import"./chunk-UQL67NEA.js";import"./chunk-ZK7UCXBX.js";import"./chunk-2YX4JWQ4.js";import"./chunk-T4KXNSN3.js";import"./chunk-LVGBQ7NP.js";import"./chunk-SK4JBJDF.js";import"./chunk-YHXW6NMN.js";import"./chunk-NG2L523L.js";import"./chunk-UE7MODZO.js";import"./chunk-HVCY6M5J.js";import"./chunk-XWU4BV73.js";import"./chunk-NUHYT7HY.js";import"./chunk-FHJWUDED.js";import"./chunk-4QXF4OT5.js";import"./chunk-6MFNDZP7.js";import"./chunk-4GGSPZK3.js";import"./chunk-IONMKU5J.js";import"./chunk-AODHXPQF.js";import"./chunk-AUG3KCLV.js";import{nb as Lt}from"./chunk-JEHPL5Z6.js";import"./chunk-DSIZQTS3.js";import"./chunk-7F3QKGB7.js";import"./chunk-OKOOSGFE.js";import"./chunk-INIZLM6Q.js";import"./chunk-ELQ5G4U6.js";import"./chunk-BF4U2LYQ.js";import"./chunk-GJ3NP2JO.js";import"./chunk-WXD24E23.js";import"./chunk-2PNC3MM4.js";import"./chunk-4QKCRKWB.js";import"./chunk-YNDFGYGN.js";import"./chunk-NEICESQ2.js";import"./chunk-TXWPPTYK.js";import"./chunk-5RFGU5IW.js";import"./chunk-QH5Z4N4A.js";import"./chunk-WTI4WCBV.js";import"./chunk-PTV7FFNF.js";import"./chunk-TAEC3WRM.js";import"./chunk-3XYKJXXO.js";import"./chunk-4A4KPPPE.js";import{a as je}from"./chunk-VAARXN34.js";import{e as Ut}from"./chunk-FK3SSGJE.js";async function nt(e,t){try{return Me(e,t)}catch(r){const n=r instanceof Pe?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new g("config",n,{cause:r})}}var ot=`${$e} Lower the effort level, then retry.`;function H(e){if(e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"){return D(e)}if(e.kind==="runtime"){if(ue(e.message))return ot;if(!e.retryable)return it(`The run failed: ${D(e)}`);return`The run failed: ${D(e)}. Retry after the connection recovers.`}return`MCode encountered an internal error: ${D(e)}. Retry; if it keeps happening, report it through an available support channel.`}function st(e){if(e.status==="timeout"){return"The run timed out. Increase --timeout or retry."}if(e.status==="limit_exceeded"){return"The run reached its step limit. Increase --max-steps or narrow the task."}if(e.status==="cancelled")return"The run was cancelled.";if(e.error?.category==="config"){const r=e.error.message?`: ${D(e.error.message)}`:"";return`The run could not start with the current configuration${r}. Open MCode and run /doctor.`}if(e.error?.category==="internal"){const r=e.error.message?`: ${D(e.error.message)}`:"";return`MCode encountered an internal error${r}. Retry; if it keeps happening, report it through an available support channel.`}if(ue(e.error?.message))return ot;const t=e.error?.message?`: ${D(e.error.message)}`:"";if(e.error?.retryable===false)return it(`The run failed${t}`);return`The run failed${t}. Retry after the connection recovers.`}function it(e){return/[.!?…]$/u.test(e)?e:`${e}.`}import{readFile as sr,realpath as ge,stat as Z}from"node:fs/promises";import{homedir as gt}from"node:os";import{basename as ht,dirname as ir,extname as ar,isAbsolute as ur,resolve as Q}from"node:path";var me=Ut(Lt(),1);function fe(e,t){if(!t)return{ok:true,value:e??null};if(!e?.trim()){return{ok:false,kind:"empty",message:"Structured output was empty."}}let r;try{r=JSON.parse(e)}catch{return{ok:false,kind:"invalid_json",message:"Structured output was not valid JSON."}}const n=new me.Ajv({allErrors:true,strict:false});const o=n.compile(t);if(!o(r)){return{ok:false,kind:"schema_mismatch",message:`Structured output did not match --output-schema: ${n.errorsText(o.errors,{separator:"; "})}`}}return{ok:true,value:r}}function at(e,t){const r=e.status==="succeeded"?t.validation??fe(e.answer,t.outputSchema):void 0;const n=Bt(e,r);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:n.sessionId,turnId:n.turnId,status:n.status==="awaiting-user-continuation"?"failed":n.status,...n.status==="succeeded"&&r?.ok?{output:r.value}:{},...n.error?{error:{...n.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},...t.usageSource!==void 0?{usageSource:t.usageSource}:{},...t.usageIncomplete!==void 0?{usageIncomplete:t.usageIncomplete}:{},durationMs:n.durationMs}}function ut(e){if(!X(e))return false;return e.schemaVersion===1&&e.type==="exec.result"&&typeof e.runId==="string"&&typeof e.sessionId==="string"&&typeof e.turnId==="string"&&typeof e.durationMs==="number"&&Number.isFinite(e.durationMs)&&qt(e.status)&&Ht(e.model)&&Wt(e.usage)&&(e.usageSource===void 0||e.usageSource==="completed_responses"||e.usageSource==="analytics_fallback"||e.usageSource==="unavailable")&&(e.usageIncomplete===void 0||typeof e.usageIncomplete==="boolean")&&Vt(e.error)}function Bt(e,t){if(e.status==="awaiting-user-continuation"){return{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:false}}}if(e.status!=="succeeded"||!t||t.ok)return e;return{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:t.message,retryable:true}}}function ct(e){new me.Ajv({allErrors:true,strict:false}).compile(e)}function qt(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function Ht(e){if(e===void 0)return true;if(!X(e))return false;return typeof e.providerId==="string"&&typeof e.modelId==="string"&&W(e.variant)&&W(e.providerSource)&&W(e.providerKind)&&W(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict")}function Wt(e){if(e===void 0)return true;if(!X(e))return false;return Object.values(e).every(t=>t===void 0||typeof t==="number"&&Number.isFinite(t))}function Vt(e){if(e===void 0)return true;if(!X(e))return false;return(e.category==="config"||e.category==="runtime"||e.category==="internal")&&W(e.code)&&typeof e.message==="string"&&(e.retryable===void 0||typeof e.retryable==="boolean")}function W(e){return e===void 0||typeof e==="string"}function X(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}import{createHash as Gt,randomUUID as Jt}from"node:crypto";import{access as zt,constants as Xt,lstat as dt,mkdir as Kt,open as Yt,readdir as lt,rename as Qt,unlink as Zt,writeFile as er}from"node:fs/promises";import{join as K,resolve as tr}from"node:path";var pe=256*1024;var rr=4*1024*1024;var nr=5e3;function mt(e){return Ue(e.replace(/("(?:authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"(?:\\.|[^"\\])*"/giu,'$1"[redacted]"'))}function or(e){if(e.length<=pe)return e;const t=Buffer.from("\n[diagnostic answer truncated: middle omitted]\n");const r=Math.floor((pe-t.length)/2);let n=r;let o=e.length-r;while(((e[n]??0)&192)===128)n-=1;while(((e[o]??0)&192)===128)o+=1;return Buffer.concat([e.subarray(0,n),t,e.subarray(o)])}async function ft(e,t){const r=tr(t,e);await Kt(r,{recursive:true,mode:448});if(!(await dt(r)).isDirectory())throw new Error("Diagnostics path must be a real directory.");await zt(r,Xt.W_OK);if((await lt(r)).length>0)throw new Error("Diagnostics directory must be empty.");return r}function pt(e){return e?Gt("sha256").update(JSON.stringify(e)).digest("hex"):void 0}function V(e){if(typeof e==="string")return mt(e);if(Array.isArray(e))return e.map(V);if(e&&typeof e==="object"){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,/^(authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)$/iu.test(t)?"[redacted]":V(r)]))}return e}var Y=class e{constructor(t,r,n){this.directory=t;this.warn=r;this.progressFile=n}directory;warn;progressFile;pending=Promise.resolve();bytes=0;droppedEvents=0;closed=false;failed=false;static async create(t,r){if((await lt(t)).length>0){throw Object.assign(new Error("Diagnostics directory must be empty."),{code:"EEXIST"})}const n=await Yt(K(t,"progress.jsonl"),"wx",384);return new e(t,r,n)}record(t){if(this.closed)return;const r=`${JSON.stringify(V({timestampMs:Date.now(),...t}))}
3
+ `;const n=Buffer.byteLength(r);if(this.bytes+n>rr){this.droppedEvents+=1;return}this.bytes+=n;this.enqueue(()=>this.progressFile.appendFile(r))}execution(t){this.json("execution.json",{schemaVersion:1,...t})}failure(t,r){const n=Buffer.from(mt(t??""));const o=n.length>pe;const i=or(n);this.json("failure.json",{schemaVersion:1,...r,answerBytes:Buffer.byteLength(t??""),savedBytes:i.length,truncated:o,redacted:true});this.enqueue(()=>this.replaceFile("failure-answer.txt",i))}async flush(t={}){this.enqueue(async()=>{const[o,i]=await Promise.all([dt(K(this.directory,"progress.jsonl")),this.progressFile.stat()]);if(!o.isFile()||o.ino!==i.ino||o.dev!==i.dev){throw new Error("Diagnostics progress file was replaced.")}});this.enqueue(()=>this.progressFile.close());this.enqueue(()=>this.replaceFile("diagnostics-status.json",`${JSON.stringify(V({...t,recoveryReady:t.recoveryReady===true&&!this.failed,diagnosticsComplete:!this.failed,droppedEventCount:this.droppedEvents}),null,2)}
4
+ `));let r;const n=await Promise.race([this.pending.then(()=>true),new Promise(o=>{r=setTimeout(()=>o(false),nr)})]);if(r)clearTimeout(r);this.closed=true;if(!n)this.reportFailure("diagnostics flush deadline exceeded");void this.pending.finally(()=>this.progressFile.close()).catch(()=>void 0);return n&&!this.failed}json(t,r){const n=`${JSON.stringify(V(r),null,2)}
5
+ `;this.enqueue(()=>this.replaceFile(t,n))}async replaceFile(t,r){const n=K(this.directory,`.${t}.${Jt()}.tmp`);try{await er(n,r,{mode:384,flag:"wx"});if(!this.closed)await Qt(n,K(this.directory,t))}finally{await Zt(n).catch(()=>void 0)}}enqueue(t){if(this.closed)return;this.pending=this.pending.then(async()=>{if(!this.closed)await t()}).catch(()=>this.reportFailure("could not write execution diagnostics"))}reportFailure(t){if(!this.failed)this.warn(`mcode diagnostics warning: ${t}
6
+ `);this.failed=true}};var cr={".csv":"text/csv",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".log":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".webp":"image/webp",".xml":"application/xml",".yaml":"application/yaml",".yml":"application/yaml"};async function wt(e,t,r,n){C(n);if(t.review)return dr(t,n);if(t.input!==void 0&&t.input!=="-"){throw f('--input currently accepts only "-".')}if(e!==void 0&&t.input!==void 0){throw f("The prompt argument and --input cannot be combined.")}if(t.session&&t.continue){throw f("--session and --continue are mutually exclusive.")}const o=F("--mode",t.mode??"standard",["standard","lightweight"]);if(o==="lightweight"&&(t.session||t.continue)){throw f("--mode lightweight requires a new Session.")}const i=F("--prompt-mode",t.promptMode??"tui",["tui","coding","work"]);const s=F("--input-format",t.inputFormat??"text",["text","json"]);const d=F("--output-format",t.outputFormat??"text",["text","json","stream-json"]);const a=F("--permission",t.permission??"smart",["ask","smart","full","off"]);if(a==="ask"){throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.")}const m=a;const l=St(t);const w=Tt(t);const c=await ye(t.cwd??process.cwd(),"--cwd");C(n);const h=t.input==="-"?await r():e??"";C(n);const x=fr(h,s);const E=await Promise.all((t.file??[]).map(y=>mr(y,c,n)));const u=et(E);if(u==="count"){throw f(`You can attach up to ${String(Ze)} files.`)}if(u==="total-bytes"){throw f("Attachments can total up to the 100 MB limit.")}if(!x.trim()&&E.length===0){throw f("A prompt, --input -, or at least one --file is required.")}const b=t.timeout===void 0?void 0:Et(t.timeout,"--timeout");const I=t.maxSteps===void 0?void 0:xt(t.maxSteps,"--max-steps");const k=t.config===void 0?void 0:await he(t.config,c,"--config");const P=t.outputSchema===void 0?void 0:await lr(t.outputSchema,c);const p=t.outputLastMessage===void 0?void 0:await vt(t.outputLastMessage,c);let v;if(t.diagnosticsDir!==void 0){if(!t.diagnosticsDir.trim())throw f("--diagnostics-dir cannot be empty.");try{v=await ft(t.diagnosticsDir,c)}catch(y){throw f(`--diagnostics-dir is invalid: ${N(y)}`)}}return{prompt:x,promptMode:i,workspaceDir:c,attachments:E,...t.model?.trim()?{model:t.model.trim()}:{},...l===void 0?{}:{effort:l},...o==="lightweight"?{contextMode:o}:{},...t.session?.trim()?{sessionId:t.session.trim()}:{},continueSession:t.continue===true,...k?{configPath:k}:{},permission:m,...b===void 0?{}:{timeoutMs:b},...I===void 0?{}:{maxSteps:I},format:d,...P===void 0?{}:{outputSchema:P},...p===void 0?{}:{outputLastMessagePath:p},...v===void 0?{}:{diagnosticsDir:v},...t.daemon===false?{noDaemon:true}:{},...t.builtinTools===false?{noBuiltinTools:true}:{},...w?{systemPromptOverrides:w}:{}}}async function dr(e,t){if(e.builtinTools===false||z(process.env)){throw f("exec review needs the built-in inspection tools; --no-builtin-tools is not supported here.")}const r=F("--output-format",e.outputFormat??"text",["text","json","stream-json"]);const n=F("--permission",e.permission??"smart",["ask","smart","full","off"]);if(n==="ask"){throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.")}const o=St(e);const i=Tt(e);const s=await ye(e.cwd??process.cwd(),"--cwd");C(t);const d=e.timeout===void 0?void 0:Et(e.timeout,"--timeout");const a=e.maxSteps===void 0?void 0:xt(e.maxSteps,"--max-steps");const m=e.config===void 0?void 0:await he(e.config,s,"--config");const l=e.outputLastMessage===void 0?void 0:await vt(e.outputLastMessage,s);return{prompt:"Please review my uncommitted changes.",workspaceDir:s,attachments:[],...e.model?.trim()?{model:e.model.trim()}:{},...o===void 0?{}:{effort:o},continueSession:false,...m?{configPath:m}:{},permission:n,...d===void 0?{}:{timeoutMs:d},...a===void 0?{}:{maxSteps:a},format:r,...l===void 0?{}:{outputLastMessagePath:l},reviewRequest:{scope:"local_changes"},...e.daemon===false?{noDaemon:true}:{},...i?{systemPromptOverrides:i}:{}}}function Tt(e){try{return Ne(e)}catch(t){throw f(N(t),t)}}async function lr(e,t){const r=e.trim();try{return yt(r)}catch(o){if(r.startsWith("{")||r.startsWith("[")||!(o instanceof SyntaxError)){throw f("--output-schema requires a JSON object.",o)}}const n=await he(e,t,"--output-schema");try{return yt(await sr(n,"utf8"))}catch(o){throw f("--output-schema requires a JSON object.",o)}}function yt(e){const t=JSON.parse(e);if(!t||typeof t!=="object"||Array.isArray(t)){throw new TypeError("schema must be a JSON object")}ct(t);return t}async function vt(e,t){const r=ee(e,t);const n=await ye(ir(r),"--output-last-message");const o=Q(n,ht(r));const i=await Z(o).catch(s=>{if(s&&typeof s==="object"&&"code"in s&&s.code==="ENOENT"){return void 0}throw f(`--output-last-message is invalid: ${N(s)}`)});if(i?.isDirectory())throw f("--output-last-message must reference a file.");return o}async function mr(e,t,r){C(r);const n=await Be(e.trim(),r).catch(m=>{C(r);throw f(`Cannot attach ${e}: ${N(m)}`)});C(r);const o=ee(n,t);const i=await ge(o).catch(m=>{throw f(`Cannot attach ${e}: ${N(m)}`)});const s=await Z(i).catch(m=>{throw f(`Cannot attach ${e}: ${N(m)}`)});C(r);if(!s.isFile())throw f(`Cannot attach ${e}: path is not a file.`);const d=ht(i);const a=cr[ar(d).toLowerCase()]??Le(d)??"application/octet-stream";return{type:a.startsWith("image/")?"image":"file",filePath:i,fileName:d,mimeType:a,sizeBytes:s.size}}function C(e){if(e?.aborted){throw new g("cancelled","Invocation was cancelled.",{cause:e.reason})}}async function ye(e,t){const r=await ge(ee(e,process.cwd())).catch(o=>{throw f(`${t} is invalid: ${N(o)}`)});const n=await Z(r);if(!n.isDirectory())throw f(`${t} must reference a directory.`);return r}async function he(e,t,r){const n=await ge(ee(e,t)).catch(i=>{throw f(`${r} is invalid: ${N(i)}`)});const o=await Z(n);if(!o.isFile())throw f(`${r} must reference a file.`);return n}function ee(e,t){const r=e.trim();if(!r)throw f("Path value cannot be empty.");const n=r==="~"?gt():r.startsWith("~/")||r.startsWith("~\\")?Q(gt(),r.slice(2)):r;return ur(n)?Q(n):Q(t,n)}function fr(e,t){if(t==="text")return e;let r;try{r=JSON.parse(e)}catch(n){throw f("--input-format json requires valid JSON.",n)}if(typeof r==="string")return r;if(r&&typeof r==="object"&&!Array.isArray(r)&&typeof r.prompt==="string"){return r.prompt}throw f("--input-format json accepts a JSON string or an object with string prompt.")}function Et(e,t){const r=/^(\d+)(ms|s|m|h)?$/i.exec(e.trim());if(!r)throw f(`${t} must be a positive duration such as 500ms, 30s, or 2m.`);const n=Number(r[1]);const o=r[2]?.toLowerCase()==="h"?36e5:r[2]?.toLowerCase()==="m"?6e4:r[2]?.toLowerCase()==="s"?1e3:1;const i=n*o;if(!Number.isSafeInteger(i)||i<1){throw f(`${t} must resolve to a positive safe integer in milliseconds.`)}return i}function xt(e,t){if(!/^\d+$/.test(e.trim()))throw f(`${t} must be a positive integer.`);const r=Number(e);if(!Number.isSafeInteger(r)||r<1){throw f(`${t} must be a positive safe integer.`)}return r}function F(e,t,r){if(r.includes(t))return t;throw f(`${e} must be one of: ${r.join(", ")}.`)}function St(e){if(e.effort===void 0)return void 0;const t=e.effort.trim();if(!t)throw f("--effort cannot be empty.");return t}function f(e,t){return new g("invocation",e,t===void 0?void 0:{cause:t})}function N(e){return e instanceof Error?e.message:String(e)}import{resolve as Ot}from"node:path";function It(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function pr(e){let t=0;let r=0;for(const n of e){if(n.foreground===true)continue;if(n.status==="queued"||n.status==="running"||n.status==="stopping"){t+=1}else if(n.deliveredAtMs===void 0){r+=1}}return{active:t,undeliveredTerminal:r}}async function Rt(e){const{runtime:t,sessionId:r}=e;if(typeof t.listBackgroundTasks!=="function")return"unsupported";const n=e.pollIntervalMs??250;const o=Date.now()+e.timeoutMs;let i=false;let s=0;for(;;){if(e.signal?.aborted)return"cancelled";let d;try{const a=await t.listBackgroundTasks(r,{includeSubagent:true});d=pr(a);s=0}catch{s+=1;if(s>=3)return"unreadable";d={active:1,undeliveredTerminal:0}}if((d.active>0||d.undeliveredTerminal>0)&&!i){i=true;e.onPending?.(d)}if(d.active===0&&d.undeliveredTerminal===0){let a;try{a=await t.getActiveRun(r)}catch{a=void 0}if(!a||a.state==="idle"||a.state==="terminal"){return"drained"}}if(Date.now()>=o)return"timeout";await new Promise(a=>{const m=setTimeout(a,Math.min(n,Math.max(0,o-Date.now())));m.unref?.()})}}var bt="Background task work is still pending after the Turn ended; the automatic completion notice has not been delivered. This exec process must exit \u2014 run under the daemon (MCODE_SERVER_MODE=auto or required) for wake Turns that outlive a single invocation.";import{randomUUID as gr}from"node:crypto";import{rename as yr,unlink as hr,writeFile as wr}from"node:fs/promises";import{basename as Tr,dirname as vr,join as Er}from"node:path";var G=class extends g{constructor(t,r){super("internal",t,r);this.name="HeadlessOutputError"}};function kt(e,t,r={}){let n=false;if(e==="stream-json"&&!r.eventProjector){throw new G("stream-json requires an Exec event projector.")}return{async event(o){if(e!=="stream-json")return;for(const i of r.eventProjector?.project(o)??[]){await te(t,`${JSON.stringify(i)}
7
+ `)}},async result(o){if(n)throw new G("ExecResult was encoded more than once.");if(!ut(o)){throw new G("Headless coordinator returned an invalid ExecResult.")}n=true;if(e==="stream-json"){for(const i of r.eventProjector?.complete(o)??[]){await te(t,`${JSON.stringify(i)}
8
+ `)}return}if(e==="json"){await te(t,`${JSON.stringify(o)}
9
+ `);return}if(o.status==="succeeded"){const i=Ge(o.output)?q(o.output):typeof o.output==="string"?He(o.output):JSON.stringify(o.output);await te(t,`${i??""}
10
+ `)}}}}async function Pt(e,t){const r=Er(vr(e),`.${Tr(e)}.${process.pid}.${gr()}.tmp`);try{await wr(r,t,{encoding:"utf8",flag:"wx"});await yr(r,e)}catch(n){await hr(r).catch(()=>void 0);throw new g("internal",`Could not write --output-last-message: ${e}`,{cause:n})}}function we(e){return t=>new Promise((r,n)=>{let o=false;const i=s=>{if(o)return;o=true;if(s.code==="EPIPE"){n(new g("brokenPipe","stdout pipe was closed.",{cause:s}));return}n(new g("internal",`stdout write failed: ${s.message}`,{cause:s}))};e.once("error",i);try{e.write(t,s=>{if(s){i(s);return}if(o)return;o=true;e.off("error",i);r()})}catch(s){e.off("error",i);i(s)}})}async function te(e,t){try{await e(t)}catch(r){if(r instanceof g)throw r;const n=r&&typeof r==="object"&&"code"in r?r.code:void 0;throw new g(n==="EPIPE"?"brokenPipe":"internal",n==="EPIPE"?"stdout pipe was closed.":"stdout writer failed.",{cause:r})}}var xr=5;var Sr=100;var ne=class{constructor(t,r={}){this.runtime=t;this.options=r}runtime;options;conversationPort(){return{sendMessage:(t,r)=>this.sendMessage(t,r),abortSession:t=>this.runtime.abortSession(t),steer:t=>this.runtime.steer(t)}}async*sendMessage(t,r){if(!t.turnId)throw re("EXEC_TURN_ID_REQUIRED","Exec requires a Turn id.");const n=t.turnId;r?.throwIfAborted();const o={seenMessageIds:new Set,seenCursors:new Set,sawEvent:false,terminal:false,heartbeatSeen:false,doneSeen:false};let i=true;let s=0;let d;for(;;){r?.throwIfAborted();let a=false;let m=false;try{const w=i?this.runtime.sendMessage(t,r):this.runtime.watchSessionTurn(t.id,n,kr(r),{...o.cursor?{afterCursor:o.cursor}:{},...!o.cursor&&o.afterMsgId?{afterMsgId:o.afterMsgId}:{}});i=false;for await(const c of w){r?.throwIfAborted();const h=c.cursor?o.seenCursors.has(c.cursor):false;if(c.cursor){o.cursor=c.cursor;if(!h){o.seenCursors.add(c.cursor);m=true}}const x=c.type==="message"&&c.message.id?o.seenMessageIds.has(c.message.id):false;const E=!c.cursor&&(c.type==="heartbeat"&&o.heartbeatSeen||c.type==="done"&&o.doneSeen);if(h||x||E)continue;if(c.type==="message")m=true;if(c.type==="heartbeat")o.heartbeatSeen=true;if(c.type==="done")o.doneSeen=true;if(!c.cursor&&c.type!=="message")m=!o.sawEvent;o.sawEvent=true;Ir(o,c);if(c.type==="resync-required"){a=true;yield c;break}yield c;if(br(c)){o.terminal=true}}}catch(w){if(r?.aborted)throw r.reason??w;d=w}if(o.terminal)return;const l=yield*this.reconcile(t,n,o,a,r);if(l.terminal)return;if(!l.recoverable){throw d??re("EXEC_STREAM_ENDED_WITHOUT_TERMINAL","Runtime stream ended without a durable terminal fact.")}s=m||l.progressed?0:s+1;if(s>(this.options.maxConsecutiveRecoveryAttempts??xr)){throw re("EXEC_STREAM_RECOVERY_EXHAUSTED","Runtime stream recovery was exhausted before a terminal fact arrived.",d)}await(this.options.wait??Pr)(this.options.reconnectDelayMs??Sr,r)}}async*reconcile(t,r,n,o,i){i?.throwIfAborted();const[s,d]=await Promise.all([this.runtime.getActiveRun(t.id),this.runtime.getSession(t.id)]);const a=(s.state==="running"||s.state==="decision-blocked")&&(!s.turnId||s.turnId===r);const m=o||!a||s.state==="idle";let l=false;let w=false;if(m){const{messages:c}=await Te(this.runtime,t.id,r);for(const h of c){if(h.id)n.afterMsgId=h.id;if(Rr(h))l=true;if(h.id&&n.seenMessageIds.has(h.id))continue;if(h.id)n.seenMessageIds.add(h.id);n.sawEvent=true;w=true;yield{type:"message",message:h}}if(o)n.cursor=void 0}if(d.status==="error"){yield{type:"session-status",status:"error",turnId:r,message:d.errorMessage??"Runtime turn failed."};return{progressed:w,recoverable:false,terminal:true}}if(d.status==="aborted"){yield{type:"session-status",status:"aborted",turnId:r};return{progressed:w,recoverable:false,terminal:true}}if(d.status==="idle"&&l){yield{type:"session-status",status:"finished",turnId:r};return{progressed:w,recoverable:false,terminal:true}}if(s.state==="decision-blocked"){throw re("INTERACTION_NOT_AVAILABLE","Runtime is waiting for user interaction from a non-interactive Exec host.")}return{progressed:w,recoverable:a||n.sawEvent,terminal:false}}};async function Te(e,t,r,n){const o=[];const i=new Set;let s;for(let d=0;d<100;d+=1){n?.throwIfAborted();const a=await e.listMessagePage(t,{limit:200,...s?{before:s}:{}});n?.throwIfAborted();o.unshift(a.messages.filter(m=>m.turnId===r));if(!a.hasMore)return{messages:o.flat(),complete:true};if(!a.nextCursor||i.has(a.nextCursor))break;i.add(a.nextCursor);s=a.nextCursor}return{messages:o.flat(),complete:false}}function Ir(e,t){if(t.type!=="message"||!t.message.id)return;e.seenMessageIds.add(t.message.id);e.afterMsgId=t.message.id}function Rr(e){return e.role==="assistant"&&(e.kind==="final"||e.finishReason==="stop"||e.finishReason==="end_turn"||e.finishReason==="stop_sequence")}function br(e){if(e.type==="error")return true;return e.type==="session-status"&&(e.status==="finished"||e.status==="error"||e.status==="aborted"||e.status==="interrupted")}function kr(e){return e??new AbortController().signal}async function Pr(e,t){if(e<=0)return;await new Promise((r,n)=>{const o=()=>{t?.removeEventListener("abort",s);r()};const i=setTimeout(o,e);const s=()=>{clearTimeout(i);t?.removeEventListener("abort",s);n(t?.reason??new Error("Exec stream recovery was cancelled."))};if(t?.aborted){s();return}t?.addEventListener("abort",s,{once:true})})}function re(e,t,r){return Object.assign(new Error(t,r===void 0?void 0:{cause:r}),{category:"runtime",code:e,retryable:false})}var oe=class{constructor(t){this.options=t;this.nowMs=t.nowMs??Date.now}options;sequence=0;started=false;completed=false;startedItems=new Set;nowMs;project(t){if(this.completed)throw new Error("Exec events cannot follow exec.completed.");const r=Mr(t);return[...this.ensureStarted(),...r.map(n=>this.itemEvent(n))]}complete(t){if(this.completed)throw new Error("exec.completed was projected more than once.");this.completed=true;const r=t.status==="succeeded"?this.event({type:"turn.completed",...t.model?{model:t.model}:{},...t.usage?{usage:t.usage}:{},...t.usageSource!==void 0?{usageSource:t.usageSource}:{},...t.usageIncomplete!==void 0?{usageIncomplete:t.usageIncomplete}:{},durationMs:t.durationMs}):this.event({type:"turn.failed",status:t.status,...t.error?{error:t.error}:{},durationMs:t.durationMs});return[...this.ensureStarted(),r,this.event({type:"exec.completed",result:t})]}ensureStarted(){if(this.started)return[];this.started=true;return[this.event({type:"exec.started"}),this.event({type:this.options.resumed?"session.resumed":"session.started"}),this.event({type:"turn.started"})]}itemEvent(t){const r=this.startedItems.has(t.item.id);if(t.completed){this.startedItems.delete(t.item.id);return this.event({type:"item.completed",item:t.item})}this.startedItems.add(t.item.id);return this.event({type:r?"item.updated":"item.started",item:t.item})}event(t){return{schemaVersion:1,sequence:++this.sequence,timestampMs:this.nowMs(),runId:this.options.runId,sessionId:this.options.sessionId,turnId:this.options.turnId,...t}}};function Mr(e){if(e.type==="delta"&&e.role==="assistant"){const t=e.messageId??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",contentDelta:e.thinking},completed:false}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",contentDelta:e.content},completed:false}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Mt(r,t,n),completed:false}))]}if(e.type!=="message"||e.message.role!=="assistant")return[];return Ar(e.message)}function Ar(e){const t=e.id??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",content:e.thinking},completed:true}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",content:e.content},completed:true}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Mt(r,t,n),completed:true}))]}function Mt(e,t,r){return{id:e.id??`${t}:tool:${String(r)}`,type:"tool_call",toolCall:e}}import{performance as se}from"node:perf_hooks";async function At(e,t,r=5e3){const n=se.now()+r;while(se.now()<n){let o;try{const s=await Promise.race([e.getActiveRun(t),new Promise(d=>{o=setTimeout(()=>d(void 0),Math.max(0,n-se.now()))})]);if(!s||s.sessionId!==t)return false;if(s.state==="idle"||s.state==="terminal")return true}catch{return false}finally{if(o)clearTimeout(o)}const i=n-se.now();if(i<=0)return false;await new Promise(s=>setTimeout(s,Math.min(50,i)))}return false}import{performance as ve}from"node:perf_hooks";var ie=class{constructor(t){this.record=t}record;active=new Map;toolStates=new Map;modelSteps=0;toolCalls=0;lastActivityAt=Date.now();droppedOperations=0;observe(t){if(t.type==="delta"){if(t.content||t.thinking||t.toolCalls?.length)this.lastActivityAt=Date.now();for(const r of t.toolCalls??[])this.tool(r)}else if(t.type==="message"){for(const r of t.message.toolCalls??[])this.tool(r)}else if(t.type==="generic"&&t.eventType==="execution.diagnostic"){const{kind:r,operationId:n,modelId:o,protocol:i,finishReason:s}=t.data;if(typeof n!=="string")return;if(r==="model_phase_started"){this.modelSteps++;this.start(n,"model")}else if(r==="model_phase_finished"||r==="model_phase_failed"){this.end(n,{finishReason:typeof s==="string"?s:void 0})}else return;this.record({kind:r,operationId:n,modelId:typeof o==="string"?o:void 0,protocol:typeof i==="string"?i:void 0})}}summary(){return{modelSteps:this.modelSteps,toolCalls:this.toolCalls,lastActivityAt:this.lastActivityAt,droppedOperations:this.droppedOperations,unfinishedOperations:[...this.active].map(([t,r])=>({operationId:t,kind:r.kind,startedAtMs:r.startedAtMs,elapsedMs:Math.max(0,ve.now()-r.startedAt)}))}}tool(t){if(!t.id)return;const r=String(t.status).toLowerCase();const n=["1","started","running","in_progress"].includes(r)?"started":["2","completed","succeeded","success"].includes(r)?"finished":["3","failed","error"].includes(r)?"failed":void 0;if(!n||this.toolStates.get(t.id)===n)return;if(this.toolStates.size>=4096&&!this.toolStates.has(t.id)){this.droppedOperations++;return}this.toolStates.set(t.id,n);if(n==="started"){this.toolCalls++;this.start(t.id,"tool");this.record({kind:"tool_started",operationId:t.id,toolName:t.name})}else{this.end(t.id,{kind:`tool_${n}`,toolName:t.name})}}start(t,r){this.lastActivityAt=Date.now();if(this.active.size>=256){this.droppedOperations++;return}this.active.set(t,{kind:r,startedAt:ve.now(),startedAtMs:this.lastActivityAt})}end(t,r){this.lastActivityAt=Date.now();const n=this.active.get(t);this.active.delete(t);this.record({kind:"operation_finished",operationId:t,...r,...n?{durationMs:Math.max(0,ve.now()-n.startedAt)}:{missingStart:true}})}};var Or=je("mcode:tui");var _r=3e5;async function Nt(e,t){const r=t.stdout??we(process.stdout);const n=t.stderr??we(process.stderr);const o=t.processRef??process;const i=t.createTurnId??It;let s=j.internal;let d;let a;const m=[];let l;let w={};let c={};let h=false;let x;const E=e.diagnosticsDir?new ie(y=>l?.record({...c,...y})):void 0;const u=Date.now();const b=new ne(t.runtime);const I=new Ye(b.conversationPort(),{...e.diagnosticsDir?{onAnswerSelection:y=>{w=y;l?.record(y)}}:{}});let k;let P=t.signal?.aborted??false;const p=()=>{P=true;void I.abort()};const v=()=>{if(P)throw new g("cancelled","Execution was cancelled.")};t.signal?.addEventListener("abort",p,{once:true});o.once("SIGINT",p);o.once("SIGTERM",p);o.once("SIGHUP",p);try{v();if(e.diagnosticsDir){l=await Y.create(e.diagnosticsDir,T=>m.push(T));v()}const y=e.model?De(e.model):void 0;await Qe(t.runtime,e.sessionId,void 0,void 0,y?{model:y}:void 0);v();const S=await Br(e,t.runtime,v);v();await jr(t.runtime,S);v();const R=await Ce({...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},session:S,runtime:t.runtime});v();const A=i();const ae=`exec_${A}`;c={version:e.version,sessionId:S.sessionId,turnId:A,runId:ae,startedAt:u,schemaHash:pt(e.outputSchema)};l?.execution(c);l?.record({kind:"execution_started",sessionId:S.sessionId,turnId:A});const Se=kt(e.format??"text",r,{...e.format==="stream-json"?{eventProjector:new oe({runId:ae,sessionId:S.sessionId,turnId:A,resumed:Boolean(e.sessionId||e.continueSession)})}:{}});const Ft=await I.execute({turnId:A,session:Promise.resolve(S),content:e.prompt,workspace:e.workspaceDir,version:e.version,...l?{executionDiagnostics:true}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...R?{model:R}:{},...e.reviewRequest?{reviewRequest:e.reviewRequest}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.timeoutMs!==void 0||e.maxSteps!==void 0?{policy:{...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.maxSteps!==void 0?{maxSteps:e.maxSteps}:{},requireAnswer:true}}:{policy:{requireAnswer:true}}},async T=>{let $;if(T.type==="message"){$=We(T.message.origin);if($){k={outcome:$,content:T.message.content??""}}}E?.observe(T);if(T.type==="session-status"){l?.record({kind:"session_status",status:T.status})}else if(T.type==="message"&&T.message.role==="assistant"){l?.record({kind:"assistant_completed",messageId:T.message.id,finishReason:T.message.finishReason,requestDurationMs:T.message.usage?.requestDurationMs})}try{await Se.event(Cr(T,$))}catch(Re){d??=Re;void I.abort();throw Re}});if(d)throw d;let M=Nr(Ft.outcome);let U;if(e.reviewRequest&&M.status==="succeeded"){const T=Dr(k);if("error"in T){M={...M,status:"failed",answer:null,error:T.error}}else{U=T.result}}x=M.answer;const L=M.status==="succeeded"?fe(M.answer,e.outputSchema):void 0;const O=Fr(e.format)||l?await $r(t.runtime,S.sessionId,A,M):{};const $t={runId:ae,...L?{validation:L}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...O.model?{model:{...O.model,...e.outputSchema&&M.status==="succeeded"?{structuredOutputMode:"native_strict"}:{}}}:{},...O.usage?{usage:O.usage}:{},..."usageSource"in O?{usageSource:O.usageSource,usageIncomplete:O.usageIncomplete}:{}};const Ie=at(M,$t);const _=U?{...Ie,output:U}:Ie;if(l&&_.status==="timeout"){h=await At(t.runtime,S.sessionId);l.record({kind:"stop_confirmed",stopped:h})}c={...c,model:O.model,status:_.status,durationMs:_.durationMs};if(_.status!=="succeeded"){l?.failure(M.answer,{...E?.summary(),...w,error:_.error,status:_.status,...L&&!L.ok?{validationKind:L.kind}:{}})}a={encoder:Se,result:_,..._.status==="succeeded"&&e.outputLastMessagePath?{lastMessage:{filePath:e.outputLastMessagePath,answer:U?q(U):M.answer??""}}:{}};if(!P&&e.ownsBackgroundWake!==false){const T=await Rt({runtime:t.runtime,sessionId:S.sessionId,timeoutMs:e.backgroundDeliveryDrainTimeoutMs??_r,signal:t.signal,onPending:$=>{l?.record({kind:"background_delivery_drain_started",...$})}});if(T==="timeout"||T==="unreadable"){m.push(`${bt}
11
+ `)}}}catch(y){const S=Dt(y);l?.failure(void 0,{error:{message:S.message},phase:"execution"});s=B(S);if(s!==j.brokenPipe){m.push(`mcode exec failed: ${H(S)}
12
+ `)}}finally{t.signal?.removeEventListener("abort",p);o.off("SIGINT",p);o.off("SIGTERM",p);o.off("SIGHUP",p);let y;let S=false;try{const R=await t.shutdown();if(R===true)y="Runtime shutdown did not complete cleanly."}catch(R){y=Fe(R,{summary:"mcode exec shutdown failed.",nextStep:"Verify no process is still running."})}if(a){if(y&&a.result.status==="succeeded"){a.result=_t(a.result,"RUNTIME_SHUTDOWN_FAILED",y);S=true}if(a.result.status==="succeeded"&&a.lastMessage){try{await Pt(a.lastMessage.filePath,a.lastMessage.answer)}catch(R){a.result=_t(a.result,"OUTPUT_LAST_MESSAGE_WRITE_FAILED",R instanceof Error?R.message:String(R))}}try{if(a.result.status!=="succeeded"&&a.result.error?.category==="internal"){l?.failure(x,{...w,status:a.result.status,error:a.result.error})}await a.encoder.result(a.result);s=_e(a.result);if(a.result.status!=="succeeded"){m.push(`mcode exec ${a.result.status}: ${st(a.result)}
13
+ `)}}catch(R){const A=Dt(R);s=B(A);if(s!==j.brokenPipe){m.push(`mcode exec failed: ${H(A)}
14
+ `)}}}else if(y&&s!==j.brokenPipe){s=j.internal}if(y&&!S)m.push(`${y}
15
+ `);l?.execution({...c,endedAt:Date.now(),shutdownComplete:!y,exitCode:s});l?.record({kind:"execution_finished",...c,exitCode:s,shutdownComplete:!y});await l?.flush({version:e.version,runId:c.runId,sessionId:c.sessionId,turnId:c.turnId,...E?.summary(),exitCode:s,shutdownComplete:!y,recoveryReady:h&&!y});Or.info("exec exit",{...typeof c["runId"]==="string"?{runId:c["runId"]}:{},...typeof c["sessionId"]==="string"?{sessionId:c["sessionId"]}:{},...typeof c["turnId"]==="string"?{turnId:c["turnId"]}:{},exitCode:s,durationMs:Date.now()-u,shutdownComplete:!y});if(s!==j.brokenPipe){for(const R of m)await Hr(n,R)}}return s}function Dr(e){if(!e){return{error:{category:"runtime",code:"REVIEW_RESULT_MISSING",message:"Runtime completed without a validated code review result.",retryable:true}}}if(e.outcome==="failed"){return{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:e.content.trim()||"Runtime rejected an invalid code review result.",retryable:true}}}const t=e.outcome==="pass"?Ve(e.content):ce(e.content);return t?{result:t}:{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:"Runtime returned an invalid code review result.",retryable:true}}}function Cr(e,t){if(e.type!=="message"||t!=="needs_changes")return e;const r=ce(e.message.content??"");return{...e,message:{...e.message,content:r?q(r):"Runtime returned an invalid code review result."}}}function _t(e,t,r){return{...e,status:"failed",output:void 0,error:{category:"internal",code:t,message:r,retryable:false}}}function Nr(e){if(e.status!=="awaiting-user-continuation")return e;return{...e,status:"failed",error:{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested user interaction from a non-interactive Exec host.",retryable:false}}}async function jr(e,t){const r=t.agentName??de;const[n,o]=await Promise.all([e.getPendingQuestionnaire(r,t.sessionId),e.listPendingPermissions()]);const i=o.some(d=>d.sessionId===t.sessionId);if(!n&&!i)return;const s=n?"a pending questionnaire":"a pending permission request";throw new g("runtime",`Session ${t.sessionId} has ${s} and requires an interactive host. Continue it in the TUI or ACP.`)}function Fr(e){return e==="json"||e==="stream-json"}async function $r(e,t,r,n){const o=new AbortController;const i=setTimeout(()=>o.abort(),1e3);const[s,d,a]=await Promise.all([Ee(()=>e.getSessionUsage(t),void 0,o.signal),Ee(()=>e.listModels(t),[],o.signal),Ee(()=>Te(e,t,r,o.signal),void 0,o.signal)]).finally(()=>clearTimeout(i));const m=s?.rows?.filter(p=>p.turnId===r)??[];const l=[...m].reverse().find(p=>p.model?.trim())?.model?.trim();const w=n.model?`${n.model.providerId}/${n.model.modelId}`:void 0;const c=d.find(p=>p.selected===true);const h=c?`${c.providerId}/${c.modelId}`:void 0;const x=Ur(l??w??h,d,n.model?.variant);const E=[...n.usageResponses??[]];const u=new Set;for(const p of a?.messages??[]){const v=le(p,r);if(!v)continue;if(v.messageId)u.add(v.messageId);if(v.messageId)Xe(E,v)}const b=Ke(E);const I=xe(b.usage??n.usage);const k=I??Lr(m);const P=n.status!=="succeeded"||n.usageIncomplete===true||!a?.complete||a.messages.some(p=>ze(p,r))||b.usageIncomplete||I!==void 0&&I.totalTokens===void 0||E.length===0||E.some(p=>!p.messageId||!u.has(p.messageId)||!xe(p.usage)||p.usageIncomplete)||(a?.messages.some(p=>{const v=le(p,r);return v!==void 0&&!v.messageId})??false);return{...x?{model:x}:{},...k?{usage:k}:{},usageSource:I?"completed_responses":k?"analytics_fallback":"unavailable",usageIncomplete:!I||P}}function Ee(e,t,r){return new Promise(n=>{const o=s=>{r.removeEventListener("abort",i);n(s)};const i=()=>o(t);r.addEventListener("abort",i,{once:true});if(r.aborted)return i();void Promise.resolve().then(e).then(o,()=>o(t))})}function Ur(e,t,r){const n=e?.indexOf("/")??-1;if(!e||n<=0||n===e.length-1)return void 0;const o=e.slice(0,n);const i=e.slice(n+1);const s=t.find(d=>d.providerId===o&&d.modelId===i);return{providerId:o,modelId:i,...s?.variant!==void 0?{variant:s.variant}:r!==void 0?{variant:r}:{},...s?.providerSource?{providerSource:s.providerSource}:{},...s?.providerKind?{providerKind:s.providerKind}:{},...s?.apiFormat?{protocol:s.apiFormat}:{}}}function Lr(e){const t=new Map;const r=[];for(const i of e){if(i.id===void 0)r.push(i);else t.set(i.id,i)}const n=[...t.values(),...r];const o={...J(n,"inputTokens"),...J(n,"outputTokens"),...J(n,"reasoningTokens"),...J(n,"cacheReadTokens"),...J(n,"cacheWriteTokens")};return xe(o)}function xe(e){if(!e)return void 0;const t={...e};delete t.totalTokens;const r=t.inputTokens;const n=t.outputTokens;const o=(r??0)+(n??0);return Object.keys(t).length===0?void 0:{...t,...(r!==void 0||n!==void 0)&&Number.isFinite(o)?{totalTokens:o}:{}}}function J(e,t){const r=e.map(o=>o[t]).filter(o=>typeof o==="number"&&Number.isFinite(o)&&o>=0);const n=r.reduce((o,i)=>o+i,0);return r.length>0&&Number.isFinite(n)?{[t]:n}:{}}function Dt(e){if(e instanceof g)return e;if(e instanceof Oe){const r=e.category==="config"||e.category==="invocation"||e.category==="cancelled"||e.category==="brokenPipe"||e.category==="internal"?e.category:"runtime";return new g(r,e.message,{cause:e})}const t=e instanceof Error?e.message:String(e);return new g("runtime",t,{cause:e})}async function Br(e,t,r){if(e.sessionId){const n=await t.getSession(e.sessionId);Ct(n,e.workspaceDir);return n}if(e.continueSession){const n=await qr(t,e.workspaceDir,r);if(!n){throw new g("runtime",`No active Session exists for workspace ${e.workspaceDir}.`)}Ct(n,e.workspaceDir);return n}return t.createSession({workspaceDir:e.workspaceDir,title:Wr(e.prompt,e.attachments?.length??0)})}async function qr(e,t,r){let n;do{const o=await e.listSessionPage({agentName:de,cursor:n,limit:50,includeArchived:false});r();const i=o.sessions.find(s=>s.archived!==true&&s.workspaceDir!==void 0&&jt(s.workspaceDir,t));if(i)return i;n=o.hasMore?o.nextCursor:void 0}while(n);return void 0}function Ct(e,t){if(qe(e)){throw new g("invocation","Sub-agent Sessions are internal and cannot be opened.")}if(e.archived){throw new g("runtime",`Session is archived: ${e.sessionId}`)}if(!e.workspaceDir||!jt(e.workspaceDir,t)){throw new g("runtime",`Session workspace does not match --cwd: ${e.sessionId}`)}}function jt(e,t){const r=Ot(e);const n=Ot(t);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}async function Hr(e,t){try{await e(t)}catch{}}function Wr(e,t){const r=e.replace(/\s+/g," ").trim();if(!r)return t===1?"Attachment run":`${t} attachments`;return r.length<=80?r:`${r.slice(0,77)}...`}async function fo(e,t,r,n={}){const o=n.processRef??process;const i=n.writeError??(u=>process.stderr.write(u));const s=n.resolveInvocation??wt;const d=n.resolveDataDir??Ae;const a=n.loadConfig??nt;const m=n.createRuntime??tt;const l=n.shutdownRuntime??rt;const w=n.runExec??Nt;const c=n.readStdin??Gr;const h=new AbortController;const x=()=>h.abort();const E=()=>{if(h.signal.aborted){throw new g("cancelled","Invocation was cancelled.")}};o.once("SIGINT",x);o.once("SIGTERM",x);o.once("SIGHUP",x);try{const u=await s(e,t,()=>c(h.signal),h.signal);E();const b=await d();E();const I=u.configPath?await a(u.configPath,{dataDir:b}):void 0;E();if(u.noBuiltinTools){process.env[be]="1"}const k=u.noBuiltinTools===true||z(process.env)||ke(process.env);const P=await m({dataDir:b,workspaceDir:u.workspaceDir,version:r,...u.configPath?{configPath:u.configPath}:{},surface:"headless",promptMode:u.promptMode??"tui",...u.systemPromptOverrides?{systemPromptOverrides:u.systemPromptOverrides}:{},permissionMode:Vr(u.permission),...u.contextMode?{contextMode:u.contextMode}:{},...t.lane?{lane:t.lane}:{},...t.profile?{profile:t.profile}:{},...u.noDaemon||k?{noDaemon:true}:{}},I?{getConfig:()=>I,configSource:"explicit"}:{});o.exitCode=await w({prompt:u.prompt,workspaceDir:u.workspaceDir,version:r,attachments:u.attachments,format:u.format,...u.model?{model:u.model}:{},...u.effort?{effort:u.effort}:{},...u.sessionId?{sessionId:u.sessionId}:{},continueSession:u.continueSession,permission:u.permission,...u.diagnosticsDir?{diagnosticsDir:u.diagnosticsDir}:{},...u.timeoutMs!==void 0?{timeoutMs:u.timeoutMs}:{},...u.maxSteps!==void 0?{maxSteps:u.maxSteps}:{},...u.outputSchema===void 0?{}:{outputSchema:u.outputSchema},...u.outputLastMessagePath===void 0?{}:{outputLastMessagePath:u.outputLastMessagePath},...u.reviewRequest?{reviewRequest:u.reviewRequest}:{},ownsBackgroundWake:Je()==="off"},{runtime:P.adapter,signal:h.signal,shutdown:()=>l(P)})}catch(u){const b=u instanceof g?u:new g("runtime",u instanceof Error?u.message:String(u),{cause:u});i(`mcode exec failed: ${H(b)}
16
+ `);o.exitCode=B(b)}finally{o.off("SIGINT",x);o.off("SIGTERM",x);o.off("SIGHUP",x)}}function Vr(e){switch(e){case"smart":return"auto";case"full":return"bypassPermissions";case"off":return"off"}}async function Gr(e,t=process.stdin){const r=[];const n=t[Symbol.asyncIterator]();try{for(;;){const o=await Jr(n,e);if(o.done)break;r.push(Buffer.isBuffer(o.value)?o.value:Buffer.from(o.value))}}finally{await n.return?.()}return Buffer.concat(r).toString("utf8")}function Jr(e,t){return new Promise((r,n)=>{const o=()=>{n(new g("cancelled","stdin input was cancelled."))};if(t.aborted){o();return}t.addEventListener("abort",o,{once:true});void e.next().then(i=>{t.removeEventListener("abort",o);r(i)},i=>{t.removeEventListener("abort",o);n(i)})})}export{Gr as readTuiStdinToEnd,fo as runTuiExecCommand};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
+ import{$ as oa,$a as mb,A as Q,Aa as Na,Ab as Wb,B as R,Ba as Oa,Bb as Xb,C as S,Ca as Pa,Cb as Yb,D as T,Da as Qa,Db as Zb,E as U,Ea as Ra,Eb as _b,F as V,Fa as Sa,Fb as $b,G as W,Ga as Ta,Gb as ac,H as X,Ha as Ua,Hb as bc,I as Y,Ia as Va,Ib as cc,J as Z,Ja as Wa,Jb as dc,K as _,Ka as Xa,Kb as ec,L as $,La as Ya,M as aa,Ma as Za,N as ba,Na as _a,O as ca,Oa as $a,P as da,Pa as ab,Qa as bb,R as ea,Ra as cb,S as fa,Sa as db,T as ga,Ta as eb,U as ha,Ua as fb,V as ia,Va as gb,W as ja,Wa as hb,X as ka,Xa as ib,Y as la,Ya as jb,Z as ma,Za as kb,_ as na,_a as lb,a,aa as pa,ab as nb,b,ba as qa,bb as ob,ca as ra,cb as pb,d as c,da as sa,db as qb,e as d,ea as ta,eb as rb,f as e,fa as ua,fb as sb,g as f,ga as va,gb as tb,h as g,ha as wa,hb as ub,i as h,ia as xa,ib as vb,j as i,ja as ya,jb as wb,k as j,ka as za,kb as xb,l as k,la as Aa,lb as yb,m as l,ma as Ba,mb as zb,n as m,na as Ca,nb as Ab,o as n,oa as Da,ob as Bb,p as F,pa as Ea,pb as Cb,q as G,qa as Fa,qb as Db,r as H,ra as Ga,rb as Nb,s as I,sa as Ha,sb as Ob,t as J,tb as Pb,u as K,ub as Qb,v as L,va as Ia,vb as Rb,w as M,wa as Ja,wb as Sb,x as N,xa as Ka,xb as Tb,y as O,ya as La,yb as Ub,z as P,za as Ma,zb as Vb}from"./chunk-XWNCITOR.js";import{a as o,b as p,c as q,d as r,e as s,f as t,g as u,h as v,i as w,j as x,k as y,l as z,m as A,n as B,o as C,p as D,q as E}from"./chunk-ISBSRM3S.js";import"./chunk-3MLT4F77.js";import"./chunk-UQL67NEA.js";import"./chunk-4GGSPZK3.js";import{a as Eb,b as Fb,c as Gb,d as Hb,e as Ib,f as Jb,g as Kb,h as Lb,i as Mb}from"./chunk-AUG3KCLV.js";import"./chunk-7F3QKGB7.js";import"./chunk-FK3SSGJE.js";export{G as AGENT_BUILTIN_MCP_TOOL_IDS,L as AGENT_BUILTIN_SKILL_IDS,F as AGENT_BUILTIN_TOOL_IDS,M as AGENT_CAPABILITY_OWNED_SKILL_IDS,k as AGENT_RUNTIME_FRAMEWORKS,Ib as ASR_PROXY_AUTH_ENV_KEYS,pa as BRAND,ba as BROWSER_CONFIG_DEFAULTS,dc as CONVERSATION_STOP_CONFIG_DEFAULTS,Sa as CUSTOM_PROVIDER_ID_PREFIX,ac as ConfigFileError,ub as ControlRootInsecureError,qb as DAEMON_CONTROL_ROOT_DIR_PREFIX,l as DEFAULT_AGENT_RUNTIME_FRAMEWORK,d as DEFAULT_CU_BACKEND,za as DEFAULT_MODEL_PRESETS,ra as DEFAULT_PORT,v as DEFAULT_PROFILE_NAME,ab as DEFAULT_SESSIONS_GENERATION,h as DEFAULT_SKILLS_CONFIG,Ya as DURABLE_CAS_DIR_BASENAME,Xa as DURABLE_ROOT_BASENAME,Za as DURABLE_RUNTIME_DB_BASENAME,$a as DURABLE_SESSIONS_DB_BASENAME,_a as DURABLE_SOCKET_BASENAME,j as EXTERNAL_SOURCE_KIND_LIST,Y as GOAL_CONFIG_DEFAULTS,Z as GOAL_CONFIG_LIMITS,V as GOAL_EVALUATOR_MODEL_POLICIES,X as GOAL_SUBAGENT_PROFILES,U as GOAL_VERIFICATION_EVIDENCE_MODES,T as GOAL_VERIFICATION_MODES,W as GOAL_VERIFIER_READONLY_PROFILE,y as InvalidProfileNameError,p as LEGACY_DATA_DIR_BASENAME,x as LEGACY_PROFILE_ENV_VAR,bb as LEGACY_ROOT,Fb as LEGACY_RUNTIME_ENV_KEYS,Qb as LOCAL_RUNTIME_AUTH_CONTEXT_FILE,cb as LegacyWriteError,Qa as MANAGED_MINIMAX_PROVIDER_ID,Eb as MANAGED_RUNTIME_KEYS,ib as MCODED_SOCKET_PATH_MAX_BYTES,lb as MCODE_SERVER_MODE_ENV,Ra as MINIMAX_API_PROVIDER_ID,o as NEW_DATA_DIR_BASENAME,H as NO_BUILTIN_TOOLS_ENV,sa as OPENCODE_PORT_OFFSET,Hb as PARENT_HINT_KEYS,w as PROFILE_ENV_VAR,f as REQUEST_MEDIA_DEFAULTS,qa as RUNTIME_ENV_PREFIX,Gb as RUNTIME_IDENTITY_KEYS,fa as SANDBOX_CONFIG_DEFAULTS,da as SANDBOX_FILESYSTEM_MODE_NAMES,J as SESSION_MCP_ONLY_ENV,mb as ServerModeConfigError,ob as ServerModeOffError,Xb as TEST_PORT_ROLE_FLOOR,Wb as TEST_PORT_ROLE_OFFSET,$ as TOOL_RESULT_COMPACTION_DEFAULTS,ya as allowsManagedMinimaxProviderOverride,$b as assertCuBackendSupported,pb as assertDaemonStartAllowed,xb as assertNoLegacyWrite,vb as assertSecureControlRoot,A as assertValidProfileName,Jb as buildChildEnv,Vb as clearLocalRuntimeAuthContextFile,Db as compareAndSetLocalModelContext,ua as detectGitPortInfo,Pb as detectPidOwner,wb as ensureControlRootLayout,yb as ensureDurableLayout,Mb as findLegacyRuntimeEnvKeys,Ob as formatPidFile,Da as getConfig,xa as getConfigPath,Zb as getCuBackend,wa as getDataDir,r as getLegacyDataDirPath,Ga as getOpenCodePort,q as getPrimaryDataDirPath,va as getProfile,ja as getRuntimeBuildEnv,la as getRuntimePresetKey,ia as getRuntimeRegion,ea as getSandboxConfigDefaults,R as isAgentBuiltinMcpToolEnabled,S as isAgentBuiltinSkillEnabled,Q as isAgentBuiltinToolEnabled,na as isBetaFeatureProdReady,Ta as isFirstPartyMinimaxMessagesRoute,oa as isInternalBuild,Na as isLegacyManagedMinimaxProvider,Ia as isLocalSourceProvenanceEnabled,Oa as isManagedProviderBaseUrl,ka as isManagedRuntime,ha as isProposalEligibleAgent,Ha as isTelemetryChannelEnabled,z as isValidProfileName,E as listProfiles,Va as listRouteModelIds,bc as loadConfigFromFile,t as migrateDefaultDataDir,u as migrateProfileDataDir,c as minimaxApiModels,I as noBuiltinToolsFromEnv,Rb as normalizeLocalRuntimeAuthContext,B as normalizeProfileSelector,O as parseAgentCapabilityConfig,n as parseAgentRuntimeConfig,m as parseAgentRuntimeFramework,N as parseAgentsConfig,ca as parseBrowserConfig,e as parseCuBackend,_ as parseGoalConfig,Nb as parsePidFile,Ka as parsePromptSuggestionRemotePolicy,g as parseRequestMediaConfig,a as parseRunawayGuardOverride,ga as parseSandboxConfig,i as parseSkillsConfig,aa as parseToolResultCompactionConfig,Yb as pickTestPort,rb as profileOfDataDir,ec as readConversationStopConfig,cc as readExplicitBetaFeatureFromFile,Tb as readLocalRuntimeAuthContext,C as readProfileEnv,zb as removeLocalProviderConfig,Ab as replaceLocalManagedMinimaxProvider,Ca as resetConfig,ta as resetGitDetect,P as resolveAgentCapabilities,ma as resolveBetaFeature,fb as resolveCasDirPath,sb as resolveDaemonControlRoot,s as resolveDataDir,db as resolveDurableRoot,kb as resolveFallbackMcodedSocketDir,jb as resolveFallbackMcodedSocketPath,Sb as resolveLocalRuntimeAuthContextPath,hb as resolveMcodedSocketPath,Wa as resolveModelAvailability,Ua as resolveModelCallRoute,Fa as resolvePort,D as resolveProfileDataDirPaths,Ea as resolvePromptConfig,La as resolvePromptSuggestionEnabled,Pa as resolveProviderAuthMode,tb as resolveRealPath,b as resolveRunawayGuardConfig,gb as resolveRuntimeDbPath,nb as resolveServerMode,eb as resolveSessionsDbPath,K as sessionMcpOnlyFromEnv,_b as setCuBackend,Aa as setLegacyByokProviderMigrationEnabled,Ba as setManagedPresetBaseUrlSyncEnabled,Kb as stripManagedRuntimeEnv,Lb as stripRuntimeBoundaryKeysFrom,Bb as updateLocalByokConfig,Cb as updateLocalModelSelection,Ma as withEffectivePromptSuggestion,Ub as writeLocalRuntimeAuthContext,Ja as writeTuiStatusLineSetting};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a,c as u}from"./chunk-AKUP5CLI.js";import{c,d}from"./chunk-V4IDVAIA.js";import{ea as l,ka as m}from"./chunk-UNEPZJKK.js";import"./chunk-ISBSRM3S.js";import"./chunk-5R2PGOIA.js";import"./chunk-UQL67NEA.js";import"./chunk-4GGSPZK3.js";import"./chunk-AUG3KCLV.js";import"./chunk-NOGL6Y6L.js";import"./chunk-FK3SSGJE.js";function p(t,y,e={}){const s=e.environment??process.env;const o=(e.readConfig??m)();const r=f=>a({configEnabled:f,environment:s});const n=r(o.telemetry.enabled);const i={enabled:n.enabled,configured:n.configured,blockedBy:n.blockedBy??null,configFile:(e.readConfigPath??l)(),channels:{usage:n,metrics:r(o.telemetry.metrics),diagnostics:r(o.telemetry.diagnostics)},optInSetting:{telemetry:{enabled:true,metrics:true,diagnostics:true}},optOutEnvironment:["MCODE_DISABLE_TELEMETRY=1","DO_NOT_TRACK=1"]};if(t==="status")return`${JSON.stringify(i,null,2)}
2
+ import{a,c as u}from"./chunk-AKUP5CLI.js";import{c,d}from"./chunk-WHBWI5OQ.js";import{ia as l,oa as m}from"./chunk-XWNCITOR.js";import"./chunk-ISBSRM3S.js";import"./chunk-3MLT4F77.js";import"./chunk-UQL67NEA.js";import"./chunk-4GGSPZK3.js";import"./chunk-AUG3KCLV.js";import"./chunk-7F3QKGB7.js";import"./chunk-FK3SSGJE.js";function p(t,y,e={}){const s=e.environment??process.env;const o=(e.readConfig??m)();const r=f=>a({configEnabled:f,environment:s});const n=r(o.telemetry.enabled);const i={enabled:n.enabled,configured:n.configured,blockedBy:n.blockedBy??null,configFile:(e.readConfigPath??l)(),channels:{usage:n,metrics:r(o.telemetry.metrics),diagnostics:r(o.telemetry.diagnostics)},optInSetting:{telemetry:{enabled:true,metrics:true,diagnostics:true}},optOutEnvironment:["MCODE_DISABLE_TELEMETRY=1","DO_NOT_TRACK=1"]};if(t==="status")return`${JSON.stringify(i,null,2)}
3
3
  `;if(!n.enabled){return`${JSON.stringify({...i,request:null,message:"Usage telemetry is disabled. No business telemetry request will be sent."},null,2)}
4
4
  `}const g=(e.resolveEnvironment??v)(s);return`${JSON.stringify({...i,request:u("tui_launch",{launch_type:"cold"},{...g,version:y,now:e.now,randomId:e.randomId})},null,2)}
5
5
  `}function v(t){return c({runtimeRegion:d(t.MAVIS_REGION)})}export{p as runMcodeTelemetryCommand};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as v}from"./chunk-LFGHL5A2.js";import{g as h,h as f,i as g}from"./chunk-PGYNNAKS.js";import{d as m}from"./chunk-V6SXVN2Z.js";import"./chunk-7WOIEENL.js";import"./chunk-PIADSVUZ.js";import"./chunk-5R2PGOIA.js";import"./chunk-UQL67NEA.js";import"./chunk-6MFNDZP7.js";import"./chunk-NOGL6Y6L.js";import"./chunk-FK3SSGJE.js";import{createInterface as $}from"node:readline/promises";import{stripVTControlCharacters as T}from"node:util";var P=80;var y=15e3;var l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var M=72;async function V(t,e={}){const n=e.application??new v({currentVersion:t});const r=e.interactive??Boolean(process.stdin.isTTY&&process.stdout.isTTY);const a=e.write??(s=>process.stdout.write(s));const c=e.schedulePendingPrefixUpdate??(()=>m());if(await c()){a(`${f()}
2
+ import{a as v}from"./chunk-ALZZ3WAV.js";import{g as h,h as f,i as g}from"./chunk-PGYNNAKS.js";import{d as m}from"./chunk-V6SXVN2Z.js";import"./chunk-7WOIEENL.js";import"./chunk-PIADSVUZ.js";import"./chunk-3MLT4F77.js";import"./chunk-UQL67NEA.js";import"./chunk-6MFNDZP7.js";import"./chunk-7F3QKGB7.js";import"./chunk-FK3SSGJE.js";import{createInterface as $}from"node:readline/promises";import{stripVTControlCharacters as T}from"node:util";var P=80;var y=15e3;var l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var M=72;async function V(t,e={}){const n=e.application??new v({currentVersion:t});const r=e.interactive??Boolean(process.stdin.isTTY&&process.stdout.isTTY);const a=e.write??(s=>process.stdout.write(s));const c=e.schedulePendingPrefixUpdate??(()=>m());if(await c()){a(`${f()}
3
3
  `);return}const i=await n.inspect();if(i.kind==="current"){a(i.source==="managed-installer"?`MCode ${i.currentVersion} is current on ${i.channel}.
4
4
  `:`MCode ${i.currentVersion} is current on @${i.packageTag}.
5
5
  `);return}if(i.kind==="ahead"){a(`MCode ${i.currentVersion} is newer than ${i.source==="managed-installer"?i.channel:`@${i.packageTag}`} ${i.latestVersion}; no update was applied.
package/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
3
- import{g as m}from"./chunks/chunk-V6SXVN2Z.js";import{v as s,w as c}from"./chunks/chunk-7WOIEENL.js";import{b as a,d as n}from"./chunks/chunk-ZPIJSTUE.js";import"./chunks/chunk-V4IDVAIA.js";import"./chunks/chunk-TRX2HFTB.js";import"./chunks/chunk-UNEPZJKK.js";import{k as i}from"./chunks/chunk-ISBSRM3S.js";import"./chunks/chunk-5R2PGOIA.js";import"./chunks/chunk-UQL67NEA.js";import"./chunks/chunk-6MFNDZP7.js";import"./chunks/chunk-4GGSPZK3.js";import"./chunks/chunk-AUG3KCLV.js";import"./chunks/chunk-NOGL6Y6L.js";import"./chunks/chunk-FK3SSGJE.js";import{fileURLToPath as f}from"node:url";async function v(){const p=s(f(__mavis_tuiPackageEntryUrl));const t=c(p);let e;try{e=n(process.argv.slice(2),t)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
4
- `);process.exitCode=1;return}const{getTuiDataDirPath:u}=await import("./chunks/data-dir-OKWMOLNQ.js");let o;try{o=u()}catch(r){if(!(r instanceof i))throw r;process.stderr.write(`${r.message}
5
- `);process.exitCode=1;return}a({dataDir:o,...e?{startupBuildEnvironment:e}:{}});const l=await m();try{const{runTuiCli:r}=await import("./chunks/main-TXP74KHK.js");await r({allowStartupEnvironmentSelection:t})}finally{l.remove()}}await v();
3
+ import{g as m}from"./chunks/chunk-V6SXVN2Z.js";import{v as s,w as c}from"./chunks/chunk-7WOIEENL.js";import{b as a,d as n}from"./chunks/chunk-WUORF7YS.js";import"./chunks/chunk-WHBWI5OQ.js";import"./chunks/chunk-TRX2HFTB.js";import"./chunks/chunk-XWNCITOR.js";import{k as i}from"./chunks/chunk-ISBSRM3S.js";import"./chunks/chunk-3MLT4F77.js";import"./chunks/chunk-UQL67NEA.js";import"./chunks/chunk-6MFNDZP7.js";import"./chunks/chunk-4GGSPZK3.js";import"./chunks/chunk-AUG3KCLV.js";import"./chunks/chunk-7F3QKGB7.js";import"./chunks/chunk-FK3SSGJE.js";import{fileURLToPath as f}from"node:url";async function v(){const p=s(f(__mavis_tuiPackageEntryUrl));const t=c(p);let e;try{e=n(process.argv.slice(2),t)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
4
+ `);process.exitCode=1;return}const{getTuiDataDirPath:u}=await import("./chunks/data-dir-6RWVCAMB.js");let o;try{o=u()}catch(r){if(!(r instanceof i))throw r;process.stderr.write(`${r.message}
5
+ `);process.exitCode=1;return}a({dataDir:o,...e?{startupBuildEnvironment:e}:{}});const l=await m();try{const{runTuiCli:r}=await import("./chunks/main-W3SJ2POE.js");await r({allowStartupEnvironmentSelection:t})}finally{l.remove()}}await v();
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
3
- import{qb as e}from"./chunks/chunk-CAY2BP2G.js";import"./chunks/chunk-DSIZQTS3.js";import"./chunks/chunk-NOGL6Y6L.js";import"./chunks/chunk-OKOOSGFE.js";import"./chunks/chunk-INIZLM6Q.js";import"./chunks/chunk-ELQ5G4U6.js";import"./chunks/chunk-BF4U2LYQ.js";import"./chunks/chunk-YNDFGYGN.js";import"./chunks/chunk-NEICESQ2.js";import"./chunks/chunk-TXWPPTYK.js";import"./chunks/chunk-5RFGU5IW.js";import"./chunks/chunk-QH5Z4N4A.js";import"./chunks/chunk-WTI4WCBV.js";import"./chunks/chunk-PTV7FFNF.js";import"./chunks/chunk-FK3SSGJE.js";try{await e()}catch(r){const s=r instanceof Error?r.stack||r.message:String(r);process.stderr.write(`[mavis-matrix-mcp-server] fatal ${s}
3
+ import{qb as e}from"./chunks/chunk-JEHPL5Z6.js";import"./chunks/chunk-DSIZQTS3.js";import"./chunks/chunk-7F3QKGB7.js";import"./chunks/chunk-OKOOSGFE.js";import"./chunks/chunk-INIZLM6Q.js";import"./chunks/chunk-ELQ5G4U6.js";import"./chunks/chunk-BF4U2LYQ.js";import"./chunks/chunk-YNDFGYGN.js";import"./chunks/chunk-NEICESQ2.js";import"./chunks/chunk-TXWPPTYK.js";import"./chunks/chunk-5RFGU5IW.js";import"./chunks/chunk-QH5Z4N4A.js";import"./chunks/chunk-WTI4WCBV.js";import"./chunks/chunk-PTV7FFNF.js";import"./chunks/chunk-FK3SSGJE.js";try{await e()}catch(r){const s=r instanceof Error?r.stack||r.message:String(r);process.stderr.write(`[mavis-matrix-mcp-server] fatal ${s}
4
4
  `);process.exitCode=1}
package/mcoded.js CHANGED
@@ -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{E as a,N as c,T as m}from"./chunks/chunk-MVI24MQ2.js";import"./chunks/chunk-NJAER6QW.js";import"./chunks/chunk-PIADSVUZ.js";import"./chunks/chunk-ZJZBXSNG.js";import"./chunks/chunk-OLQR4XQZ.js";import"./chunks/chunk-ASRGXT22.js";import"./chunks/chunk-FJEP2EHP.js";import"./chunks/chunk-HMLSH6YL.js";import"./chunks/chunk-PIV6YF7B.js";import"./chunks/chunk-D2BEUF36.js";import"./chunks/chunk-2EBHD6KJ.js";import"./chunks/chunk-3KTXNSLL.js";import"./chunks/chunk-SKLKXOH4.js";import"./chunks/chunk-QASV4FRT.js";import"./chunks/chunk-W7O5Y6VY.js";import"./chunks/chunk-E3RI7IHR.js";import"./chunks/chunk-NT6GUYYJ.js";import"./chunks/chunk-3ZEDGMQ4.js";import"./chunks/chunk-TRX2HFTB.js";import"./chunks/chunk-UNEPZJKK.js";import"./chunks/chunk-ISBSRM3S.js";import"./chunks/chunk-5R2PGOIA.js";import"./chunks/chunk-UQL67NEA.js";import"./chunks/chunk-ZK7UCXBX.js";import"./chunks/chunk-2YX4JWQ4.js";import"./chunks/chunk-T4KXNSN3.js";import"./chunks/chunk-LVGBQ7NP.js";import"./chunks/chunk-SK4JBJDF.js";import"./chunks/chunk-YHXW6NMN.js";import"./chunks/chunk-NG2L523L.js";import"./chunks/chunk-UE7MODZO.js";import"./chunks/chunk-HVCY6M5J.js";import"./chunks/chunk-XWU4BV73.js";import"./chunks/chunk-NUHYT7HY.js";import"./chunks/chunk-FHJWUDED.js";import"./chunks/chunk-4QXF4OT5.js";import"./chunks/chunk-6MFNDZP7.js";import"./chunks/chunk-4GGSPZK3.js";import"./chunks/chunk-IONMKU5J.js";import"./chunks/chunk-AODHXPQF.js";import"./chunks/chunk-AUG3KCLV.js";import"./chunks/chunk-CAY2BP2G.js";import"./chunks/chunk-DSIZQTS3.js";import"./chunks/chunk-NOGL6Y6L.js";import"./chunks/chunk-OKOOSGFE.js";import"./chunks/chunk-INIZLM6Q.js";import"./chunks/chunk-ELQ5G4U6.js";import"./chunks/chunk-BF4U2LYQ.js";import"./chunks/chunk-GJ3NP2JO.js";import"./chunks/chunk-WXD24E23.js";import"./chunks/chunk-2PNC3MM4.js";import"./chunks/chunk-4QKCRKWB.js";import"./chunks/chunk-YNDFGYGN.js";import"./chunks/chunk-NEICESQ2.js";import"./chunks/chunk-TXWPPTYK.js";import"./chunks/chunk-5RFGU5IW.js";import"./chunks/chunk-QH5Z4N4A.js";import"./chunks/chunk-WTI4WCBV.js";import"./chunks/chunk-PTV7FFNF.js";import"./chunks/chunk-TAEC3WRM.js";import"./chunks/chunk-3XYKJXXO.js";import"./chunks/chunk-4A4KPPPE.js";import{a as i}from"./chunks/chunk-VAARXN34.js";import"./chunks/chunk-FK3SSGJE.js";import t from"node:process";var E=i("mcode:rpc");var u=1;async function p(o={}){const d=o.argv??t.argv.slice(2);const e=o.env??t.env;const r=o.homeDir??e["HOME"];if(e["MAVIS_REGION"]===void 0||e["MAVIS_BUILD_ENV"]===void 0){try{const{readProfileStartupEnvironment:f}=await import("./chunks/startup-env-7N4YIYLR.js");const n=f(e,r);if(e["MAVIS_REGION"]===void 0&&n.region!==void 0){e["MAVIS_REGION"]=n.region}if(e["MAVIS_BUILD_ENV"]===void 0&&n.buildEnv!==void 0){e["MAVIS_BUILD_ENV"]=n.buildEnv}}catch{}}if(a(e)==="echo"){return c({argv:d,env:e,homeDir:r})}const s=await m({argv:d,env:e,homeDir:r});return s.daemon}p().catch(o=>{E.error("mcoded: startup failed",{err:o});t.exitCode=u});export{u as MCODED_START_FAILURE_EXIT_CODE,p as mcodedDaemonEntry};
2
+ import{E as a,N as c,T as m}from"./chunks/chunk-O5EROATK.js";import"./chunks/chunk-NJAER6QW.js";import"./chunks/chunk-PIADSVUZ.js";import"./chunks/chunk-ZJZBXSNG.js";import"./chunks/chunk-OLQR4XQZ.js";import"./chunks/chunk-ASRGXT22.js";import"./chunks/chunk-FJEP2EHP.js";import"./chunks/chunk-HMLSH6YL.js";import"./chunks/chunk-PIV6YF7B.js";import"./chunks/chunk-D2BEUF36.js";import"./chunks/chunk-2EBHD6KJ.js";import"./chunks/chunk-3KTXNSLL.js";import"./chunks/chunk-SKLKXOH4.js";import"./chunks/chunk-QASV4FRT.js";import"./chunks/chunk-W7O5Y6VY.js";import"./chunks/chunk-E3RI7IHR.js";import"./chunks/chunk-NT6GUYYJ.js";import"./chunks/chunk-3ZEDGMQ4.js";import"./chunks/chunk-TRX2HFTB.js";import"./chunks/chunk-XWNCITOR.js";import"./chunks/chunk-ISBSRM3S.js";import"./chunks/chunk-3MLT4F77.js";import"./chunks/chunk-UQL67NEA.js";import"./chunks/chunk-ZK7UCXBX.js";import"./chunks/chunk-2YX4JWQ4.js";import"./chunks/chunk-T4KXNSN3.js";import"./chunks/chunk-LVGBQ7NP.js";import"./chunks/chunk-SK4JBJDF.js";import"./chunks/chunk-YHXW6NMN.js";import"./chunks/chunk-NG2L523L.js";import"./chunks/chunk-UE7MODZO.js";import"./chunks/chunk-HVCY6M5J.js";import"./chunks/chunk-XWU4BV73.js";import"./chunks/chunk-NUHYT7HY.js";import"./chunks/chunk-FHJWUDED.js";import"./chunks/chunk-4QXF4OT5.js";import"./chunks/chunk-6MFNDZP7.js";import"./chunks/chunk-4GGSPZK3.js";import"./chunks/chunk-IONMKU5J.js";import"./chunks/chunk-AODHXPQF.js";import"./chunks/chunk-AUG3KCLV.js";import"./chunks/chunk-JEHPL5Z6.js";import"./chunks/chunk-DSIZQTS3.js";import"./chunks/chunk-7F3QKGB7.js";import"./chunks/chunk-OKOOSGFE.js";import"./chunks/chunk-INIZLM6Q.js";import"./chunks/chunk-ELQ5G4U6.js";import"./chunks/chunk-BF4U2LYQ.js";import"./chunks/chunk-GJ3NP2JO.js";import"./chunks/chunk-WXD24E23.js";import"./chunks/chunk-2PNC3MM4.js";import"./chunks/chunk-4QKCRKWB.js";import"./chunks/chunk-YNDFGYGN.js";import"./chunks/chunk-NEICESQ2.js";import"./chunks/chunk-TXWPPTYK.js";import"./chunks/chunk-5RFGU5IW.js";import"./chunks/chunk-QH5Z4N4A.js";import"./chunks/chunk-WTI4WCBV.js";import"./chunks/chunk-PTV7FFNF.js";import"./chunks/chunk-TAEC3WRM.js";import"./chunks/chunk-3XYKJXXO.js";import"./chunks/chunk-4A4KPPPE.js";import{a as i}from"./chunks/chunk-VAARXN34.js";import"./chunks/chunk-FK3SSGJE.js";import t from"node:process";var E=i("mcode:rpc");var u=1;async function p(o={}){const d=o.argv??t.argv.slice(2);const e=o.env??t.env;const r=o.homeDir??e["HOME"];if(e["MAVIS_REGION"]===void 0||e["MAVIS_BUILD_ENV"]===void 0){try{const{readProfileStartupEnvironment:f}=await import("./chunks/startup-env-7N4YIYLR.js");const n=f(e,r);if(e["MAVIS_REGION"]===void 0&&n.region!==void 0){e["MAVIS_REGION"]=n.region}if(e["MAVIS_BUILD_ENV"]===void 0&&n.buildEnv!==void 0){e["MAVIS_BUILD_ENV"]=n.buildEnv}}catch{}}if(a(e)==="echo"){return c({argv:d,env:e,homeDir:r})}const s=await m({argv:d,env:e,homeDir:r});return s.daemon}p().catch(o=>{E.error("mcoded: startup failed",{err:o});t.exitCode=u});export{u as MCODED_START_FAILURE_EXIT_CODE,p as mcodedDaemonEntry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niwa-labs/ncode",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/release.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.1.0",
3
- "tag": "v0.1.0",
4
- "revision": "8e781966bdbd2089827a83d316a832f6334075be",
5
- "buildNode": "v22.22.2"
2
+ "version": "0.1.1",
3
+ "tag": "v0.1.1",
4
+ "revision": "bb58473d6fc6130fcb5bc68225fe43146ac6b502",
5
+ "buildNode": "v24.22.3"
6
6
  }
@@ -1,14 +0,0 @@
1
- import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as q,b as N,c as g,f as O,h as U,j as K}from"./chunk-BWR3NJFR.js";import{a as f,b as _,c as s,h as V,j as $,k as C,l as x,m as J,n as b}from"./chunk-K6C7372U.js";import{a as k,b as B}from"./chunk-THPIH2MC.js";import{b as H}from"./chunk-Y3W4VZGR.js";import{h as F}from"./chunk-U6RWF7BC.js";import"./chunk-ME57CPMB.js";import{c as j,e as D}from"./chunk-ZPIJSTUE.js";import"./chunk-V4IDVAIA.js";import"./chunk-TRX2HFTB.js";import"./chunk-UNEPZJKK.js";import{m as I}from"./chunk-ISBSRM3S.js";import"./chunk-5R2PGOIA.js";import"./chunk-UQL67NEA.js";import"./chunk-4GGSPZK3.js";import"./chunk-AUG3KCLV.js";import"./chunk-DSIZQTS3.js";import"./chunk-NOGL6Y6L.js";import"./chunk-FK3SSGJE.js";var le=new Set(["git","changes","projects"]);var de="use a named profile with its own account, sessions, and settings";function z(e){return e.addOption(X())}function X(){return new s("--profile <name>",de).argParser(pe)}function G(e,o={}){const t=e.argument("[prompt]","task to execute in the interactive TUI").addOption(new s("-m, --model <provider/model>","select the model for this Session only")).addOption(new s("--lane <lane>","managed backend lane for test or staging builds")).addOption(X()).addOption(new s("--session [id]","open a Session by id, or browse Sessions when id is omitted")).addOption(new s("-c, --continue","continue the latest Session in the current workspace")).addOption(new s("--tui-mode <mode>","TUI mode: regular (default) or fullscreen").argParser(ce)).addOption(new s("--mode <mode>","Context mode: standard (default) or lightweight").argParser(Z)).addOption(new s("--resume <id>").hideHelp()).addOption(new s("--no-daemon","run the agent in this process without the daemon (overrides MCODE_SERVER_MODE)"));C(t).allowExcessArguments(false).showHelpAfterError();if(o.allowStartupEnvironmentSelection){t.addOption(new s("--env <environment>","startup environment for the internal package: test, staging (pre), or prod").argParser(me))}return t}function Q(e,o){if(e&&le.has(e)){throw new Error("too many arguments")}const t=typeof o.session==="string"?o.session.trim():void 0;const u=o.resume?.trim();const i=o.session===true;const l=[Boolean(t||i),Boolean(u),o.continue===true].filter(Boolean).length;if(l>1){throw new Error("--session, --continue, and --resume cannot be combined")}if(o.mode==="lightweight"&&(t||u||i||o.continue)){throw new Error("--mode lightweight requires a new Session")}const a=t||u;const r=o.model?.trim();if(o.model!==void 0){V(r??"");if(i){throw new Error("--model requires a Session id with --session; use --session <id> or --continue.")}}const d=b(o);return{...e?{initialPrompt:e}:{},...r?{model:r}:{},...a?{sessionId:a}:{},...i?{showSessionPicker:true}:{},...o.continue?{continueLatestSession:true}:{},...o.tuiMode?{tuiMode:o.tuiMode}:{},...o.mode==="lightweight"?{contextMode:"lightweight"}:{},...o.lane?{lane:o.lane}:{},...o.profile?{profile:o.profile}:{},...o.daemon===false?{noDaemon:true}:{},...d?{systemPromptOverrides:d}:{}}}function W(e){const o=e.argument("[prompt]","task to execute").addOption(new s("--input <source>",'read explicit input; only "-" is supported')).addOption(new s("--input-format <format>","input format: text or json").default("text")).addOption(new s("--cwd <path>","workspace directory")).addOption(new s("--file <path>","attach a file (repeatable)").argParser(fe).default([])).addOption(new s("--model <provider/model>","override the model for this Run only")).addOption(new s("--effort <level>","override the reasoning effort for this Run only")).addOption(new s("--mode <mode>","Context mode: standard (default) or lightweight").argParser(Z)).addOption(new s("--prompt-mode <mode>","Prompt mode: tui, coding, or work").choices(["tui","coding","work"]).default("tui")).addOption(new s("--session <id>","run in an existing active Session")).addOption(new s("--continue","continue the latest active Session in --cwd")).addOption(new s("--config <path>","use an explicit Runtime config file for this process")).addOption(new s("--permission <policy>","permission policy: smart, full, or off (ask requires TUI/ACP)").default("smart")).addOption(new s("--timeout <duration>","Run timeout, for example 30s or 2m")).addOption(new s("--max-steps <count>","maximum assistant steps")).addOption(new s("--output-format <format>","output format: text, json, or stream-json")).addOption(new s("--diagnostics-dir <path>","save bounded execution diagnostics to a fresh directory")).addOption(new s("--output-schema <schema>","JSON Schema file or inline object for the final answer")).addOption(new s("-o, --output-last-message <path>","write the final agent message to a file")).addOption(new s("--no-daemon","run the agent in this process without the daemon (overrides MCODE_SERVER_MODE)"));return C(o)}function Y(e){const o=e.addOption(new s("--cwd <path>","workspace directory")).addOption(new s("--model <provider/model>","override the model for this Run only")).addOption(new s("--effort <level>","override the reasoning effort for this Run only")).addOption(new s("--config <path>","use an explicit Runtime config file for this process")).addOption(new s("--permission <policy>","permission policy: smart, full, or off (ask requires TUI/ACP)").default("smart")).addOption(new s("--timeout <duration>","Run timeout, for example 30s or 2m")).addOption(new s("--max-steps <count>","maximum assistant steps")).addOption(new s("--output-format <format>","output format: text, json, or stream-json")).addOption(new s("-o, --output-last-message <path>","write the final review result to a file"));return C(o).allowExcessArguments(false).showHelpAfterError()}function ce(e){if(e==="regular"||e==="fullscreen")return e;throw new f("TUI mode must be regular or fullscreen")}function Z(e){if(e==="standard"||e==="lightweight")return e;throw new f("mode must be standard or lightweight")}function me(e){try{return j(e)}catch(o){throw new f(o instanceof Error?o.message:String(o))}}function pe(e){try{return I(e)}catch(o){throw new f(o instanceof Error?o.message:String(o))}}function fe(e,o){return[...o,e]}function ie(e){let o;const t=n=>({...n,...o?{lane:o}:{}});const u=n=>o?oe(e)(n,o):oe(e)(n);const i=n=>o?ne(e)(n,o):ne(e)(n);const l=n=>(e.runDaemon??Me)(n);const a=n=>e.runProfile?o?e.runProfile(n,o):e.runProfile(n):Ce(n);const r=G(new _().name("ncode").description("Ncode \u2014 terminal coding agent for MiniMax\nAn independent Niwa Labs fork of MiniMax Code (MCode), built with Pi.").version(O(e.version)).enablePositionalOptions(),{allowStartupEnvironmentSelection:e.allowStartupEnvironmentSelection}).action((n,c)=>e.launchTui(t(Q(n,c))));r.command("version").description("Show the Ncode, upstream MCode, and Pi versions").action(()=>{process.stdout.write(`${O(e.version)}
3
- `)});r.hook("preAction",(n,c)=>{J(c);o=(e.resolveLane??D)(r.opts().lane)});r.command("init").description("Analyze the codebase and generate AGENTS.md with the Runtime init Skill").argument("[directory]","project directory",".").action(n=>e.launchTui(t({initialPrompt:"/init",workspaceDir:n})));const d=r.command("exec").description("Run one prompt without starting the TUI");W(d).action((n,c)=>{const p=x(d,c);return o?e.runExec(n,p,o):e.runExec(n,p)});Y(d.command("review").description("Review staged, unstaged, and untracked local changes")).action((n,c)=>{const p=x(c,ge(d,c));return o?e.runExec(void 0,p,o):e.runExec(void 0,p)});const w=C(r.command("acp").description("Run MiniMax Code as an Agent Client Protocol server over stdio").option("--no-daemon","host the runtime in this process without the daemon (overrides MCODE_SERVER_MODE)")).allowExcessArguments(false).action((n,c)=>{const p=he(e);const L=b(x(c,n));const T=n.profile;const S=n.daemon===false;if(L)return p(o,L,T,S);return o?p(o,void 0,T,S):p(void 0,void 0,T,S)});w.command("login").description("Sign in to use MiniMax Code Agent features").option("--region <region>","account region: cn or global",A).option("--no-browser","print the authorization URL without opening a browser").allowExcessArguments(false).action(n=>o?e.runLogin(n.region,n.browser!==false,o,n.profile):e.runLogin(n.region,n.browser!==false,void 0,n.profile));r.command("login").description("Sign in to use MiniMax Code Agent features").option("--region <region>","account region: cn or global",A).option("--no-browser","print the authorization URL without opening a browser").allowExcessArguments(false).action(n=>o?e.runLogin(n.region,n.browser!==false,o,n.profile):e.runLogin(n.region,n.browser!==false,void 0,n.profile));r.command("logout").description("Sign out of the MiniMax account used by this CLI").option("--region <region>","account region: cn or global",A).allowExcessArguments(false).action(n=>e.runLogout(n.region,n.profile));r.command("update").description("Check for and install a Minimax Code update").allowExcessArguments(false).action(e.runUpdate);const y=r.command("telemetry").description("Inspect anonymous TUI usage reporting");y.command("status").description("Show whether usage reporting is enabled and why").allowExcessArguments(false).action(()=>re(e)("status"));y.command("preview").description("Show a representative decoded request without sending it").allowExcessArguments(false).action(()=>re(e)("preview"));const v=r.command("provider").description("Manage model providers and API keys").allowExcessArguments(false).action(()=>e.launchTui(t({initialPrompt:"/provider"})));v.command("list").description("List configured providers").option("--json","print a JSON document").action(n=>u({action:"list",json:n.json}));v.command("add").description("Add a custom provider").requiredOption("--name <name>","provider display name").requiredOption("--base-url <url>","provider API base URL").option("--api-format <format>",k.join(", "),ve,"anthropic-messages").option("--model <id>","model ID (repeatable)",we,[]).option("--api-key-env <name>","environment variable containing the API key").option("--context-limit <tokens>","context limit for every listed model",te).option("--output-limit <tokens>","output limit for every listed model",te).option("--support-image","declare image input support for every listed model").option("--use","test the first model, then save and select it as the default").action(n=>{if(n.model.length===0){throw new Error("At least one --model <id> is required.")}return u({action:"add",name:n.name,baseUrl:n.baseUrl,apiFormat:n.apiFormat,models:n.model,contextLimit:n.contextLimit,outputLimit:n.outputLimit,supportImage:n.supportImage,apiKeyEnv:n.apiKeyEnv,saveAndUse:n.use})});v.command("remove").description("Remove a custom provider").argument("<provider-id>","custom_provider:<id>").option("--yes","confirm removal").action((n,c)=>u({action:"remove",providerId:n,confirmed:Boolean(c.yes)}));v.command("test").description("Test a provider or one configured model").argument("<provider-id>","provider id").option("--model <id>","test one model").option("--json","print a JSON document").action((n,c)=>u({action:"test",providerId:n,modelId:c.model,json:c.json}));v.command("use").description("Choose the MiniMax credential source").argument("<source>","token-plan or api-key",ye).action(n=>u({action:"use",source:n}));v.command("set-minimax-key").description("Save and use a MiniMax API key").option("--api-key-env <name>","environment variable containing the API key").action(n=>u({action:"set-minimax-key",apiKeyEnv:n.apiKeyEnv}));const P=r.command("plugin").description("Manage MiniMax Code Plugins").allowExcessArguments(false).action(()=>e.launchTui(t({initialPrompt:"/plugins"})));P.command("list").description("List installed or available Plugins").option("-m, --marketplace <marketplace>","official or local",ee).option("--available","include uninstalled Plugins").option("--json","print a JSON document").action(n=>i({action:"list",marketplace:n.marketplace,available:n.available,json:n.json}));for(const n of["add","remove","enable","disable"]){P.command(n).description(`${Pe(n)} a Plugin`).argument("<plugin[@marketplace]>","Plugin selector").option("-m, --marketplace <marketplace>","official or local",ee).option("--json","print a JSON document").action((c,p)=>i({action:n,selector:c,marketplace:p.marketplace,json:p.json}))}const M=P.command("marketplace").description("List or refresh MiniMax Code Plugin sources");M.command("list").description("List Plugin sources").option("--json","print a JSON document").action(n=>i({action:"marketplace-list",json:n.json}));M.command("upgrade").description("Refresh all Plugin source snapshots").option("--json","print a JSON document").action(n=>i({action:"marketplace-upgrade",json:n.json}));const h=r.command("profile").description("Inspect and remove named auth profiles");h.command("list").description("List profiles and their sign-in state").option("--json","print a JSON document").allowExcessArguments(false).action(n=>a({action:"list",json:n.json}));h.command("current").description("Show the profile this invocation resolved to").allowExcessArguments(false).action(()=>a({action:"current"}));h.command("remove").description("Delete a profile data directory").argument("<name>","profile name").option("--yes","confirm removal").allowExcessArguments(false).action((n,c)=>a({action:"remove",name:n,confirmed:Boolean(c.yes)}));const m=r.command("daemon").description("Run and manage the shared mcoded daemon (MCODE_SERVER_MODE)");m.command("run").description("Run the mcoded daemon in the foreground; refused while MCODE_SERVER_MODE=off").option("--data-dir <dir>","serve this data directory instead of the profile default").allowExcessArguments(false).action(n=>l({action:"run",dataDir:n.dataDir,profile:E(m)}));m.command("status").description("Show the daemon state for this profile/data directory").option("--json","print a JSON document").allowExcessArguments(false).action(n=>l({action:"status",json:n.json,profile:E(m)}));m.command("stop").description("Gracefully stop the daemon for this profile/data directory").option("--force","stop even with active runs (they are killed)").allowExcessArguments(false).action(n=>l({action:"stop",force:n.force,profile:E(m)}));m.command("restart").description("Restart the daemon for this profile/data directory").option("--force","restart even with active runs (they are killed)").allowExcessArguments(false).action(n=>l({action:"restart",force:n.force,profile:E(m)}));m.command("recover").description("Remove the stale mcoded.lock / socket debris of a crashed daemon (a live holder is never touched)").allowExcessArguments(false).action(()=>l({action:"recover",profile:E(m)}));const R=new U;R.registerAll(e.commandContributions??[]);for(const n of R.freeze()){if(r.commands.some(c=>c.name()===n.name)){throw new Error(`Duplicate CLI command name: ${n.name}`)}n.register(r,e)}ae(r);return r}function E(e){return e.opts().profile}function ae(e){const o=e.options.some(t=>t.attributeName()==="profile");if(!o)z(e);for(const t of e.commands){ae(t)}}function ge(e,o){const t={...o.opts(),review:true};const u=new Set(o.options.map(i=>i.attributeName()));for(const i of e.options){const l=i.attributeName();if(e.getOptionValueSource(l)!=="cli")continue;if(!u.has(l)){o.error(`error: option '${i.long}' is not supported by 'exec review'`,{code:"commander.unknownOption"})}if($.has(l))continue;if(o.getOptionValueSource(l)!=="cli"){Object.assign(t,{[l]:e.getOptionValue(l)})}}return t}function we(e,o){return[...o,e]}function A(e){if(e==="cn")return"cn";if(e==="global")return"en";throw new f('expected "cn" or "global"')}function ve(e){if(B(e))return e;throw new f(`expected one of: ${k.join(", ")}`)}function ye(e){if(e==="token-plan")return"token_plan";if(e==="api-key")return"minimax_api_key";throw new f('expected "token-plan" or "api-key"')}function ee(e){const o=e.trim().toLocaleLowerCase();if(o==="official"||o==="local")return o;throw new f('expected "official" or "local"')}function Pe(e){if(e==="add")return"Install";if(e==="remove")return"Uninstall";return e==="enable"?"Enable":"Disable"}function oe(e){if(!e.runProvider)throw new Error("Provider management is unavailable.");return e.runProvider}function ne(e){if(!e.runPlugin)throw new Error("Plugin management is unavailable.");return e.runPlugin}function he(e){if(!e.runAcp)throw new Error("ACP server is unavailable.");return e.runAcp}function re(e){if(!e.runTelemetry)throw new Error("Telemetry inspection is unavailable.");return e.runTelemetry}async function Ce(e){const{runMcodeProfileCommand:o}=await import("./profile-command-ZHVREBWO.js");process.stdout.write(`${await o({request:e})}
4
- `)}async function Me(e){const{runMcodeDaemonCommand:o}=await import("./run-daemon-command-NDOIPTKF.js");process.stdout.write(`${await o({request:e})}
5
- `)}function te(e){const o=Number(e);if(!Number.isSafeInteger(o)||o<=0){throw new f("expected a positive safe integer")}return o}var se=250;var Ee="minimax-code";async function oo(e={}){const o=e.processRef??process;o.title=Ee;const t=K(o.env);const u=e.supportsNodeVersion??(l=>N(l));if(!u(o.versions.node)){o.stderr.write(`Minimax Code supports Node.js ${q}; current version is ${o.versions.node}.
6
- `);o.exitCode=1;return}let i;try{(e.configureNetworkProxy??H)({environment:o.env,writeWarning:a=>o.stderr.write(`${a}
7
- `)});const l=e.createProgram??ie;await l({version:g,allowStartupEnvironmentSelection:e.allowStartupEnvironmentSelection,launchTui:async({initialPrompt:a,model:r,sessionId:d,showSessionPicker:w,continueLatestSession:y,workspaceDir:v,tuiMode:P,contextMode:M,lane:h,profile:m,noDaemon:R,systemPromptOverrides:n})=>{const c=e.launchTui??xe;await c({version:g,...a?{initialPrompt:a}:{},...r?{model:r}:{},...d?{sessionId:d}:{},...w?{showSessionPicker:true}:{},...y?{continueLatestSession:true}:{},...v?{workspaceDir:v}:{},...P?{tuiMode:P}:{},...M?{contextMode:M}:{},...h?{lane:h}:{},...m?{profile:m}:{},...R?{noDaemon:true}:{},...n?{systemPromptOverrides:n}:{},...t?{resumeDraftAfterLogin:true}:{}});i="force"},runExec:async(a,r,d)=>{const w=e.runExec??be;await w(a,d?{...r,lane:d}:r,g);i="natural"},runAcp:async(a,r,d,w)=>{const y=e.runAcp??Te;await y(g,a,r,d,w);i="natural"},runLogin:async(a,r,d,w)=>{const y=e.runLogin??Se;o.stdout.write(`${await y(a,r,d,w)}
8
- `);i="natural"},runLogout:async(a,r)=>{const d=e.runLogout??Oe;o.stdout.write(`${await d(a,r)}
9
- `);i="natural"},runUpdate:async()=>{i="natural";const a=e.runUpdate??ke;await a(g)},runProvider:async(a,r)=>{const d=e.runProvider??Ae;o.stdout.write(`${await d(a,g,r)}
10
- `);i="natural"},runPlugin:async(a,r)=>{const d=e.runPlugin??Le;o.stdout.write(`${await d(a,g,r)}
11
- `);i="natural"},runTelemetry:async a=>{const r=e.runTelemetry??Ie;o.stdout.write(await r(a,g,o.env));i="natural"},runProfile:async a=>{const r=e.runProfile??je;o.stdout.write(`${await r(a,o.env)}
12
- `);i="natural"},runDaemon:async a=>{const r=e.runDaemon??De;o.stdout.write(`${await r(a,o.env)}
13
- `);i="natural"}}).parseAsync(o.argv,{from:"node"});if(i){const a=typeof o.exitCode==="number"?o.exitCode:0;await Promise.all([ue(o.stdout,e.outputDrainTimeoutMs??se),ue(o.stderr,e.outputDrainTimeoutMs??se)]);if((e.platform??process.platform)==="win32"&&i==="natural"){o.exitCode=a}else{o.exit(a)}}}catch(l){o.stderr.write(`${await Re(l)}
14
- `);o.exitCode=1}}async function Re(e){const o=F(e);if(!/better[-_]sqlite3/iu.test(o)||!/Could not locate the bindings file|Cannot find (?:module|package)|NODE_MODULE_VERSION|Module did not self-register/iu.test(o)){return o}const{buildMcodePackageManagerCommand:t,resolveMcodeNpmPrefixInstall:u}=await import("./install-source-CKWWUSXG.js");if(u()){return["MCode could not load its native SQLite dependency.","The Node runtime recorded by this installation no longer loads it (for example after a Homebrew Node upgrade).","Reinstall with the original installer to repair this installation.","",`Original error: ${o}`].join("\n")}const i=t("npm-global",g);return["MCode could not load its native SQLite dependency.","If npm reported blocked install scripts, the installation needs explicit script approval.","Reinstall with the original installer. For npm installations, run:",` ${i.display} --foreground-scripts`,"",`Original error: ${o}`].join("\n")}function ue(e,o){if(e.destroyed||e.writableEnded)return Promise.resolve();return new Promise(t=>{let u=false;let i;const l=()=>a(true);const a=(r=false)=>{if(u)return;u=true;if(i)clearTimeout(i);if(!r)e.off?.("error",l);t()};i=setTimeout(a,o);i.unref?.();e.once?.("error",l);try{e.write("",r=>a(Boolean(r)))}catch{a()}})}async function xe(e){const{launchTui:o}=await import("./launcher-4QSNU24J.js");await o(e)}async function be(e,o,t){const{runTuiExecCommand:u}=await import("./run-exec-command-VNT4IKOJ.js");await u(e,o,t)}async function Te(e,o,t,u,i){const{runTuiAcpCommand:l}=await import("./run-acp-command-2CJQDXHQ.js");await l(e,{},o,t,u,i)}async function Se(e,o=true,t,u){const{runTuiLogin:i}=await import("./auth-command-QNQ32TBI.js");return i({region:e,openBrowser:o,lane:t,profile:u})}async function Oe(e,o){const{runTuiLogout:t}=await import("./auth-command-QNQ32TBI.js");return t({region:e,profile:o})}async function ke(e){const{runMcodeUpdate:o}=await import("./update-4VPIX7FP.js");await o(e)}async function Ae(e,o,t){const{runMcodeProviderCommand:u}=await import("./provider-command-BGKOLCUG.js");return u({request:e,version:o,lane:t})}async function Le(e,o,t){const{runMcodePluginCommand:u}=await import("./plugin-command-NGTATXBX.js");return u({request:e,version:o,lane:t})}async function Ie(e,o,t){const{runMcodeTelemetryCommand:u}=await import("./telemetry-command-6FE4WQ4Q.js");return u(e,o,{environment:t})}async function je(e,o){const{runMcodeProfileCommand:t}=await import("./profile-command-ZHVREBWO.js");return t({request:e,environment:o})}async function De(e,o){const{runMcodeDaemonCommand:t}=await import("./run-daemon-command-NDOIPTKF.js");return t({request:e,environment:o})}export{ue as drainTuiOutput,oo as runTuiCli};
@@ -1,2 +0,0 @@
1
- import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as x}from"./chunk-UMGGEC4N.js";import{e as E,f as N,g as U}from"./chunk-JLFN6WSO.js";import"./chunk-6LDRLO4Y.js";import"./chunk-V4IDVAIA.js";import{F as M,I as S,J as h,L as T,O as L,P as f,Q as p,R as q,S as j,T as F}from"./chunk-MVI24MQ2.js";import"./chunk-NJAER6QW.js";import"./chunk-PIADSVUZ.js";import"./chunk-ZJZBXSNG.js";import"./chunk-OLQR4XQZ.js";import"./chunk-ASRGXT22.js";import"./chunk-FJEP2EHP.js";import"./chunk-HMLSH6YL.js";import"./chunk-PIV6YF7B.js";import"./chunk-D2BEUF36.js";import"./chunk-2EBHD6KJ.js";import"./chunk-3KTXNSLL.js";import"./chunk-SKLKXOH4.js";import"./chunk-QASV4FRT.js";import"./chunk-W7O5Y6VY.js";import"./chunk-E3RI7IHR.js";import"./chunk-NT6GUYYJ.js";import"./chunk-3ZEDGMQ4.js";import"./chunk-TRX2HFTB.js";import{Oa as C,R,S as b,Sa as A,Wa as P,fb as I}from"./chunk-UNEPZJKK.js";import"./chunk-ISBSRM3S.js";import"./chunk-5R2PGOIA.js";import"./chunk-UQL67NEA.js";import"./chunk-ZK7UCXBX.js";import"./chunk-2YX4JWQ4.js";import"./chunk-T4KXNSN3.js";import"./chunk-LVGBQ7NP.js";import"./chunk-SK4JBJDF.js";import"./chunk-YHXW6NMN.js";import"./chunk-NG2L523L.js";import"./chunk-UE7MODZO.js";import"./chunk-HVCY6M5J.js";import"./chunk-XWU4BV73.js";import"./chunk-NUHYT7HY.js";import"./chunk-FHJWUDED.js";import"./chunk-4QXF4OT5.js";import"./chunk-6MFNDZP7.js";import"./chunk-4GGSPZK3.js";import"./chunk-IONMKU5J.js";import"./chunk-AODHXPQF.js";import"./chunk-AUG3KCLV.js";import"./chunk-CAY2BP2G.js";import"./chunk-DSIZQTS3.js";import"./chunk-NOGL6Y6L.js";import"./chunk-OKOOSGFE.js";import"./chunk-INIZLM6Q.js";import"./chunk-ELQ5G4U6.js";import"./chunk-BF4U2LYQ.js";import"./chunk-GJ3NP2JO.js";import"./chunk-WXD24E23.js";import"./chunk-2PNC3MM4.js";import"./chunk-4QKCRKWB.js";import"./chunk-YNDFGYGN.js";import"./chunk-NEICESQ2.js";import"./chunk-TXWPPTYK.js";import"./chunk-5RFGU5IW.js";import"./chunk-QH5Z4N4A.js";import"./chunk-WTI4WCBV.js";import"./chunk-PTV7FFNF.js";import"./chunk-TAEC3WRM.js";import"./chunk-3XYKJXXO.js";import"./chunk-4A4KPPPE.js";import"./chunk-VAARXN34.js";import"./chunk-FK3SSGJE.js";import v from"node:fs";import B from"node:net";import g from"node:path";import _ from"node:process";import{spawn as G}from"node:child_process";var J=2e4;function O(){return{region:R(),buildEnv:b()}}function y(e){if(typeof e.region!=="string"||typeof e.buildEnv!=="string"){return O()}return{region:e.region,buildEnv:e.buildEnv}}var W=200;var X=100;var K=1e4;async function he(e){const r=e.environment??_.env;const n=e.homeDir??r["HOME"];const t=q({profile:e.request.profile,dataDir:e.request.dataDir,homeDir:n,env:r});switch(e.request.action){case"run":return z(e,r,n);case"status":return Q(t,e,r,n);case"stop":return ne(t,e);case"restart":return te(t,e,r);case"recover":return ee(t)}}async function z(e,r,n){let t=false;const o=await F({argv:[...e.request.profile?["--profile",e.request.profile]:[],...e.request.dataDir?["--data-dir",e.request.dataDir]:[]],env:r,...n!==void 0?{homeDir:n}:{},onMcodeToolsReadiness:i=>{t=i.ready},createHost:i=>x({...i,...t?{productCapabilities:{mcodeTools:true}}:{}})});await o.done;return`mcoded stopped (socket ${o.daemon.socketPath})`}async function Q(e,r,n,t){const o=f(e.controlRoot);const i=p(e.controlRoot);const s=o===void 0?void 0:y(o);const a=o===void 0||s===void 0?void 0:await E(o.socketPath,{...i!==void 0?{token:i}:{},dataDir:e.dataDir,env:s,timeoutMs:2e3});const $=C(e.profile,t??n["HOME"]);const l=ae($);const m=Y(e.controlRoot);const w={running:a?.ok===true,controlRoot:e.controlRoot,dataDir:e.dataDir,profile:e.profile,manifest:o??null,probeError:a&&!a.ok?a.error:null,holderAlive:o?h(o.pid):null,staleLock:m,legacyDataPath:l};if(r.request.json)return JSON.stringify(w,null,2);const d=m?Z(m.holderPid,e.profile):null;if(!o){return[`mcoded is not running`,` control root: ${e.controlRoot}`,` data dir: ${e.dataDir}`,...l?[` legacy daemon data present: ${l} (not used)`]:[],...d?[` ${d}`]:[]].join("\n")}if(a?.ok){const c=O();const u=s??c;const D=u.region===c.region&&u.buildEnv===c.buildEnv?"":` (your env: region=${c.region} buildEnv=${c.buildEnv})`;return[`mcoded is running (state: ${o.state})`,` pid: ${o.pid}`,` socket: ${o.socketPath}`,` data dir: ${o.dataDir}`,` profile: ${o.profile??"default"}`,` env: region=${o.region} buildEnv=${o.buildEnv}${D}`,` protocol: v${o.protocol}`,` started at: ${o.startedAt}`,...l?[` legacy daemon data present: ${l} (not used)`]:[]].join("\n")}return[`mcoded is not responding (manifest state: ${o.state})`,` pid: ${o.pid} (${h(o.pid)?"alive but not answering":"gone"})`,` socket: ${o.socketPath}`,` error: ${a&&!a.ok?a.error:"probe not attempted"}`,...d?[` ${d}`]:[]].join("\n")}function Y(e){const r=g.join(e,M);try{v.statSync(r)}catch{return null}const n=S(r);if(n!==void 0&&h(n))return null;return{holderPid:n??null}}function Z(e,r){const n=`mcode daemon recover${r?` --profile ${r}`:""}`;return e===null?`stale lock (unparsable record) \u2014 run \`${n}\``:`stale lock from dead pid ${e} \u2014 run \`${n}\``}async function ee(e){const r=g.join(e.controlRoot,M);const n=A(e.controlRoot);const t=[`control root: ${e.controlRoot}`];const o=S(r);const i=v.existsSync(r);if(i&&o!==void 0&&h(o)){return[`nothing recovered \u2014 mcoded.lock is held by LIVE pid ${o}`,...t,` a live daemon owns this root; use \`mcode daemon stop\` instead`].join("\n")}if(!i){t.push(`mcoded.lock: absent (nothing to recover)`)}else if(o===void 0){const a=T(r);t.push(a?`mcoded.lock: removed unparsable debris (torn record)`:`mcoded.lock: unparsable debris could NOT be removed (changed while recovering)`)}else{const a=T(r);t.push(a?`mcoded.lock: removed stale lock of dead pid ${o}`:`mcoded.lock: stale lock of dead pid ${o} could NOT be removed (changed while recovering)`)}let s;if(v.existsSync(n)){if(await oe(n)){s=`socket ${n}: still answers \u2014 left untouched (a daemon is serving)`}else{try{v.unlinkSync(n);s=`socket ${n}: removed stale socket file (nothing answered)`}catch(a){s=`socket ${n}: could not be removed (${a.message})`}}}else{s=`socket ${n}: absent (nothing to recover)`}t.push(` ${s}`);return[`mcoded recover report`,...t].join("\n")}function oe(e){return new Promise(r=>{const n=B.connect(e);n.once("connect",()=>{n.destroy();r(true)});n.once("error",()=>{n.destroy();r(false)})})}var k=class extends Error{constructor(n){super(n);this.report=n;this.name="DaemonDrainRefusalError"}report};async function ne(e,r){const n=f(e.controlRoot);if(!n){return`mcoded is not running (no daemon manifest in ${e.controlRoot})`}const t=await V(e,n,r.request.force,"stop");if(t)throw new k(t);const o=await N(n.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:y(n),timeoutMs:1e4});if(o.ok)return`mcoded stopped (pid ${n.pid})`;if(o.errno==="ENOENT"||o.errno==="ECONNREFUSED"){return`mcoded is not running (socket ${n.socketPath} does not answer)`}throw new Error(`Failed to stop mcoded: ${o.errorCode??""} ${o.error}`.trim())}async function V(e,r,n,t){if(n)return void 0;const o=await U(r.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:y(r),timeoutMs:2e3});if(!o.ok){if(o.errno==="ENOENT"||o.errno==="ECONNREFUSED")return void 0;return[`cannot verify mcoded (pid ${r.pid}) is idle; refusing to ${t} without --force`,` status probe failed: ${o.errorCode?`${o.errorCode}: `:""}${o.error}`,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs would be killed).`].join("\n")}if(o.data.runs.length>0){const i=o.data.runs.map(s=>` ${s.sessionId} running ${re(s.elapsedMs)} (${s.method})`);return[`mcoded has ${o.data.runs.length} active run${o.data.runs.length===1?"":"s"}; refusing to ${t} without --force`,...i,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs will be killed).`].join("\n")}if(!o.data.activeRunsReported){const i=o.data.activeTurns;if(i===void 0){return[`cannot verify mcoded (pid ${r.pid}) is idle; refusing to ${t} without --force`,` the daemon reported neither activeRuns nor activeTurns`,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs would be killed).`].join("\n")}if(i>0){return[`mcoded has ${i} active turn${i===1?"":"s"}; refusing to ${t} without --force`,` (the daemon did not report the per-run list)`,`Use \`mcode daemon ${t} --force\` to stop anyway (active runs will be killed).`].join("\n")}}return void 0}function re(e){return`${Math.max(1,Math.round(e/1e3))}s`}async function te(e,r,n){const t=f(e.controlRoot);if(t){const d=await V(e,t,r.request.force,"restart");if(d)throw new k(d);const c=y(t);const u=await N(t.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:c,timeoutMs:1e4});if(!u.ok&&u.errno!=="ENOENT"&&u.errno!=="ECONNREFUSED"){throw new Error(`Failed to stop the previous mcoded: ${u.error}`)}await ie(t.socketPath,c,r)}const o=_.argv[1];if(!o){throw new Error("Cannot restart: this process has no entry script (process.argv[1]).")}const i={...n,MINIMAX_DATA_DIR:e.dataDir,MAVIS_REGION:R(),MAVIS_BUILD_ENV:b(),...e.profile?{MINIMAX_PROFILE:e.profile}:{}};const s=i[P]?.trim().toLowerCase();if(s===void 0||s===""||s==="off"){i[P]="auto"}const a=[_.execPath,o,"daemon","run","--data-dir",e.dataDir,...e.profile?["--profile",e.profile]:[]];I(e.controlRoot);const $=r.spawnDaemon??(({argv:d,env:c,logFd:u})=>{const D=G(d[0],d.slice(1),{detached:true,stdio:["ignore",u,u],env:c});D.unref();return D});const l=j(e.controlRoot,i);try{$({argv:a,env:l.childEnv,logFd:l.fd})}finally{v.closeSync(l.fd)}const m=await se(e,r);if(!m.ok){throw new Error(`mcoded did not become ready within ${r.request.waitTimeoutMs??J} ms: ${m.error}. See ${g.join(e.controlRoot,L,"mcoded.log")}`)}const w=f(e.controlRoot);return`mcoded restarted (pid ${w?.pid??"?"}, socket ${m.socketPath})`}async function ie(e,r,n){const t=n.sleep??H;const o=Date.now()+K;for(;;){const i=await E(e,{env:r,timeoutMs:1e3});if(!i.ok&&(i.errno==="ENOENT"||i.errno==="ECONNREFUSED"))return;if(Date.now()>o)return;await t(X)}}async function se(e,r){const n=r.sleep??H;const t=Date.now()+(r.request.waitTimeoutMs??J);let o="socket never appeared";for(;;){const i=f(e.controlRoot);if(i&&i.state.startsWith("failed:")){return{ok:false,error:`daemon start failed (${i.state})`}}if(i){const s=await E(i.socketPath,{token:p(e.controlRoot),dataDir:e.dataDir,env:O(),timeoutMs:1e3});if(s.ok)return{ok:true,socketPath:i.socketPath};o=s.error}if(Date.now()>t)return{ok:false,error:o};await n(W)}}function H(e){return new Promise(r=>{setTimeout(r,e)})}function ae(e){for(const r of["durable-history","workspace"]){const n=g.join(e,r);try{if(v.statSync(n).isDirectory())return n}catch{}}return null}export{k as DaemonDrainRefusalError,he as runMcodeDaemonCommand};
@@ -1,16 +0,0 @@
1
- import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as $e,b as Le,d as Be,e as ue,f as qe,g as He,h as q}from"./chunk-ELHMZ5OD.js";import{d as N,e as g,f as Me,g as B,h as Ae,i as Oe,n as De}from"./chunk-K6C7372U.js";import{c as Ve,d as de,e as Ge,f as Je,i as ze,l as Xe}from"./chunk-XSWWOH4F.js";import{a as Fe,b as Ke,d as Ye}from"./chunk-SRTYTXAC.js";import{a as Qe,b as Ze}from"./chunk-36COWQLE.js";import"./chunk-MI4YWYJF.js";import{e as Ce,f as je,g as ae,h as _,i as Ne}from"./chunk-U6RWF7BC.js";import"./chunk-E25NCIC6.js";import{c as Ue,s as ce,w as We}from"./chunk-RD7XROJD.js";import{a as Pe}from"./chunk-ME57CPMB.js";import"./chunk-PBGCNSGZ.js";import"./chunk-UMGGEC4N.js";import"./chunk-JLFN6WSO.js";import"./chunk-6LDRLO4Y.js";import{d as ke}from"./chunk-R7NDEPS3.js";import"./chunk-ZPIJSTUE.js";import"./chunk-V4IDVAIA.js";import"./chunk-MVI24MQ2.js";import"./chunk-NJAER6QW.js";import"./chunk-PIADSVUZ.js";import"./chunk-ZJZBXSNG.js";import"./chunk-OLQR4XQZ.js";import"./chunk-ASRGXT22.js";import"./chunk-FJEP2EHP.js";import"./chunk-HMLSH6YL.js";import"./chunk-PIV6YF7B.js";import"./chunk-D2BEUF36.js";import"./chunk-2EBHD6KJ.js";import"./chunk-3KTXNSLL.js";import"./chunk-SKLKXOH4.js";import"./chunk-QASV4FRT.js";import"./chunk-W7O5Y6VY.js";import"./chunk-E3RI7IHR.js";import"./chunk-NT6GUYYJ.js";import"./chunk-3ZEDGMQ4.js";import"./chunk-TRX2HFTB.js";import{Cb as Re,Db as be}from"./chunk-UNEPZJKK.js";import"./chunk-ISBSRM3S.js";import"./chunk-5R2PGOIA.js";import"./chunk-UQL67NEA.js";import"./chunk-ZK7UCXBX.js";import"./chunk-2YX4JWQ4.js";import"./chunk-T4KXNSN3.js";import"./chunk-LVGBQ7NP.js";import"./chunk-SK4JBJDF.js";import"./chunk-YHXW6NMN.js";import"./chunk-NG2L523L.js";import"./chunk-UE7MODZO.js";import"./chunk-HVCY6M5J.js";import"./chunk-XWU4BV73.js";import"./chunk-NUHYT7HY.js";import"./chunk-FHJWUDED.js";import"./chunk-4QXF4OT5.js";import"./chunk-6MFNDZP7.js";import"./chunk-4GGSPZK3.js";import"./chunk-IONMKU5J.js";import"./chunk-AODHXPQF.js";import"./chunk-AUG3KCLV.js";import{nb as Ft}from"./chunk-CAY2BP2G.js";import"./chunk-DSIZQTS3.js";import"./chunk-NOGL6Y6L.js";import"./chunk-OKOOSGFE.js";import"./chunk-INIZLM6Q.js";import"./chunk-ELQ5G4U6.js";import"./chunk-BF4U2LYQ.js";import"./chunk-GJ3NP2JO.js";import"./chunk-WXD24E23.js";import"./chunk-2PNC3MM4.js";import"./chunk-4QKCRKWB.js";import"./chunk-YNDFGYGN.js";import"./chunk-NEICESQ2.js";import"./chunk-TXWPPTYK.js";import"./chunk-5RFGU5IW.js";import"./chunk-QH5Z4N4A.js";import"./chunk-WTI4WCBV.js";import"./chunk-PTV7FFNF.js";import"./chunk-TAEC3WRM.js";import"./chunk-3XYKJXXO.js";import"./chunk-4A4KPPPE.js";import{a as _e}from"./chunk-VAARXN34.js";import{e as Nt}from"./chunk-FK3SSGJE.js";async function et(e,t){try{return be(e,t)}catch(r){const n=r instanceof Re?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new g("config",n,{cause:r})}}var tt=`${je} Lower the effort level, then retry.`;function H(e){if(e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"){return _(e)}if(e.kind==="runtime"){if(ae(e.message))return tt;if(!e.retryable)return nt(`The run failed: ${_(e)}`);return`The run failed: ${_(e)}. Retry after the connection recovers.`}return`MCode encountered an internal error: ${_(e)}. Retry; if it keeps happening, report it through an available support channel.`}function rt(e){if(e.status==="timeout"){return"The run timed out. Increase --timeout or retry."}if(e.status==="limit_exceeded"){return"The run reached its step limit. Increase --max-steps or narrow the task."}if(e.status==="cancelled")return"The run was cancelled.";if(e.error?.category==="config"){const r=e.error.message?`: ${_(e.error.message)}`:"";return`The run could not start with the current configuration${r}. Open MCode and run /doctor.`}if(e.error?.category==="internal"){const r=e.error.message?`: ${_(e.error.message)}`:"";return`MCode encountered an internal error${r}. Retry; if it keeps happening, report it through an available support channel.`}if(ae(e.error?.message))return tt;const t=e.error?.message?`: ${_(e.error.message)}`:"";if(e.error?.retryable===false)return nt(`The run failed${t}`);return`The run failed${t}. Retry after the connection recovers.`}function nt(e){return/[.!?…]$/u.test(e)?e:`${e}.`}import{readFile as rr,realpath as pe,stat as Q}from"node:fs/promises";import{homedir as mt}from"node:os";import{basename as pt,dirname as nr,extname as or,isAbsolute as sr,resolve as Y}from"node:path";var le=Nt(Ft(),1);function me(e,t){if(!t)return{ok:true,value:e??null};if(!e?.trim()){return{ok:false,kind:"empty",message:"Structured output was empty."}}let r;try{r=JSON.parse(e)}catch{return{ok:false,kind:"invalid_json",message:"Structured output was not valid JSON."}}const n=new le.Ajv({allErrors:true,strict:false});const o=n.compile(t);if(!o(r)){return{ok:false,kind:"schema_mismatch",message:`Structured output did not match --output-schema: ${n.errorsText(o.errors,{separator:"; "})}`}}return{ok:true,value:r}}function ot(e,t){const r=e.status==="succeeded"?t.validation??me(e.answer,t.outputSchema):void 0;const n=$t(e,r);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:n.sessionId,turnId:n.turnId,status:n.status==="awaiting-user-continuation"?"failed":n.status,...n.status==="succeeded"&&r?.ok?{output:r.value}:{},...n.error?{error:{...n.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},...t.usageSource!==void 0?{usageSource:t.usageSource}:{},...t.usageIncomplete!==void 0?{usageIncomplete:t.usageIncomplete}:{},durationMs:n.durationMs}}function st(e){if(!z(e))return false;return e.schemaVersion===1&&e.type==="exec.result"&&typeof e.runId==="string"&&typeof e.sessionId==="string"&&typeof e.turnId==="string"&&typeof e.durationMs==="number"&&Number.isFinite(e.durationMs)&&Ut(e.status)&&Lt(e.model)&&Bt(e.usage)&&(e.usageSource===void 0||e.usageSource==="completed_responses"||e.usageSource==="analytics_fallback"||e.usageSource==="unavailable")&&(e.usageIncomplete===void 0||typeof e.usageIncomplete==="boolean")&&qt(e.error)}function $t(e,t){if(e.status==="awaiting-user-continuation"){return{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:false}}}if(e.status!=="succeeded"||!t||t.ok)return e;return{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:t.message,retryable:true}}}function it(e){new le.Ajv({allErrors:true,strict:false}).compile(e)}function Ut(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function Lt(e){if(e===void 0)return true;if(!z(e))return false;return typeof e.providerId==="string"&&typeof e.modelId==="string"&&W(e.variant)&&W(e.providerSource)&&W(e.providerKind)&&W(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict")}function Bt(e){if(e===void 0)return true;if(!z(e))return false;return Object.values(e).every(t=>t===void 0||typeof t==="number"&&Number.isFinite(t))}function qt(e){if(e===void 0)return true;if(!z(e))return false;return(e.category==="config"||e.category==="runtime"||e.category==="internal")&&W(e.code)&&typeof e.message==="string"&&(e.retryable===void 0||typeof e.retryable==="boolean")}function W(e){return e===void 0||typeof e==="string"}function z(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}import{createHash as Ht,randomUUID as Wt}from"node:crypto";import{access as Vt,constants as Gt,lstat as at,mkdir as Jt,open as zt,readdir as ut,rename as Xt,unlink as Kt,writeFile as Yt}from"node:fs/promises";import{join as X,resolve as Qt}from"node:path";var fe=256*1024;var Zt=4*1024*1024;var er=5e3;function ct(e){return Ne(e.replace(/("(?:authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"(?:\\.|[^"\\])*"/giu,'$1"[redacted]"'))}function tr(e){if(e.length<=fe)return e;const t=Buffer.from("\n[diagnostic answer truncated: middle omitted]\n");const r=Math.floor((fe-t.length)/2);let n=r;let o=e.length-r;while(((e[n]??0)&192)===128)n-=1;while(((e[o]??0)&192)===128)o+=1;return Buffer.concat([e.subarray(0,n),t,e.subarray(o)])}async function dt(e,t){const r=Qt(t,e);await Jt(r,{recursive:true,mode:448});if(!(await at(r)).isDirectory())throw new Error("Diagnostics path must be a real directory.");await Vt(r,Gt.W_OK);if((await ut(r)).length>0)throw new Error("Diagnostics directory must be empty.");return r}function lt(e){return e?Ht("sha256").update(JSON.stringify(e)).digest("hex"):void 0}function V(e){if(typeof e==="string")return ct(e);if(Array.isArray(e))return e.map(V);if(e&&typeof e==="object"){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,/^(authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)$/iu.test(t)?"[redacted]":V(r)]))}return e}var K=class e{constructor(t,r,n){this.directory=t;this.warn=r;this.progressFile=n}directory;warn;progressFile;pending=Promise.resolve();bytes=0;droppedEvents=0;closed=false;failed=false;static async create(t,r){if((await ut(t)).length>0){throw Object.assign(new Error("Diagnostics directory must be empty."),{code:"EEXIST"})}const n=await zt(X(t,"progress.jsonl"),"wx",384);return new e(t,r,n)}record(t){if(this.closed)return;const r=`${JSON.stringify(V({timestampMs:Date.now(),...t}))}
3
- `;const n=Buffer.byteLength(r);if(this.bytes+n>Zt){this.droppedEvents+=1;return}this.bytes+=n;this.enqueue(()=>this.progressFile.appendFile(r))}execution(t){this.json("execution.json",{schemaVersion:1,...t})}failure(t,r){const n=Buffer.from(ct(t??""));const o=n.length>fe;const i=tr(n);this.json("failure.json",{schemaVersion:1,...r,answerBytes:Buffer.byteLength(t??""),savedBytes:i.length,truncated:o,redacted:true});this.enqueue(()=>this.replaceFile("failure-answer.txt",i))}async flush(t={}){this.enqueue(async()=>{const[o,i]=await Promise.all([at(X(this.directory,"progress.jsonl")),this.progressFile.stat()]);if(!o.isFile()||o.ino!==i.ino||o.dev!==i.dev){throw new Error("Diagnostics progress file was replaced.")}});this.enqueue(()=>this.progressFile.close());this.enqueue(()=>this.replaceFile("diagnostics-status.json",`${JSON.stringify(V({...t,recoveryReady:t.recoveryReady===true&&!this.failed,diagnosticsComplete:!this.failed,droppedEventCount:this.droppedEvents}),null,2)}
4
- `));let r;const n=await Promise.race([this.pending.then(()=>true),new Promise(o=>{r=setTimeout(()=>o(false),er)})]);if(r)clearTimeout(r);this.closed=true;if(!n)this.reportFailure("diagnostics flush deadline exceeded");void this.pending.finally(()=>this.progressFile.close()).catch(()=>void 0);return n&&!this.failed}json(t,r){const n=`${JSON.stringify(V(r),null,2)}
5
- `;this.enqueue(()=>this.replaceFile(t,n))}async replaceFile(t,r){const n=X(this.directory,`.${t}.${Wt()}.tmp`);try{await Yt(n,r,{mode:384,flag:"wx"});if(!this.closed)await Xt(n,X(this.directory,t))}finally{await Kt(n).catch(()=>void 0)}}enqueue(t){if(this.closed)return;this.pending=this.pending.then(async()=>{if(!this.closed)await t()}).catch(()=>this.reportFailure("could not write execution diagnostics"))}reportFailure(t){if(!this.failed)this.warn(`mcode diagnostics warning: ${t}
6
- `);this.failed=true}};var ir={".csv":"text/csv",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".log":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".webp":"image/webp",".xml":"application/xml",".yaml":"application/yaml",".yml":"application/yaml"};async function gt(e,t,r,n){C(n);if(t.review)return ar(t,n);if(t.input!==void 0&&t.input!=="-"){throw f('--input currently accepts only "-".')}if(e!==void 0&&t.input!==void 0){throw f("The prompt argument and --input cannot be combined.")}if(t.session&&t.continue){throw f("--session and --continue are mutually exclusive.")}const o=F("--mode",t.mode??"standard",["standard","lightweight"]);if(o==="lightweight"&&(t.session||t.continue)){throw f("--mode lightweight requires a new Session.")}const i=F("--prompt-mode",t.promptMode??"tui",["tui","coding","work"]);const s=F("--input-format",t.inputFormat??"text",["text","json"]);const d=F("--output-format",t.outputFormat??"text",["text","json","stream-json"]);const a=F("--permission",t.permission??"smart",["ask","smart","full","off"]);if(a==="ask"){throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.")}const m=a;const l=vt(t);const w=yt(t);const c=await ge(t.cwd??process.cwd(),"--cwd");C(n);const h=t.input==="-"?await r():e??"";C(n);const x=dr(h,s);const E=await Promise.all((t.file??[]).map(y=>cr(y,c,n)));const u=Ye(E);if(u==="count"){throw f(`You can attach up to ${String(Ke)} files.`)}if(u==="total-bytes"){throw f("Attachments can total up to the 100 MB limit.")}if(!x.trim()&&E.length===0){throw f("A prompt, --input -, or at least one --file is required.")}const b=t.timeout===void 0?void 0:wt(t.timeout,"--timeout");const I=t.maxSteps===void 0?void 0:Tt(t.maxSteps,"--max-steps");const k=t.config===void 0?void 0:await ye(t.config,c,"--config");const A=t.outputSchema===void 0?void 0:await ur(t.outputSchema,c);const p=t.outputLastMessage===void 0?void 0:await ht(t.outputLastMessage,c);let v;if(t.diagnosticsDir!==void 0){if(!t.diagnosticsDir.trim())throw f("--diagnostics-dir cannot be empty.");try{v=await dt(t.diagnosticsDir,c)}catch(y){throw f(`--diagnostics-dir is invalid: ${j(y)}`)}}return{prompt:x,promptMode:i,workspaceDir:c,attachments:E,...t.model?.trim()?{model:t.model.trim()}:{},...l===void 0?{}:{effort:l},...o==="lightweight"?{contextMode:o}:{},...t.session?.trim()?{sessionId:t.session.trim()}:{},continueSession:t.continue===true,...k?{configPath:k}:{},permission:m,...b===void 0?{}:{timeoutMs:b},...I===void 0?{}:{maxSteps:I},format:d,...A===void 0?{}:{outputSchema:A},...p===void 0?{}:{outputLastMessagePath:p},...v===void 0?{}:{diagnosticsDir:v},...t.daemon===false?{noDaemon:true}:{},...w?{systemPromptOverrides:w}:{}}}async function ar(e,t){const r=F("--output-format",e.outputFormat??"text",["text","json","stream-json"]);const n=F("--permission",e.permission??"smart",["ask","smart","full","off"]);if(n==="ask"){throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.")}const o=vt(e);const i=yt(e);const s=await ge(e.cwd??process.cwd(),"--cwd");C(t);const d=e.timeout===void 0?void 0:wt(e.timeout,"--timeout");const a=e.maxSteps===void 0?void 0:Tt(e.maxSteps,"--max-steps");const m=e.config===void 0?void 0:await ye(e.config,s,"--config");const l=e.outputLastMessage===void 0?void 0:await ht(e.outputLastMessage,s);return{prompt:"Please review my uncommitted changes.",workspaceDir:s,attachments:[],...e.model?.trim()?{model:e.model.trim()}:{},...o===void 0?{}:{effort:o},continueSession:false,...m?{configPath:m}:{},permission:n,...d===void 0?{}:{timeoutMs:d},...a===void 0?{}:{maxSteps:a},format:r,...l===void 0?{}:{outputLastMessagePath:l},reviewRequest:{scope:"local_changes"},...e.daemon===false?{noDaemon:true}:{},...i?{systemPromptOverrides:i}:{}}}function yt(e){try{return De(e)}catch(t){throw f(j(t),t)}}async function ur(e,t){const r=e.trim();try{return ft(r)}catch(o){if(r.startsWith("{")||r.startsWith("[")||!(o instanceof SyntaxError)){throw f("--output-schema requires a JSON object.",o)}}const n=await ye(e,t,"--output-schema");try{return ft(await rr(n,"utf8"))}catch(o){throw f("--output-schema requires a JSON object.",o)}}function ft(e){const t=JSON.parse(e);if(!t||typeof t!=="object"||Array.isArray(t)){throw new TypeError("schema must be a JSON object")}it(t);return t}async function ht(e,t){const r=Z(e,t);const n=await ge(nr(r),"--output-last-message");const o=Y(n,pt(r));const i=await Q(o).catch(s=>{if(s&&typeof s==="object"&&"code"in s&&s.code==="ENOENT"){return void 0}throw f(`--output-last-message is invalid: ${j(s)}`)});if(i?.isDirectory())throw f("--output-last-message must reference a file.");return o}async function cr(e,t,r){C(r);const n=await $e(e.trim(),r).catch(m=>{C(r);throw f(`Cannot attach ${e}: ${j(m)}`)});C(r);const o=Z(n,t);const i=await pe(o).catch(m=>{throw f(`Cannot attach ${e}: ${j(m)}`)});const s=await Q(i).catch(m=>{throw f(`Cannot attach ${e}: ${j(m)}`)});C(r);if(!s.isFile())throw f(`Cannot attach ${e}: path is not a file.`);const d=pt(i);const a=ir[or(d).toLowerCase()]??Fe(d)??"application/octet-stream";return{type:a.startsWith("image/")?"image":"file",filePath:i,fileName:d,mimeType:a,sizeBytes:s.size}}function C(e){if(e?.aborted){throw new g("cancelled","Invocation was cancelled.",{cause:e.reason})}}async function ge(e,t){const r=await pe(Z(e,process.cwd())).catch(o=>{throw f(`${t} is invalid: ${j(o)}`)});const n=await Q(r);if(!n.isDirectory())throw f(`${t} must reference a directory.`);return r}async function ye(e,t,r){const n=await pe(Z(e,t)).catch(i=>{throw f(`${r} is invalid: ${j(i)}`)});const o=await Q(n);if(!o.isFile())throw f(`${r} must reference a file.`);return n}function Z(e,t){const r=e.trim();if(!r)throw f("Path value cannot be empty.");const n=r==="~"?mt():r.startsWith("~/")||r.startsWith("~\\")?Y(mt(),r.slice(2)):r;return sr(n)?Y(n):Y(t,n)}function dr(e,t){if(t==="text")return e;let r;try{r=JSON.parse(e)}catch(n){throw f("--input-format json requires valid JSON.",n)}if(typeof r==="string")return r;if(r&&typeof r==="object"&&!Array.isArray(r)&&typeof r.prompt==="string"){return r.prompt}throw f("--input-format json accepts a JSON string or an object with string prompt.")}function wt(e,t){const r=/^(\d+)(ms|s|m|h)?$/i.exec(e.trim());if(!r)throw f(`${t} must be a positive duration such as 500ms, 30s, or 2m.`);const n=Number(r[1]);const o=r[2]?.toLowerCase()==="h"?36e5:r[2]?.toLowerCase()==="m"?6e4:r[2]?.toLowerCase()==="s"?1e3:1;const i=n*o;if(!Number.isSafeInteger(i)||i<1){throw f(`${t} must resolve to a positive safe integer in milliseconds.`)}return i}function Tt(e,t){if(!/^\d+$/.test(e.trim()))throw f(`${t} must be a positive integer.`);const r=Number(e);if(!Number.isSafeInteger(r)||r<1){throw f(`${t} must be a positive safe integer.`)}return r}function F(e,t,r){if(r.includes(t))return t;throw f(`${e} must be one of: ${r.join(", ")}.`)}function vt(e){if(e.effort===void 0)return void 0;const t=e.effort.trim();if(!t)throw f("--effort cannot be empty.");return t}function f(e,t){return new g("invocation",e,t===void 0?void 0:{cause:t})}function j(e){return e instanceof Error?e.message:String(e)}import{resolve as Pt}from"node:path";function Et(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function lr(e){let t=0;let r=0;for(const n of e){if(n.foreground===true)continue;if(n.status==="queued"||n.status==="running"||n.status==="stopping"){t+=1}else if(n.deliveredAtMs===void 0){r+=1}}return{active:t,undeliveredTerminal:r}}async function xt(e){const{runtime:t,sessionId:r}=e;if(typeof t.listBackgroundTasks!=="function")return"unsupported";const n=e.pollIntervalMs??250;const o=Date.now()+e.timeoutMs;let i=false;let s=0;for(;;){if(e.signal?.aborted)return"cancelled";let d;try{const a=await t.listBackgroundTasks(r,{includeSubagent:true});d=lr(a);s=0}catch{s+=1;if(s>=3)return"unreadable";d={active:1,undeliveredTerminal:0}}if((d.active>0||d.undeliveredTerminal>0)&&!i){i=true;e.onPending?.(d)}if(d.active===0&&d.undeliveredTerminal===0){let a;try{a=await t.getActiveRun(r)}catch{a=void 0}if(!a||a.state==="idle"||a.state==="terminal"){return"drained"}}if(Date.now()>=o)return"timeout";await new Promise(a=>{const m=setTimeout(a,Math.min(n,Math.max(0,o-Date.now())));m.unref?.()})}}var St="Background task work is still pending after the Turn ended; the automatic completion notice has not been delivered. This exec process must exit \u2014 run under the daemon (MCODE_SERVER_MODE=auto or required) for wake Turns that outlive a single invocation.";import{randomUUID as mr}from"node:crypto";import{rename as fr,unlink as pr,writeFile as gr}from"node:fs/promises";import{basename as yr,dirname as hr,join as wr}from"node:path";var G=class extends g{constructor(t,r){super("internal",t,r);this.name="HeadlessOutputError"}};function It(e,t,r={}){let n=false;if(e==="stream-json"&&!r.eventProjector){throw new G("stream-json requires an Exec event projector.")}return{async event(o){if(e!=="stream-json")return;for(const i of r.eventProjector?.project(o)??[]){await ee(t,`${JSON.stringify(i)}
7
- `)}},async result(o){if(n)throw new G("ExecResult was encoded more than once.");if(!st(o)){throw new G("Headless coordinator returned an invalid ExecResult.")}n=true;if(e==="stream-json"){for(const i of r.eventProjector?.complete(o)??[]){await ee(t,`${JSON.stringify(i)}
8
- `)}return}if(e==="json"){await ee(t,`${JSON.stringify(o)}
9
- `);return}if(o.status==="succeeded"){const i=He(o.output)?q(o.output):typeof o.output==="string"?Le(o.output):JSON.stringify(o.output);await ee(t,`${i??""}
10
- `)}}}}async function Rt(e,t){const r=wr(hr(e),`.${yr(e)}.${process.pid}.${mr()}.tmp`);try{await gr(r,t,{encoding:"utf8",flag:"wx"});await fr(r,e)}catch(n){await pr(r).catch(()=>void 0);throw new g("internal",`Could not write --output-last-message: ${e}`,{cause:n})}}function he(e){return t=>new Promise((r,n)=>{let o=false;const i=s=>{if(o)return;o=true;if(s.code==="EPIPE"){n(new g("brokenPipe","stdout pipe was closed.",{cause:s}));return}n(new g("internal",`stdout write failed: ${s.message}`,{cause:s}))};e.once("error",i);try{e.write(t,s=>{if(s){i(s);return}if(o)return;o=true;e.off("error",i);r()})}catch(s){e.off("error",i);i(s)}})}async function ee(e,t){try{await e(t)}catch(r){if(r instanceof g)throw r;const n=r&&typeof r==="object"&&"code"in r?r.code:void 0;throw new g(n==="EPIPE"?"brokenPipe":"internal",n==="EPIPE"?"stdout pipe was closed.":"stdout writer failed.",{cause:r})}}var Tr=5;var vr=100;var re=class{constructor(t,r={}){this.runtime=t;this.options=r}runtime;options;conversationPort(){return{sendMessage:(t,r)=>this.sendMessage(t,r),abortSession:t=>this.runtime.abortSession(t),steer:t=>this.runtime.steer(t)}}async*sendMessage(t,r){if(!t.turnId)throw te("EXEC_TURN_ID_REQUIRED","Exec requires a Turn id.");const n=t.turnId;r?.throwIfAborted();const o={seenMessageIds:new Set,seenCursors:new Set,sawEvent:false,terminal:false,heartbeatSeen:false,doneSeen:false};let i=true;let s=0;let d;for(;;){r?.throwIfAborted();let a=false;let m=false;try{const w=i?this.runtime.sendMessage(t,r):this.runtime.watchSessionTurn(t.id,n,Ir(r),{...o.cursor?{afterCursor:o.cursor}:{},...!o.cursor&&o.afterMsgId?{afterMsgId:o.afterMsgId}:{}});i=false;for await(const c of w){r?.throwIfAborted();const h=c.cursor?o.seenCursors.has(c.cursor):false;if(c.cursor){o.cursor=c.cursor;if(!h){o.seenCursors.add(c.cursor);m=true}}const x=c.type==="message"&&c.message.id?o.seenMessageIds.has(c.message.id):false;const E=!c.cursor&&(c.type==="heartbeat"&&o.heartbeatSeen||c.type==="done"&&o.doneSeen);if(h||x||E)continue;if(c.type==="message")m=true;if(c.type==="heartbeat")o.heartbeatSeen=true;if(c.type==="done")o.doneSeen=true;if(!c.cursor&&c.type!=="message")m=!o.sawEvent;o.sawEvent=true;Er(o,c);if(c.type==="resync-required"){a=true;yield c;break}yield c;if(Sr(c)){o.terminal=true}}}catch(w){if(r?.aborted)throw r.reason??w;d=w}if(o.terminal)return;const l=yield*this.reconcile(t,n,o,a,r);if(l.terminal)return;if(!l.recoverable){throw d??te("EXEC_STREAM_ENDED_WITHOUT_TERMINAL","Runtime stream ended without a durable terminal fact.")}s=m||l.progressed?0:s+1;if(s>(this.options.maxConsecutiveRecoveryAttempts??Tr)){throw te("EXEC_STREAM_RECOVERY_EXHAUSTED","Runtime stream recovery was exhausted before a terminal fact arrived.",d)}await(this.options.wait??Rr)(this.options.reconnectDelayMs??vr,r)}}async*reconcile(t,r,n,o,i){i?.throwIfAborted();const[s,d]=await Promise.all([this.runtime.getActiveRun(t.id),this.runtime.getSession(t.id)]);const a=(s.state==="running"||s.state==="decision-blocked")&&(!s.turnId||s.turnId===r);const m=o||!a||s.state==="idle";let l=false;let w=false;if(m){const{messages:c}=await we(this.runtime,t.id,r);for(const h of c){if(h.id)n.afterMsgId=h.id;if(xr(h))l=true;if(h.id&&n.seenMessageIds.has(h.id))continue;if(h.id)n.seenMessageIds.add(h.id);n.sawEvent=true;w=true;yield{type:"message",message:h}}if(o)n.cursor=void 0}if(d.status==="error"){yield{type:"session-status",status:"error",turnId:r,message:d.errorMessage??"Runtime turn failed."};return{progressed:w,recoverable:false,terminal:true}}if(d.status==="aborted"){yield{type:"session-status",status:"aborted",turnId:r};return{progressed:w,recoverable:false,terminal:true}}if(d.status==="idle"&&l){yield{type:"session-status",status:"finished",turnId:r};return{progressed:w,recoverable:false,terminal:true}}if(s.state==="decision-blocked"){throw te("INTERACTION_NOT_AVAILABLE","Runtime is waiting for user interaction from a non-interactive Exec host.")}return{progressed:w,recoverable:a||n.sawEvent,terminal:false}}};async function we(e,t,r,n){const o=[];const i=new Set;let s;for(let d=0;d<100;d+=1){n?.throwIfAborted();const a=await e.listMessagePage(t,{limit:200,...s?{before:s}:{}});n?.throwIfAborted();o.unshift(a.messages.filter(m=>m.turnId===r));if(!a.hasMore)return{messages:o.flat(),complete:true};if(!a.nextCursor||i.has(a.nextCursor))break;i.add(a.nextCursor);s=a.nextCursor}return{messages:o.flat(),complete:false}}function Er(e,t){if(t.type!=="message"||!t.message.id)return;e.seenMessageIds.add(t.message.id);e.afterMsgId=t.message.id}function xr(e){return e.role==="assistant"&&(e.kind==="final"||e.finishReason==="stop"||e.finishReason==="end_turn"||e.finishReason==="stop_sequence")}function Sr(e){if(e.type==="error")return true;return e.type==="session-status"&&(e.status==="finished"||e.status==="error"||e.status==="aborted"||e.status==="interrupted")}function Ir(e){return e??new AbortController().signal}async function Rr(e,t){if(e<=0)return;await new Promise((r,n)=>{const o=()=>{t?.removeEventListener("abort",s);r()};const i=setTimeout(o,e);const s=()=>{clearTimeout(i);t?.removeEventListener("abort",s);n(t?.reason??new Error("Exec stream recovery was cancelled."))};if(t?.aborted){s();return}t?.addEventListener("abort",s,{once:true})})}function te(e,t,r){return Object.assign(new Error(t,r===void 0?void 0:{cause:r}),{category:"runtime",code:e,retryable:false})}var ne=class{constructor(t){this.options=t;this.nowMs=t.nowMs??Date.now}options;sequence=0;started=false;completed=false;startedItems=new Set;nowMs;project(t){if(this.completed)throw new Error("Exec events cannot follow exec.completed.");const r=br(t);return[...this.ensureStarted(),...r.map(n=>this.itemEvent(n))]}complete(t){if(this.completed)throw new Error("exec.completed was projected more than once.");this.completed=true;const r=t.status==="succeeded"?this.event({type:"turn.completed",...t.model?{model:t.model}:{},...t.usage?{usage:t.usage}:{},...t.usageSource!==void 0?{usageSource:t.usageSource}:{},...t.usageIncomplete!==void 0?{usageIncomplete:t.usageIncomplete}:{},durationMs:t.durationMs}):this.event({type:"turn.failed",status:t.status,...t.error?{error:t.error}:{},durationMs:t.durationMs});return[...this.ensureStarted(),r,this.event({type:"exec.completed",result:t})]}ensureStarted(){if(this.started)return[];this.started=true;return[this.event({type:"exec.started"}),this.event({type:this.options.resumed?"session.resumed":"session.started"}),this.event({type:"turn.started"})]}itemEvent(t){const r=this.startedItems.has(t.item.id);if(t.completed){this.startedItems.delete(t.item.id);return this.event({type:"item.completed",item:t.item})}this.startedItems.add(t.item.id);return this.event({type:r?"item.updated":"item.started",item:t.item})}event(t){return{schemaVersion:1,sequence:++this.sequence,timestampMs:this.nowMs(),runId:this.options.runId,sessionId:this.options.sessionId,turnId:this.options.turnId,...t}}};function br(e){if(e.type==="delta"&&e.role==="assistant"){const t=e.messageId??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",contentDelta:e.thinking},completed:false}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",contentDelta:e.content},completed:false}]:[],...(e.toolCalls??[]).map((r,n)=>({item:bt(r,t,n),completed:false}))]}if(e.type!=="message"||e.message.role!=="assistant")return[];return kr(e.message)}function kr(e){const t=e.id??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",content:e.thinking},completed:true}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",content:e.content},completed:true}]:[],...(e.toolCalls??[]).map((r,n)=>({item:bt(r,t,n),completed:true}))]}function bt(e,t,r){return{id:e.id??`${t}:tool:${String(r)}`,type:"tool_call",toolCall:e}}import{performance as oe}from"node:perf_hooks";async function kt(e,t,r=5e3){const n=oe.now()+r;while(oe.now()<n){let o;try{const s=await Promise.race([e.getActiveRun(t),new Promise(d=>{o=setTimeout(()=>d(void 0),Math.max(0,n-oe.now()))})]);if(!s||s.sessionId!==t)return false;if(s.state==="idle"||s.state==="terminal")return true}catch{return false}finally{if(o)clearTimeout(o)}const i=n-oe.now();if(i<=0)return false;await new Promise(s=>setTimeout(s,Math.min(50,i)))}return false}import{performance as Te}from"node:perf_hooks";var se=class{constructor(t){this.record=t}record;active=new Map;toolStates=new Map;modelSteps=0;toolCalls=0;lastActivityAt=Date.now();droppedOperations=0;observe(t){if(t.type==="delta"){if(t.content||t.thinking||t.toolCalls?.length)this.lastActivityAt=Date.now();for(const r of t.toolCalls??[])this.tool(r)}else if(t.type==="message"){for(const r of t.message.toolCalls??[])this.tool(r)}else if(t.type==="generic"&&t.eventType==="execution.diagnostic"){const{kind:r,operationId:n,modelId:o,protocol:i,finishReason:s}=t.data;if(typeof n!=="string")return;if(r==="model_phase_started"){this.modelSteps++;this.start(n,"model")}else if(r==="model_phase_finished"||r==="model_phase_failed"){this.end(n,{finishReason:typeof s==="string"?s:void 0})}else return;this.record({kind:r,operationId:n,modelId:typeof o==="string"?o:void 0,protocol:typeof i==="string"?i:void 0})}}summary(){return{modelSteps:this.modelSteps,toolCalls:this.toolCalls,lastActivityAt:this.lastActivityAt,droppedOperations:this.droppedOperations,unfinishedOperations:[...this.active].map(([t,r])=>({operationId:t,kind:r.kind,startedAtMs:r.startedAtMs,elapsedMs:Math.max(0,Te.now()-r.startedAt)}))}}tool(t){if(!t.id)return;const r=String(t.status).toLowerCase();const n=["1","started","running","in_progress"].includes(r)?"started":["2","completed","succeeded","success"].includes(r)?"finished":["3","failed","error"].includes(r)?"failed":void 0;if(!n||this.toolStates.get(t.id)===n)return;if(this.toolStates.size>=4096&&!this.toolStates.has(t.id)){this.droppedOperations++;return}this.toolStates.set(t.id,n);if(n==="started"){this.toolCalls++;this.start(t.id,"tool");this.record({kind:"tool_started",operationId:t.id,toolName:t.name})}else{this.end(t.id,{kind:`tool_${n}`,toolName:t.name})}}start(t,r){this.lastActivityAt=Date.now();if(this.active.size>=256){this.droppedOperations++;return}this.active.set(t,{kind:r,startedAt:Te.now(),startedAtMs:this.lastActivityAt})}end(t,r){this.lastActivityAt=Date.now();const n=this.active.get(t);this.active.delete(t);this.record({kind:"operation_finished",operationId:t,...r,...n?{durationMs:Math.max(0,Te.now()-n.startedAt)}:{missingStart:true}})}};var Pr=_e("mcode:tui");var Mr=3e5;async function Dt(e,t){const r=t.stdout??he(process.stdout);const n=t.stderr??he(process.stderr);const o=t.processRef??process;const i=t.createTurnId??Et;let s=N.internal;let d;let a;const m=[];let l;let w={};let c={};let h=false;let x;const E=e.diagnosticsDir?new se(y=>l?.record({...c,...y})):void 0;const u=Date.now();const b=new re(t.runtime);const I=new ze(b.conversationPort(),{...e.diagnosticsDir?{onAnswerSelection:y=>{w=y;l?.record(y)}}:{}});let k;let A=t.signal?.aborted??false;const p=()=>{A=true;void I.abort()};const v=()=>{if(A)throw new g("cancelled","Execution was cancelled.")};t.signal?.addEventListener("abort",p,{once:true});o.once("SIGINT",p);o.once("SIGTERM",p);o.once("SIGHUP",p);try{v();if(e.diagnosticsDir){l=await K.create(e.diagnosticsDir,T=>m.push(T));v()}const y=e.model?Ae(e.model):void 0;await Xe(t.runtime,e.sessionId,void 0,void 0,y?{model:y}:void 0);v();const S=await $r(e,t.runtime,v);v();await _r(t.runtime,S);v();const R=await Oe({...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},session:S,runtime:t.runtime});v();const M=i();const ie=`exec_${M}`;c={version:e.version,sessionId:S.sessionId,turnId:M,runId:ie,startedAt:u,schemaHash:lt(e.outputSchema)};l?.execution(c);l?.record({kind:"execution_started",sessionId:S.sessionId,turnId:M});const xe=It(e.format??"text",r,{...e.format==="stream-json"?{eventProjector:new ne({runId:ie,sessionId:S.sessionId,turnId:M,resumed:Boolean(e.sessionId||e.continueSession)})}:{}});const Ct=await I.execute({turnId:M,session:Promise.resolve(S),content:e.prompt,workspace:e.workspaceDir,version:e.version,...l?{executionDiagnostics:true}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...R?{model:R}:{},...e.reviewRequest?{reviewRequest:e.reviewRequest}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.timeoutMs!==void 0||e.maxSteps!==void 0?{policy:{...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.maxSteps!==void 0?{maxSteps:e.maxSteps}:{},requireAnswer:true}}:{policy:{requireAnswer:true}}},async T=>{let $;if(T.type==="message"){$=Be(T.message.origin);if($){k={outcome:$,content:T.message.content??""}}}E?.observe(T);if(T.type==="session-status"){l?.record({kind:"session_status",status:T.status})}else if(T.type==="message"&&T.message.role==="assistant"){l?.record({kind:"assistant_completed",messageId:T.message.id,finishReason:T.message.finishReason,requestDurationMs:T.message.usage?.requestDurationMs})}try{await xe.event(Or(T,$))}catch(Ie){d??=Ie;void I.abort();throw Ie}});if(d)throw d;let P=Dr(Ct.outcome);let U;if(e.reviewRequest&&P.status==="succeeded"){const T=Ar(k);if("error"in T){P={...P,status:"failed",answer:null,error:T.error}}else{U=T.result}}x=P.answer;const L=P.status==="succeeded"?me(P.answer,e.outputSchema):void 0;const O=Cr(e.format)||l?await jr(t.runtime,S.sessionId,M,P):{};const jt={runId:ie,...L?{validation:L}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...O.model?{model:{...O.model,...e.outputSchema&&P.status==="succeeded"?{structuredOutputMode:"native_strict"}:{}}}:{},...O.usage?{usage:O.usage}:{},..."usageSource"in O?{usageSource:O.usageSource,usageIncomplete:O.usageIncomplete}:{}};const Se=ot(P,jt);const D=U?{...Se,output:U}:Se;if(l&&D.status==="timeout"){h=await kt(t.runtime,S.sessionId);l.record({kind:"stop_confirmed",stopped:h})}c={...c,model:O.model,status:D.status,durationMs:D.durationMs};if(D.status!=="succeeded"){l?.failure(P.answer,{...E?.summary(),...w,error:D.error,status:D.status,...L&&!L.ok?{validationKind:L.kind}:{}})}a={encoder:xe,result:D,...D.status==="succeeded"&&e.outputLastMessagePath?{lastMessage:{filePath:e.outputLastMessagePath,answer:U?q(U):P.answer??""}}:{}};if(!A&&e.ownsBackgroundWake!==false){const T=await xt({runtime:t.runtime,sessionId:S.sessionId,timeoutMs:e.backgroundDeliveryDrainTimeoutMs??Mr,signal:t.signal,onPending:$=>{l?.record({kind:"background_delivery_drain_started",...$})}});if(T==="timeout"||T==="unreadable"){m.push(`${St}
11
- `)}}}catch(y){const S=At(y);l?.failure(void 0,{error:{message:S.message},phase:"execution"});s=B(S);if(s!==N.brokenPipe){m.push(`mcode exec failed: ${H(S)}
12
- `)}}finally{t.signal?.removeEventListener("abort",p);o.off("SIGINT",p);o.off("SIGTERM",p);o.off("SIGHUP",p);let y;let S=false;try{const R=await t.shutdown();if(R===true)y="Runtime shutdown did not complete cleanly."}catch(R){y=Ce(R,{summary:"mcode exec shutdown failed.",nextStep:"Verify no process is still running."})}if(a){if(y&&a.result.status==="succeeded"){a.result=Mt(a.result,"RUNTIME_SHUTDOWN_FAILED",y);S=true}if(a.result.status==="succeeded"&&a.lastMessage){try{await Rt(a.lastMessage.filePath,a.lastMessage.answer)}catch(R){a.result=Mt(a.result,"OUTPUT_LAST_MESSAGE_WRITE_FAILED",R instanceof Error?R.message:String(R))}}try{if(a.result.status!=="succeeded"&&a.result.error?.category==="internal"){l?.failure(x,{...w,status:a.result.status,error:a.result.error})}await a.encoder.result(a.result);s=Me(a.result);if(a.result.status!=="succeeded"){m.push(`mcode exec ${a.result.status}: ${rt(a.result)}
13
- `)}}catch(R){const M=At(R);s=B(M);if(s!==N.brokenPipe){m.push(`mcode exec failed: ${H(M)}
14
- `)}}}else if(y&&s!==N.brokenPipe){s=N.internal}if(y&&!S)m.push(`${y}
15
- `);l?.execution({...c,endedAt:Date.now(),shutdownComplete:!y,exitCode:s});l?.record({kind:"execution_finished",...c,exitCode:s,shutdownComplete:!y});await l?.flush({version:e.version,runId:c.runId,sessionId:c.sessionId,turnId:c.turnId,...E?.summary(),exitCode:s,shutdownComplete:!y,recoveryReady:h&&!y});Pr.info("exec exit",{...typeof c["runId"]==="string"?{runId:c["runId"]}:{},...typeof c["sessionId"]==="string"?{sessionId:c["sessionId"]}:{},...typeof c["turnId"]==="string"?{turnId:c["turnId"]}:{},exitCode:s,durationMs:Date.now()-u,shutdownComplete:!y});if(s!==N.brokenPipe){for(const R of m)await Lr(n,R)}}return s}function Ar(e){if(!e){return{error:{category:"runtime",code:"REVIEW_RESULT_MISSING",message:"Runtime completed without a validated code review result.",retryable:true}}}if(e.outcome==="failed"){return{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:e.content.trim()||"Runtime rejected an invalid code review result.",retryable:true}}}const t=e.outcome==="pass"?qe(e.content):ue(e.content);return t?{result:t}:{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:"Runtime returned an invalid code review result.",retryable:true}}}function Or(e,t){if(e.type!=="message"||t!=="needs_changes")return e;const r=ue(e.message.content??"");return{...e,message:{...e.message,content:r?q(r):"Runtime returned an invalid code review result."}}}function Mt(e,t,r){return{...e,status:"failed",output:void 0,error:{category:"internal",code:t,message:r,retryable:false}}}function Dr(e){if(e.status!=="awaiting-user-continuation")return e;return{...e,status:"failed",error:{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested user interaction from a non-interactive Exec host.",retryable:false}}}async function _r(e,t){const r=t.agentName??ce;const[n,o]=await Promise.all([e.getPendingQuestionnaire(r,t.sessionId),e.listPendingPermissions()]);const i=o.some(d=>d.sessionId===t.sessionId);if(!n&&!i)return;const s=n?"a pending questionnaire":"a pending permission request";throw new g("runtime",`Session ${t.sessionId} has ${s} and requires an interactive host. Continue it in the TUI or ACP.`)}function Cr(e){return e==="json"||e==="stream-json"}async function jr(e,t,r,n){const o=new AbortController;const i=setTimeout(()=>o.abort(),1e3);const[s,d,a]=await Promise.all([ve(()=>e.getSessionUsage(t),void 0,o.signal),ve(()=>e.listModels(t),[],o.signal),ve(()=>we(e,t,r,o.signal),void 0,o.signal)]).finally(()=>clearTimeout(i));const m=s?.rows?.filter(p=>p.turnId===r)??[];const l=[...m].reverse().find(p=>p.model?.trim())?.model?.trim();const w=n.model?`${n.model.providerId}/${n.model.modelId}`:void 0;const c=d.find(p=>p.selected===true);const h=c?`${c.providerId}/${c.modelId}`:void 0;const x=Nr(l??w??h,d,n.model?.variant);const E=[...n.usageResponses??[]];const u=new Set;for(const p of a?.messages??[]){const v=de(p,r);if(!v)continue;if(v.messageId)u.add(v.messageId);if(v.messageId)Ge(E,v)}const b=Je(E);const I=Ee(b.usage??n.usage);const k=I??Fr(m);const A=n.status!=="succeeded"||n.usageIncomplete===true||!a?.complete||a.messages.some(p=>Ve(p,r))||b.usageIncomplete||I!==void 0&&I.totalTokens===void 0||E.length===0||E.some(p=>!p.messageId||!u.has(p.messageId)||!Ee(p.usage)||p.usageIncomplete)||(a?.messages.some(p=>{const v=de(p,r);return v!==void 0&&!v.messageId})??false);return{...x?{model:x}:{},...k?{usage:k}:{},usageSource:I?"completed_responses":k?"analytics_fallback":"unavailable",usageIncomplete:!I||A}}function ve(e,t,r){return new Promise(n=>{const o=s=>{r.removeEventListener("abort",i);n(s)};const i=()=>o(t);r.addEventListener("abort",i,{once:true});if(r.aborted)return i();void Promise.resolve().then(e).then(o,()=>o(t))})}function Nr(e,t,r){const n=e?.indexOf("/")??-1;if(!e||n<=0||n===e.length-1)return void 0;const o=e.slice(0,n);const i=e.slice(n+1);const s=t.find(d=>d.providerId===o&&d.modelId===i);return{providerId:o,modelId:i,...s?.variant!==void 0?{variant:s.variant}:r!==void 0?{variant:r}:{},...s?.providerSource?{providerSource:s.providerSource}:{},...s?.providerKind?{providerKind:s.providerKind}:{},...s?.apiFormat?{protocol:s.apiFormat}:{}}}function Fr(e){const t=new Map;const r=[];for(const i of e){if(i.id===void 0)r.push(i);else t.set(i.id,i)}const n=[...t.values(),...r];const o={...J(n,"inputTokens"),...J(n,"outputTokens"),...J(n,"reasoningTokens"),...J(n,"cacheReadTokens"),...J(n,"cacheWriteTokens")};return Ee(o)}function Ee(e){if(!e)return void 0;const t={...e};delete t.totalTokens;const r=t.inputTokens;const n=t.outputTokens;const o=(r??0)+(n??0);return Object.keys(t).length===0?void 0:{...t,...(r!==void 0||n!==void 0)&&Number.isFinite(o)?{totalTokens:o}:{}}}function J(e,t){const r=e.map(o=>o[t]).filter(o=>typeof o==="number"&&Number.isFinite(o)&&o>=0);const n=r.reduce((o,i)=>o+i,0);return r.length>0&&Number.isFinite(n)?{[t]:n}:{}}function At(e){if(e instanceof g)return e;if(e instanceof Pe){const r=e.category==="config"||e.category==="invocation"||e.category==="cancelled"||e.category==="brokenPipe"||e.category==="internal"?e.category:"runtime";return new g(r,e.message,{cause:e})}const t=e instanceof Error?e.message:String(e);return new g("runtime",t,{cause:e})}async function $r(e,t,r){if(e.sessionId){const n=await t.getSession(e.sessionId);Ot(n,e.workspaceDir);return n}if(e.continueSession){const n=await Ur(t,e.workspaceDir,r);if(!n){throw new g("runtime",`No active Session exists for workspace ${e.workspaceDir}.`)}Ot(n,e.workspaceDir);return n}return t.createSession({workspaceDir:e.workspaceDir,title:Br(e.prompt,e.attachments?.length??0)})}async function Ur(e,t,r){let n;do{const o=await e.listSessionPage({agentName:ce,cursor:n,limit:50,includeArchived:false});r();const i=o.sessions.find(s=>s.archived!==true&&s.workspaceDir!==void 0&&_t(s.workspaceDir,t));if(i)return i;n=o.hasMore?o.nextCursor:void 0}while(n);return void 0}function Ot(e,t){if(Ue(e)){throw new g("invocation","Sub-agent Sessions are internal and cannot be opened.")}if(e.archived){throw new g("runtime",`Session is archived: ${e.sessionId}`)}if(!e.workspaceDir||!_t(e.workspaceDir,t)){throw new g("runtime",`Session workspace does not match --cwd: ${e.sessionId}`)}}function _t(e,t){const r=Pt(e);const n=Pt(t);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}async function Lr(e,t){try{await e(t)}catch{}}function Br(e,t){const r=e.replace(/\s+/g," ").trim();if(!r)return t===1?"Attachment run":`${t} attachments`;return r.length<=80?r:`${r.slice(0,77)}...`}async function ao(e,t,r,n={}){const o=n.processRef??process;const i=n.writeError??(u=>process.stderr.write(u));const s=n.resolveInvocation??gt;const d=n.resolveDataDir??ke;const a=n.loadConfig??et;const m=n.createRuntime??Qe;const l=n.shutdownRuntime??Ze;const w=n.runExec??Dt;const c=n.readStdin??Hr;const h=new AbortController;const x=()=>h.abort();const E=()=>{if(h.signal.aborted){throw new g("cancelled","Invocation was cancelled.")}};o.once("SIGINT",x);o.once("SIGTERM",x);o.once("SIGHUP",x);try{const u=await s(e,t,()=>c(h.signal),h.signal);E();const b=await d();E();const I=u.configPath?await a(u.configPath,{dataDir:b}):void 0;E();const k=await m({dataDir:b,workspaceDir:u.workspaceDir,version:r,...u.configPath?{configPath:u.configPath}:{},surface:"headless",promptMode:u.promptMode??"tui",...u.systemPromptOverrides?{systemPromptOverrides:u.systemPromptOverrides}:{},permissionMode:qr(u.permission),...u.contextMode?{contextMode:u.contextMode}:{},...t.lane?{lane:t.lane}:{},...t.profile?{profile:t.profile}:{},...u.noDaemon?{noDaemon:true}:{}},I?{getConfig:()=>I,configSource:"explicit"}:{});o.exitCode=await w({prompt:u.prompt,workspaceDir:u.workspaceDir,version:r,attachments:u.attachments,format:u.format,...u.model?{model:u.model}:{},...u.effort?{effort:u.effort}:{},...u.sessionId?{sessionId:u.sessionId}:{},continueSession:u.continueSession,permission:u.permission,...u.diagnosticsDir?{diagnosticsDir:u.diagnosticsDir}:{},...u.timeoutMs!==void 0?{timeoutMs:u.timeoutMs}:{},...u.maxSteps!==void 0?{maxSteps:u.maxSteps}:{},...u.outputSchema===void 0?{}:{outputSchema:u.outputSchema},...u.outputLastMessagePath===void 0?{}:{outputLastMessagePath:u.outputLastMessagePath},...u.reviewRequest?{reviewRequest:u.reviewRequest}:{},ownsBackgroundWake:We()==="off"},{runtime:k.adapter,signal:h.signal,shutdown:()=>l(k)})}catch(u){const b=u instanceof g?u:new g("runtime",u instanceof Error?u.message:String(u),{cause:u});i(`mcode exec failed: ${H(b)}
16
- `);o.exitCode=B(b)}finally{o.off("SIGINT",x);o.off("SIGTERM",x);o.off("SIGHUP",x)}}function qr(e){switch(e){case"smart":return"auto";case"full":return"bypassPermissions";case"off":return"off"}}async function Hr(e,t=process.stdin){const r=[];const n=t[Symbol.asyncIterator]();try{for(;;){const o=await Wr(n,e);if(o.done)break;r.push(Buffer.isBuffer(o.value)?o.value:Buffer.from(o.value))}}finally{await n.return?.()}return Buffer.concat(r).toString("utf8")}function Wr(e,t){return new Promise((r,n)=>{const o=()=>{n(new g("cancelled","stdin input was cancelled."))};if(t.aborted){o();return}t.addEventListener("abort",o,{once:true});void e.next().then(i=>{t.removeEventListener("abort",o);r(i)},i=>{t.removeEventListener("abort",o);n(i)})})}export{Hr as readTuiStdinToEnd,ao as runTuiExecCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{$ as oa,$a as mb,A as Q,Aa as Na,Ab as Wb,B as R,Ba as Oa,Bb as Xb,C as S,Ca as Pa,Cb as Yb,D as T,Da as Qa,Db as Zb,E as U,Ea as Ra,Eb as _b,F as V,Fa as Sa,Fb as $b,G as W,Ga as Ta,Gb as ac,H as X,Ha as Ua,I as Y,Ia as Va,J as Z,Ja as Wa,K as _,Ka as Xa,L as $,La as Ya,Ma as Za,N as aa,Na as _a,O as ba,Oa as $a,P as ca,Pa as ab,Q as da,Qa as bb,R as ea,Ra as cb,S as fa,Sa as db,T as ga,Ta as eb,U as ha,Ua as fb,V as ia,Va as gb,W as ja,Wa as hb,X as ka,Xa as ib,Y as la,Ya as jb,Z as ma,Za as kb,_ as na,_a as lb,a,aa as pa,ab as nb,b,ba as qa,bb as ob,ca as ra,cb as pb,d as c,da as sa,db as qb,e as d,ea as ta,eb as rb,f as e,fa as ua,fb as sb,g as f,ga as va,gb as tb,h as g,ha as wa,hb as ub,i as h,ia as xa,ib as vb,j as i,ja as ya,jb as wb,k as j,ka as za,kb as xb,l as k,la as Aa,lb as yb,m as l,ma as Ba,mb as zb,n as m,na as Ca,nb as Jb,o as n,oa as Da,ob as Kb,p as F,pb as Lb,q as G,qb as Mb,r as H,ra as Ea,rb as Nb,s as I,sa as Fa,sb as Ob,t as J,ta as Ga,tb as Pb,u as K,ua as Ha,ub as Qb,v as L,va as Ia,vb as Rb,w as M,wa as Ja,wb as Sb,x as N,xa as Ka,xb as Tb,y as O,ya as La,yb as Ub,z as P,za as Ma,zb as Vb}from"./chunk-UNEPZJKK.js";import{a as o,b as p,c as q,d as r,e as s,f as t,g as u,h as v,i as w,j as x,k as y,l as z,m as A,n as B,o as C,p as D,q as E}from"./chunk-ISBSRM3S.js";import"./chunk-5R2PGOIA.js";import"./chunk-UQL67NEA.js";import"./chunk-4GGSPZK3.js";import{a as Ab,b as Bb,c as Cb,d as Db,e as Eb,f as Fb,g as Gb,h as Hb,i as Ib}from"./chunk-AUG3KCLV.js";import"./chunk-NOGL6Y6L.js";import"./chunk-FK3SSGJE.js";export{G as AGENT_BUILTIN_MCP_TOOL_IDS,H as AGENT_BUILTIN_SKILL_IDS,F as AGENT_BUILTIN_TOOL_IDS,I as AGENT_CAPABILITY_OWNED_SKILL_IDS,k as AGENT_RUNTIME_FRAMEWORKS,Eb as ASR_PROXY_AUTH_ENV_KEYS,la as BRAND,Z as BROWSER_CONFIG_DEFAULTS,$b as CONVERSATION_STOP_CONFIG_DEFAULTS,Oa as CUSTOM_PROVIDER_ID_PREFIX,Yb as ConfigFileError,qb as ControlRootInsecureError,mb as DAEMON_CONTROL_ROOT_DIR_PREFIX,l as DEFAULT_AGENT_RUNTIME_FRAMEWORK,d as DEFAULT_CU_BACKEND,va as DEFAULT_MODEL_PRESETS,na as DEFAULT_PORT,v as DEFAULT_PROFILE_NAME,Ya as DEFAULT_SESSIONS_GENERATION,h as DEFAULT_SKILLS_CONFIG,Ua as DURABLE_CAS_DIR_BASENAME,Ta as DURABLE_ROOT_BASENAME,Va as DURABLE_RUNTIME_DB_BASENAME,Xa as DURABLE_SESSIONS_DB_BASENAME,Wa as DURABLE_SOCKET_BASENAME,j as EXTERNAL_SOURCE_KIND_LIST,U as GOAL_CONFIG_DEFAULTS,V as GOAL_CONFIG_LIMITS,R as GOAL_EVALUATOR_MODEL_POLICIES,T as GOAL_SUBAGENT_PROFILES,Q as GOAL_VERIFICATION_EVIDENCE_MODES,P as GOAL_VERIFICATION_MODES,S as GOAL_VERIFIER_READONLY_PROFILE,y as InvalidProfileNameError,p as LEGACY_DATA_DIR_BASENAME,x as LEGACY_PROFILE_ENV_VAR,Za as LEGACY_ROOT,Bb as LEGACY_RUNTIME_ENV_KEYS,Mb as LOCAL_RUNTIME_AUTH_CONTEXT_FILE,_a as LegacyWriteError,Ma as MANAGED_MINIMAX_PROVIDER_ID,Ab as MANAGED_RUNTIME_KEYS,eb as MCODED_SOCKET_PATH_MAX_BYTES,hb as MCODE_SERVER_MODE_ENV,Na as MINIMAX_API_PROVIDER_ID,o as NEW_DATA_DIR_BASENAME,oa as OPENCODE_PORT_OFFSET,Db as PARENT_HINT_KEYS,w as PROFILE_ENV_VAR,f as REQUEST_MEDIA_DEFAULTS,ma as RUNTIME_ENV_PREFIX,Cb as RUNTIME_IDENTITY_KEYS,ba as SANDBOX_CONFIG_DEFAULTS,$ as SANDBOX_FILESYSTEM_MODE_NAMES,ib as ServerModeConfigError,kb as ServerModeOffError,Tb as TEST_PORT_ROLE_FLOOR,Sb as TEST_PORT_ROLE_OFFSET,X as TOOL_RESULT_COMPACTION_DEFAULTS,ua as allowsManagedMinimaxProviderOverride,Xb as assertCuBackendSupported,lb as assertDaemonStartAllowed,tb as assertNoLegacyWrite,rb as assertSecureControlRoot,A as assertValidProfileName,Fb as buildChildEnv,Rb as clearLocalRuntimeAuthContextFile,zb as compareAndSetLocalModelContext,qa as detectGitPortInfo,Lb as detectPidOwner,sb as ensureControlRootLayout,ub as ensureDurableLayout,Ib as findLegacyRuntimeEnvKeys,Kb as formatPidFile,za as getConfig,ta as getConfigPath,Vb as getCuBackend,sa as getDataDir,r as getLegacyDataDirPath,Ca as getOpenCodePort,q as getPrimaryDataDirPath,ra as getProfile,fa as getRuntimeBuildEnv,ha as getRuntimePresetKey,ea as getRuntimeRegion,aa as getSandboxConfigDefaults,N as isAgentBuiltinMcpToolEnabled,O as isAgentBuiltinSkillEnabled,M as isAgentBuiltinToolEnabled,ja as isBetaFeatureProdReady,Pa as isFirstPartyMinimaxMessagesRoute,ka as isInternalBuild,Ja as isLegacyManagedMinimaxProvider,Ea as isLocalSourceProvenanceEnabled,Ka as isManagedProviderBaseUrl,ga as isManagedRuntime,da as isProposalEligibleAgent,Da as isTelemetryChannelEnabled,z as isValidProfileName,E as listProfiles,Ra as listRouteModelIds,Zb as loadConfigFromFile,t as migrateDefaultDataDir,u as migrateProfileDataDir,c as minimaxApiModels,Nb as normalizeLocalRuntimeAuthContext,B as normalizeProfileSelector,K as parseAgentCapabilityConfig,n as parseAgentRuntimeConfig,m as parseAgentRuntimeFramework,J as parseAgentsConfig,_ as parseBrowserConfig,e as parseCuBackend,W as parseGoalConfig,Jb as parsePidFile,Ga as parsePromptSuggestionRemotePolicy,g as parseRequestMediaConfig,a as parseRunawayGuardOverride,ca as parseSandboxConfig,i as parseSkillsConfig,Y as parseToolResultCompactionConfig,Ub as pickTestPort,nb as profileOfDataDir,ac as readConversationStopConfig,_b as readExplicitBetaFeatureFromFile,Pb as readLocalRuntimeAuthContext,C as readProfileEnv,vb as removeLocalProviderConfig,wb as replaceLocalManagedMinimaxProvider,ya as resetConfig,pa as resetGitDetect,L as resolveAgentCapabilities,ia as resolveBetaFeature,bb as resolveCasDirPath,ob as resolveDaemonControlRoot,s as resolveDataDir,$a as resolveDurableRoot,gb as resolveFallbackMcodedSocketDir,fb as resolveFallbackMcodedSocketPath,Ob as resolveLocalRuntimeAuthContextPath,db as resolveMcodedSocketPath,Sa as resolveModelAvailability,Qa as resolveModelCallRoute,Ba as resolvePort,D as resolveProfileDataDirPaths,Aa as resolvePromptConfig,Ha as resolvePromptSuggestionEnabled,La as resolveProviderAuthMode,pb as resolveRealPath,b as resolveRunawayGuardConfig,cb as resolveRuntimeDbPath,jb as resolveServerMode,ab as resolveSessionsDbPath,Wb as setCuBackend,wa as setLegacyByokProviderMigrationEnabled,xa as setManagedPresetBaseUrlSyncEnabled,Gb as stripManagedRuntimeEnv,Hb as stripRuntimeBoundaryKeysFrom,xb as updateLocalByokConfig,yb as updateLocalModelSelection,Ia as withEffectivePromptSuggestion,Qb as writeLocalRuntimeAuthContext,Fa as writeTuiStatusLineSetting};