@minimax-ai/code 0.3.1 → 0.3.3

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 (31) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/CHANGELOG.zh-CN.md +32 -0
  3. package/README.md +14 -0
  4. package/README.zh-CN.md +23 -12
  5. package/chunks/{application-AG6XR6TH.js → application-2DVWZRSC.js} +1 -1
  6. package/chunks/{auth-command-MIT2ROTA.js → auth-command-M34DRUOJ.js} +1 -1
  7. package/chunks/{chunk-T7V3D5XQ.js → chunk-2LLMI3OF.js} +1 -1
  8. package/chunks/{chunk-L2BHZE4F.js → chunk-AQSBE25I.js} +586 -586
  9. package/chunks/{chunk-FO5IMY26.js → chunk-D3NBJEJ2.js} +1 -1
  10. package/chunks/{chunk-YRXRNL2F.js → chunk-EFJXTS5E.js} +1 -1
  11. package/chunks/chunk-IEL7EQIF.js +5 -0
  12. package/chunks/{chunk-IBEXP44J.js → chunk-LTIHXDFE.js} +1 -1
  13. package/chunks/{chunk-AOZUEPXI.js → chunk-OYVCWRBD.js} +6 -6
  14. package/chunks/{chunk-NF23WB7F.js → chunk-TYJKJAGQ.js} +1 -1
  15. package/chunks/{chunk-F33I4QSG.js → chunk-WYLGAV2H.js} +399 -385
  16. package/chunks/chunk-YKYKYGJQ.js +2 -0
  17. package/chunks/{data-dir-335LYS7R.js → data-dir-4HGM3ZJQ.js} +1 -1
  18. package/chunks/launcher-TTIS7XGW.js +244 -0
  19. package/chunks/{lifecycle-O4VWU5MP.js → lifecycle-UX7R2ISB.js} +1 -1
  20. package/chunks/main-Z35ONZIQ.js +29 -0
  21. package/chunks/{plugin-command-T6LW4ONC.js → plugin-command-TKAIQMF3.js} +1 -1
  22. package/chunks/{provider-command-2JVOUOBS.js → provider-command-VWLG5VAP.js} +1 -1
  23. package/chunks/{run-acp-command-DWPL6R6W.js → run-acp-command-CMZGKQE3.js} +2 -2
  24. package/chunks/{run-exec-command-5UZ7WFH4.js → run-exec-command-NLNOSTZK.js} +1 -1
  25. package/chunks/{update-J2OGG3ZH.js → update-N3TZCYN3.js} +1 -1
  26. package/cli.js +2 -1
  27. package/package.json +1 -1
  28. package/chunks/chunk-77VGHMFO.js +0 -5
  29. package/chunks/chunk-VTJC5EVO.js +0 -2
  30. package/chunks/launcher-P2FIIDHG.js +0 -244
  31. package/chunks/main-PUHNEWJZ.js +0 -29
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as Z}from"./chunk-T7V3D5XQ.js";import{a as te,d as re}from"./chunk-VTJC5EVO.js";import{a as oe,b as ie}from"./chunk-F33I4QSG.js";import"./chunk-DGZI73PE.js";import{s as H,wd as Oe}from"./chunk-L2BHZE4F.js";import{b as Y,c as x}from"./chunk-A2CQYOXE.js";import{c as Q,q as O}from"./chunk-ZXUXZKGU.js";import"./chunk-YRXRNL2F.js";import"./chunk-PPIEC7ZM.js";import"./chunk-C3JRMX7L.js";import"./chunk-R6GVNV7J.js";import"./chunk-75PL5LYJ.js";import"./chunk-VYI2WX6B.js";import"./chunk-JAU52A7E.js";import"./chunk-HQ2U4QVQ.js";import"./chunk-4Y64C4JT.js";import{d as K}from"./chunk-FO5IMY26.js";import"./chunk-77VGHMFO.js";import{Na as J,Oa as z}from"./chunk-PGOU6MFH.js";import"./chunk-MMRA4VD2.js";import"./chunk-CWWDVX6C.js";import"./chunk-ZITT4GJK.js";import{a as ee,b as ne}from"./chunk-YPMJNO4T.js";import"./chunk-AGWQ62YH.js";import"./chunk-LOQ4VVEN.js";import"./chunk-ECV3PLKX.js";import"./chunk-PWQHCWDV.js";import"./chunk-SHXPTUWI.js";import"./chunk-IIHJNKC3.js";import"./chunk-II4JKPH5.js";import"./chunk-KSPFS4MM.js";import"./chunk-CK62QLTS.js";import"./chunk-WFWSBUYD.js";import{e as Ae}from"./chunk-D76SO2ME.js";var h=Object.freeze({success:0,invocation:2,config:3,runtime:4,timeout:6,limit:7,internal:70,cancelled:130,brokenPipe:141}),m=class extends O{constructor(r,n,o){super(r,n,{code:`exec.${r}`,retryable:r==="runtime",...o});this.kind=r;this.name="TuiExecError"}};function se(e){switch(e.status){case"succeeded":return h.success;case"failed":return e.error?.category==="config"?h.config:e.error?.category==="internal"?h.internal:h.runtime;case"timeout":return h.timeout;case"cancelled":return h.cancelled;case"limit_exceeded":return h.limit}return h.internal}function v(e){return e instanceof m?h[e.kind]:h.internal}async function ae(e,t){try{return z(e,t)}catch(r){let n=r instanceof J?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new m("config",n,{cause:r})}}function I(e){return e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"?x(e):e.kind==="runtime"?`The run failed: ${x(e)}. Retry after the connection recovers.`:`MCode encountered an internal error: ${x(e)}. Retry; if it keeps happening, report it through an available support channel.`}function ue(e){return e.status==="timeout"?"The run timed out. Increase --timeout or retry.":e.status==="limit_exceeded"?"The run reached its step limit. Increase --max-steps or narrow the task.":e.status==="cancelled"?"The run was cancelled.":e.error?.category==="config"?`The run could not start with the current configuration${e.error.message?`: ${x(e.error.message)}`:""}. Open MCode and run /doctor.`:e.error?.category==="internal"?`MCode encountered an internal error${e.error.message?`: ${x(e.error.message)}`:""}. Retry; if it keeps happening, report it through an available support channel.`:`The run failed${e.error?.message?`: ${x(e.error.message)}`:""}. Retry after the connection recovers.`}import{readFile as Ue,realpath as V,stat as j}from"node:fs/promises";import{homedir as fe}from"node:os";import{basename as ge,dirname as Le,extname as He,isAbsolute as We,resolve as N}from"node:path";var W=Ae(Oe(),1);function ce(e,t){let r=_e(e,t.outputSchema);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:r.sessionId,turnId:r.turnId,status:r.status==="awaiting-user-continuation"?"failed":r.status,...r.status==="succeeded"?{output:me(r.answer,t.outputSchema)}:{},...r.error?{error:{...r.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},durationMs:r.durationMs}}function de(e){return _(e)?e.schemaVersion===1&&e.type==="exec.result"&&typeof e.runId=="string"&&typeof e.sessionId=="string"&&typeof e.turnId=="string"&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&Ne(e.status)&&je(e.model)&&De(e.usage)&&$e(e.error):!1}function _e(e,t){if(e.status==="awaiting-user-continuation")return{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:!1}};if(e.status!=="succeeded"||!t)return e;try{return me(e.answer,t),e}catch(r){return{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:r instanceof Error?r.message:"Structured output was not valid JSON.",retryable:!0}}}}function me(e,t){if(!t)return e??null;if(!e?.trim())throw new Error("Structured output was empty.");let r;try{r=JSON.parse(e)}catch(s){throw new Error("Structured output was not valid JSON.",{cause:s})}let n=new W.Ajv({allErrors:!0,strict:!1}),o=n.compile(t);if(!o(r)){let s=n.errorsText(o.errors,{separator:"; "});throw new Error(`Structured output did not match --output-schema: ${s}`)}return r}function le(e){new W.Ajv({allErrors:!0,strict:!1}).compile(e)}function Ne(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function je(e){return e===void 0?!0:_(e)?typeof e.providerId=="string"&&typeof e.modelId=="string"&&b(e.variant)&&b(e.providerSource)&&b(e.providerKind)&&b(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict"):!1}function De(e){return e===void 0?!0:_(e)?Object.values(e).every(t=>t===void 0||typeof t=="number"&&Number.isFinite(t)):!1}function $e(e){return e===void 0?!0:_(e)?(e.category==="config"||e.category==="runtime"||e.category==="internal")&&b(e.code)&&typeof e.message=="string"&&(e.retryable===void 0||typeof e.retryable=="boolean"):!1}function b(e){return e===void 0||typeof e=="string"}function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qe={".csv":"text/csv",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".log":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".webp":"image/webp",".xml":"application/xml",".yaml":"application/yaml",".yml":"application/yaml"};async function ye(e,t,r,n){if(R(n),t.input!==void 0&&t.input!=="-")throw f('--input currently accepts only "-".');if(e!==void 0&&t.input!==void 0)throw f("The prompt argument and --input cannot be combined.");if(t.session&&t.continue)throw f("--session and --continue are mutually exclusive.");let o=q("--input-format",t.inputFormat??"text",["text","json"]),s=q("--output-format",t.outputFormat??"text",["text","json","stream-json"]),i=q("--permission",t.permission??"smart",["ask","smart","full","off"]);if(i==="ask")throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.");let l=i,d=await he(t.cwd??process.cwd(),"--cwd");R(n);let g=t.input==="-"?await r():e??"";R(n);let E=Be(g,o),p=await Promise.all((t.file??[]).map(S=>Xe(S,d,n))),c=ne(p);if(c==="count")throw f(`You can attach up to ${String(10)} files.`);if(c==="total-bytes")throw f("Attachments can total up to the 100 MB limit.");if(!E.trim()&&p.length===0)throw f("A prompt, --input -, or at least one --file is required.");let u=t.timeout===void 0?void 0:Je(t.timeout,"--timeout"),y=t.maxSteps===void 0?void 0:ze(t.maxSteps,"--max-steps"),a=t.config===void 0?void 0:await Ee(t.config,d,"--config"),w=t.outputSchema===void 0?void 0:await Ve(t.outputSchema,d),T=t.outputLastMessage===void 0?void 0:await Ge(t.outputLastMessage,d);return{prompt:E,workspaceDir:d,attachments:p,...t.model?.trim()?{model:t.model.trim()}:{},...t.session?.trim()?{sessionId:t.session.trim()}:{},continueSession:t.continue===!0,...a?{configPath:a}:{},permission:l,...u===void 0?{}:{timeoutMs:u},...y===void 0?{}:{maxSteps:y},format:s,...w===void 0?{}:{outputSchema:w},...T===void 0?{}:{outputLastMessagePath:T}}}async function Ve(e,t){let r=e.trim();try{return pe(r)}catch(o){if(r.startsWith("{")||r.startsWith("[")||!(o instanceof SyntaxError))throw f("--output-schema requires a JSON object.",o)}let n=await Ee(e,t,"--output-schema");try{return pe(await Ue(n,"utf8"))}catch(o){throw f("--output-schema requires a JSON object.",o)}}function pe(e){let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("schema must be a JSON object");return le(t),t}async function Ge(e,t){let r=D(e,t),n=await he(Le(r),"--output-last-message"),o=N(n,ge(r));if((await j(o).catch(i=>{if(!(i&&typeof i=="object"&&"code"in i&&i.code==="ENOENT"))throw f(`--output-last-message is invalid: ${P(i)}`)}))?.isDirectory())throw f("--output-last-message must reference a file.");return o}async function Xe(e,t,r){R(r);let n=D(e,t),o=await V(n).catch(d=>{throw f(`Cannot attach ${e}: ${P(d)}`)}),s=await j(o).catch(d=>{throw f(`Cannot attach ${e}: ${P(d)}`)});if(R(r),!s.isFile())throw f(`Cannot attach ${e}: path is not a file.`);let i=ge(o),l=qe[He(i).toLowerCase()]??ee(i)??"application/octet-stream";return{type:l.startsWith("image/")?"image":"file",filePath:o,fileName:i,mimeType:l,sizeBytes:s.size}}function R(e){if(e?.aborted)throw new m("cancelled","Invocation was cancelled.",{cause:e.reason})}async function he(e,t){let r=await V(D(e,process.cwd())).catch(o=>{throw f(`${t} is invalid: ${P(o)}`)});if(!(await j(r)).isDirectory())throw f(`${t} must reference a directory.`);return r}async function Ee(e,t,r){let n=await V(D(e,t)).catch(s=>{throw f(`${r} is invalid: ${P(s)}`)});if(!(await j(n)).isFile())throw f(`${r} must reference a file.`);return n}function D(e,t){let r=e.trim();if(!r)throw f("Path value cannot be empty.");let n=r==="~"?fe():r.startsWith("~/")||r.startsWith("~\\")?N(fe(),r.slice(2)):r;return We(n)?N(n):N(t,n)}function Be(e,t){if(t==="text")return e;let r;try{r=JSON.parse(e)}catch(n){throw f("--input-format json requires valid JSON.",n)}if(typeof r=="string")return r;if(r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.prompt=="string")return r.prompt;throw f("--input-format json accepts a JSON string or an object with string prompt.")}function Je(e,t){let r=/^(\d+)(ms|s|m|h)?$/i.exec(e.trim());if(!r)throw f(`${t} must be a positive duration such as 500ms, 30s, or 2m.`);let n=Number(r[1]),o=r[2]?.toLowerCase()==="h"?36e5:r[2]?.toLowerCase()==="m"?6e4:r[2]?.toLowerCase()==="s"?1e3:1,s=n*o;if(!Number.isSafeInteger(s)||s<1)throw f(`${t} must resolve to a positive safe integer in milliseconds.`);return s}function ze(e,t){if(!/^\d+$/.test(e.trim()))throw f(`${t} must be a positive integer.`);let r=Number(e);if(!Number.isSafeInteger(r)||r<1)throw f(`${t} must be a positive safe integer.`);return r}function q(e,t,r){if(r.includes(t))return t;throw f(`${e} must be one of: ${r.join(", ")}.`)}function f(e,t){return new m("invocation",e,t===void 0?void 0:{cause:t})}function P(e){return e instanceof Error?e.message:String(e)}import{resolve as ve}from"node:path";function we(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}import{randomUUID as Qe}from"node:crypto";import{rename as Ze,unlink as et,writeFile as tt}from"node:fs/promises";import{basename as rt,dirname as nt,join as ot}from"node:path";var $=class{constructor(t){this.options=t;this.nowMs=t.nowMs??Date.now}sequence=0;started=!1;completed=!1;startedItems=new Set;nowMs;project(t){if(this.completed)throw new Error("Exec events cannot follow exec.completed.");let r=Ke(t);return[...this.ensureStarted(),...r.map(n=>this.itemEvent(n))]}complete(t){if(this.completed)throw new Error("exec.completed was projected more than once.");this.completed=!0;let r=t.status==="succeeded"?this.event({type:"turn.completed",...t.model?{model:t.model}:{},...t.usage?{usage:t.usage}:{},durationMs:t.durationMs}):this.event({type:"turn.failed",status:t.status,...t.error?{error:t.error}:{},durationMs:t.durationMs});return[...this.ensureStarted(),r,this.event({type:"exec.completed",result:t})]}ensureStarted(){return this.started?[]:(this.started=!0,[this.event({type:"exec.started"}),this.event({type:this.options.resumed?"session.resumed":"session.started"}),this.event({type:"turn.started"})])}itemEvent(t){let r=this.startedItems.has(t.item.id);return t.completed?(this.startedItems.delete(t.item.id),this.event({type:"item.completed",item:t.item})):(this.startedItems.add(t.item.id),this.event({type:r?"item.updated":"item.started",item:t.item}))}event(t){return{schemaVersion:1,sequence:++this.sequence,timestampMs:this.nowMs(),runId:this.options.runId,sessionId:this.options.sessionId,turnId:this.options.turnId,...t}}};function Ke(e){if(e.type==="delta"&&e.role==="assistant"){let t=e.messageId??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",contentDelta:e.thinking},completed:!1}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",contentDelta:e.content},completed:!1}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Te(r,t,n),completed:!1}))]}return e.type!=="message"||e.message.role!=="assistant"?[]:Ye(e.message)}function Ye(e){let t=e.id??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",content:e.thinking},completed:!0}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",content:e.content},completed:!0}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Te(r,t,n),completed:!0}))]}function Te(e,t,r){return{id:e.id??`${t}:tool:${String(r)}`,type:"tool_call",toolCall:e}}var M=class extends m{constructor(t,r){super("internal",t,r),this.name="HeadlessOutputError"}};function xe(e,t,r={}){let n=!1;if(e==="stream-json"&&!r.eventProjector)throw new M("stream-json requires an Exec event projector.");return{async event(o){if(e==="stream-json")for(let s of r.eventProjector?.project(o)??[])await F(t,`${JSON.stringify(s)}
2
+ import{a as Z}from"./chunk-2LLMI3OF.js";import{a as te,d as re}from"./chunk-YKYKYGJQ.js";import{a as oe,b as ie}from"./chunk-WYLGAV2H.js";import"./chunk-DGZI73PE.js";import{s as H,wd as Oe}from"./chunk-AQSBE25I.js";import{b as Y,c as x}from"./chunk-A2CQYOXE.js";import{c as Q,q as O}from"./chunk-ZXUXZKGU.js";import"./chunk-EFJXTS5E.js";import"./chunk-PPIEC7ZM.js";import"./chunk-C3JRMX7L.js";import"./chunk-R6GVNV7J.js";import"./chunk-75PL5LYJ.js";import"./chunk-VYI2WX6B.js";import"./chunk-JAU52A7E.js";import"./chunk-HQ2U4QVQ.js";import"./chunk-4Y64C4JT.js";import{d as K}from"./chunk-D3NBJEJ2.js";import"./chunk-IEL7EQIF.js";import{Na as J,Oa as z}from"./chunk-PGOU6MFH.js";import"./chunk-MMRA4VD2.js";import"./chunk-CWWDVX6C.js";import"./chunk-ZITT4GJK.js";import{a as ee,b as ne}from"./chunk-YPMJNO4T.js";import"./chunk-AGWQ62YH.js";import"./chunk-LOQ4VVEN.js";import"./chunk-ECV3PLKX.js";import"./chunk-PWQHCWDV.js";import"./chunk-SHXPTUWI.js";import"./chunk-IIHJNKC3.js";import"./chunk-II4JKPH5.js";import"./chunk-KSPFS4MM.js";import"./chunk-CK62QLTS.js";import"./chunk-WFWSBUYD.js";import{e as Ae}from"./chunk-D76SO2ME.js";var h=Object.freeze({success:0,invocation:2,config:3,runtime:4,timeout:6,limit:7,internal:70,cancelled:130,brokenPipe:141}),m=class extends O{constructor(r,n,o){super(r,n,{code:`exec.${r}`,retryable:r==="runtime",...o});this.kind=r;this.name="TuiExecError"}};function se(e){switch(e.status){case"succeeded":return h.success;case"failed":return e.error?.category==="config"?h.config:e.error?.category==="internal"?h.internal:h.runtime;case"timeout":return h.timeout;case"cancelled":return h.cancelled;case"limit_exceeded":return h.limit}return h.internal}function v(e){return e instanceof m?h[e.kind]:h.internal}async function ae(e,t){try{return z(e,t)}catch(r){let n=r instanceof J?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new m("config",n,{cause:r})}}function I(e){return e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"?x(e):e.kind==="runtime"?`The run failed: ${x(e)}. Retry after the connection recovers.`:`MCode encountered an internal error: ${x(e)}. Retry; if it keeps happening, report it through an available support channel.`}function ue(e){return e.status==="timeout"?"The run timed out. Increase --timeout or retry.":e.status==="limit_exceeded"?"The run reached its step limit. Increase --max-steps or narrow the task.":e.status==="cancelled"?"The run was cancelled.":e.error?.category==="config"?`The run could not start with the current configuration${e.error.message?`: ${x(e.error.message)}`:""}. Open MCode and run /doctor.`:e.error?.category==="internal"?`MCode encountered an internal error${e.error.message?`: ${x(e.error.message)}`:""}. Retry; if it keeps happening, report it through an available support channel.`:`The run failed${e.error?.message?`: ${x(e.error.message)}`:""}. Retry after the connection recovers.`}import{readFile as Ue,realpath as V,stat as j}from"node:fs/promises";import{homedir as fe}from"node:os";import{basename as ge,dirname as Le,extname as He,isAbsolute as We,resolve as N}from"node:path";var W=Ae(Oe(),1);function ce(e,t){let r=_e(e,t.outputSchema);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:r.sessionId,turnId:r.turnId,status:r.status==="awaiting-user-continuation"?"failed":r.status,...r.status==="succeeded"?{output:me(r.answer,t.outputSchema)}:{},...r.error?{error:{...r.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},durationMs:r.durationMs}}function de(e){return _(e)?e.schemaVersion===1&&e.type==="exec.result"&&typeof e.runId=="string"&&typeof e.sessionId=="string"&&typeof e.turnId=="string"&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&Ne(e.status)&&je(e.model)&&De(e.usage)&&$e(e.error):!1}function _e(e,t){if(e.status==="awaiting-user-continuation")return{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:!1}};if(e.status!=="succeeded"||!t)return e;try{return me(e.answer,t),e}catch(r){return{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:r instanceof Error?r.message:"Structured output was not valid JSON.",retryable:!0}}}}function me(e,t){if(!t)return e??null;if(!e?.trim())throw new Error("Structured output was empty.");let r;try{r=JSON.parse(e)}catch(s){throw new Error("Structured output was not valid JSON.",{cause:s})}let n=new W.Ajv({allErrors:!0,strict:!1}),o=n.compile(t);if(!o(r)){let s=n.errorsText(o.errors,{separator:"; "});throw new Error(`Structured output did not match --output-schema: ${s}`)}return r}function le(e){new W.Ajv({allErrors:!0,strict:!1}).compile(e)}function Ne(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function je(e){return e===void 0?!0:_(e)?typeof e.providerId=="string"&&typeof e.modelId=="string"&&b(e.variant)&&b(e.providerSource)&&b(e.providerKind)&&b(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict"):!1}function De(e){return e===void 0?!0:_(e)?Object.values(e).every(t=>t===void 0||typeof t=="number"&&Number.isFinite(t)):!1}function $e(e){return e===void 0?!0:_(e)?(e.category==="config"||e.category==="runtime"||e.category==="internal")&&b(e.code)&&typeof e.message=="string"&&(e.retryable===void 0||typeof e.retryable=="boolean"):!1}function b(e){return e===void 0||typeof e=="string"}function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qe={".csv":"text/csv",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".log":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".webp":"image/webp",".xml":"application/xml",".yaml":"application/yaml",".yml":"application/yaml"};async function ye(e,t,r,n){if(R(n),t.input!==void 0&&t.input!=="-")throw f('--input currently accepts only "-".');if(e!==void 0&&t.input!==void 0)throw f("The prompt argument and --input cannot be combined.");if(t.session&&t.continue)throw f("--session and --continue are mutually exclusive.");let o=q("--input-format",t.inputFormat??"text",["text","json"]),s=q("--output-format",t.outputFormat??"text",["text","json","stream-json"]),i=q("--permission",t.permission??"smart",["ask","smart","full","off"]);if(i==="ask")throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.");let l=i,d=await he(t.cwd??process.cwd(),"--cwd");R(n);let g=t.input==="-"?await r():e??"";R(n);let E=Be(g,o),p=await Promise.all((t.file??[]).map(S=>Xe(S,d,n))),c=ne(p);if(c==="count")throw f(`You can attach up to ${String(10)} files.`);if(c==="total-bytes")throw f("Attachments can total up to the 100 MB limit.");if(!E.trim()&&p.length===0)throw f("A prompt, --input -, or at least one --file is required.");let u=t.timeout===void 0?void 0:Je(t.timeout,"--timeout"),y=t.maxSteps===void 0?void 0:ze(t.maxSteps,"--max-steps"),a=t.config===void 0?void 0:await Ee(t.config,d,"--config"),w=t.outputSchema===void 0?void 0:await Ve(t.outputSchema,d),T=t.outputLastMessage===void 0?void 0:await Ge(t.outputLastMessage,d);return{prompt:E,workspaceDir:d,attachments:p,...t.model?.trim()?{model:t.model.trim()}:{},...t.session?.trim()?{sessionId:t.session.trim()}:{},continueSession:t.continue===!0,...a?{configPath:a}:{},permission:l,...u===void 0?{}:{timeoutMs:u},...y===void 0?{}:{maxSteps:y},format:s,...w===void 0?{}:{outputSchema:w},...T===void 0?{}:{outputLastMessagePath:T}}}async function Ve(e,t){let r=e.trim();try{return pe(r)}catch(o){if(r.startsWith("{")||r.startsWith("[")||!(o instanceof SyntaxError))throw f("--output-schema requires a JSON object.",o)}let n=await Ee(e,t,"--output-schema");try{return pe(await Ue(n,"utf8"))}catch(o){throw f("--output-schema requires a JSON object.",o)}}function pe(e){let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("schema must be a JSON object");return le(t),t}async function Ge(e,t){let r=D(e,t),n=await he(Le(r),"--output-last-message"),o=N(n,ge(r));if((await j(o).catch(i=>{if(!(i&&typeof i=="object"&&"code"in i&&i.code==="ENOENT"))throw f(`--output-last-message is invalid: ${P(i)}`)}))?.isDirectory())throw f("--output-last-message must reference a file.");return o}async function Xe(e,t,r){R(r);let n=D(e,t),o=await V(n).catch(d=>{throw f(`Cannot attach ${e}: ${P(d)}`)}),s=await j(o).catch(d=>{throw f(`Cannot attach ${e}: ${P(d)}`)});if(R(r),!s.isFile())throw f(`Cannot attach ${e}: path is not a file.`);let i=ge(o),l=qe[He(i).toLowerCase()]??ee(i)??"application/octet-stream";return{type:l.startsWith("image/")?"image":"file",filePath:o,fileName:i,mimeType:l,sizeBytes:s.size}}function R(e){if(e?.aborted)throw new m("cancelled","Invocation was cancelled.",{cause:e.reason})}async function he(e,t){let r=await V(D(e,process.cwd())).catch(o=>{throw f(`${t} is invalid: ${P(o)}`)});if(!(await j(r)).isDirectory())throw f(`${t} must reference a directory.`);return r}async function Ee(e,t,r){let n=await V(D(e,t)).catch(s=>{throw f(`${r} is invalid: ${P(s)}`)});if(!(await j(n)).isFile())throw f(`${r} must reference a file.`);return n}function D(e,t){let r=e.trim();if(!r)throw f("Path value cannot be empty.");let n=r==="~"?fe():r.startsWith("~/")||r.startsWith("~\\")?N(fe(),r.slice(2)):r;return We(n)?N(n):N(t,n)}function Be(e,t){if(t==="text")return e;let r;try{r=JSON.parse(e)}catch(n){throw f("--input-format json requires valid JSON.",n)}if(typeof r=="string")return r;if(r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.prompt=="string")return r.prompt;throw f("--input-format json accepts a JSON string or an object with string prompt.")}function Je(e,t){let r=/^(\d+)(ms|s|m|h)?$/i.exec(e.trim());if(!r)throw f(`${t} must be a positive duration such as 500ms, 30s, or 2m.`);let n=Number(r[1]),o=r[2]?.toLowerCase()==="h"?36e5:r[2]?.toLowerCase()==="m"?6e4:r[2]?.toLowerCase()==="s"?1e3:1,s=n*o;if(!Number.isSafeInteger(s)||s<1)throw f(`${t} must resolve to a positive safe integer in milliseconds.`);return s}function ze(e,t){if(!/^\d+$/.test(e.trim()))throw f(`${t} must be a positive integer.`);let r=Number(e);if(!Number.isSafeInteger(r)||r<1)throw f(`${t} must be a positive safe integer.`);return r}function q(e,t,r){if(r.includes(t))return t;throw f(`${e} must be one of: ${r.join(", ")}.`)}function f(e,t){return new m("invocation",e,t===void 0?void 0:{cause:t})}function P(e){return e instanceof Error?e.message:String(e)}import{resolve as ve}from"node:path";function we(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}import{randomUUID as Qe}from"node:crypto";import{rename as Ze,unlink as et,writeFile as tt}from"node:fs/promises";import{basename as rt,dirname as nt,join as ot}from"node:path";var $=class{constructor(t){this.options=t;this.nowMs=t.nowMs??Date.now}sequence=0;started=!1;completed=!1;startedItems=new Set;nowMs;project(t){if(this.completed)throw new Error("Exec events cannot follow exec.completed.");let r=Ke(t);return[...this.ensureStarted(),...r.map(n=>this.itemEvent(n))]}complete(t){if(this.completed)throw new Error("exec.completed was projected more than once.");this.completed=!0;let r=t.status==="succeeded"?this.event({type:"turn.completed",...t.model?{model:t.model}:{},...t.usage?{usage:t.usage}:{},durationMs:t.durationMs}):this.event({type:"turn.failed",status:t.status,...t.error?{error:t.error}:{},durationMs:t.durationMs});return[...this.ensureStarted(),r,this.event({type:"exec.completed",result:t})]}ensureStarted(){return this.started?[]:(this.started=!0,[this.event({type:"exec.started"}),this.event({type:this.options.resumed?"session.resumed":"session.started"}),this.event({type:"turn.started"})])}itemEvent(t){let r=this.startedItems.has(t.item.id);return t.completed?(this.startedItems.delete(t.item.id),this.event({type:"item.completed",item:t.item})):(this.startedItems.add(t.item.id),this.event({type:r?"item.updated":"item.started",item:t.item}))}event(t){return{schemaVersion:1,sequence:++this.sequence,timestampMs:this.nowMs(),runId:this.options.runId,sessionId:this.options.sessionId,turnId:this.options.turnId,...t}}};function Ke(e){if(e.type==="delta"&&e.role==="assistant"){let t=e.messageId??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",contentDelta:e.thinking},completed:!1}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",contentDelta:e.content},completed:!1}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Te(r,t,n),completed:!1}))]}return e.type!=="message"||e.message.role!=="assistant"?[]:Ye(e.message)}function Ye(e){let t=e.id??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",content:e.thinking},completed:!0}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",content:e.content},completed:!0}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Te(r,t,n),completed:!0}))]}function Te(e,t,r){return{id:e.id??`${t}:tool:${String(r)}`,type:"tool_call",toolCall:e}}var M=class extends m{constructor(t,r){super("internal",t,r),this.name="HeadlessOutputError"}};function xe(e,t,r={}){let n=!1;if(e==="stream-json"&&!r.eventProjector)throw new M("stream-json requires an Exec event projector.");return{async event(o){if(e==="stream-json")for(let s of r.eventProjector?.project(o)??[])await F(t,`${JSON.stringify(s)}
3
3
  `)},async result(o){if(n)throw new M("ExecResult was encoded more than once.");if(!de(o))throw new M("Headless coordinator returned an invalid ExecResult.");if(n=!0,e==="stream-json"){for(let s of r.eventProjector?.complete(o)??[])await F(t,`${JSON.stringify(s)}
4
4
  `);return}if(e==="json"){await F(t,`${JSON.stringify(o)}
5
5
  `);return}if(o.status==="succeeded"){let s=typeof o.output=="string"?Z(o.output):JSON.stringify(o.output);await F(t,`${s??""}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as h,b as f,c as g}from"./chunk-NF23WB7F.js";import"./chunk-C3JRMX7L.js";import{r as m}from"./chunk-AOZUEPXI.js";import"./chunk-O6RIRKRN.js";import"./chunk-HQ2U4QVQ.js";import"./chunk-MMRA4VD2.js";import"./chunk-CWWDVX6C.js";import"./chunk-D76SO2ME.js";import{createInterface as M}from"node:readline/promises";import{stripVTControlCharacters as w}from"node:util";var $=80,T=15e3,l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],v=72;async function V(t,e={}){let n=e.application??new g({currentVersion:t}),r=e.interactive??!!(process.stdin.isTTY&&process.stdout.isTTY),a=e.write??(s=>process.stdout.write(s)),c=e.schedulePendingPrefixUpdate??(()=>m());if(await c()){a(`${h()}
2
+ import{a as h,b as f,c as g}from"./chunk-TYJKJAGQ.js";import"./chunk-C3JRMX7L.js";import{t as m}from"./chunk-OYVCWRBD.js";import"./chunk-O6RIRKRN.js";import"./chunk-HQ2U4QVQ.js";import"./chunk-MMRA4VD2.js";import"./chunk-CWWDVX6C.js";import"./chunk-D76SO2ME.js";import{createInterface as M}from"node:readline/promises";import{stripVTControlCharacters as w}from"node:util";var $=80,T=15e3,l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],v=72;async function V(t,e={}){let n=e.application??new g({currentVersion:t}),r=e.interactive??!!(process.stdin.isTTY&&process.stdout.isTTY),a=e.write??(s=>process.stdout.write(s)),c=e.schedulePendingPrefixUpdate??(()=>m());if(await c()){a(`${h()}
3
3
  `);return}let i=await n.inspect();if(i.kind==="current"){a(i.source==="managed-installer"?`MCode ${i.currentVersion} is current on ${i.channel}.
4
4
  `:`MCode ${i.currentVersion} is current on @${i.packageTag}.
5
5
  `);return}if(i.kind==="ahead"){a(`MCode ${i.currentVersion} is newer than ${i.source==="managed-installer"?i.channel:`@${i.packageTag}`} ${i.latestVersion}; no update was applied.
package/cli.js CHANGED
@@ -1,3 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
3
- import{u as r}from"./chunks/chunk-AOZUEPXI.js";import"./chunks/chunk-O6RIRKRN.js";import"./chunks/chunk-HQ2U4QVQ.js";import{k as i}from"./chunks/chunk-77VGHMFO.js";import"./chunks/chunk-PGOU6MFH.js";import"./chunks/chunk-MMRA4VD2.js";import"./chunks/chunk-CWWDVX6C.js";import"./chunks/chunk-ZITT4GJK.js";import"./chunks/chunk-D76SO2ME.js";var{getTuiDataDirPath:o}=await import("./chunks/data-dir-335LYS7R.js");i({dataDir:o()});var a=await r();try{let{runTuiCli:t}=await import("./chunks/main-PUHNEWJZ.js");await t()}finally{a.remove()}
3
+ import{n,o as a,w as s}from"./chunks/chunk-OYVCWRBD.js";import"./chunks/chunk-O6RIRKRN.js";import"./chunks/chunk-HQ2U4QVQ.js";import{k as o,m as i}from"./chunks/chunk-IEL7EQIF.js";import"./chunks/chunk-PGOU6MFH.js";import"./chunks/chunk-MMRA4VD2.js";import"./chunks/chunk-CWWDVX6C.js";import"./chunks/chunk-ZITT4GJK.js";import"./chunks/chunk-D76SO2ME.js";import{fileURLToPath as u}from"node:url";async function l(){let c=n(u(__mavis_tuiPackageEntryUrl)),t=a(c),r;try{r=i(process.argv.slice(2),t)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}
4
+ `),process.exitCode=1;return}let{getTuiDataDirPath:m}=await import("./chunks/data-dir-4HGM3ZJQ.js");o({dataDir:m(),...r?{startupBuildEnvironment:r}:{}});let p=await s();try{let{runTuiCli:e}=await import("./chunks/main-Z35ONZIQ.js");await e({allowStartupEnvironmentSelection:t})}finally{p.remove()}}await l();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@minimax-ai/code",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Minimax Code — terminal coding agent",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,5 +0,0 @@
1
- import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{P as Q,a as we,ga as ee}from"./chunk-PGOU6MFH.js";import{e as ge}from"./chunk-D76SO2ME.js";var d="mcode-public",c=["agent.default"],l="agent-backend";var Ee={cn:{dev:"https://account.minimaxi.com",test:"https://account.minimaxi.com",staging:"https://account.minimaxi.com",prod:"https://account.minimaxi.com"},en:{dev:"https://account.minimax.io",test:"https://account.minimax.io",staging:"https://account.minimax.io",prod:"https://account.minimax.io"}};function ht(t,e){if([t.MCODE_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT,t.MCODE_OAUTH_TOKEN_ENDPOINT,t.MCODE_OAUTH_REVOCATION_ENDPOINT].every(s=>!s?.trim())){let s=Ee[e.region][e.buildEnv];return{deviceAuthorizationEndpoint:`${s}/oauth2/device/code`,...te(e.buildEnv),tokenEndpoint:`${s}/oauth2/token`,revocationEndpoint:`${s}/oauth2/revoke`}}let i=z(t.MCODE_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT),o=z(t.MCODE_OAUTH_TOKEN_ENDPOINT),r=z(t.MCODE_OAUTH_REVOCATION_ENDPOINT);if(!i||!o||!r)throw new TypeError("Shared MCode OAuth requires all three public OAuth endpoints to be configured.");return{deviceAuthorizationEndpoint:i,...te(e.buildEnv),tokenEndpoint:o,revocationEndpoint:r}}function te(t){return t==="staging"?{deviceAuthorizationHeaders:{"X-User-Pre":"1"}}:{}}function z(t){if(t?.trim())try{let e=new URL(t);return e.protocol!=="https:"||e.username||e.password||e.hash?void 0:e.toString()}catch{return}}import{createHash as ye}from"node:crypto";import{join as m,resolve as _e}from"node:path";function H(t){let e=m(_e(t.dataDir),"auth"),n=m(e,t.buildEnv,t.region,d),i=`com.minimax.mcode.oauth.${t.buildEnv}.${t.region}`,o=ye("sha256").update(`${e}\0${d}`).digest("base64url");return{authHome:e,namespaceHome:n,lockPath:m(n,"auth.lock"),statePath:m(n,"auth-state.json"),credentialPath:m(n,"auth.json"),legacyLockPath:m(e,"auth.lock"),legacyStatePath:m(e,"auth-state.json"),legacyEncryptedCredentialPath:m(e,"credentials.enc"),buildEnv:t.buildEnv,region:t.region,credentialKey:{service:i,account:o}}}var ie=ge(we(),1);import{open as Me}from"node:fs/promises";import{chmod as ne,mkdir as Ae,open as ve,rename as Se,unlink as Te}from"node:fs/promises";import{dirname as Ce}from"node:path";async function M(t){await Ae(t,{recursive:!0,mode:448}),process.platform!=="win32"&&await ne(t,448)}async function I(t,e){let n=Ce(t);await M(n);let i=`${t}.${process.pid}.${Date.now()}.tmp`,o=await ve(i,"wx",384);try{await o.writeFile(e,{encoding:"utf8"}),await o.sync()}finally{await o.close()}try{process.platform!=="win32"&&await ne(i,384),await Se(i,t)}catch(r){throw await Te(i).catch(()=>{}),r}}import{dirname as ke}from"node:path";var g=class{lockPath;staleMs;retries;constructor(e,n={}){this.lockPath=e,this.staleMs=n.staleMs??3e4,this.retries=n.retries??120}async withLock(e){await M(ke(this.lockPath)),await(await Me(this.lockPath,"a",384)).close();let i=await ie.default.lock(this.lockPath,{realpath:!1,stale:this.staleMs,retries:{retries:this.retries,factor:1.15,minTimeout:5,maxTimeout:250}});try{return await e()}finally{await i()}}};import{readFile as Oe}from"node:fs/promises";var w=2,Ie=1,Pe=/access[_-]?token|refresh[_-]?token|device[_-]?code|code[_-]?verifier/iu;function oe(t){if(!(typeof t!="object"||t===null))for(let[e,n]of Object.entries(t)){if(Pe.test(e))throw new TypeError("Sensitive OAuth fields cannot be persisted in auth-state.json.");oe(n)}}function re(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Invalid OAuth state.");let e=t;if(!(typeof e.schemaVersion=="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=Ie&&e.schemaVersion<=w&&["anonymous","authorizing","authenticated","refreshing","scope_upgrade_required","logging_out","logout_pending","expired","error"].includes(e.status)&&(e.schemaVersion===1&&(e.storeKind==="os-keyring"||e.storeKind==="file")||e.schemaVersion===w&&e.storeKind==="file")&&e.clientId==="mcode-public"&&Array.isArray(e.scopes)&&e.scopes.every(i=>typeof i=="string")&&e.audience==="agent-backend"&&xe(e.buildEnv,e.region)&&(e.expiresAtMs===void 0||typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs))&&Number.isSafeInteger(e.generation)&&e.generation>=0&&(e.authorization===void 0||be(e.authorization))))throw new TypeError("Invalid OAuth state.");return oe(e),e}function xe(t,e){return t===void 0&&e===void 0?!0:(t==="dev"||t==="test"||t==="staging"||t==="prod")&&(e==="cn"||e==="en")}function be(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return typeof e.leaseId=="string"&&e.leaseId.length>0&&typeof e.leaseExpiresAtMs=="number"&&Number.isFinite(e.leaseExpiresAtMs)&&V(e.userCode)&&V(e.verificationUri)&&V(e.verificationUriComplete)}function V(t){return t===void 0||typeof t=="string"}var E=class{path;constructor(e){this.path=e}async read(){let e;try{e=await Oe(this.path,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{return re(JSON.parse(e))}catch(n){throw n instanceof TypeError?n:new TypeError("Invalid OAuth state.")}}async write(e){let n=re(e);await I(this.path,`${JSON.stringify(n,null,2)}
3
- `)}};async function Re(t){let e=await Ne(t),n=new E(t.statePath);await new g(t.lockPath).withLock(async()=>{let o=await n.read();if(o?.schemaVersion===w)return;let r=o??e;r&&await n.write(De(r,t))})}async function Ne(t){let e=new E(t.legacyStatePath);return new g(t.legacyLockPath).withLock(async()=>{let i=await e.read();if(!Ue(i,t))return null;let{authorization:o,...r}=i;return await e.write({...r,status:"error"}),i})}function Ue(t,e){return t!==null&&t.status!=="error"&&t.buildEnv===e.buildEnv&&t.region===e.region}function De(t,e){return{schemaVersion:w,status:"anonymous",storeKind:"file",clientId:"mcode-public",scopes:["agent.default"],audience:"agent-backend",buildEnv:e.buildEnv,region:e.region,generation:t.generation+1}}import{createHash as Le,randomBytes as ze}from"node:crypto";var He="urn:ietf:params:oauth:grant-type:device_code",p=class extends Error{code;constructor(e,n="The OAuth server returned an invalid response."){super(n),this.code=e,this.name="OAuthProtocolError"}},j=class{options;fetchImpl;sleep;now;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.sleep=e.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.now=e.now??Date.now}async startDeviceAuthorization(e={}){let n=ze(32).toString("base64url"),i=Le("sha256").update(n,"ascii").digest("base64url"),o=await this.postForm(this.options.deviceAuthorizationEndpoint,{client_id:d,scope:c.join(" "),audience:l,code_challenge:i,code_challenge_method:"S256"},{headers:this.options.deviceAuthorizationHeaders,signal:e.signal}),r=u(o,"user_code"),s=u(o,"device_code"),a=x(o,"expired_in"),h=!s&&!!r&&a!==void 0,X=s??(h?r:void 0),D=u(o,"verification_uri")??u(o,"verification_url"),Y=x(o,"expires_in")??Be(a,this.now()),L=x(o,"interval"),me=h&&L!==void 0?L/1e3:L??5;if(!X||!r||!D||!Y)throw new p("invalid_device_authorization_response");return{deviceCode:X,codeVerifier:n,...h?{tokenPollingParameter:"user_code"}:{},userCode:r,verificationUri:D,...u(o,"verification_uri_complete")||h?{verificationUriComplete:u(o,"verification_uri_complete")??D}:{},expiresInSec:Y,intervalSec:me}}async pollDeviceToken(e,n={}){let i=this.now()+e.expiresInSec*1e3,o=e.intervalSec*1e3;for(;this.now()<i;){n.signal?.throwIfAborted();let r=e.tokenPollingParameter==="user_code"?{user_code:e.userCode}:{device_code:e.deviceCode},s=await this.postFormAllowOAuthError(this.options.tokenEndpoint,{grant_type:He,...r,client_id:d,code_verifier:e.codeVerifier},{signal:n.signal}),a=u(s.body,"status");if(s.ok&&a==="pending"){await P(this.sleep,o,n.signal);continue}if(s.ok&&a==="slow_down"){o+=5e3,await P(this.sleep,o,n.signal);continue}if(s.ok&&(a==="denied"||a==="access_denied"))throw new p("access_denied");if(s.ok&&(a==="expired"||a==="expired_token"))throw new p("expired_token");if(s.ok)return se(s.body);if(s.error==="authorization_pending"){await P(this.sleep,o,n.signal);continue}if(s.error==="slow_down"){o+=5e3,await P(this.sleep,o,n.signal);continue}throw new p(s.error??"device_authorization_failed")}throw new p("expired_token","The OAuth device authorization expired.")}async refreshToken(e){let n=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:d,scope:c.join(" "),audience:l});return se(n,e)}async revokeToken(e){let n=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:d},{allowEmptySuccess:!0});if(!n.ok)throw new p(n.error??"oauth_request_failed")}async postForm(e,n,i={}){let o=await this.postFormAllowOAuthError(e,n,i);if(!o.ok)throw new p(o.error??"oauth_request_failed");return o.body}async postFormAllowOAuthError(e,n,i={}){let o=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...i.headers},body:new URLSearchParams(n),signal:i.signal}),r=b(await o.json().catch(()=>{}));if(!r&&o.ok&&i.allowEmptySuccess)return{ok:!0,body:{}};if(!r)throw new p("invalid_json_response");let s=u(r,"error");return{ok:o.ok&&!s,body:r,...s?{error:s}:{}}}};async function P(t,e,n){if(!n){await t(e);return}n.throwIfAborted();let i,o=()=>i(n.reason),r=new Promise((s,a)=>{i=a});n.addEventListener("abort",o,{once:!0});try{await Promise.race([t(e),r])}finally{n.removeEventListener("abort",o)}}function se(t,e){let n=u(t,"access_token"),i=u(t,"refresh_token")??e,o=u(t,"token_type"),r=x(t,"expires_in"),s=n?Ve(n):void 0,a=je(t.scope??s?.scope??s?.scp);if(!n||!i||o?.toLowerCase()!=="bearer"||!r||!a.includes(c[0]))throw new p("invalid_token_response");return{accessToken:n,refreshToken:i,tokenType:"Bearer",scopes:a,audience:l,expiresInSec:r,...u(s,"sub")?{subject:u(s,"sub")}:{},...u(s,"account_id")?{accountId:u(s,"account_id")}:{}}}function Ve(t){let e=t.split(".");if(!(e.length!==3||!e[1]))try{return b(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return}}function je(t){return typeof t=="string"?t.split(/\s+/u).filter(Boolean):Array.isArray(t)&&t.every(e=>typeof e=="string")?t:[]}function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function u(t,e){let i=b(t)?.[e];return typeof i=="string"&&i.trim()?i.trim():void 0}function x(t,e){let i=b(t)?.[e];return typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0}function Be(t,e){if(t===void 0)return;if(t<1e12)return t;let n=t-e;return n>0?Math.ceil(n/1e3):void 0}import{randomUUID as F}from"node:crypto";import{watchFile as Fe,unwatchFile as Ke}from"node:fs";var $e=600*1e3,qe=250,A=class extends Error{code="AUTH_REQUIRED";constructor(){super("MCode authentication is required."),this.name="AuthRequiredError"}},S=class extends Error{code="AUTH_LOGIN_CANCELLED";constructor(){super("MCode OAuth device authorization was cancelled."),this.name="AuthLoginCancelledError"}},T=class extends Error{missingScopes;code="AUTH_SCOPE_UPGRADE_REQUIRED";constructor(e){super("The current MCode authorization does not include the required scope."),this.missingScopes=e,this.name="AuthScopeUpgradeRequiredError"}},C=class extends Error{code="AUTH_RESOURCE_CONTRACT_MISMATCH";constructor(){super("The stored credential does not match the MCode resource contract."),this.name="AuthResourceContractMismatchError"}},K=class extends Error{active;requested;code="AUTH_DOMAIN_CONFLICT";constructor(e,n){super(`MCode is signed in to ${e.buildEnv}/${e.region}; sign out before using ${n.buildEnv}/${n.region}.`),this.active=e,this.requested=n,this.name="AuthDomainConflictError"}},$=class{options;stateStore;lock;now;sleep;authorizationLeaseMs;statePollIntervalMs;createLeaseId;loginPromise;loginAbortController;initializePromise;constructor(e){this.options=e,this.stateStore=new E(e.namespace.statePath),this.lock=new g(e.namespace.lockPath),this.now=e.now??Date.now,this.sleep=e.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.authorizationLeaseMs=e.authorizationLeaseMs??$e,this.statePollIntervalMs=e.statePollIntervalMs??qe,this.createLeaseId=e.createLeaseId??F}async getStatus(){await this.initialize();let e=await this.stateStore.read();if(!e)return{status:"anonymous",generation:0,scopes:[]};if(e.status==="authorizing"||e.status==="refreshing"){let n=await this.recoverInterruptedCredentialCommit(e);return y(n)}if(e.status==="authenticated"||e.status==="expired"){let n=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!n||n.generation!==e.generation)return y({...e,status:"error"});try{_(n,[...c])}catch(o){if(o instanceof T)return y({...k(n,this.options.credentialStore.kind,this.options.namespace),status:"scope_upgrade_required"});if(o instanceof C)return y({...e,status:"error"});throw o}let i=k(n,this.options.credentialStore.kind,this.options.namespace);return e.status==="expired"||n.expiresAtMs<=this.now()?y({...i,status:"expired"}):y(i)}return y(e)}login(e={}){if(!this.loginPromise){let n=new AbortController,i=this.initialize().then(()=>this.runLogin(e,n.signal)).finally(()=>{this.loginPromise===i&&(this.loginPromise=void 0,this.loginAbortController=void 0)});this.loginAbortController=n,this.loginPromise=i}return this.loginPromise}async cancelLogin(){let e=this.loginAbortController,n=this.loginPromise;if(!(!e||!n)){e.abort();try{await n}catch(i){if(!(i instanceof S))throw i}}}async getAccessToken(e){await this.initialize(),We(e.requiredScopes);let n=await this.readUsableCredential(e.requiredScopes);return n.credential.expiresAtMs-this.now()>=e.minValidityMs?B(n.credential):this.lock.withLock(async()=>{let i=await this.readUsableCredential(e.requiredScopes);return i.credential.expiresAtMs-this.now()>=e.minValidityMs?B(i.credential):this.refreshCredential(i)})}async handleUnauthorized(e){await this.initialize();try{return await this.lock.withLock(async()=>{let n=await this.readUsableCredential([...c]);return n.credential.generation>e.generation?"retry":n.credential.generation<e.generation?"logout":(await this.refreshCredential(n),"retry")})}catch(n){if(n instanceof A)return"logout";throw n}}async logout(e){return await this.initialize(),this.lock.withLock(async()=>{let n=await this.stateStore.read(),i=await this.options.credentialStore.get(this.options.namespace.credentialKey),o=Math.max(n?.generation??0,i?.generation??0);if(!i&&(!n||n.status==="anonymous"))return{status:"anonymous",generation:o};let r=o+1;if(await this.stateStore.write(v({status:"logging_out",generation:r,storeKind:this.options.credentialStore.kind},this.options.namespace)),e.revoke&&i)try{await this.options.oauthClient.revokeToken(i.refreshToken)}catch{return await this.stateStore.write(v({status:"logout_pending",generation:r,storeKind:this.options.credentialStore.kind},this.options.namespace)),{status:"logout_pending",generation:r}}return await this.options.credentialStore.delete(this.options.namespace.credentialKey),await this.stateStore.write(v({status:"anonymous",generation:r,storeKind:this.options.credentialStore.kind},this.options.namespace)),{status:"anonymous",generation:r}})}watch(e){let n=()=>{this.getStatus().then(e).catch(()=>{})};return Fe(this.options.namespace.statePath,{interval:this.statePollIntervalMs},n),()=>Ke(this.options.namespace.statePath,n)}initialize(){return this.initializePromise??=(async()=>{await this.options.initialize?.(),await this.options.credentialStore.healthCheck()})(),this.initializePromise}async runLogin(e,n){for(;;){q(n);let i=this.createLeaseId(),o=await this.lock.withLock(async()=>{let r=await this.stateStore.read();Ze(r,this.options.namespace);let s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(r&&s&&r.generation===s.generation&&(r.status==="authenticated"||r.status==="expired"||r.status==="refreshing"))try{return _(s,[...c]),r.status==="authenticated"&&s.expiresAtMs>this.now()?{kind:"authenticated",generation:s.generation}:{kind:"refresh"}}catch(h){if(!(h instanceof T)&&!(h instanceof C))throw h}if(r?.status==="authorizing"&&r.authorization&&r.authorization.leaseExpiresAtMs>this.now())return{kind:"wait",leaseExpiresAtMs:r.authorization.leaseExpiresAtMs};let a=Math.max(r?.generation??0,s?.generation??0);return await this.stateStore.write({...v({status:"authorizing",generation:a,storeKind:this.options.credentialStore.kind},this.options.namespace),authorization:{leaseId:i,leaseExpiresAtMs:this.now()+this.authorizationLeaseMs}}),{kind:"owner"}});if(o.kind==="authenticated")return{status:"authenticated",generation:o.generation};if(o.kind==="refresh"){await this.getAccessToken({requiredScopes:[...c],minValidityMs:Number.MAX_SAFE_INTEGER});let r=await this.stateStore.read();if(r?.status==="authenticated")return{status:"authenticated",generation:r.generation};continue}if(o.kind==="wait"){let r=await this.waitForAuthorization(o.leaseExpiresAtMs,e.onDeviceAuthorization,n);if(r)return r;continue}try{let r=await this.options.oauthClient.startDeviceAuthorization({signal:n});await this.publishAuthorizationProgress(i,r),e.onDeviceAuthorization?.(Je(r));let s=await this.options.oauthClient.pollDeviceToken(r,{signal:n});return await this.commitLogin(i,s)}catch(r){let s=n.aborted;throw await this.releaseAuthorizationLease(i,s?"anonymous":"error"),s?new S:r}}}async commitLogin(e,n){return this.lock.withLock(async()=>{let i=await this.stateStore.read();if(i?.status!=="authorizing"||i.authorization?.leaseId!==e)throw new A;let o=await this.options.credentialStore.get(this.options.namespace.credentialKey),r=Math.max(i.generation,o?.generation??0)+1,s=ae(n,r,this.now(),F());return await this.options.credentialStore.put(this.options.namespace.credentialKey,s),await this.stateStore.write(k(s,this.options.credentialStore.kind,this.options.namespace)),{status:"authenticated",generation:r}})}async waitForAuthorization(e,n,i){let o=!1;for(;this.now()<e;){q(i);let r=await this.stateStore.read();if(!o&&r?.status==="authorizing"&&r.authorization?.userCode&&r.authorization.verificationUri&&(n?.({userCode:r.authorization.userCode,verificationUri:r.authorization.verificationUri,...r.authorization.verificationUriComplete?{verificationUriComplete:r.authorization.verificationUriComplete}:{},expiresInSec:Math.max(1,Math.ceil((r.authorization.leaseExpiresAtMs-this.now())/1e3))}),o=!0),r?.status==="authenticated"){let s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(s&&s.generation===r.generation)return _(s,[...c]),{status:"authenticated",generation:r.generation}}if(r?.status!=="authorizing")return;await Ge(this.sleep,this.statePollIntervalMs,i)}}async publishAuthorizationProgress(e,n){await this.lock.withLock(async()=>{let i=await this.stateStore.read();if(i?.status!=="authorizing"||i.authorization?.leaseId!==e)throw new A;await this.stateStore.write({...i,authorization:{...i.authorization,userCode:n.userCode,verificationUri:n.verificationUri,...n.verificationUriComplete?{verificationUriComplete:n.verificationUriComplete}:{}}})})}async releaseAuthorizationLease(e,n){await this.lock.withLock(async()=>{let i=await this.stateStore.read();i?.status!=="authorizing"||i.authorization?.leaseId!==e||await this.stateStore.write(v({status:n,generation:i.generation,storeKind:this.options.credentialStore.kind},this.options.namespace))})}async recoverInterruptedCredentialCommit(e){let n=await this.options.credentialStore.get(this.options.namespace.credentialKey);return!n||n.generation<=e.generation?e:(_(n,[...c]),this.lock.withLock(async()=>{let i=await this.stateStore.read(),o=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!i||!o||i.status!=="authorizing"&&i.status!=="refreshing"||o.generation<=i.generation)return i??e;_(o,[...c]);let r=k(o,this.options.credentialStore.kind,this.options.namespace);return await this.stateStore.write(r),r}))}async readUsableCredential(e){let n=await this.stateStore.read();if(!n||n.status!=="authenticated"&&n.status!=="expired"&&n.status!=="refreshing")throw new A;let i=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!i||n.generation!==i.generation)throw new A;return _(i,e),{state:n,credential:i}}async refreshCredential(e){await this.stateStore.write({...e.state,status:"refreshing"});let n;try{n=await this.options.oauthClient.refreshToken(e.credential.refreshToken)}catch(o){throw await this.stateStore.write({...e.state,status:"expired"}),o}let i=ae(n,Math.max(e.state.generation,e.credential.generation)+1,this.now(),e.credential.loginEpoch);return await this.options.credentialStore.put(this.options.namespace.credentialKey,i),await this.stateStore.write(k(i,this.options.credentialStore.kind,this.options.namespace)),B(i)}};function q(t){if(t?.aborted)throw new S}async function Ge(t,e,n){if(!n){await t(e);return}q(n);let i,o=()=>i(new S),r=new Promise((s,a)=>{i=a});n.addEventListener("abort",o,{once:!0});try{await Promise.race([t(e),r])}finally{n.removeEventListener("abort",o)}}function Je(t){return{userCode:t.userCode,verificationUri:t.verificationUri,...t.verificationUriComplete?{verificationUriComplete:t.verificationUriComplete}:{},expiresInSec:t.expiresInSec}}function v(t,e){return{schemaVersion:w,status:t.status,storeKind:t.storeKind,clientId:d,scopes:[...c],audience:l,buildEnv:e.buildEnv,region:e.region,generation:t.generation}}function k(t,e,n){return{...v({status:"authenticated",generation:t.generation,storeKind:e},n),scopes:t.scopes,expiresAtMs:t.expiresAtMs}}function ae(t,e,n,i=F()){let o={schemaVersion:1,accessToken:t.accessToken,refreshToken:t.refreshToken,tokenType:t.tokenType,clientId:d,scopes:t.scopes,audience:l,expiresAtMs:n+t.expiresInSec*1e3,generation:e,loginEpoch:i,...t.subject?{subject:t.subject}:{},...t.accountId?{accountId:t.accountId}:{}};if(_(o,[...c]),t.audience!==l)throw new C;return o}function We(t){let e=t.filter(n=>!c.includes(n));if(e.length>0)throw new T(e)}function _(t,e){if(t.clientId!==d||t.audience!==l||t.tokenType!=="Bearer")throw new C;let n=e.filter(i=>!t.scopes.includes(i));if(n.length>0)throw new T(n)}function y(t){return{status:t.status,generation:t.generation,scopes:t.scopes,...t.buildEnv===void 0?{}:{buildEnv:t.buildEnv},...t.region===void 0?{}:{region:t.region},...t.expiresAtMs===void 0?{}:{expiresAtMs:t.expiresAtMs}}}function Ze(t,e){if(!(!t||t.status==="anonymous"||t.buildEnv===void 0||t.region===void 0||t.buildEnv===e.buildEnv&&t.region===e.region))throw new K({buildEnv:t.buildEnv,region:t.region},{buildEnv:e.buildEnv,region:e.region})}function B(t){return{accessToken:t.accessToken,expiresAtMs:t.expiresAtMs,generation:t.generation,scopes:c,audience:l}}import{readFile as Qe,stat as ce}from"node:fs/promises";import{join as et}from"node:path";var Xe=1,Ye=1,f=class extends Error{code="CREDENTIAL_RECORD_CORRUPT";constructor(){super("The stored OAuth credential record is invalid."),this.name="CredentialRecordCorruptError"}},R=class extends Error{code="AUTH_CREDENTIAL_STORE_PERMISSION";constructor(){super("The OAuth credential file permissions are not private."),this.name="CredentialStorePermissionError"}};function G(t){return t===void 0||typeof t=="string"}function J(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new f;let e=t,n=e.scopes,i=Array.isArray(n)&&n.every(r=>typeof r=="string");if(!(typeof e.schemaVersion=="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=Ye&&e.schemaVersion<=Xe&&typeof e.accessToken=="string"&&e.accessToken.length>0&&typeof e.refreshToken=="string"&&e.refreshToken.length>0&&e.tokenType==="Bearer"&&e.clientId===d&&i&&e.audience===l&&typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs)&&Number.isSafeInteger(e.generation)&&e.generation>=0&&G(e.subject)&&G(e.accountId)&&G(e.loginEpoch)))throw new f;return e}var Z=1;function W(t){return`${t.service}\0${t.account}`}function ue(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new f;let e=t;if(e.schemaVersion!==Z||typeof e.records!="object"||e.records===null||Array.isArray(e.records))throw new f;let n=Object.fromEntries(Object.entries(e.records).map(([i,o])=>[i,J(o)]));return{schemaVersion:Z,records:n}}var N=class{kind="file";authHome;path;constructor(e){this.authHome=e.authHome,this.path=et(e.authHome,"auth.json")}async get(e){return(await this.readPayload()).records[W(e)]??null}async put(e,n){let i=await this.readPayload();i.records[W(e)]=J(n),await this.writePayload(i)}async delete(e){let n=await this.readPayload();delete n.records[W(e)],await this.writePayload(n)}async healthCheck(){await M(this.authHome),await this.assertPrivatePermissions()}async readPayload(){let e;try{await this.assertPrivatePermissions(),e=await Qe(this.path,"utf8")}catch(n){if(n.code==="ENOENT")return{schemaVersion:Z,records:{}};throw n}try{return ue(JSON.parse(e))}catch(n){throw n instanceof f?n:new f}}async assertPrivatePermissions(){if(process.platform!=="win32")try{let[e,n]=await Promise.all([ce(this.authHome),ce(this.path)]);if((e.mode&63)!==0||(n.mode&63)!==0)throw new R}catch(e){if(e.code==="ENOENT")return;throw e}}async writePayload(e){let n=ue(e);await I(this.path,`${JSON.stringify(n,null,2)}
4
- `)}};function tt(t){return new N(t)}function U(t={}){let e=t.embeddedBuildEnvironment??de(),n=t.runtimeBuildEnv??Q();return{region:t.runtimeRegion??"cn",buildEnv:e??nt(n)}}function vn(t=de()){return t??"dev"}function de(){return"prod"}function nt(t){return t==="dev"?"test":t}import ot from"node:fs";import O from"node:fs";import he from"node:path";var le="preferences",it="mcode-region.json";function pe(t,e){try{let n=JSON.parse(O.readFileSync(fe(t),"utf8"));if(n.version!==1||!n.regions||typeof n.regions!="object")return;let i=n.regions[e];return i==="cn"||i==="en"?i:void 0}catch{return}}function Mn(t,e){let n=he.join(t,le);O.mkdirSync(n,{recursive:!0,mode:448});let i=fe(t),r={version:1,regions:{...rt(i),[e.buildEnv]:e.region},updatedAtMs:Date.now()},s=`${i}.${process.pid}.${Date.now()}.tmp`;return O.writeFileSync(s,`${JSON.stringify(r,null,2)}
5
- `,{encoding:"utf8",mode:384}),O.renameSync(s,i),i}function fe(t){return he.join(t,le,it)}function rt(t){try{let e=JSON.parse(O.readFileSync(t,"utf8"));return e.version!==1||!e.regions||typeof e.regions!="object"?{}:Object.fromEntries(Object.entries(e.regions).filter(([n,i])=>(n==="dev"||n==="test"||n==="staging"||n==="prod")&&(i==="cn"||i==="en")))}catch{return{}}}var st=/^[A-Za-z0-9._-]+$/u;function Rn(t={}){ee(!1);let{target:e=process.env,dataDir:n,...i}=t,o=U(i),r=n?pe(n,o.buildEnv):void 0,s=n?at(n,o.buildEnv):void 0,a=ut(e.MAVIS_REGION),h=U({...i,runtimeRegion:i.runtimeRegion??a??r??s?.region??"cn"});return n&&(e.MINIMAX_DATA_DIR=n,e.MAVIS_DATA_DIR=n),e.MAVIS_REGION=h.region,e.MAVIS_BUILD_ENV=h.buildEnv,e.__MAVIS_RUNTIME_MANAGED="1",h}function Nn(t,e=U().buildEnv){if(t===void 0)return;if(e!=="test"&&e!=="staging")throw new Error("--lane is only supported in test or staging builds.");let n=t.trim();if(!st.test(n))throw new Error("--lane only accepts letters, numbers, dot, underscore, and hyphen.");return n}function at(t,e){let n=["cn","en"].filter(o=>{try{let r=H({dataDir:t,buildEnv:e,region:o}),s=JSON.parse(ot.readFileSync(r.statePath,"utf8"));return s.buildEnv===e&&s.region===o&&ct(s.status)}catch{return!1}}),i=n.length===1?n[0]:void 0;return i?{buildEnv:e,region:i}:void 0}function ct(t){return t==="authorizing"||t==="authenticated"||t==="refreshing"||t==="scope_upgrade_required"||t==="expired"}function ut(t){return t==="cn"||t==="en"?t:void 0}export{c as a,H as b,Re as c,j as d,ht as e,$ as f,tt as g,U as h,vn as i,Mn as j,Rn as k,Nn as l};
@@ -1,2 +0,0 @@
1
- import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{q as R}from"./chunk-ZXUXZKGU.js";var L=1e3,P=class{constructor(t,n={}){this.runtime=t;this.options=n;this.nowMs=n.nowMs??Date.now}activeRun;retiringRun;nowMs;activeTurnId(){return this.activeRun?.turnId}retiringTurnId(){return this.retiringRun?.turnId}retirement(){return this.retiringRun?.settlement}async execute(t,n=()=>{},i,r){if(this.activeRun)throw new Error("A run is already active.");if(this.retiringRun)throw new Error("The previous run is still stopping.");let o=G(t.turnId);this.activeRun=o;let T=this.nowMs(),g,c,b=!1,u="succeeded",f=null,d="",a,h=0,p;try{if(c=await W(t.session,o.controller.signal),!c)throw o.controller.signal.reason??new Error("Turn cancelled before Session setup.");o.sessionId=c.sessionId,t.policy?.timeoutMs!==void 0&&(g=setTimeout(()=>{this.stopActive(o,"timeout").catch(()=>{})},t.policy.timeoutMs),g.unref?.());let l=this.runtime.sendMessage(N(t,c),o.controller.signal)[Symbol.asyncIterator]();try{for(;;){let E=await l.next();if(E.done)break;let s=E.value;b||(b=!0,i?.());let I=B(s);if(I){u="awaiting-user-continuation",a=I,await x(n,s);break}if(U(s)){if(p=C(p,s.message.usage),t.policy?.maxSteps!==void 0&&h>=t.policy.maxSteps){u="limit_exceeded",await this.stopActive(o,"limit");break}if(h+=1,s.message.toolCalls?.length)f=null,d="";else{let w=s.message.content?.trim()?s.message.content:d;f=w.trim()?w:null,d=""}}else D(s)&&(d+=s.content);let v=j(s);v&&(u=v.status,a=v.error),await x(n,s)}}finally{await l.return?.(void 0)}d.trim()&&(f=d),t.policy?.requireAnswer===!0&&u==="succeeded"&&f===null&&(u="failed",a={category:"runtime",code:"EMPTY_RESPONSE",message:"Runtime completed without a final assistant response.",retryable:!0}),u=M(o.stopReason,u)}catch(l){o.stopReason||o.controller.signal.aborted?u=M(o.stopReason,"cancelled"):(u="failed",a=Q(l))}finally{g&&clearTimeout(g),this.activeRun===o&&(this.activeRun=void 0)}let y={sessionId:c?.sessionId??"",turnId:t.turnId,status:u,answer:f,...t.model?{model:{...t.model}}:{},...p?{usage:p}:{},...a?{error:a}:{},durationMs:Math.max(0,this.nowMs()-T)};if(r)try{await r(y)}catch{u="failed";let l={category:"internal",code:"AUTOMATION_RESULT_WRITE_FAILED",message:"Could not publish the TUI automation result.",retryable:!0};a=l,y={...y,status:u,error:l}}return o.resolveSettled(),{turnId:t.turnId,...c?{session:c}:{},status:u,outcome:y,...a?.message?{error:a.message}:{}}}async abort(){let t=this.activeRun;return t?(t.abortPromise??=this.stopAndSettle(t),t.abortPromise):!1}async stopAndSettle(t){let n=await this.stopActive(t,"user_stop"),i=t.settled.then(()=>n),r=await z(i,this.options.cancellationSettlementTimeoutMs??L);if(this.activeRun===t&&(this.activeRun=void 0),r.settled)return r.value;let o={turnId:t.turnId,settlement:i};return o.settlement=i.finally(()=>{this.retiringRun===o&&(this.retiringRun=void 0)}),this.retiringRun=o,n}async stopActive(t,n){t.stopReason??=n;let i=t.sessionId,r=i?this.runtime.abortSession({id:i,turnId:t.turnId,reason:n==="limit"?"max_steps":n}).catch(()=>!1):Promise.resolve(!0);return t.controller.abort(new Error(`Turn stopped: ${n}`)),r}};function C(e,t){if(!t)return e;let n={...m(e,t,"totalTokens"),...m(e,t,"inputTokens"),...m(e,t,"outputTokens"),...m(e,t,"reasoningTokens"),...m(e,t,"cacheReadTokens"),...m(e,t,"cacheWriteTokens")};return Object.keys(n).length>0?n:e}function m(e,t,n){let i=t[n];return typeof i!="number"||!Number.isFinite(i)?{}:{[n]:(e?.[n]??0)+i}}function N(e,t){return{id:t.sessionId,turnId:e.turnId,content:e.content,...e.clientIntent?{clientIntent:e.clientIntent}:{},...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 U(e){return e.type==="message"&&e.message.role==="assistant"}function D(e){return e.type==="delta"&&e.role==="assistant"&&typeof e.content=="string"}function F(e){return e.type==="generic"&&(e.eventType.includes("questionnaire")||e.eventType==="runtime.action-required"&&e.data.kind==="questionnaire")}function B(e){if(F(e))return{category:"runtime",code:"QUESTIONNAIRE_REQUIRED",message:"Questionnaire requires user input.",retryable:!0}}function j(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:!0}};if(e.type==="error")return{status:"failed",error:{category:"runtime",message:e.message,retryable:!0}};if(e.type==="session-status"){if(e.status==="error")return{status:"failed",error:{category:"runtime",message:e.message??"Runtime turn failed.",retryable:!0}};if(e.status==="aborted"||e.status==="interrupted")return{status:"cancelled"}}}function Q(e){if(e instanceof R)return{category:e.category==="config"||e.category==="internal"?e.category:"runtime",code:e.code,message:e.message,retryable:e.retryable};if(e&&typeof e=="object"){let 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:!0}}}return{category:"runtime",message:e instanceof Error?e.message:String(e),retryable:!0}}function M(e,t){return e==="timeout"?"timeout":e==="limit"?"limit_exceeded":e==="user_stop"?"cancelled":t}async function x(e,t){try{await e(t)}catch{}}function G(e){let t=()=>{},n=new Promise(i=>{t=i});return{turnId:e,controller:new AbortController,settled:n,resolveSettled:t}}async function W(e,t){if(!t.aborted)return new Promise((n,i)=>{let r=()=>t.removeEventListener("abort",o),o=()=>{r(),n(void 0)};t.addEventListener("abort",o,{once:!0}),e.then(T=>{r(),n(T)},T=>{r(),i(T)})})}async function z(e,t){if(t<=0)return{settled:!1};let n,i=await Promise.race([e.then(r=>({settled:!0,value:r})),new Promise(r=>{n=setTimeout(()=>r({settled:!1}),t),n.unref?.()})]);return n&&clearTimeout(n),i}var _="Sign in to MiniMax to use Agent features. Run /login, then retry.",A="Sign in to MiniMax to use Agent features. Run `mcode login`, then retry.",S=class extends R{constructor(n,i=A){super("config",i,{code:"auth.login_required",retryable:!1});this.account=n;this.name="TuiLoginRequiredError"}};function X(e){return e.modelSource?e.modelSource==="token-plan":e.authMode==="managed-login"}function O(e){return e.status==="needs-login"||X(e)&&e.managedTokenPresent!==!0}function $(e){return O(e)||e.managedTokenPresent===!1}async function k(e,t,n){let i=await e.getAccountStatus(t);return n?.(i),i}async function q(e,t,n=A,i){let r=await k(e,t,i);if(O(r))throw new S(r,n);return r}async function H(e,t,n=A,i){let r=await k(e,t,i);if(r.managedTokenPresent!==!0)throw new S(r,n);return r}async function J(e,t,n){let i=e.getAccountStatus;i&&await q({getAccountStatus:i.bind(e)},t,_,n)}async function Z(e,t,n){let i=e.getAccountStatus;i&&await H({getAccountStatus:i.bind(e)},t,_,n)}export{P as a,S as b,$ as c,q as d,J as e,Z as f};