@niwa-labs/ncode 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/CHANGELOG.zh-CN.md +5 -0
  3. package/README.md +2 -2
  4. package/chunks/{application-A3S2LMBY.js → application-6B6N6MDM.js} +1 -1
  5. package/chunks/{auth-command-QNQ32TBI.js → auth-command-L57HWPOO.js} +1 -1
  6. package/chunks/{chunk-6LDRLO4Y.js → chunk-3LRARE6Z.js} +1 -1
  7. package/chunks/{chunk-5R2PGOIA.js → chunk-3MLT4F77.js} +1 -1
  8. package/chunks/{chunk-NOGL6Y6L.js → chunk-7F3QKGB7.js} +1 -1
  9. package/chunks/{chunk-LFGHL5A2.js → chunk-ALZZ3WAV.js} +1 -1
  10. package/chunks/{chunk-RD7XROJD.js → chunk-CUPCI2YC.js} +1 -1
  11. package/chunks/{chunk-OOBSLGMR.js → chunk-DBSRTVJC.js} +1 -1
  12. package/chunks/{chunk-XSWWOH4F.js → chunk-GS7TCNDK.js} +1 -1
  13. package/chunks/{chunk-36COWQLE.js → chunk-GZPVFWYD.js} +1 -1
  14. package/chunks/{chunk-CAY2BP2G.js → chunk-JEHPL5Z6.js} +1 -1
  15. package/chunks/{chunk-R7NDEPS3.js → chunk-LC7ZI6EV.js} +1 -1
  16. package/chunks/{chunk-ELHMZ5OD.js → chunk-NWMN2FDO.js} +1 -1
  17. package/chunks/{chunk-MVI24MQ2.js → chunk-O5EROATK.js} +664 -664
  18. package/chunks/{chunk-UMGGEC4N.js → chunk-QIYZZJVO.js} +1 -1
  19. package/chunks/{chunk-PBGCNSGZ.js → chunk-QMBFFQPV.js} +1 -1
  20. package/chunks/{chunk-JLFN6WSO.js → chunk-RZDVNG5Z.js} +1 -1
  21. package/chunks/{chunk-MI4YWYJF.js → chunk-UEPKZSE6.js} +1 -1
  22. package/chunks/{chunk-V4IDVAIA.js → chunk-WHBWI5OQ.js} +1 -1
  23. package/chunks/{chunk-ZPIJSTUE.js → chunk-WUORF7YS.js} +1 -1
  24. package/chunks/{chunk-UNEPZJKK.js → chunk-XWNCITOR.js} +5 -5
  25. package/chunks/{data-dir-OKWMOLNQ.js → data-dir-6RWVCAMB.js} +1 -1
  26. package/chunks/{launcher-4QSNU24J.js → launcher-B3C4PQ6Q.js} +3 -3
  27. package/chunks/{lifecycle-ELQ2EYO3.js → lifecycle-56K655PJ.js} +1 -1
  28. package/chunks/main-W3SJ2POE.js +14 -0
  29. package/chunks/{plugin-command-NGTATXBX.js → plugin-command-EBSKJLM3.js} +1 -1
  30. package/chunks/{profile-command-ZHVREBWO.js → profile-command-HIJDJDEL.js} +1 -1
  31. package/chunks/{provider-command-BGKOLCUG.js → provider-command-VCCPLOXR.js} +1 -1
  32. package/chunks/{run-acp-command-2CJQDXHQ.js → run-acp-command-FBV27QBE.js} +13 -13
  33. package/chunks/run-daemon-command-PZ2TU524.js +2 -0
  34. package/chunks/run-exec-command-K7BC2HEI.js +16 -0
  35. package/chunks/src-7ZMHMWLX.js +2 -0
  36. package/chunks/{telemetry-command-6FE4WQ4Q.js → telemetry-command-ZYOF64Y4.js} +1 -1
  37. package/chunks/{update-4VPIX7FP.js → update-ZKUCGIOR.js} +1 -1
  38. package/cli.js +3 -3
  39. package/matrix-mcp-stdio.js +1 -1
  40. package/mcoded.js +1 -1
  41. package/package.json +1 -1
  42. package/release.json +4 -4
  43. package/chunks/main-TXP74KHK.js +0 -14
  44. package/chunks/run-daemon-command-NDOIPTKF.js +0 -2
  45. package/chunks/run-exec-command-VNT4IKOJ.js +0 -16
  46. package/chunks/src-ED5HBSWE.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as Q,b as Z,c as ee,d as ne,e as de}from"./chunk-JLFN6WSO.js";import{G as te,H as re,K as oe,O as ie,P as F,Q as L,R as se,S as ae}from"./chunk-MVI24MQ2.js";import{R as I,S as _,Sa as q,Ya as $,fb as X}from"./chunk-UNEPZJKK.js";import{h as J,i as B,j as K}from"./chunk-ISBSRM3S.js";import{a as Y}from"./chunk-VAARXN34.js";import{spawn as _e}from"node:child_process";import{randomUUID as ve}from"node:crypto";import Re from"node:fs";import fe from"node:path";import y from"node:process";var v=Y("mcode:rpc");function Me(e){return e.startsWith("MCODE_")||e.startsWith("MINIMAX_")||e.startsWith("__MAVIS_")}function Ee(e=y.env,n=y.cwd()){const t={};for(const[r,o]of Object.entries(e)){if(o===void 0||Me(r))continue;t[r]=o}return{cwd:n,env:t}}var Pe=2e4;var Ae=200;function Ce(e){const n=e.environment??y.env;const t=e.seams??{};const r=t.sleep??(s=>new Promise(a=>setTimeout(a,s)));const o=t.spawnDaemon??(({argv:s,env:a,logFd:d})=>{const l=_e(s[0],s.slice(1),{detached:true,stdio:["ignore",d,d],env:a});l.unref();return l});const i=t.daemonAlive??(async()=>{const s=F(e.targets.controlRoot);if(s===void 0)return false;const a=L(e.targets.controlRoot);const d=await de(s.socketPath,{...a!==void 0?{token:a}:{},dataDir:s.dataDir,env:{region:I(),buildEnv:_()},timeoutMs:1e3});return d.ok});return async()=>{let s;try{s=oe(fe.join(e.targets.controlRoot,te))}catch(a){if(a instanceof re)return false;throw a}try{if(await i())return false;const a=y.argv[1];if(!a)throw new Error("Cannot auto-spawn mcoded: no entry script (process.argv[1]).");const d=e.targets.profile||null;const l={...n,MINIMAX_DATA_DIR:e.targets.dataDir,MAVIS_REGION:I(),MAVIS_BUILD_ENV:_(),...d!==null?{[B]:d}:{}};if(d===null){delete l[B];delete l[K]}const m=l["MCODE_SERVER_MODE"]?.trim().toLowerCase();if(m===void 0||m===""||m==="off"){l["MCODE_SERVER_MODE"]="auto"}X(e.targets.controlRoot);const g=ae(e.targets.controlRoot,l);try{o({argv:[y.execPath,a,"daemon","run","--data-dir",e.targets.dataDir,"--profile",d??J],env:g.childEnv,logFd:g.fd})}finally{Re.closeSync(g.fd)}const h=Date.now()+Pe;while(!await i()){if(Date.now()>h)return true;await r(Ae)}return true}finally{s.release()}}}var G=class{client;remote;goalEnabled=false;askSessions=new Map;attachedSessions=new Set;reattachReadyMs;reattachSleep;constructor(n,t,r={}){this.client=n;this.remote=t;this.reattachReadyMs=r.reattachReadyMs??xe;this.reattachSleep=r.reattachSleep??me;this.client.onReconnected(()=>{void this.refreshGoalEnabled();void this.refreshSnapshot()})}async refreshGoalEnabled(){try{this.goalEnabled=await this.remote.isGoalEnabled()}catch{this.goalEnabled=false}}isGoalEnabled(){return this.goalEnabled}async sendMessage(n,t,r){t?.signal?.throwIfAborted();const o=T(n);await this.attachBestEffort(o);const i=await this.openTurnStream("sendMessage",r?[n,r]:[n]);if(!i.ok)return i;return{ok:true,source:ce(i.source,t?.signal,{sessionId:o??"",...typeof n.turnId==="string"?{turnId:n.turnId}:{},readyMs:this.reattachReadyMs,sleep:this.reattachSleep,resume:(s,a)=>this.reopenTurnStream(o,s,a),waitForReady:s=>this.waitForClientReady(s)})}}async resumeSession(n,t){t?.signal?.throwIfAborted();const r=T(n);await this.attachBestEffort(r);const o=await this.openTurnStream("resumeSession",[n]);if(!o.ok)return o;return{ok:true,source:ce(o.source,t?.signal,{sessionId:r??"",readyMs:this.reattachReadyMs,sleep:this.reattachSleep,resume:(i,s)=>this.reopenTurnStream(r,i,s),waitForReady:i=>this.waitForClientReady(i)})}}watchEvents(n){const t=this.client.subscribe({scope:"catalog+attached"});const r=this.askSessions;const o=a=>this.attachDelegatedChild(a);const i=()=>this.refreshSnapshotSoon();const s=(async function*(){const a=new Set;const d=l=>{const m=l.payload;if(l.type==="permission.resolved")a.delete(m.requestId??"");if(l.type!=="permission.ask")return true;const g=m.requestId;if(g&&a.has(g))return false;if(g)a.add(g);return true};try{for await(const l of t.events){if(!d(l.event))continue;if(De(r,l.event))i();yield l.event;for(const m of await o(l.event)){if(d(m))yield m}}}finally{if(n?.aborted)t.stop()}})();n?.addEventListener("abort",()=>t.stop(),{once:true});void t.gapped.then(()=>{void this.refreshSnapshot();for(const a of this.attachedSessions)void this.attachBestEffort(a)});return{events:s,gapped:t.gapped,stop:()=>t.stop(),[Symbol.asyncIterator]:()=>s}}async listPendingPermissions(n){const t=await this.remote.listPendingPermissions(n);this.noteSnapshotRequests(t.requests??[]);return t}async getSession(n){await this.attachBestEffort(T(n));return await this.remote.getSession(n)}async getMessages(n){await this.attachBestEffort(T(n));return await this.remote.getMessages(n)}async getSessionTree(n){await this.attachBestEffort(T(n));return await this.remote.getSessionTree(n)}async listSessionInputSummaries(n){await this.attachBestEffort(T(n));return await this.remote.listSessionInputSummaries(n)}async createSession(n){const t=await this.remote.createSession(n);const r=t.session?.id;if(typeof r==="string"&&r.length>0)await this.attachBestEffort(r);return t}async replyPermission(n){const t=this.askSessions.get(n.requestId);return await this.remote.replyPermission({...n,...t!==void 0?{sessionId:t}:{}})}get delegated(){return this.remote}noteSnapshotRequests(n){for(const t of n)Ne(this.askSessions,t)}refreshSnapshotInFlight;refreshSnapshotSoon(){this.refreshSnapshotInFlight??=(async()=>{try{await this.listPendingPermissions({})}catch{}finally{this.refreshSnapshotInFlight=void 0}})()}async refreshSnapshot(){try{await this.listPendingPermissions({})}catch{}}async attachDelegatedChild(n){if(n.type!=="session.created")return[];const{sessionId:t,parentSessionId:r}=n.payload;if(!r||!this.attachedSessions.has(r))return[];await this.attachBestEffort(t);try{const o=await this.listPendingPermissions({});return(o.requests??[]).filter(i=>i.sessionId===t&&typeof i.requestId==="string").map(i=>({type:"permission.ask",timestamp:Date.now(),source:"local-runtime",payload:{...i,requestId:i.requestId,sessionId:t,agentName:typeof i.agentName==="string"?i.agentName:"",toolName:typeof i.toolName==="string"?i.toolName:"",ruleContents:Array.isArray(i.ruleContents)?i.ruleContents:[],reason:typeof i.reason==="string"?i.reason:"",allowAlwaysSupported:i.allowAlwaysSupported===true,createdAt:typeof i.createdAt==="number"?i.createdAt:Date.now()}}))}catch{return[]}}async attachBestEffort(n){if(n===void 0)return;try{await this.client.sessionAttach(n,"owner",Ee());this.attachedSessions.add(n)}catch{}}async reopenTurnStream(n,t,r){if(n===void 0)throw new Error("cannot reattach a turn without a session id");const o={id:n,...t!==void 0?{afterCursor:t}:{},...r!==void 0?{afterMsgId:r}:{}};const i=await this.openTurnStream("resumeSession",[o]);if(!i.ok){throw new Error(`resumeSession refused (${i.status}): ${i.body.message??"unknown refusal"}`)}return i.source}waitForClientReady(n){if(this.client.connectionState==="ready")return Promise.resolve();if(n<=0){return Promise.reject(new Error(`mcoded client is ${this.client.connectionState}, not ready`))}return new Promise((t,r)=>{const o=setTimeout(()=>{i();r(new Error(`mcoded client did not become ready within ${n}ms (state: ${this.client.connectionState})`))},n);const i=this.client.onStateChange(s=>{if(s!=="ready"&&s!=="closed")return;clearTimeout(o);i();if(s==="ready")t();else r(new Error("mcoded client closed while waiting for the reconnect"))})})}async openTurnStream(n,t){try{return{ok:true,source:await this.client.openStream(n,t)}}catch(r){if(r instanceof Z&&r.data!==void 0){const o=r.data;if(typeof o.status==="number"){return{ok:false,status:o.status,body:o.body}}}throw r}}};function T(e){const n=e.id??e.sessionId;return typeof n==="string"&&n.length>0?n:void 0}function De(e,n){const t=n.type;if(t!=="permission.ask"&&t!=="questionnaire.ask")return false;const r=n.payload??{};const o=r["requestId"];const i=r["sessionId"];if(typeof o==="string"&&typeof i==="string")e.set(o,i);return true}function Ne(e,n){if(typeof n.requestId==="string"&&typeof n.sessionId==="string"){e.set(n.requestId,n.sessionId)}}var xe=6e4;var ue=3;var Oe=[1e3,2e3,4e3];var R=class extends Error{};var M=class extends Error{sessionId;turnId;reason;attempts;cause;constructor(n){super(`turn stream detached (reason: ${n.reason}, attempts: ${n.attempts})`);this.name="TurnStreamDetached";this.sessionId=n.sessionId;this.turnId=n.turnId;this.reason=n.reason;this.attempts=n.attempts}};function ce(e,n,t){let r=false;let o=e;const i=()=>{if(r||n===void 0)return;r=true;if(n.reason instanceof R)o.detach();else void o.abort().catch(()=>void 0)};n?.addEventListener("abort",i,{once:true});const s=t.sleep??me;const a=(async function*(){try{let d=e;let l;let m;let g;let h=0;let C=0;let W=0;const H=Date.now();v.info("turn-stream-open",{sessionId:t.sessionId,turnId:t.turnId,streamId:d.streamId});for(;;){let D=false;for await(const N of d.frames){n?.throwIfAborted();const x=Be(N);if(x.messageId)m=x.messageId;if(x.resync)D=true;if(D)continue;const b=Fe(N);if(b!==void 0&&l!==void 0&&Number(b)<=Number(l)){C+=1;continue}if(b!==void 0)l=b;h+=1;const O=Date.now();if(O-W>=5e3){W=O;v.info("turn-stream-progress",{sessionId:t.sessionId,turnId:t.turnId,streamId:d.streamId,frames:h,skipped:C,cursor:l,elapsedMs:O-H})}yield N}const w=await d.ended;if(n?.reason instanceof R)return;v.info("turn-stream-ended",{sessionId:t.sessionId,turnId:t.turnId,streamId:d.streamId,reason:w.reason,resumable:w.resumable,frames:h,skipped:C,cursor:l,elapsedMs:Date.now()-H});if(D){if(!m||g===m){throw new M({sessionId:t.sessionId,turnId:t.turnId,reason:"resync-durable-anchor-unavailable",attempts:1})}g=m;l=void 0;d=await le(t,n,void 0,"resync-required",s,m);o=d;continue}if(w.reason==="done"||w.reason==="aborted")return;if(w.resumable!==true)return;d=await le(t,n,l,w.reason,s);o=d}}finally{n?.removeEventListener("abort",i);if(n?.aborted&&!r)i()}})();return a}async function le(e,n,t,r,o,i){let s;for(let a=1;a<=ue;a+=1){v.warn("turn-stream-detached",{sessionId:e.sessionId,reason:r,attempt:a});try{n?.throwIfAborted();await e.waitForReady(e.readyMs);return await e.resume(t,i)}catch(d){s=d;if(n?.aborted)throw d;await o(Oe[a-1]??0,n)}}throw new M({sessionId:e.sessionId,...e.turnId!==void 0?{turnId:e.turnId}:{},reason:r,attempts:ue})}function Be(e){const n=e.dataJson;if(!n||!n.includes('"agent_message"')&&!n.includes('"resume_overflow"'))return{};try{const t=JSON.parse(n);if(t?.type==="resume_overflow")return{resync:true};const r=t?.agent_message?.msg_id;return typeof r==="string"&&r?{messageId:r}:{}}catch{return{}}}function Fe(e){const n=e.cursor;return typeof n==="string"&&n.length>0?n:void 0}function me(e,n){return new Promise(t=>{if(n?.aborted||e<=0){t();return}const r=setTimeout(i,e);const o=()=>i();n?.addEventListener("abort",o,{once:true});function i(){clearTimeout(r);n?.removeEventListener("abort",o);t()}})}function Le(e,n={}){const t=new ne(e);const r=new G(e,t,n);const o=new Proxy(r,{get(i,s,a){if(s in i)return Reflect.get(i,s,a);const d=Reflect.get(t,s,a);return typeof d==="function"?d.bind(t):d}});return{cliService:o,tuiCli:r}}async function qn(e,n={}){const t=e.daemonTargets??se({profile:e.profile,dataDir:e.dataDir,homeDir:e.homeDir??e.environment?.["HOME"],env:e.environment??y.env});const r=n.clientInstanceId??ve();const o={tokenGetter:()=>{try{return L(t.controlRoot)}catch{return void 0}},dataDir:t.dataDir,env:{region:I(),buildEnv:_()},clientInstanceId:r,promptMode:e.promptMode??"tui",client:{kind:e.clientKind??"tui",pid:y.pid,...y.env["MCODE_BUILD_ID"]?{buildId:y.env["MCODE_BUILD_ID"]}:{},cwd:y.cwd()}};const i=new Q({logPath:fe.join(t.controlRoot,ie,"mcoded.log")});const s=Ce({targets:t,...e.environment?{environment:e.environment}:{},...n.spawnSeams?{seams:n.spawnSeams}:{}});const a={socketPath:F(t.controlRoot)?.socketPath??q(t.controlRoot),handshake:o,...e.autoSpawn===false?{}:{spawn:s},crashLoop:i,...e.readyTimeoutMs!==void 0?{readyTimeoutMs:e.readyTimeoutMs}:{}};const d=new ee(a);const{cliService:l,tuiCli:m}=Le(d,e.reattachReadyMs!==void 0?{reattachReadyMs:e.reattachReadyMs}:{});const g=(async()=>{await d.connect();await m.refreshGoalEnabled()})();return{cliService:l,ready:g,apiHost:{close:async()=>{d.close()}},notifyAuthContextChanged:async()=>{await d.daemonAuthSync()},connectionState:()=>d.connectionState,onConnectionStateChange:h=>d.onStateChange(h),clientInstanceId:r,socketPath:a.socketPath}}function $n(e=y.env){return $(e)}var Ge=["local-task:","local-background-task:","team-plan:"];var je=new Set(["explore","worker","verifier"]);function ge(e){return e.sessionKind==="task"||Ge.some(n=>e.purpose?.startsWith(n))}function Ve(e){if(e.sessionType!=="branch"||!e.parentSessionId){return false}return ge(e)}function Ue(e){const n=e.agentName?.trim().toLocaleLowerCase();return n!==void 0&&je.has(n)}function Yn(e){return ge(e)||Ue(e)}function Qn(e,n){const t=[];const r=new Set;const o=new Set([n]);let i=true;while(i){i=false;for(const s of e){if(r.has(s.sessionId)||!Ve(s)||!o.has(s.parentSessionId)){continue}t.push(s);r.add(s.sessionId);o.add(s.sessionId);i=true}}return t}function Zn(e){return{sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.agentName?{agentName:e.agentName}:{},...e.title?{task:e.title}:{},status:ze(e.status),...pe("createdAtMs",e.createdAt),...pe("updatedAtMs",e.updatedAt),...e.errorMessage?{errorMessage:e.errorMessage}:{}}}function et(e){return e.status==="queued"||e.status==="running"}function ze(e){const n=e?.trim().toLocaleLowerCase().replaceAll("-","_");if(!n)return"unknown";if(n==="queued"||n==="pending"||n==="created"){return"queued"}if(n==="running"||n==="started"||n==="active"||n==="busy"||n==="processing"||n==="in_progress"){return"running"}if(n==="finished"||n==="completed"||n==="succeeded"||n==="success"){return"completed"}if(n==="idle")return"completed";if(n==="error"||n==="failed"||n==="lost")return"failed";if(n==="aborted"||n==="interrupted"||n==="cancelled"||n==="canceled"||n==="stopped"){return"stopped"}return"unknown"}function pe(e,n){if(typeof n==="number"&&Number.isFinite(n))return{[e]:n};if(typeof n!=="string")return{};const t=Number(n);if(Number.isFinite(t))return{[e]:t};const r=Date.parse(n);return Number.isFinite(r)?{[e]:r}:{}}var tt="mavis";var j=64*1024;var We=400;function he(e){const n=en(e.toolName);const t=k(e.input);if(!n)return void 0;const r=Xe(e.status,e.error);const o=nn(n)?He(t??{},e.output):tn(n)?t?Je(t):[]:[];if(o.length===0)return void 0;return{schemaVersion:1,state:r,blocks:o}}function He(e,n){const t=S(e,["path","filePath","file_path"]);const r=qe(n);if(r){return[r.omitted===void 0?ye(t,r.diff):Ke(t,r.diff,r.omitted)]}return $e(e).map(({oldText:o,newText:i})=>{const s=[...o.split("\n").map(a=>`- ${a}`),...i.split("\n").map(a=>`+ ${a}`)].join("\n");return ye(t,s)})}function Je(e){const n=S(e,["path","filePath","file_path"]);const t=S(e,["content","fileContent","file_content"]);if(t===void 0)return[];const r=E(t);if(t.includes("\0")){return[{kind:"summary",...n?{path:n}:{},message:"Binary content cannot be previewed safely.",reason:"binary",byteCount:r}]}if(r>j){return[{kind:"summary",...n?{path:n}:{},message:`File preview omitted because it is ${sn(r)}.`,reason:"too-large",byteCount:r}]}return[{kind:"file",...n?{path:n}:{},content:t,lineCount:t.split("\n").length,truncated:false}]}function ye(e,n){const t=n.split("\n");const r=E(n);const o=t.slice(0,We);const i=r>j;let s=o.join("\n");if(i)s=on(s,j);const a=Math.max(0,t.length-s.split("\n").length);return{kind:"diff",...e?{path:e}:{},diff:s,addedLines:Se(t,"+"),removedLines:Se(t,"-"),truncated:a>0||i,...a>0?{omittedLines:a}:{}}}function Ke(e,n,t){return{kind:"summary",...e?{path:e}:{},message:n,reason:t==="timeout"?"unavailable":"too-large"}}function qe(e){const n=k(e);if(!n)return void 0;const t=[n,k(n.result),k(n.output)].filter(r=>r!==void 0);for(const r of t){const o=k(r.details);const i=o?S(o,["diff","previewDiff","preview_diff"]):void 0;if(i){const s=o?S(o,["diffOmitted","diff_omitted"]):void 0;return s===void 0?{diff:i}:{diff:i,omitted:s}}}return void 0}function $e(e){const n=rn(e.edits);const t=(n??[]).flatMap(i=>{const s=k(i);const a=s?S(s,["oldText","old_text"]):void 0;const d=s?S(s,["newText","new_text"]):void 0;return a!==void 0&&d!==void 0?[{oldText:a,newText:d}]:[]});const r=S(e,["oldText","old_text"]);const o=S(e,["newText","new_text"]);if(r!==void 0&&o!==void 0){t.push({oldText:r,newText:o})}return t}function Xe(e,n){if(Ze(n)||Qe(e))return"not-applied";return Ye(e)?"applied":"proposed"}function Ye(e){return e===2||e==="2"||e==="completed"||e==="complete"||e==="done"||e==="finished"||e==="succeeded"||e==="success"}function Qe(e){return e===3||e==="3"||e==="failed"||e==="error"}function Ze(e){return e!==void 0&&e!==null&&e!==""}function en(e){const n=e?.trim().toLocaleLowerCase().replace(/[^a-z0-9]/gu,"");return n||void 0}function nn(e){return e==="edit"||e==="editfile"||e==="replace"}function tn(e){return e==="write"||e==="writefile"||e==="createfile"}function k(e){const n=we(e);return n!==null&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function rn(e){const n=we(e);return Array.isArray(n)?n:void 0}function we(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return void 0}}function S(e,n){for(const t of n){const r=e[t];if(typeof r==="string")return r}return void 0}function Se(e,n){return e.filter(t=>t.startsWith(n)&&!t.startsWith(n.repeat(3))).length}function E(e){return new TextEncoder().encode(e).byteLength}function on(e,n){if(E(e)<=n)return e;let t=0;let r=e.length;while(t<r){const o=Math.ceil((t+r)/2);if(E(e.slice(0,o))<=n)t=o;else r=o-1}return e.slice(0,t)}function sn(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(e<10*1024?1:0)} KiB`}var an=2;var dn=6;var un=10;var cn=3;var ln=4;var fn=5;var mn="assistant_message_discarded";function st(e,n){const t=e.dataJson?.trim();if(!t)return void 0;if(t==="[DONE]")return Te({type:"done",turnId:n},e);let r;try{r=JSON.parse(t)}catch{return void 0}const o=c(r);if(!o)return void 0;const i=u(o,["turn_id","turnId"])??n;const s=o.type;let a;if(s===un||s==="heartbeat"){a={type:"heartbeat",turnId:i}}else if(s===an||s==="agent_message"){const d=c(o.agent_message)??c(o.agentMessage);a=d?gn(d,i):void 0}else if(pn(o)){const d=c(o.agent_message_chunk)??c(o.agentMessageChunk);a=d?yn(d,i):void 0}else if(s==="error"){a={type:"error",message:u(o,["error","message"])??"Runtime stream failed",turnId:i}}else if(s==="session_status"){a=hn(o,i)}else if(s===cn||s===ln){a=Tn(o,i)}else if(s===fn){a=wn(o,i)}else if(s==="resume_overflow"){a={type:"resync-required",turnId:i}}else if(typeof s==="string"){const d={...o};delete d.type;delete d.turnId;a={type:"generic",eventType:s,data:d,turnId:i}}return a?Te(a,e):void 0}function pn(e){return e.type===dn&&("agent_message_chunk"in e||"agentMessageChunk"in e)||e.type==="agent_message_chunk"}function gn(e,n){const t=Sn(e,n);if(t)return t;const r=ke(e,n);if(r.role==="unknown")return void 0;if(r.role==="assistant"&&r.finishReason==="error"){return{type:"error",message:r.content?.trim()||"Runtime stream failed",turnId:n}}return{type:"message",message:r}}function yn(e,n){const t=ke(e,n);if(t.role!=="assistant")return void 0;return p({type:"delta",messageId:t.id,turnId:t.turnId??n,role:t.role,content:t.content,thinking:t.thinking,toolCalls:t.toolCalls,timestamp:t.timestamp,chunkIndex:f(e,["chunk_index","chunkIndex"]),finish:e.finish===true?true:void 0})}function Sn(e,n){const t=u(e,["msg_content","msgContent","content"]);if(!t)return void 0;let r;try{r=c(JSON.parse(t))}catch{return void 0}const o=r?u(r,["eventType"]):void 0;if(!r||!o)return void 0;const i=f(e,["msg_type","msgType","message_type","messageType"])===3;if(!i&&!["session.spawned","communication.message","delegation.message","todo_updated"].includes(o)){return void 0}const s={...r};delete s.eventType;return p({type:"generic",eventType:o,data:s,turnId:u(e,["turn_id","turnId"])??n,messageId:u(e,["msg_id","msgId","id"]),timestamp:f(e,["timestamp"])})}function hn(e,n){const t=c(e.session_status)??{};const r=kn(u(t,["type","status"]));return r?p({type:"session-status",status:r,message:u(t,["message"]),turnId:n}):void 0}function wn(e,n){const t=c(c(e.payload)?.trace)??c(e.trace);if(!t||u(t,["phase"])!==mn)return void 0;let r;const o=u(t,["attrs_json","attrsJson"]);if(o!==void 0){try{r=c(JSON.parse(o))}catch{r=void 0}}r??=c(t.attrs);const i=r?u(r,["message_id","messageId"]):void 0;if(!i)return void 0;return{type:"assistant-discarded",messageId:i,turnId:u(e,["turn_id","turnId"])??n}}function Tn(e,n){const t=c(e.payload)??{};const r=bn(f(t,["status"]));if(!r)return void 0;const o=c(t.error);return p({type:"session-status",status:r,message:u(o??t,["message","detail"]),turnId:n})}function kn(e){if(e==="idle"||e==="started"||e==="finished"||e==="error"||e==="aborted"||e==="interrupted"){return e}return void 0}function bn(e){if(e===1||e===2)return"started";if(e===3)return"idle";if(e===4)return"error";if(e===5)return"aborted";if(e===6)return"finished";return void 0}function Te(e,n){return n.cursor?{...e,cursor:n.cursor}:e}function ke(e,n){return In(c(e)??{},n)}function In(e,n){const t=u(e,["role"])==="compactionSummary";return p({id:u(e,["msg_id","msgId","id"]),turnId:u(e,["turn_id","turnId"])??n,role:t?"assistant":Bn(u(e,["role"]))??"unknown",kind:Mn(u(e,["kind"]))??(t?"compaction":void 0),customType:u(e,["customType","custom_type","eventType","event_type"]),source:u(e,["source"]),origin:z(e.origin??e.originJson??e.origin_json),error:u(e,["error"]),tokensBefore:f(e,["tokensBefore","tokens_before"]),tokensAfter:f(e,["tokensAfter","tokens_after"]),content:u(e,["msg_content","msgContent","content"])??(t?u(e,["summary"]):void 0),editContent:u(e,["editContent"]),thinking:u(e,["thinking_content","thinkingContent","thinking"]),thinkingDurationMs:f(e,["thinking_duration_ms","thinkingDurationMs"]),toolCalls:xn(be(P(e,["tool_calls","toolCalls"])),On(e.rawJson??e.raw_json)),toolResult:Rn(c(e.toolResult??e.tool_result)),parts:En(P(e,["parts"])),attachments:Pn(P(e,["attachments"])),timestamp:f(e,["timestamp","createdAt","created_at"]),finishReason:u(e,["finish_reason","finishReason"]),usage:vn(c(e.usage)),actions:_n(c(e.actions))})}function _n(e){if(!e)return void 0;const n=p({fork:U(e,["fork"]),rewind:U(e,["rewind"])});return Object.keys(n).length>0?n:void 0}function vn(e){if(!e)return void 0;const n=p({totalTokens:f(e,["total_tokens","totalTokens"]),inputTokens:f(e,["input_tokens","inputTokens"]),outputTokens:f(e,["output_tokens","outputTokens"]),reasoningTokens:f(e,["reasoning","reasoning_tokens","reasoningTokens"]),requestDurationMs:f(e,["request_duration_ms","requestDurationMs"]),decodeDurationMs:f(e,["decode_duration_ms","decodeDurationMs"]),cacheReadTokens:f(e,["cache_read","cacheRead","cache_read_tokens"]),cacheWriteTokens:f(e,["cache_write","cacheWrite","cache_write_tokens"])});return Object.keys(n).length>0?n:void 0}function Rn(e){if(!e)return void 0;const n=u(e,["toolCallId","tool_call_id"]);if(!n)return void 0;const t=c(e.details);const r=t?p({taskId:u(t,["taskId","task_id"]),subSessionId:u(t,["subSessionId","sub_session_id"]),subTurnId:u(t,["subTurnId","sub_turn_id"])}):void 0;return p({toolCallId:n,toolName:u(e,["toolName","tool_name"]),isError:U(e,["isError","is_error"]),details:r&&Object.keys(r).length>0?r:void 0})}function Mn(e){if(e==="preamble"||e==="final"||e==="compaction_start"||e==="compaction"||e==="compaction_failed"||e==="review_start"||e==="review_result"||e==="review_failed"||e==="review_aborted"||e==="review_interrupted"){return e}return void 0}function at(e){if(e.parts?.length)return[...e.parts];return[...e.thinking?.trim()?[p({type:"thinking",content:e.thinking,durationMs:e.thinkingDurationMs})]:[],...e.content?.trim()?[{type:"text",content:e.content}]:[],...(e.toolCalls??[]).map(n=>({type:"tool",toolCall:n}))]}function En(e){if(!e)return void 0;const n=e.flatMap(t=>{const r=c(t);if(!r)return[];const o=u(r,["id","part_id","partId"]);const i=u(r,["type","kind"]);if(i==="thinking"||i==="cognitive_text"){const s=u(r,["content","text","thinking"]);if(s===void 0)return[];return[p({id:o,type:"thinking",content:s,durationMs:f(r,["durationMs","duration_ms"])})]}if(i==="text"){const s=u(r,["content","text"]);return s===void 0?[]:[p({id:o,type:"text",content:s})]}if(i==="tool"||i==="tool_call"||i==="toolCall"){const s=c(r.toolCall??r.tool_call)??r;const[a]=be([s])??[];return a?[p({id:o,type:"tool",toolCall:a})]:[]}return[]});return n.length>0?n:void 0}function Pn(e){if(!e)return void 0;const n=e.flatMap(t=>{const r=c(t);if(!r)return[];const o=c(r.meta)??r;const i=c(r.local);const s=c(r.cloud);const a=u(o,["mimeType","mime_type"])??u(r,["mimeType","mime_type"])??"application/octet-stream";const d=u(o,["attachmentType","attachment_type","type"])??u(r,["attachmentType","attachment_type","type"]);return[p({type:d==="image"||a.startsWith("image/")?"image":"file",fileName:u(o,["fileName","file_name"])??u(r,["fileName","file_name"])??"attachment",mimeType:a,sizeBytes:f(o,["sizeBytes","size_bytes"]),filePath:(i?u(i,["filePath","file_path"]):void 0)??u(r,["filePath","file_path"]),assetId:i?u(i,["assetId","asset_id"]):void 0,previewUrl:u(r,["previewUrl","preview_url"])??(s?u(s,["url"]):void 0)})]});return n.length>0?n:void 0}function be(e){if(!e)return void 0;const n=e.flatMap(t=>{const r=c(t);if(!r)return[];const o=u(r,["tool_name","tool_call_name","toolName","name"]);if(!o)return[];const i=p({id:u(r,["tool_call_id","toolCallId","id"]),name:o,status:u(r,["tool_call_status","toolCallStatus","status"])??f(r,["tool_call_status","toolCallStatus","status"]),input:z(V(r,["tool_call_args","toolCallArgs","args","arguments","input"])),output:z(V(r,["tool_call_result_data","toolCallResultData","tool_call_result","toolCallResult","result","output"])),error:V(r,["tool_call_error","toolCallError","error"]),parentToolCallId:Ie(r),durationMs:f(r,["tool_call_duration_ms","toolCallDurationMs","durationMs","duration_ms"]),permission:Nn(r.permission)});const s=he({toolName:i.name,status:i.status,input:i.input,output:i.output,error:i.error});return[{...i,...s?{structuredPreview:s}:{}}]});return n.length>0?n:void 0}function Ie(e){const n=u(e,["parent_tool_call_id","parentToolCallId"]);return n!==void 0&&n.trim().length>0?n:void 0}var An=new Set(["classifier","rule","mode","hook","user"]);var Cn=new Set(["builtin","session","agent","global"]);var Dn=new Set(["default","auto","bypassPermissions","acceptEdits","dontAsk","off"]);function Nn(e){if(!e||typeof e!=="object"||Array.isArray(e))return void 0;const n=e;const t=n.decision;const r=n.decidedBy;const o=n.ruleKind;const i=n.mode;const s=n.reason;if(t!=="allow"&&t!=="deny")return void 0;if(typeof r!=="string"||!An.has(r))return void 0;if(o!==null&&(typeof o!=="string"||!Cn.has(o))){return void 0}if(typeof i!=="string"||!Dn.has(i))return void 0;if(typeof s!=="string"||s.trim().length===0)return void 0;return{decision:t,decidedBy:r,ruleKind:o,mode:i,reason:s}}function xn(e,n){if(!e||!n?.size)return e;return e.map(t=>{if(t.parentToolCallId!==void 0||t.id===void 0)return t;const r=n.get(t.id);return r===void 0?t:{...t,parentToolCallId:r}})}function On(e){if(typeof e!=="string"||!e.trim())return void 0;let n;try{n=JSON.parse(e)}catch{return void 0}const t=c(n);const r=t?P(t,["tool_calls","toolCalls"]):void 0;if(!r)return void 0;const o=new Map;r.forEach(i=>{const s=c(i);if(!s)return;const a=u(s,["tool_call_id","toolCallId","id"]);const d=Ie(s);if(a!==void 0&&d!==void 0)o.set(a,d)});return o.size>0?o:void 0}function Bn(e){if(e==="user"||e==="assistant"||e==="system")return e;return e===void 0?void 0:"unknown"}function c(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function u(e,n){for(const t of n){if(typeof e[t]==="string")return e[t]}return void 0}function f(e,n){for(const t of n){const r=e[t];if(typeof r==="number"&&Number.isFinite(r))return r;if(typeof r==="string"&&r.trim()){const o=Number(r);if(Number.isFinite(o))return o}}return void 0}function U(e,n){for(const t of n){if(typeof e[t]==="boolean")return e[t]}return void 0}function P(e,n){for(const t of n){if(Array.isArray(e[t]))return e[t]}return void 0}function V(e,n){for(const t of n){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}return void 0}function z(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function p(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}var A=["default","auto","bypassPermissions"];var Fn={default:"Ask",auto:"Auto",bypassPermissions:"Full access",off:"Off"};var Ln={default:"ASK",auto:"AUTO",bypassPermissions:"FULL",off:"OFF"};function ut(e){return A.find(n=>n===e)}function ct(e){return Fn[e]}function lt(e){return Ln[e]}function ft(e){return e==="bypassPermissions"}function mt(e){return typeof e==="boolean"?e:void 0}function pt(e){if(e===void 0)return"Managed by host";return e?"Recoverable":"Permanent"}function gt(e){if(e==="off")return"default";const n=A.indexOf(e);return A[(n+1)%A.length]}export{Ve as a,Ue as b,Yn as c,Qn as d,Zn as e,et as f,he as g,st as h,ke as i,at as j,A as k,ut as l,ct as m,lt as n,ft as o,mt as p,pt as q,gt as r,tt as s,R as t,M as u,qn as v,$n as w};
2
+ import{a as Q,b as Z,c as ee,d as ne,e as de}from"./chunk-RZDVNG5Z.js";import{G as te,H as re,K as oe,O as ie,P as F,Q as L,R as se,S as ae}from"./chunk-O5EROATK.js";import{V as I,W as _,Wa as q,ab as $,jb as X}from"./chunk-XWNCITOR.js";import{h as J,i as B,j as K}from"./chunk-ISBSRM3S.js";import{a as Y}from"./chunk-VAARXN34.js";import{spawn as _e}from"node:child_process";import{randomUUID as ve}from"node:crypto";import Re from"node:fs";import fe from"node:path";import y from"node:process";var v=Y("mcode:rpc");function Me(e){return e.startsWith("MCODE_")||e.startsWith("MINIMAX_")||e.startsWith("__MAVIS_")}function Ee(e=y.env,n=y.cwd()){const t={};for(const[r,o]of Object.entries(e)){if(o===void 0||Me(r))continue;t[r]=o}return{cwd:n,env:t}}var Pe=2e4;var Ae=200;function Ce(e){const n=e.environment??y.env;const t=e.seams??{};const r=t.sleep??(s=>new Promise(a=>setTimeout(a,s)));const o=t.spawnDaemon??(({argv:s,env:a,logFd:d})=>{const l=_e(s[0],s.slice(1),{detached:true,stdio:["ignore",d,d],env:a});l.unref();return l});const i=t.daemonAlive??(async()=>{const s=F(e.targets.controlRoot);if(s===void 0)return false;const a=L(e.targets.controlRoot);const d=await de(s.socketPath,{...a!==void 0?{token:a}:{},dataDir:s.dataDir,env:{region:I(),buildEnv:_()},timeoutMs:1e3});return d.ok});return async()=>{let s;try{s=oe(fe.join(e.targets.controlRoot,te))}catch(a){if(a instanceof re)return false;throw a}try{if(await i())return false;const a=y.argv[1];if(!a)throw new Error("Cannot auto-spawn mcoded: no entry script (process.argv[1]).");const d=e.targets.profile||null;const l={...n,MINIMAX_DATA_DIR:e.targets.dataDir,MAVIS_REGION:I(),MAVIS_BUILD_ENV:_(),...d!==null?{[B]:d}:{}};if(d===null){delete l[B];delete l[K]}const m=l["MCODE_SERVER_MODE"]?.trim().toLowerCase();if(m===void 0||m===""||m==="off"){l["MCODE_SERVER_MODE"]="auto"}X(e.targets.controlRoot);const g=ae(e.targets.controlRoot,l);try{o({argv:[y.execPath,a,"daemon","run","--data-dir",e.targets.dataDir,"--profile",d??J],env:g.childEnv,logFd:g.fd})}finally{Re.closeSync(g.fd)}const h=Date.now()+Pe;while(!await i()){if(Date.now()>h)return true;await r(Ae)}return true}finally{s.release()}}}var G=class{client;remote;goalEnabled=false;askSessions=new Map;attachedSessions=new Set;reattachReadyMs;reattachSleep;constructor(n,t,r={}){this.client=n;this.remote=t;this.reattachReadyMs=r.reattachReadyMs??xe;this.reattachSleep=r.reattachSleep??me;this.client.onReconnected(()=>{void this.refreshGoalEnabled();void this.refreshSnapshot()})}async refreshGoalEnabled(){try{this.goalEnabled=await this.remote.isGoalEnabled()}catch{this.goalEnabled=false}}isGoalEnabled(){return this.goalEnabled}async sendMessage(n,t,r){t?.signal?.throwIfAborted();const o=T(n);await this.attachBestEffort(o);const i=await this.openTurnStream("sendMessage",r?[n,r]:[n]);if(!i.ok)return i;return{ok:true,source:ce(i.source,t?.signal,{sessionId:o??"",...typeof n.turnId==="string"?{turnId:n.turnId}:{},readyMs:this.reattachReadyMs,sleep:this.reattachSleep,resume:(s,a)=>this.reopenTurnStream(o,s,a),waitForReady:s=>this.waitForClientReady(s)})}}async resumeSession(n,t){t?.signal?.throwIfAborted();const r=T(n);await this.attachBestEffort(r);const o=await this.openTurnStream("resumeSession",[n]);if(!o.ok)return o;return{ok:true,source:ce(o.source,t?.signal,{sessionId:r??"",readyMs:this.reattachReadyMs,sleep:this.reattachSleep,resume:(i,s)=>this.reopenTurnStream(r,i,s),waitForReady:i=>this.waitForClientReady(i)})}}watchEvents(n){const t=this.client.subscribe({scope:"catalog+attached"});const r=this.askSessions;const o=a=>this.attachDelegatedChild(a);const i=()=>this.refreshSnapshotSoon();const s=(async function*(){const a=new Set;const d=l=>{const m=l.payload;if(l.type==="permission.resolved")a.delete(m.requestId??"");if(l.type!=="permission.ask")return true;const g=m.requestId;if(g&&a.has(g))return false;if(g)a.add(g);return true};try{for await(const l of t.events){if(!d(l.event))continue;if(De(r,l.event))i();yield l.event;for(const m of await o(l.event)){if(d(m))yield m}}}finally{if(n?.aborted)t.stop()}})();n?.addEventListener("abort",()=>t.stop(),{once:true});void t.gapped.then(()=>{void this.refreshSnapshot();for(const a of this.attachedSessions)void this.attachBestEffort(a)});return{events:s,gapped:t.gapped,stop:()=>t.stop(),[Symbol.asyncIterator]:()=>s}}async listPendingPermissions(n){const t=await this.remote.listPendingPermissions(n);this.noteSnapshotRequests(t.requests??[]);return t}async getSession(n){await this.attachBestEffort(T(n));return await this.remote.getSession(n)}async getMessages(n){await this.attachBestEffort(T(n));return await this.remote.getMessages(n)}async getSessionTree(n){await this.attachBestEffort(T(n));return await this.remote.getSessionTree(n)}async listSessionInputSummaries(n){await this.attachBestEffort(T(n));return await this.remote.listSessionInputSummaries(n)}async createSession(n){const t=await this.remote.createSession(n);const r=t.session?.id;if(typeof r==="string"&&r.length>0)await this.attachBestEffort(r);return t}async replyPermission(n){const t=this.askSessions.get(n.requestId);return await this.remote.replyPermission({...n,...t!==void 0?{sessionId:t}:{}})}get delegated(){return this.remote}noteSnapshotRequests(n){for(const t of n)Ne(this.askSessions,t)}refreshSnapshotInFlight;refreshSnapshotSoon(){this.refreshSnapshotInFlight??=(async()=>{try{await this.listPendingPermissions({})}catch{}finally{this.refreshSnapshotInFlight=void 0}})()}async refreshSnapshot(){try{await this.listPendingPermissions({})}catch{}}async attachDelegatedChild(n){if(n.type!=="session.created")return[];const{sessionId:t,parentSessionId:r}=n.payload;if(!r||!this.attachedSessions.has(r))return[];await this.attachBestEffort(t);try{const o=await this.listPendingPermissions({});return(o.requests??[]).filter(i=>i.sessionId===t&&typeof i.requestId==="string").map(i=>({type:"permission.ask",timestamp:Date.now(),source:"local-runtime",payload:{...i,requestId:i.requestId,sessionId:t,agentName:typeof i.agentName==="string"?i.agentName:"",toolName:typeof i.toolName==="string"?i.toolName:"",ruleContents:Array.isArray(i.ruleContents)?i.ruleContents:[],reason:typeof i.reason==="string"?i.reason:"",allowAlwaysSupported:i.allowAlwaysSupported===true,createdAt:typeof i.createdAt==="number"?i.createdAt:Date.now()}}))}catch{return[]}}async attachBestEffort(n){if(n===void 0)return;try{await this.client.sessionAttach(n,"owner",Ee());this.attachedSessions.add(n)}catch{}}async reopenTurnStream(n,t,r){if(n===void 0)throw new Error("cannot reattach a turn without a session id");const o={id:n,...t!==void 0?{afterCursor:t}:{},...r!==void 0?{afterMsgId:r}:{}};const i=await this.openTurnStream("resumeSession",[o]);if(!i.ok){throw new Error(`resumeSession refused (${i.status}): ${i.body.message??"unknown refusal"}`)}return i.source}waitForClientReady(n){if(this.client.connectionState==="ready")return Promise.resolve();if(n<=0){return Promise.reject(new Error(`mcoded client is ${this.client.connectionState}, not ready`))}return new Promise((t,r)=>{const o=setTimeout(()=>{i();r(new Error(`mcoded client did not become ready within ${n}ms (state: ${this.client.connectionState})`))},n);const i=this.client.onStateChange(s=>{if(s!=="ready"&&s!=="closed")return;clearTimeout(o);i();if(s==="ready")t();else r(new Error("mcoded client closed while waiting for the reconnect"))})})}async openTurnStream(n,t){try{return{ok:true,source:await this.client.openStream(n,t)}}catch(r){if(r instanceof Z&&r.data!==void 0){const o=r.data;if(typeof o.status==="number"){return{ok:false,status:o.status,body:o.body}}}throw r}}};function T(e){const n=e.id??e.sessionId;return typeof n==="string"&&n.length>0?n:void 0}function De(e,n){const t=n.type;if(t!=="permission.ask"&&t!=="questionnaire.ask")return false;const r=n.payload??{};const o=r["requestId"];const i=r["sessionId"];if(typeof o==="string"&&typeof i==="string")e.set(o,i);return true}function Ne(e,n){if(typeof n.requestId==="string"&&typeof n.sessionId==="string"){e.set(n.requestId,n.sessionId)}}var xe=6e4;var ue=3;var Oe=[1e3,2e3,4e3];var R=class extends Error{};var M=class extends Error{sessionId;turnId;reason;attempts;cause;constructor(n){super(`turn stream detached (reason: ${n.reason}, attempts: ${n.attempts})`);this.name="TurnStreamDetached";this.sessionId=n.sessionId;this.turnId=n.turnId;this.reason=n.reason;this.attempts=n.attempts}};function ce(e,n,t){let r=false;let o=e;const i=()=>{if(r||n===void 0)return;r=true;if(n.reason instanceof R)o.detach();else void o.abort().catch(()=>void 0)};n?.addEventListener("abort",i,{once:true});const s=t.sleep??me;const a=(async function*(){try{let d=e;let l;let m;let g;let h=0;let C=0;let W=0;const H=Date.now();v.info("turn-stream-open",{sessionId:t.sessionId,turnId:t.turnId,streamId:d.streamId});for(;;){let D=false;for await(const N of d.frames){n?.throwIfAborted();const x=Be(N);if(x.messageId)m=x.messageId;if(x.resync)D=true;if(D)continue;const b=Fe(N);if(b!==void 0&&l!==void 0&&Number(b)<=Number(l)){C+=1;continue}if(b!==void 0)l=b;h+=1;const O=Date.now();if(O-W>=5e3){W=O;v.info("turn-stream-progress",{sessionId:t.sessionId,turnId:t.turnId,streamId:d.streamId,frames:h,skipped:C,cursor:l,elapsedMs:O-H})}yield N}const w=await d.ended;if(n?.reason instanceof R)return;v.info("turn-stream-ended",{sessionId:t.sessionId,turnId:t.turnId,streamId:d.streamId,reason:w.reason,resumable:w.resumable,frames:h,skipped:C,cursor:l,elapsedMs:Date.now()-H});if(D){if(!m||g===m){throw new M({sessionId:t.sessionId,turnId:t.turnId,reason:"resync-durable-anchor-unavailable",attempts:1})}g=m;l=void 0;d=await le(t,n,void 0,"resync-required",s,m);o=d;continue}if(w.reason==="done"||w.reason==="aborted")return;if(w.resumable!==true)return;d=await le(t,n,l,w.reason,s);o=d}}finally{n?.removeEventListener("abort",i);if(n?.aborted&&!r)i()}})();return a}async function le(e,n,t,r,o,i){let s;for(let a=1;a<=ue;a+=1){v.warn("turn-stream-detached",{sessionId:e.sessionId,reason:r,attempt:a});try{n?.throwIfAborted();await e.waitForReady(e.readyMs);return await e.resume(t,i)}catch(d){s=d;if(n?.aborted)throw d;await o(Oe[a-1]??0,n)}}throw new M({sessionId:e.sessionId,...e.turnId!==void 0?{turnId:e.turnId}:{},reason:r,attempts:ue})}function Be(e){const n=e.dataJson;if(!n||!n.includes('"agent_message"')&&!n.includes('"resume_overflow"'))return{};try{const t=JSON.parse(n);if(t?.type==="resume_overflow")return{resync:true};const r=t?.agent_message?.msg_id;return typeof r==="string"&&r?{messageId:r}:{}}catch{return{}}}function Fe(e){const n=e.cursor;return typeof n==="string"&&n.length>0?n:void 0}function me(e,n){return new Promise(t=>{if(n?.aborted||e<=0){t();return}const r=setTimeout(i,e);const o=()=>i();n?.addEventListener("abort",o,{once:true});function i(){clearTimeout(r);n?.removeEventListener("abort",o);t()}})}function Le(e,n={}){const t=new ne(e);const r=new G(e,t,n);const o=new Proxy(r,{get(i,s,a){if(s in i)return Reflect.get(i,s,a);const d=Reflect.get(t,s,a);return typeof d==="function"?d.bind(t):d}});return{cliService:o,tuiCli:r}}async function qn(e,n={}){const t=e.daemonTargets??se({profile:e.profile,dataDir:e.dataDir,homeDir:e.homeDir??e.environment?.["HOME"],env:e.environment??y.env});const r=n.clientInstanceId??ve();const o={tokenGetter:()=>{try{return L(t.controlRoot)}catch{return void 0}},dataDir:t.dataDir,env:{region:I(),buildEnv:_()},clientInstanceId:r,promptMode:e.promptMode??"tui",client:{kind:e.clientKind??"tui",pid:y.pid,...y.env["MCODE_BUILD_ID"]?{buildId:y.env["MCODE_BUILD_ID"]}:{},cwd:y.cwd()}};const i=new Q({logPath:fe.join(t.controlRoot,ie,"mcoded.log")});const s=Ce({targets:t,...e.environment?{environment:e.environment}:{},...n.spawnSeams?{seams:n.spawnSeams}:{}});const a={socketPath:F(t.controlRoot)?.socketPath??q(t.controlRoot),handshake:o,...e.autoSpawn===false?{}:{spawn:s},crashLoop:i,...e.readyTimeoutMs!==void 0?{readyTimeoutMs:e.readyTimeoutMs}:{}};const d=new ee(a);const{cliService:l,tuiCli:m}=Le(d,e.reattachReadyMs!==void 0?{reattachReadyMs:e.reattachReadyMs}:{});const g=(async()=>{await d.connect();await m.refreshGoalEnabled()})();return{cliService:l,ready:g,apiHost:{close:async()=>{d.close()}},notifyAuthContextChanged:async()=>{await d.daemonAuthSync()},connectionState:()=>d.connectionState,onConnectionStateChange:h=>d.onStateChange(h),clientInstanceId:r,socketPath:a.socketPath}}function $n(e=y.env){return $(e)}var Ge=["local-task:","local-background-task:","team-plan:"];var je=new Set(["explore","worker","verifier"]);function ge(e){return e.sessionKind==="task"||Ge.some(n=>e.purpose?.startsWith(n))}function Ve(e){if(e.sessionType!=="branch"||!e.parentSessionId){return false}return ge(e)}function Ue(e){const n=e.agentName?.trim().toLocaleLowerCase();return n!==void 0&&je.has(n)}function Yn(e){return ge(e)||Ue(e)}function Qn(e,n){const t=[];const r=new Set;const o=new Set([n]);let i=true;while(i){i=false;for(const s of e){if(r.has(s.sessionId)||!Ve(s)||!o.has(s.parentSessionId)){continue}t.push(s);r.add(s.sessionId);o.add(s.sessionId);i=true}}return t}function Zn(e){return{sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.agentName?{agentName:e.agentName}:{},...e.title?{task:e.title}:{},status:ze(e.status),...pe("createdAtMs",e.createdAt),...pe("updatedAtMs",e.updatedAt),...e.errorMessage?{errorMessage:e.errorMessage}:{}}}function et(e){return e.status==="queued"||e.status==="running"}function ze(e){const n=e?.trim().toLocaleLowerCase().replaceAll("-","_");if(!n)return"unknown";if(n==="queued"||n==="pending"||n==="created"){return"queued"}if(n==="running"||n==="started"||n==="active"||n==="busy"||n==="processing"||n==="in_progress"){return"running"}if(n==="finished"||n==="completed"||n==="succeeded"||n==="success"){return"completed"}if(n==="idle")return"completed";if(n==="error"||n==="failed"||n==="lost")return"failed";if(n==="aborted"||n==="interrupted"||n==="cancelled"||n==="canceled"||n==="stopped"){return"stopped"}return"unknown"}function pe(e,n){if(typeof n==="number"&&Number.isFinite(n))return{[e]:n};if(typeof n!=="string")return{};const t=Number(n);if(Number.isFinite(t))return{[e]:t};const r=Date.parse(n);return Number.isFinite(r)?{[e]:r}:{}}var tt="mavis";var j=64*1024;var We=400;function he(e){const n=en(e.toolName);const t=k(e.input);if(!n)return void 0;const r=Xe(e.status,e.error);const o=nn(n)?He(t??{},e.output):tn(n)?t?Je(t):[]:[];if(o.length===0)return void 0;return{schemaVersion:1,state:r,blocks:o}}function He(e,n){const t=S(e,["path","filePath","file_path"]);const r=qe(n);if(r){return[r.omitted===void 0?ye(t,r.diff):Ke(t,r.diff,r.omitted)]}return $e(e).map(({oldText:o,newText:i})=>{const s=[...o.split("\n").map(a=>`- ${a}`),...i.split("\n").map(a=>`+ ${a}`)].join("\n");return ye(t,s)})}function Je(e){const n=S(e,["path","filePath","file_path"]);const t=S(e,["content","fileContent","file_content"]);if(t===void 0)return[];const r=E(t);if(t.includes("\0")){return[{kind:"summary",...n?{path:n}:{},message:"Binary content cannot be previewed safely.",reason:"binary",byteCount:r}]}if(r>j){return[{kind:"summary",...n?{path:n}:{},message:`File preview omitted because it is ${sn(r)}.`,reason:"too-large",byteCount:r}]}return[{kind:"file",...n?{path:n}:{},content:t,lineCount:t.split("\n").length,truncated:false}]}function ye(e,n){const t=n.split("\n");const r=E(n);const o=t.slice(0,We);const i=r>j;let s=o.join("\n");if(i)s=on(s,j);const a=Math.max(0,t.length-s.split("\n").length);return{kind:"diff",...e?{path:e}:{},diff:s,addedLines:Se(t,"+"),removedLines:Se(t,"-"),truncated:a>0||i,...a>0?{omittedLines:a}:{}}}function Ke(e,n,t){return{kind:"summary",...e?{path:e}:{},message:n,reason:t==="timeout"?"unavailable":"too-large"}}function qe(e){const n=k(e);if(!n)return void 0;const t=[n,k(n.result),k(n.output)].filter(r=>r!==void 0);for(const r of t){const o=k(r.details);const i=o?S(o,["diff","previewDiff","preview_diff"]):void 0;if(i){const s=o?S(o,["diffOmitted","diff_omitted"]):void 0;return s===void 0?{diff:i}:{diff:i,omitted:s}}}return void 0}function $e(e){const n=rn(e.edits);const t=(n??[]).flatMap(i=>{const s=k(i);const a=s?S(s,["oldText","old_text"]):void 0;const d=s?S(s,["newText","new_text"]):void 0;return a!==void 0&&d!==void 0?[{oldText:a,newText:d}]:[]});const r=S(e,["oldText","old_text"]);const o=S(e,["newText","new_text"]);if(r!==void 0&&o!==void 0){t.push({oldText:r,newText:o})}return t}function Xe(e,n){if(Ze(n)||Qe(e))return"not-applied";return Ye(e)?"applied":"proposed"}function Ye(e){return e===2||e==="2"||e==="completed"||e==="complete"||e==="done"||e==="finished"||e==="succeeded"||e==="success"}function Qe(e){return e===3||e==="3"||e==="failed"||e==="error"}function Ze(e){return e!==void 0&&e!==null&&e!==""}function en(e){const n=e?.trim().toLocaleLowerCase().replace(/[^a-z0-9]/gu,"");return n||void 0}function nn(e){return e==="edit"||e==="editfile"||e==="replace"}function tn(e){return e==="write"||e==="writefile"||e==="createfile"}function k(e){const n=we(e);return n!==null&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function rn(e){const n=we(e);return Array.isArray(n)?n:void 0}function we(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return void 0}}function S(e,n){for(const t of n){const r=e[t];if(typeof r==="string")return r}return void 0}function Se(e,n){return e.filter(t=>t.startsWith(n)&&!t.startsWith(n.repeat(3))).length}function E(e){return new TextEncoder().encode(e).byteLength}function on(e,n){if(E(e)<=n)return e;let t=0;let r=e.length;while(t<r){const o=Math.ceil((t+r)/2);if(E(e.slice(0,o))<=n)t=o;else r=o-1}return e.slice(0,t)}function sn(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(e<10*1024?1:0)} KiB`}var an=2;var dn=6;var un=10;var cn=3;var ln=4;var fn=5;var mn="assistant_message_discarded";function st(e,n){const t=e.dataJson?.trim();if(!t)return void 0;if(t==="[DONE]")return Te({type:"done",turnId:n},e);let r;try{r=JSON.parse(t)}catch{return void 0}const o=c(r);if(!o)return void 0;const i=u(o,["turn_id","turnId"])??n;const s=o.type;let a;if(s===un||s==="heartbeat"){a={type:"heartbeat",turnId:i}}else if(s===an||s==="agent_message"){const d=c(o.agent_message)??c(o.agentMessage);a=d?gn(d,i):void 0}else if(pn(o)){const d=c(o.agent_message_chunk)??c(o.agentMessageChunk);a=d?yn(d,i):void 0}else if(s==="error"){a={type:"error",message:u(o,["error","message"])??"Runtime stream failed",turnId:i}}else if(s==="session_status"){a=hn(o,i)}else if(s===cn||s===ln){a=Tn(o,i)}else if(s===fn){a=wn(o,i)}else if(s==="resume_overflow"){a={type:"resync-required",turnId:i}}else if(typeof s==="string"){const d={...o};delete d.type;delete d.turnId;a={type:"generic",eventType:s,data:d,turnId:i}}return a?Te(a,e):void 0}function pn(e){return e.type===dn&&("agent_message_chunk"in e||"agentMessageChunk"in e)||e.type==="agent_message_chunk"}function gn(e,n){const t=Sn(e,n);if(t)return t;const r=ke(e,n);if(r.role==="unknown")return void 0;if(r.role==="assistant"&&r.finishReason==="error"){return{type:"error",message:r.content?.trim()||"Runtime stream failed",turnId:n}}return{type:"message",message:r}}function yn(e,n){const t=ke(e,n);if(t.role!=="assistant")return void 0;return p({type:"delta",messageId:t.id,turnId:t.turnId??n,role:t.role,content:t.content,thinking:t.thinking,toolCalls:t.toolCalls,timestamp:t.timestamp,chunkIndex:f(e,["chunk_index","chunkIndex"]),finish:e.finish===true?true:void 0})}function Sn(e,n){const t=u(e,["msg_content","msgContent","content"]);if(!t)return void 0;let r;try{r=c(JSON.parse(t))}catch{return void 0}const o=r?u(r,["eventType"]):void 0;if(!r||!o)return void 0;const i=f(e,["msg_type","msgType","message_type","messageType"])===3;if(!i&&!["session.spawned","communication.message","delegation.message","todo_updated"].includes(o)){return void 0}const s={...r};delete s.eventType;return p({type:"generic",eventType:o,data:s,turnId:u(e,["turn_id","turnId"])??n,messageId:u(e,["msg_id","msgId","id"]),timestamp:f(e,["timestamp"])})}function hn(e,n){const t=c(e.session_status)??{};const r=kn(u(t,["type","status"]));return r?p({type:"session-status",status:r,message:u(t,["message"]),turnId:n}):void 0}function wn(e,n){const t=c(c(e.payload)?.trace)??c(e.trace);if(!t||u(t,["phase"])!==mn)return void 0;let r;const o=u(t,["attrs_json","attrsJson"]);if(o!==void 0){try{r=c(JSON.parse(o))}catch{r=void 0}}r??=c(t.attrs);const i=r?u(r,["message_id","messageId"]):void 0;if(!i)return void 0;return{type:"assistant-discarded",messageId:i,turnId:u(e,["turn_id","turnId"])??n}}function Tn(e,n){const t=c(e.payload)??{};const r=bn(f(t,["status"]));if(!r)return void 0;const o=c(t.error);return p({type:"session-status",status:r,message:u(o??t,["message","detail"]),turnId:n})}function kn(e){if(e==="idle"||e==="started"||e==="finished"||e==="error"||e==="aborted"||e==="interrupted"){return e}return void 0}function bn(e){if(e===1||e===2)return"started";if(e===3)return"idle";if(e===4)return"error";if(e===5)return"aborted";if(e===6)return"finished";return void 0}function Te(e,n){return n.cursor?{...e,cursor:n.cursor}:e}function ke(e,n){return In(c(e)??{},n)}function In(e,n){const t=u(e,["role"])==="compactionSummary";return p({id:u(e,["msg_id","msgId","id"]),turnId:u(e,["turn_id","turnId"])??n,role:t?"assistant":Bn(u(e,["role"]))??"unknown",kind:Mn(u(e,["kind"]))??(t?"compaction":void 0),customType:u(e,["customType","custom_type","eventType","event_type"]),source:u(e,["source"]),origin:z(e.origin??e.originJson??e.origin_json),error:u(e,["error"]),tokensBefore:f(e,["tokensBefore","tokens_before"]),tokensAfter:f(e,["tokensAfter","tokens_after"]),content:u(e,["msg_content","msgContent","content"])??(t?u(e,["summary"]):void 0),editContent:u(e,["editContent"]),thinking:u(e,["thinking_content","thinkingContent","thinking"]),thinkingDurationMs:f(e,["thinking_duration_ms","thinkingDurationMs"]),toolCalls:xn(be(P(e,["tool_calls","toolCalls"])),On(e.rawJson??e.raw_json)),toolResult:Rn(c(e.toolResult??e.tool_result)),parts:En(P(e,["parts"])),attachments:Pn(P(e,["attachments"])),timestamp:f(e,["timestamp","createdAt","created_at"]),finishReason:u(e,["finish_reason","finishReason"]),usage:vn(c(e.usage)),actions:_n(c(e.actions))})}function _n(e){if(!e)return void 0;const n=p({fork:U(e,["fork"]),rewind:U(e,["rewind"])});return Object.keys(n).length>0?n:void 0}function vn(e){if(!e)return void 0;const n=p({totalTokens:f(e,["total_tokens","totalTokens"]),inputTokens:f(e,["input_tokens","inputTokens"]),outputTokens:f(e,["output_tokens","outputTokens"]),reasoningTokens:f(e,["reasoning","reasoning_tokens","reasoningTokens"]),requestDurationMs:f(e,["request_duration_ms","requestDurationMs"]),decodeDurationMs:f(e,["decode_duration_ms","decodeDurationMs"]),cacheReadTokens:f(e,["cache_read","cacheRead","cache_read_tokens"]),cacheWriteTokens:f(e,["cache_write","cacheWrite","cache_write_tokens"])});return Object.keys(n).length>0?n:void 0}function Rn(e){if(!e)return void 0;const n=u(e,["toolCallId","tool_call_id"]);if(!n)return void 0;const t=c(e.details);const r=t?p({taskId:u(t,["taskId","task_id"]),subSessionId:u(t,["subSessionId","sub_session_id"]),subTurnId:u(t,["subTurnId","sub_turn_id"])}):void 0;return p({toolCallId:n,toolName:u(e,["toolName","tool_name"]),isError:U(e,["isError","is_error"]),details:r&&Object.keys(r).length>0?r:void 0})}function Mn(e){if(e==="preamble"||e==="final"||e==="compaction_start"||e==="compaction"||e==="compaction_failed"||e==="review_start"||e==="review_result"||e==="review_failed"||e==="review_aborted"||e==="review_interrupted"){return e}return void 0}function at(e){if(e.parts?.length)return[...e.parts];return[...e.thinking?.trim()?[p({type:"thinking",content:e.thinking,durationMs:e.thinkingDurationMs})]:[],...e.content?.trim()?[{type:"text",content:e.content}]:[],...(e.toolCalls??[]).map(n=>({type:"tool",toolCall:n}))]}function En(e){if(!e)return void 0;const n=e.flatMap(t=>{const r=c(t);if(!r)return[];const o=u(r,["id","part_id","partId"]);const i=u(r,["type","kind"]);if(i==="thinking"||i==="cognitive_text"){const s=u(r,["content","text","thinking"]);if(s===void 0)return[];return[p({id:o,type:"thinking",content:s,durationMs:f(r,["durationMs","duration_ms"])})]}if(i==="text"){const s=u(r,["content","text"]);return s===void 0?[]:[p({id:o,type:"text",content:s})]}if(i==="tool"||i==="tool_call"||i==="toolCall"){const s=c(r.toolCall??r.tool_call)??r;const[a]=be([s])??[];return a?[p({id:o,type:"tool",toolCall:a})]:[]}return[]});return n.length>0?n:void 0}function Pn(e){if(!e)return void 0;const n=e.flatMap(t=>{const r=c(t);if(!r)return[];const o=c(r.meta)??r;const i=c(r.local);const s=c(r.cloud);const a=u(o,["mimeType","mime_type"])??u(r,["mimeType","mime_type"])??"application/octet-stream";const d=u(o,["attachmentType","attachment_type","type"])??u(r,["attachmentType","attachment_type","type"]);return[p({type:d==="image"||a.startsWith("image/")?"image":"file",fileName:u(o,["fileName","file_name"])??u(r,["fileName","file_name"])??"attachment",mimeType:a,sizeBytes:f(o,["sizeBytes","size_bytes"]),filePath:(i?u(i,["filePath","file_path"]):void 0)??u(r,["filePath","file_path"]),assetId:i?u(i,["assetId","asset_id"]):void 0,previewUrl:u(r,["previewUrl","preview_url"])??(s?u(s,["url"]):void 0)})]});return n.length>0?n:void 0}function be(e){if(!e)return void 0;const n=e.flatMap(t=>{const r=c(t);if(!r)return[];const o=u(r,["tool_name","tool_call_name","toolName","name"]);if(!o)return[];const i=p({id:u(r,["tool_call_id","toolCallId","id"]),name:o,status:u(r,["tool_call_status","toolCallStatus","status"])??f(r,["tool_call_status","toolCallStatus","status"]),input:z(V(r,["tool_call_args","toolCallArgs","args","arguments","input"])),output:z(V(r,["tool_call_result_data","toolCallResultData","tool_call_result","toolCallResult","result","output"])),error:V(r,["tool_call_error","toolCallError","error"]),parentToolCallId:Ie(r),durationMs:f(r,["tool_call_duration_ms","toolCallDurationMs","durationMs","duration_ms"]),permission:Nn(r.permission)});const s=he({toolName:i.name,status:i.status,input:i.input,output:i.output,error:i.error});return[{...i,...s?{structuredPreview:s}:{}}]});return n.length>0?n:void 0}function Ie(e){const n=u(e,["parent_tool_call_id","parentToolCallId"]);return n!==void 0&&n.trim().length>0?n:void 0}var An=new Set(["classifier","rule","mode","hook","user"]);var Cn=new Set(["builtin","session","agent","global"]);var Dn=new Set(["default","auto","bypassPermissions","acceptEdits","dontAsk","off"]);function Nn(e){if(!e||typeof e!=="object"||Array.isArray(e))return void 0;const n=e;const t=n.decision;const r=n.decidedBy;const o=n.ruleKind;const i=n.mode;const s=n.reason;if(t!=="allow"&&t!=="deny")return void 0;if(typeof r!=="string"||!An.has(r))return void 0;if(o!==null&&(typeof o!=="string"||!Cn.has(o))){return void 0}if(typeof i!=="string"||!Dn.has(i))return void 0;if(typeof s!=="string"||s.trim().length===0)return void 0;return{decision:t,decidedBy:r,ruleKind:o,mode:i,reason:s}}function xn(e,n){if(!e||!n?.size)return e;return e.map(t=>{if(t.parentToolCallId!==void 0||t.id===void 0)return t;const r=n.get(t.id);return r===void 0?t:{...t,parentToolCallId:r}})}function On(e){if(typeof e!=="string"||!e.trim())return void 0;let n;try{n=JSON.parse(e)}catch{return void 0}const t=c(n);const r=t?P(t,["tool_calls","toolCalls"]):void 0;if(!r)return void 0;const o=new Map;r.forEach(i=>{const s=c(i);if(!s)return;const a=u(s,["tool_call_id","toolCallId","id"]);const d=Ie(s);if(a!==void 0&&d!==void 0)o.set(a,d)});return o.size>0?o:void 0}function Bn(e){if(e==="user"||e==="assistant"||e==="system")return e;return e===void 0?void 0:"unknown"}function c(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function u(e,n){for(const t of n){if(typeof e[t]==="string")return e[t]}return void 0}function f(e,n){for(const t of n){const r=e[t];if(typeof r==="number"&&Number.isFinite(r))return r;if(typeof r==="string"&&r.trim()){const o=Number(r);if(Number.isFinite(o))return o}}return void 0}function U(e,n){for(const t of n){if(typeof e[t]==="boolean")return e[t]}return void 0}function P(e,n){for(const t of n){if(Array.isArray(e[t]))return e[t]}return void 0}function V(e,n){for(const t of n){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}return void 0}function z(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function p(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}var A=["default","auto","bypassPermissions"];var Fn={default:"Ask",auto:"Auto",bypassPermissions:"Full access",off:"Off"};var Ln={default:"ASK",auto:"AUTO",bypassPermissions:"FULL",off:"OFF"};function ut(e){return A.find(n=>n===e)}function ct(e){return Fn[e]}function lt(e){return Ln[e]}function ft(e){return e==="bypassPermissions"}function mt(e){return typeof e==="boolean"?e:void 0}function pt(e){if(e===void 0)return"Managed by host";return e?"Recoverable":"Permanent"}function gt(e){if(e==="off")return"default";const n=A.indexOf(e);return A[(n+1)%A.length]}export{Ve as a,Ue as b,Yn as c,Qn as d,Zn as e,et as f,he as g,st as h,ke as i,at as j,A as k,ut as l,ct as m,lt as n,ft as o,mt as p,pt as q,gt as r,tt as s,R as t,M as u,qn as v,$n as w};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as f,c as y,f as A,g as M}from"./chunk-PBGCNSGZ.js";import{a as v}from"./chunk-6LDRLO4Y.js";import{a as m}from"./chunk-ZPIJSTUE.js";import{c as u}from"./chunk-V4IDVAIA.js";import{a as p,e as g}from"./chunk-TRX2HFTB.js";import{tb as h}from"./chunk-UNEPZJKK.js";import{isAbsolute as S,resolve as w}from"node:path";import{spawn as b}from"node:child_process";import{fileURLToPath as P}from"node:url";function $(e){return t=>T(t,e)}function T(e,t){const i=I(e,t);const[o,r]=process.platform==="darwin"?["open",[i]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",i]]:["xdg-open",[i]];return new Promise((n,a)=>{const s=b(o,r,{detached:true,stdio:"ignore",windowsHide:true});s.once("error",a);s.once("spawn",()=>{s.unref();n()})})}function I(e,t){if(/^https?:\/\//iu.test(e))return e;if(/^file:\/\//iu.test(e))return P(e);return S(e)?e:w(t,e)}var O="mcode-internal";function F(e){try{const t=new URL(e);t.searchParams.set("client_surface","tui");t.searchParams.set("download_source",O);return t.toString()}catch{return e}}async function E(e){const t=e.writeAuthContext??A;const i=e.writeVerifiedIdentity??y;const o=new v({authContextGetter:()=>void 0,region:e.scope.region,buildEnv:e.scope.buildEnv,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}});const r=h(e.dataDir);const n=await o.getAuthContextForAuth({accessToken:e.accessToken}).catch(()=>void 0);const a={accessToken:e.accessToken,...n?.realUserID?{realUserID:n.realUserID}:{},...n?.userEmail?{userEmail:n.userEmail}:{},...n?.userName?{userName:n.userName}:{},...n?.subUserName?{subUserName:n.subUserName}:{}};t(e.dataDir,a,e.scope,{expectedSharedAuth:r});if(n?.realUserID){i(e.dataDir,e.scope,e.accessToken,n)}}var k={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimax.cn"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};function C(e){const t=k[e.region][e.buildEnv];return`${t}/auth/logout?logout_redirect_uri=${encodeURIComponent(t)}`}var d=class{constructor(t){this.options=t;const i=u();this.scope={region:t.region??i.region,buildEnv:t.buildEnv??i.buildEnv}}options;scope;async login(t,i=this.scope.region){this.track("login_click",{});try{const o={...this.scope,region:i};const r=!D(o,this.scope);let n=this.options.sharedAuthCore;if(r){if(!this.options.resolveSharedAuthCore){throw new Error(B(this.scope,o))}n=this.options.resolveSharedAuthCore(i)}const a=(await n.getStatus()).status==="authenticated";let s=false;await n.login({onDeviceAuthorization:x=>{s=true;t?.({state:"device-authorization",...x})}});this.persistRegionPreference(o);const l=a&&!s;if(!l){await this.projectLoginIdentityCache(o,n)}const R={state:l?"already-authenticated":"authenticated",message:l?r?`Already signed in with ${c(o.region)}.`:"Already signed in with MiniMax.":r?`Signed in with ${c(o.region)}.`:"Signed in with MiniMax.",...r?{restartRequired:true}:{}};this.trackLoginResult("1","");return R}catch(o){this.trackLoginResult("2",L(o));throw o}}async logout(){this.track("logout_click",{});const t=await this.options.sharedAuthCore.getStatus();const i=await this.options.sharedAuthCore.logout({revoke:true});this.clearCachedLoginIdentity();const o=C(this.scope);if(t.status==="anonymous"&&i.status==="anonymous"){return{state:"already-signed-out",message:"Already signed out of MiniMax.",logoutUrl:o}}return{state:"signed-out",logoutUrl:o,message:i.status==="logout_pending"?`Signed out locally from ${c(this.scope.region)} across MCode. Server revocation is pending until the network recovers.`:`Signed out of ${c(this.scope.region)} on Desktop, CLI/TUI, and embedded mcode-tools.`}}trackLoginResult(t,i){this.track("login_result",{source:this.options.telemetrySource??"mcode_cli",result_type:t,fail_reason:i,login_type:"minimax_oauth"})}persistRegionPreference(t){try{this.options.writeRegionPreference?.(this.options.dataDir,t)}catch{}}async projectLoginIdentityCache(t,i){try{const o=await i.getAccessToken({requiredScopes:[...p],minValidityMs:0});const r=o.accessToken.trim();if(!r)return;await E({dataDir:this.options.dataDir,scope:t,accessToken:r,...this.options.fetchImpl?{fetchImpl:this.options.fetchImpl}:{}})}catch{}}clearCachedLoginIdentity(){try{M(this.options.dataDir,this.scope)}catch{}}track(t,i){try{this.options.telemetry?.track(t,i)}catch{}}};function L(e){const t=e instanceof Error?e.message:String(e);if(/cancel/iu.test(t))return"3";if(/network|offline|fetch|ECONN|ENOTFOUND|ETIMEDOUT/iu.test(t))return"2";if(/oauth|authorization|login failed|invalid login state/iu.test(t))return"5";if(/server|HTTP 5\d\d/iu.test(t))return"1";return"4"}function D(e,t){return e.region===t.region&&e.buildEnv===t.buildEnv}function B(e,t){if(e.region!==t.region){return`Signed in to ${c(e.region)}. Run \`mcode logout\` before signing in to ${c(t.region)}.`}return`Signed in to another MiniMax ${e.buildEnv} environment. Run \`mcode logout\` before signing in to ${t.buildEnv}.`}function c(e){return e==="cn"?"MiniMax China":"MiniMax Global"}function se(e){const t=u({runtimeRegion:e.region,runtimeBuildEnv:e.buildEnv});const i=e.region??t.region;const o=e.buildEnv??t.buildEnv;const r={dataDir:e.dataDir,region:i,buildEnv:o,...e.telemetry?{telemetry:e.telemetry}:{},...e.telemetrySource?{telemetrySource:e.telemetrySource}:{},writeRegionPreference:e.writeRegionPreference??m,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}};const n=s=>(e.createSharedSession??f)({dataDir:e.dataDir,region:s,buildEnv:o,oauthEndpoints:g(e.oauthEndpointEnvironment??process.env,{buildEnv:o,region:s})});const a=e.sharedAuthCore??n(i);return new d({...r,sharedAuthCore:a,resolveSharedAuthCore:n})}export{$ as a,F as b,se as c};
2
+ import{a as f,c as y,f as A,g as M}from"./chunk-QMBFFQPV.js";import{a as v}from"./chunk-3LRARE6Z.js";import{a as m}from"./chunk-WUORF7YS.js";import{c as u}from"./chunk-WHBWI5OQ.js";import{a as p,e as g}from"./chunk-TRX2HFTB.js";import{xb as h}from"./chunk-XWNCITOR.js";import{isAbsolute as S,resolve as w}from"node:path";import{spawn as b}from"node:child_process";import{fileURLToPath as P}from"node:url";function $(e){return t=>T(t,e)}function T(e,t){const i=I(e,t);const[o,r]=process.platform==="darwin"?["open",[i]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",i]]:["xdg-open",[i]];return new Promise((n,a)=>{const s=b(o,r,{detached:true,stdio:"ignore",windowsHide:true});s.once("error",a);s.once("spawn",()=>{s.unref();n()})})}function I(e,t){if(/^https?:\/\//iu.test(e))return e;if(/^file:\/\//iu.test(e))return P(e);return S(e)?e:w(t,e)}var O="mcode-internal";function F(e){try{const t=new URL(e);t.searchParams.set("client_surface","tui");t.searchParams.set("download_source",O);return t.toString()}catch{return e}}async function E(e){const t=e.writeAuthContext??A;const i=e.writeVerifiedIdentity??y;const o=new v({authContextGetter:()=>void 0,region:e.scope.region,buildEnv:e.scope.buildEnv,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}});const r=h(e.dataDir);const n=await o.getAuthContextForAuth({accessToken:e.accessToken}).catch(()=>void 0);const a={accessToken:e.accessToken,...n?.realUserID?{realUserID:n.realUserID}:{},...n?.userEmail?{userEmail:n.userEmail}:{},...n?.userName?{userName:n.userName}:{},...n?.subUserName?{subUserName:n.subUserName}:{}};t(e.dataDir,a,e.scope,{expectedSharedAuth:r});if(n?.realUserID){i(e.dataDir,e.scope,e.accessToken,n)}}var k={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimax.cn"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};function C(e){const t=k[e.region][e.buildEnv];return`${t}/auth/logout?logout_redirect_uri=${encodeURIComponent(t)}`}var d=class{constructor(t){this.options=t;const i=u();this.scope={region:t.region??i.region,buildEnv:t.buildEnv??i.buildEnv}}options;scope;async login(t,i=this.scope.region){this.track("login_click",{});try{const o={...this.scope,region:i};const r=!D(o,this.scope);let n=this.options.sharedAuthCore;if(r){if(!this.options.resolveSharedAuthCore){throw new Error(B(this.scope,o))}n=this.options.resolveSharedAuthCore(i)}const a=(await n.getStatus()).status==="authenticated";let s=false;await n.login({onDeviceAuthorization:x=>{s=true;t?.({state:"device-authorization",...x})}});this.persistRegionPreference(o);const l=a&&!s;if(!l){await this.projectLoginIdentityCache(o,n)}const R={state:l?"already-authenticated":"authenticated",message:l?r?`Already signed in with ${c(o.region)}.`:"Already signed in with MiniMax.":r?`Signed in with ${c(o.region)}.`:"Signed in with MiniMax.",...r?{restartRequired:true}:{}};this.trackLoginResult("1","");return R}catch(o){this.trackLoginResult("2",L(o));throw o}}async logout(){this.track("logout_click",{});const t=await this.options.sharedAuthCore.getStatus();const i=await this.options.sharedAuthCore.logout({revoke:true});this.clearCachedLoginIdentity();const o=C(this.scope);if(t.status==="anonymous"&&i.status==="anonymous"){return{state:"already-signed-out",message:"Already signed out of MiniMax.",logoutUrl:o}}return{state:"signed-out",logoutUrl:o,message:i.status==="logout_pending"?`Signed out locally from ${c(this.scope.region)} across MCode. Server revocation is pending until the network recovers.`:`Signed out of ${c(this.scope.region)} on Desktop, CLI/TUI, and embedded mcode-tools.`}}trackLoginResult(t,i){this.track("login_result",{source:this.options.telemetrySource??"mcode_cli",result_type:t,fail_reason:i,login_type:"minimax_oauth"})}persistRegionPreference(t){try{this.options.writeRegionPreference?.(this.options.dataDir,t)}catch{}}async projectLoginIdentityCache(t,i){try{const o=await i.getAccessToken({requiredScopes:[...p],minValidityMs:0});const r=o.accessToken.trim();if(!r)return;await E({dataDir:this.options.dataDir,scope:t,accessToken:r,...this.options.fetchImpl?{fetchImpl:this.options.fetchImpl}:{}})}catch{}}clearCachedLoginIdentity(){try{M(this.options.dataDir,this.scope)}catch{}}track(t,i){try{this.options.telemetry?.track(t,i)}catch{}}};function L(e){const t=e instanceof Error?e.message:String(e);if(/cancel/iu.test(t))return"3";if(/network|offline|fetch|ECONN|ENOTFOUND|ETIMEDOUT/iu.test(t))return"2";if(/oauth|authorization|login failed|invalid login state/iu.test(t))return"5";if(/server|HTTP 5\d\d/iu.test(t))return"1";return"4"}function D(e,t){return e.region===t.region&&e.buildEnv===t.buildEnv}function B(e,t){if(e.region!==t.region){return`Signed in to ${c(e.region)}. Run \`mcode logout\` before signing in to ${c(t.region)}.`}return`Signed in to another MiniMax ${e.buildEnv} environment. Run \`mcode logout\` before signing in to ${t.buildEnv}.`}function c(e){return e==="cn"?"MiniMax China":"MiniMax Global"}function se(e){const t=u({runtimeRegion:e.region,runtimeBuildEnv:e.buildEnv});const i=e.region??t.region;const o=e.buildEnv??t.buildEnv;const r={dataDir:e.dataDir,region:i,buildEnv:o,...e.telemetry?{telemetry:e.telemetry}:{},...e.telemetrySource?{telemetrySource:e.telemetrySource}:{},writeRegionPreference:e.writeRegionPreference??m,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}};const n=s=>(e.createSharedSession??f)({dataDir:e.dataDir,region:s,buildEnv:o,oauthEndpoints:g(e.oauthEndpointEnvironment??process.env,{buildEnv:o,region:s})});const a=e.sharedAuthCore??n(i);return new d({...r,sharedAuthCore:a,resolveSharedAuthCore:n})}export{$ as a,F as b,se as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{s as N,t as D,u as Q}from"./chunk-RD7XROJD.js";import{a as p}from"./chunk-ME57CPMB.js";var v=["totalTokens","inputTokens","outputTokens","reasoningTokens","cacheReadTokens","cacheWriteTokens"];function w(e,t){return e.role==="assistant"&&(e.turnId===void 0||e.turnId===t)&&e.kind?.startsWith("compaction")===true}function F(e,t){if(e.role!=="assistant"||e.turnId!==void 0&&e.turnId!==t||w(e,t))return void 0;const i=Object.fromEntries(v.flatMap(r=>T(e.usage?.[r])?[[r,e.usage?.[r]]]:[]));const n=v.some(r=>e.usage?.[r]!==void 0&&!T(e.usage?.[r]));return{...e.id?.trim()?{messageId:e.id}:{},...Object.keys(i).length?{usage:i}:{},...n?{usageIncomplete:true}:{}}}function j(e,t){const i=t.messageId?e.findIndex(r=>r.messageId===t.messageId):-1;const n=e[i];if(!n){e.push(t);return}e[i]={...n,...t,...n.usage||t.usage?{usage:{...n.usage,...t.usage}}:{}}}function B(e){let t=e.length===0||e.some(n=>!T(n.usage?.inputTokens)||!T(n.usage?.outputTokens)||n.usageIncomplete);const i=Object.fromEntries(v.flatMap(n=>{const r=e.map(a=>a.usage?.[n]).filter(T);if(!r.length)return[];const u=r.reduce((a,l)=>a+l,0);if(!Number.isFinite(u)){t=true;return[]}return[[n,u]]}));return{...Object.keys(i).length?{usage:i}:{},usageIncomplete:t}}function T(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function G(e,t){const i=e.type==="message"?e.message.turnId:e.turnId;if(i&&i!==t)return false;const n=e.type==="message"?e.message.toolCalls:e.type==="delta"?e.toolCalls:void 0;return n?.some(r=>{if(r.error||r.status!==2&&r.status!=="2"&&r.status!=="finished")return false;if(!r.output||typeof r.output!=="object"||Array.isArray(r.output))return false;const u=r.output.details;return typeof u==="object"&&u!==null&&!Array.isArray(u)&&u.waiting_for_user===true})??false}async function W(e,t,i,n=N,r){const u=await e.getPendingQuestionnaire?.(n,t,r);return u?.requester?.sessionId===t&&u.requester.runId===i?u:void 0}var K=2147483647;var J=1e3;var q=class{constructor(t,i={}){this.runtime=t;this.options=i;this.nowMs=i.nowMs??Date.now}runtime;options;activeRun;retiringRun;nowMs;activeTurnId(){return this.activeRun?.turnId}detachActiveRun(t){const i=this.activeRun;if(!i||t!==void 0&&i.turnId!==t)return false;this.activeRun=void 0;return true}retireCompletedRun(t){const i=this.activeRun;if(!i||i.turnId!==t)return false;this.activeRun=void 0;i.controller.abort(new D("Runtime turn already settled."));return true}retiringTurnId(){return this.retiringRun?.turnId}retirement(){return this.retiringRun?.settlement}async*sendWithQueueRecovery(t,i,n,r){const u=Z(t,i,r);let a=false;try{for await(const l of this.runtime.sendMessage(u,n)){a=true;yield l}}catch(l){if(a||r!==void 0||!(l instanceof p)||l.code!=="local_session_queue_paused"||!t.onQueuePaused||n.aborted)throw l;const c=await t.onQueuePaused(i.sessionId,n);n.throwIfAborted();if(c==="cancel")throw new p("cancelled","The draft was kept.",{code:"PAUSED_QUEUE_SEND_CANCELLED"});yield*this.runtime.sendMessage(u,n,{pausedQueueAction:c==="paused-queue-clear"?"clear":"keep"})}}async execute(t,i=()=>void 0,n,r){if(this.activeRun)throw new Error("A run is already active.");if(this.retiringRun)throw new Error("The previous run is still stopping.");const u=se(t.turnId);this.activeRun=u;const a=this.nowMs();let l;let c;let E=false;let s="succeeded";let m=null;let f="";let d;let P=0;const y=[];let _=false;let M=false;let x=false;try{c=await oe(t.session,u.controller.signal);if(!c){throw u.controller.signal.reason??new Error("Turn cancelled before Session setup.")}u.sessionId=c.sessionId;let g;if(t.policy?.timeoutMs!==void 0){g=this.nowMs()+t.policy.timeoutMs;l=ae(()=>{void this.stopActive(u,"timeout").catch(()=>void 0)},t.policy.timeoutMs)}const C=this.sendWithQueueRecovery(t,c,u.controller.signal,g)[Symbol.asyncIterator]();try{while(true){const U=await C.next();if(U.done)break;const o=U.value;if(o.type==="done")x=true;M||=G(o,t.turnId);if(!E){E=true;n?.()}const O=ie(o);if(O){s="awaiting-user-continuation";d=O;await $(i,o);break}if(ee(o)){const b=w(o.message,t.turnId);_||=b;const L=F(o.message,t.turnId);if(L)j(y,L);if(!b&&t.policy?.maxSteps!==void 0&&P>=t.policy.maxSteps){s="limit_exceeded";await this.stopActive(u,"limit");break}if(!b)P+=1;if(o.message.toolCalls?.length){this.reportAnswerSelection({kind:"answer_excluded",messageId:o.message.id,reason:"tool_calls"});m=null;f=""}else{const A=o.message.content?.trim()?o.message.content:f;m=A.trim()?A:null;this.reportAnswerSelection({kind:"answer_selected",messageId:o.message.id,answerSource:o.message.content?.trim()?"completed_message":"completed_message_draft",answerBytes:Buffer.byteLength(A),finishReason:o.message.finishReason});f=""}}else if(te(o)){f+=o.content}const h=re(o);if(h){s=h.status;d=h.error}await $(i,o)}}finally{await C.return?.(void 0)}if(f.trim()){this.reportAnswerSelection({kind:"answer_selected",answerSource:"trailing_draft",answerBytes:Buffer.byteLength(f),replacedAnswer:m!==null});m=f}if(s==="succeeded"&&!u.controller.signal.aborted&&(M||await W(this.runtime,c.sessionId,t.turnId,c.agentName,u.controller.signal))){s="awaiting-user-continuation";m=null;d=z()}if(!x&&!u.controller.signal.aborted&&u.stopReason===void 0&&s!=="cancelled"&&s!=="awaiting-user-continuation"&&s!=="limit_exceeded"){s="failed";d={category:"runtime",code:"TURN_DETACHED",message:"The turn window closed before the turn ended; the turn may still be running.",retryable:true};m=null}if(t.policy?.requireAnswer===true&&s==="succeeded"&&m===null){s="failed";d={category:"runtime",code:"EMPTY_RESPONSE",message:"Runtime completed without a final assistant response.",retryable:true}}s=X(u.stopReason,s)}catch(g){if(u.stopReason||u.controller.signal.aborted){s=X(u.stopReason,"cancelled")}else{s="failed";d=ue(g)}}finally{l?.clear();if(this.activeRun===u)this.activeRun=void 0}const{usage:k}=B(y);let R={sessionId:c?.sessionId??"",turnId:t.turnId,status:s,answer:m,...t.model?{model:{...t.model}}:{},...k?{usage:k}:{},...y.length?{usageResponses:y}:{},..._?{usageIncomplete:true}:{},...d?{error:d}:{},durationMs:Math.max(0,this.nowMs()-a)};if(r){try{await r(R)}catch{s="failed";const g={category:"internal",code:"AUTOMATION_RESULT_WRITE_FAILED",message:"Could not publish the TUI automation result.",retryable:true};d=g;R={...R,status:s,error:g}}}u.resolveSettled();return{turnId:t.turnId,...c?{session:c}:{},status:s,outcome:R,...d?.message?{error:d.message}:{}}}async abort(){const t=this.activeRun;if(!t)return false;t.abortPromise??=this.stopAndSettle(t);return t.abortPromise}reportAnswerSelection(t){try{this.options.onAnswerSelection?.(t)}catch{}}async stopAndSettle(t){const i=await this.stopActive(t,"user_stop");const n=t.settled.then(()=>i);const r=await ce(n,this.options.cancellationSettlementTimeoutMs??J);if(this.activeRun===t)this.activeRun=void 0;if(r.settled)return r.value;const u={turnId:t.turnId,settlement:n};u.settlement=n.finally(()=>{if(this.retiringRun===u)this.retiringRun=void 0});this.retiringRun=u;return i}async stopActive(t,i){t.stopReason??=i;const n=t.sessionId;const r=n?await this.runtime.abortSession({id:n,turnId:t.turnId,reason:i==="limit"?"max_steps":i}).catch(()=>false):true;t.controller.abort(new Error(`Turn stopped: ${i}`));return r}};function Z(e,t,i){return{id:t.sessionId,turnId:e.turnId,content:e.content,...e.displayContent!==void 0?{displayContent:e.displayContent}:{},...i!==void 0?{executionDeadlineAtMs:i}:{},...e.executionDiagnostics?{executionDiagnostics:true}:{},...e.clientIntent?{clientIntent:e.clientIntent}:{},...e.reviewRequest?{reviewRequest:e.reviewRequest}:{},...e.attachments?.length?{attachments:e.attachments.map(n=>({meta:{attachmentType:n.type,fileName:n.fileName,mimeType:n.mimeType,sizeBytes:n.sizeBytes},local:{...n.filePath?{filePath:n.filePath}:{},...n.assetId?{assetId:n.assetId}:{}}}))}:{},...e.model?{model:{...e.model}}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{}}}function ee(e){return e.type==="message"&&e.message.role==="assistant"}function te(e){return e.type==="delta"&&e.role==="assistant"&&typeof e.content==="string"}function ne(e){return e.type==="generic"&&(e.eventType==="questionnaire.ask"||e.eventType==="runtime.action-required"&&e.data.kind==="questionnaire")}function ie(e){if(!ne(e))return void 0;return z()}function z(){return{category:"runtime",code:"QUESTIONNAIRE_REQUIRED",message:"Questionnaire requires user input.",retryable:true}}function re(e){if(e.type==="generic"&&e.eventType==="messages-rewound"){return{status:"failed",error:{category:"runtime",code:"CONTENT_REVIEW_BLOCKED",message:"Content review blocked the request.",retryable:true}}}if(e.type==="error"){return{status:"failed",error:{category:"runtime",message:e.message,retryable:true}}}if(e.type!=="session-status")return void 0;if(e.status==="error"){return{status:"failed",error:{category:"runtime",message:e.message??"Runtime turn failed.",retryable:true}}}if(e.status==="aborted"||e.status==="interrupted"){return{status:"cancelled"}}return void 0}function ue(e){if(e instanceof Q){return{category:"runtime",code:"TURN_DETACHED",message:`The turn window closed before the turn ended; the turn may still be running. (reason: ${e.reason}, attempts: ${e.attempts})`,retryable:true}}if(e instanceof p){const t=e.category==="config"||e.category==="internal"?e.category:"runtime";return{category:t,code:e.code,message:e.message,retryable:e.retryable}}if(e&&typeof e==="object"){const t=e;if(typeof t.message==="string"){return{category:t.category==="config"||t.category==="internal"?t.category:"runtime",...typeof t.code==="string"?{code:t.code}:{},message:t.message,...typeof t.retryable==="boolean"?{retryable:t.retryable}:{retryable:true}}}}return{category:"runtime",message:e instanceof Error?e.message:String(e),retryable:true}}function X(e,t){if(e==="timeout")return"timeout";if(e==="limit")return"limit_exceeded";if(e==="user_stop")return"cancelled";return t}async function $(e,t){try{await e(t)}catch{}}function se(e){let t=()=>void 0;const i=new Promise(n=>{t=n});return{turnId:e,controller:new AbortController,settled:i,resolveSettled:t}}async function oe(e,t){if(t.aborted)return void 0;return new Promise((i,n)=>{const r=()=>t.removeEventListener("abort",u);const u=()=>{r();i(void 0)};t.addEventListener("abort",u,{once:true});e.then(a=>{r();i(a)},a=>{r();n(a)})})}function ae(e,t){let i=t;let n;let r=false;const u=()=>{if(r)return;if(i<=0){e();return}const a=Math.min(i,K);i-=a;n=setTimeout(u,a);n.unref?.()};u();return{clear(){r=true;if(n)clearTimeout(n)}}}async function ce(e,t){if(t<=0)return{settled:false};let i;const n=await Promise.race([e.then(r=>({settled:true,value:r})),new Promise(r=>{i=setTimeout(()=>r({settled:false}),t);i.unref?.()})]);if(i)clearTimeout(i);return n}var H="Sign in to MiniMax to use Agent features. Run /login, then retry.";var I="Sign in to MiniMax to use Agent features. Run `mcode login`, then retry.";var S=class extends p{constructor(i,n=I){super("config",n,{code:"auth.login_required",retryable:false});this.account=i;this.name="TuiLoginRequiredError"}account};function de(e){if(e.modelSource)return e.modelSource==="token-plan";return e.authMode==="managed-login"}function V(e){return e.status==="needs-login"||de(e)&&e.managedTokenPresent!==true}function we(e){return V(e)}async function Y(e,t,i,n){const r=await e.getAccountStatus(t,{...n,includeMembership:false});i?.(r);return r}async function le(e,t,i=I,n,r){const u=await Y(e,t,n,r);if(V(u)){throw new S(u,i)}return u}async function me(e,t,i=I,n){const r=await Y(e,t,n,{requireManagedAuth:true});if(r.managedTokenPresent!==true){throw new S(r,i)}return r}async function Ie(e,t,i){const n=e.getAccountStatus;if(!n)return;await le({getAccountStatus:n.bind(e)},t,H,i)}async function Ee(e,t,i){const n=e.getAccountStatus;if(!n)return;await me({getAccountStatus:n.bind(e)},t,H,i)}import{stripVTControlCharacters as fe}from"node:util";function Me(e,t=240){return Array.from(ge(e).replace(/[\u00ad\u061c\u200b\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]/gu,"").replace(/\s+/gu," ").trim()).slice(0,t).join("")}function ge(e){const t=e.replace(/(?:\u001b\]|\u009d)[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b[P^_X]|[\u0090\u0098\u009e\u009f])[\s\S]*?(?:\u001b\\|\u009c|$)/gu,"");return fe(t).replace(/\r\n/gu,"\n").replace(/\r/gu," ").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu,"")}export{Me as a,ge as b,w as c,F as d,j as e,B as f,W as g,J as h,q as i,S as j,we as k,le as l,Ie as m,Ee as n};
2
+ import{s as N,t as D,u as Q}from"./chunk-CUPCI2YC.js";import{a as p}from"./chunk-ME57CPMB.js";var v=["totalTokens","inputTokens","outputTokens","reasoningTokens","cacheReadTokens","cacheWriteTokens"];function w(e,t){return e.role==="assistant"&&(e.turnId===void 0||e.turnId===t)&&e.kind?.startsWith("compaction")===true}function F(e,t){if(e.role!=="assistant"||e.turnId!==void 0&&e.turnId!==t||w(e,t))return void 0;const i=Object.fromEntries(v.flatMap(r=>T(e.usage?.[r])?[[r,e.usage?.[r]]]:[]));const n=v.some(r=>e.usage?.[r]!==void 0&&!T(e.usage?.[r]));return{...e.id?.trim()?{messageId:e.id}:{},...Object.keys(i).length?{usage:i}:{},...n?{usageIncomplete:true}:{}}}function j(e,t){const i=t.messageId?e.findIndex(r=>r.messageId===t.messageId):-1;const n=e[i];if(!n){e.push(t);return}e[i]={...n,...t,...n.usage||t.usage?{usage:{...n.usage,...t.usage}}:{}}}function B(e){let t=e.length===0||e.some(n=>!T(n.usage?.inputTokens)||!T(n.usage?.outputTokens)||n.usageIncomplete);const i=Object.fromEntries(v.flatMap(n=>{const r=e.map(a=>a.usage?.[n]).filter(T);if(!r.length)return[];const u=r.reduce((a,l)=>a+l,0);if(!Number.isFinite(u)){t=true;return[]}return[[n,u]]}));return{...Object.keys(i).length?{usage:i}:{},usageIncomplete:t}}function T(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function G(e,t){const i=e.type==="message"?e.message.turnId:e.turnId;if(i&&i!==t)return false;const n=e.type==="message"?e.message.toolCalls:e.type==="delta"?e.toolCalls:void 0;return n?.some(r=>{if(r.error||r.status!==2&&r.status!=="2"&&r.status!=="finished")return false;if(!r.output||typeof r.output!=="object"||Array.isArray(r.output))return false;const u=r.output.details;return typeof u==="object"&&u!==null&&!Array.isArray(u)&&u.waiting_for_user===true})??false}async function W(e,t,i,n=N,r){const u=await e.getPendingQuestionnaire?.(n,t,r);return u?.requester?.sessionId===t&&u.requester.runId===i?u:void 0}var K=2147483647;var J=1e3;var q=class{constructor(t,i={}){this.runtime=t;this.options=i;this.nowMs=i.nowMs??Date.now}runtime;options;activeRun;retiringRun;nowMs;activeTurnId(){return this.activeRun?.turnId}detachActiveRun(t){const i=this.activeRun;if(!i||t!==void 0&&i.turnId!==t)return false;this.activeRun=void 0;return true}retireCompletedRun(t){const i=this.activeRun;if(!i||i.turnId!==t)return false;this.activeRun=void 0;i.controller.abort(new D("Runtime turn already settled."));return true}retiringTurnId(){return this.retiringRun?.turnId}retirement(){return this.retiringRun?.settlement}async*sendWithQueueRecovery(t,i,n,r){const u=Z(t,i,r);let a=false;try{for await(const l of this.runtime.sendMessage(u,n)){a=true;yield l}}catch(l){if(a||r!==void 0||!(l instanceof p)||l.code!=="local_session_queue_paused"||!t.onQueuePaused||n.aborted)throw l;const c=await t.onQueuePaused(i.sessionId,n);n.throwIfAborted();if(c==="cancel")throw new p("cancelled","The draft was kept.",{code:"PAUSED_QUEUE_SEND_CANCELLED"});yield*this.runtime.sendMessage(u,n,{pausedQueueAction:c==="paused-queue-clear"?"clear":"keep"})}}async execute(t,i=()=>void 0,n,r){if(this.activeRun)throw new Error("A run is already active.");if(this.retiringRun)throw new Error("The previous run is still stopping.");const u=se(t.turnId);this.activeRun=u;const a=this.nowMs();let l;let c;let E=false;let s="succeeded";let m=null;let f="";let d;let P=0;const y=[];let _=false;let M=false;let x=false;try{c=await oe(t.session,u.controller.signal);if(!c){throw u.controller.signal.reason??new Error("Turn cancelled before Session setup.")}u.sessionId=c.sessionId;let g;if(t.policy?.timeoutMs!==void 0){g=this.nowMs()+t.policy.timeoutMs;l=ae(()=>{void this.stopActive(u,"timeout").catch(()=>void 0)},t.policy.timeoutMs)}const C=this.sendWithQueueRecovery(t,c,u.controller.signal,g)[Symbol.asyncIterator]();try{while(true){const U=await C.next();if(U.done)break;const o=U.value;if(o.type==="done")x=true;M||=G(o,t.turnId);if(!E){E=true;n?.()}const O=ie(o);if(O){s="awaiting-user-continuation";d=O;await $(i,o);break}if(ee(o)){const b=w(o.message,t.turnId);_||=b;const L=F(o.message,t.turnId);if(L)j(y,L);if(!b&&t.policy?.maxSteps!==void 0&&P>=t.policy.maxSteps){s="limit_exceeded";await this.stopActive(u,"limit");break}if(!b)P+=1;if(o.message.toolCalls?.length){this.reportAnswerSelection({kind:"answer_excluded",messageId:o.message.id,reason:"tool_calls"});m=null;f=""}else{const A=o.message.content?.trim()?o.message.content:f;m=A.trim()?A:null;this.reportAnswerSelection({kind:"answer_selected",messageId:o.message.id,answerSource:o.message.content?.trim()?"completed_message":"completed_message_draft",answerBytes:Buffer.byteLength(A),finishReason:o.message.finishReason});f=""}}else if(te(o)){f+=o.content}const h=re(o);if(h){s=h.status;d=h.error}await $(i,o)}}finally{await C.return?.(void 0)}if(f.trim()){this.reportAnswerSelection({kind:"answer_selected",answerSource:"trailing_draft",answerBytes:Buffer.byteLength(f),replacedAnswer:m!==null});m=f}if(s==="succeeded"&&!u.controller.signal.aborted&&(M||await W(this.runtime,c.sessionId,t.turnId,c.agentName,u.controller.signal))){s="awaiting-user-continuation";m=null;d=z()}if(!x&&!u.controller.signal.aborted&&u.stopReason===void 0&&s!=="cancelled"&&s!=="awaiting-user-continuation"&&s!=="limit_exceeded"){s="failed";d={category:"runtime",code:"TURN_DETACHED",message:"The turn window closed before the turn ended; the turn may still be running.",retryable:true};m=null}if(t.policy?.requireAnswer===true&&s==="succeeded"&&m===null){s="failed";d={category:"runtime",code:"EMPTY_RESPONSE",message:"Runtime completed without a final assistant response.",retryable:true}}s=X(u.stopReason,s)}catch(g){if(u.stopReason||u.controller.signal.aborted){s=X(u.stopReason,"cancelled")}else{s="failed";d=ue(g)}}finally{l?.clear();if(this.activeRun===u)this.activeRun=void 0}const{usage:k}=B(y);let R={sessionId:c?.sessionId??"",turnId:t.turnId,status:s,answer:m,...t.model?{model:{...t.model}}:{},...k?{usage:k}:{},...y.length?{usageResponses:y}:{},..._?{usageIncomplete:true}:{},...d?{error:d}:{},durationMs:Math.max(0,this.nowMs()-a)};if(r){try{await r(R)}catch{s="failed";const g={category:"internal",code:"AUTOMATION_RESULT_WRITE_FAILED",message:"Could not publish the TUI automation result.",retryable:true};d=g;R={...R,status:s,error:g}}}u.resolveSettled();return{turnId:t.turnId,...c?{session:c}:{},status:s,outcome:R,...d?.message?{error:d.message}:{}}}async abort(){const t=this.activeRun;if(!t)return false;t.abortPromise??=this.stopAndSettle(t);return t.abortPromise}reportAnswerSelection(t){try{this.options.onAnswerSelection?.(t)}catch{}}async stopAndSettle(t){const i=await this.stopActive(t,"user_stop");const n=t.settled.then(()=>i);const r=await ce(n,this.options.cancellationSettlementTimeoutMs??J);if(this.activeRun===t)this.activeRun=void 0;if(r.settled)return r.value;const u={turnId:t.turnId,settlement:n};u.settlement=n.finally(()=>{if(this.retiringRun===u)this.retiringRun=void 0});this.retiringRun=u;return i}async stopActive(t,i){t.stopReason??=i;const n=t.sessionId;const r=n?await this.runtime.abortSession({id:n,turnId:t.turnId,reason:i==="limit"?"max_steps":i}).catch(()=>false):true;t.controller.abort(new Error(`Turn stopped: ${i}`));return r}};function Z(e,t,i){return{id:t.sessionId,turnId:e.turnId,content:e.content,...e.displayContent!==void 0?{displayContent:e.displayContent}:{},...i!==void 0?{executionDeadlineAtMs:i}:{},...e.executionDiagnostics?{executionDiagnostics:true}:{},...e.clientIntent?{clientIntent:e.clientIntent}:{},...e.reviewRequest?{reviewRequest:e.reviewRequest}:{},...e.attachments?.length?{attachments:e.attachments.map(n=>({meta:{attachmentType:n.type,fileName:n.fileName,mimeType:n.mimeType,sizeBytes:n.sizeBytes},local:{...n.filePath?{filePath:n.filePath}:{},...n.assetId?{assetId:n.assetId}:{}}}))}:{},...e.model?{model:{...e.model}}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{}}}function ee(e){return e.type==="message"&&e.message.role==="assistant"}function te(e){return e.type==="delta"&&e.role==="assistant"&&typeof e.content==="string"}function ne(e){return e.type==="generic"&&(e.eventType==="questionnaire.ask"||e.eventType==="runtime.action-required"&&e.data.kind==="questionnaire")}function ie(e){if(!ne(e))return void 0;return z()}function z(){return{category:"runtime",code:"QUESTIONNAIRE_REQUIRED",message:"Questionnaire requires user input.",retryable:true}}function re(e){if(e.type==="generic"&&e.eventType==="messages-rewound"){return{status:"failed",error:{category:"runtime",code:"CONTENT_REVIEW_BLOCKED",message:"Content review blocked the request.",retryable:true}}}if(e.type==="error"){return{status:"failed",error:{category:"runtime",message:e.message,retryable:true}}}if(e.type!=="session-status")return void 0;if(e.status==="error"){return{status:"failed",error:{category:"runtime",message:e.message??"Runtime turn failed.",retryable:true}}}if(e.status==="aborted"||e.status==="interrupted"){return{status:"cancelled"}}return void 0}function ue(e){if(e instanceof Q){return{category:"runtime",code:"TURN_DETACHED",message:`The turn window closed before the turn ended; the turn may still be running. (reason: ${e.reason}, attempts: ${e.attempts})`,retryable:true}}if(e instanceof p){const t=e.category==="config"||e.category==="internal"?e.category:"runtime";return{category:t,code:e.code,message:e.message,retryable:e.retryable}}if(e&&typeof e==="object"){const t=e;if(typeof t.message==="string"){return{category:t.category==="config"||t.category==="internal"?t.category:"runtime",...typeof t.code==="string"?{code:t.code}:{},message:t.message,...typeof t.retryable==="boolean"?{retryable:t.retryable}:{retryable:true}}}}return{category:"runtime",message:e instanceof Error?e.message:String(e),retryable:true}}function X(e,t){if(e==="timeout")return"timeout";if(e==="limit")return"limit_exceeded";if(e==="user_stop")return"cancelled";return t}async function $(e,t){try{await e(t)}catch{}}function se(e){let t=()=>void 0;const i=new Promise(n=>{t=n});return{turnId:e,controller:new AbortController,settled:i,resolveSettled:t}}async function oe(e,t){if(t.aborted)return void 0;return new Promise((i,n)=>{const r=()=>t.removeEventListener("abort",u);const u=()=>{r();i(void 0)};t.addEventListener("abort",u,{once:true});e.then(a=>{r();i(a)},a=>{r();n(a)})})}function ae(e,t){let i=t;let n;let r=false;const u=()=>{if(r)return;if(i<=0){e();return}const a=Math.min(i,K);i-=a;n=setTimeout(u,a);n.unref?.()};u();return{clear(){r=true;if(n)clearTimeout(n)}}}async function ce(e,t){if(t<=0)return{settled:false};let i;const n=await Promise.race([e.then(r=>({settled:true,value:r})),new Promise(r=>{i=setTimeout(()=>r({settled:false}),t);i.unref?.()})]);if(i)clearTimeout(i);return n}var H="Sign in to MiniMax to use Agent features. Run /login, then retry.";var I="Sign in to MiniMax to use Agent features. Run `mcode login`, then retry.";var S=class extends p{constructor(i,n=I){super("config",n,{code:"auth.login_required",retryable:false});this.account=i;this.name="TuiLoginRequiredError"}account};function de(e){if(e.modelSource)return e.modelSource==="token-plan";return e.authMode==="managed-login"}function V(e){return e.status==="needs-login"||de(e)&&e.managedTokenPresent!==true}function we(e){return V(e)}async function Y(e,t,i,n){const r=await e.getAccountStatus(t,{...n,includeMembership:false});i?.(r);return r}async function le(e,t,i=I,n,r){const u=await Y(e,t,n,r);if(V(u)){throw new S(u,i)}return u}async function me(e,t,i=I,n){const r=await Y(e,t,n,{requireManagedAuth:true});if(r.managedTokenPresent!==true){throw new S(r,i)}return r}async function Ie(e,t,i){const n=e.getAccountStatus;if(!n)return;await le({getAccountStatus:n.bind(e)},t,H,i)}async function Ee(e,t,i){const n=e.getAccountStatus;if(!n)return;await me({getAccountStatus:n.bind(e)},t,H,i)}import{stripVTControlCharacters as fe}from"node:util";function Me(e,t=240){return Array.from(ge(e).replace(/[\u00ad\u061c\u200b\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]/gu,"").replace(/\s+/gu," ").trim()).slice(0,t).join("")}function ge(e){const t=e.replace(/(?:\u001b\]|\u009d)[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b[P^_X]|[\u0090\u0098\u009e\u009f])[\s\S]*?(?:\u001b\\|\u009c|$)/gu,"");return fe(t).replace(/\r\n/gu,"\n").replace(/\r/gu," ").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu,"")}export{Me as a,ge as b,w as c,F as d,j as e,B as f,W as g,J as h,q as i,S as j,we as k,le as l,Ie as m,Ee as n};