@minimax-ai/code 0.4.8 → 0.4.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/CHANGELOG.zh-CN.md +23 -0
- package/README.md +16 -3
- package/README.zh-CN.md +20 -2
- package/chunks/{chunk-E6MMSL54.js → chunk-CYA33574.js} +469 -469
- package/chunks/{chunk-SLRPB56L.js → chunk-HJ6CAPCI.js} +1 -1
- package/chunks/{chunk-LOASZMQB.js → chunk-PMTJEVJF.js} +407 -407
- package/chunks/{chunk-DIMUZAUA.js → chunk-VOK3LP4U.js} +1 -1
- package/chunks/{launcher-NIEXEZF5.js → launcher-BO2AIPOJ.js} +138 -138
- package/chunks/{lifecycle-EEX754QU.js → lifecycle-JTZ4IFVL.js} +1 -1
- package/chunks/{main-ANDH2IE5.js → main-RV5CLB2O.js} +10 -10
- package/chunks/{plugin-command-STBEQNGX.js → plugin-command-XCLCU4X3.js} +1 -1
- package/chunks/{provider-command-MKVRALX5.js → provider-command-TITVCVLJ.js} +1 -1
- package/chunks/{run-acp-command-2AEYGDBH.js → run-acp-command-2SHKZJNF.js} +2 -2
- package/chunks/run-exec-command-BQ2G5OY7.js +17 -0
- package/cli.js +1 -1
- package/package.json +1 -1
- package/chunks/run-exec-command-LVG3YSVK.js +0 -17
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
|
|
2
|
-
import{a as Oe,b as _e}from"./chunk-E6MMSL54.js";import"./chunk-R6GVNV7J.js";import"./chunk-4ESEMCSG.js";import{b as Ie,d as be,e as oe,f as ke,g as Pe,h as $}from"./chunk-DIMUZAUA.js";import{id as mt,k as se}from"./chunk-LOASZMQB.js";import"./chunk-VPHVKGPT.js";import{b as xe,c as M,d as ve}from"./chunk-A2CQYOXE.js";import"./chunk-C3JRMX7L.js";import{a as Me,d as Ae}from"./chunk-SLRPB56L.js";import{c as Re,q as G}from"./chunk-XYXCVIX2.js";import"./chunk-KCTHWRGJ.js";import{a as Se,b as Ce}from"./chunk-YPMJNO4T.js";import"./chunk-PPIEC7ZM.js";import"./chunk-X4N2MWNJ.js";import"./chunk-75PL5LYJ.js";import"./chunk-SHXPTUWI.js";import"./chunk-4Y64C4JT.js";import"./chunk-X5PAB4UH.js";import"./chunk-AABEG2OJ.js";import"./chunk-SD6SJL3L.js";import"./chunk-PWQHCWDV.js";import"./chunk-HQ2U4QVQ.js";import{d as Te}from"./chunk-HMP2XYHW.js";import"./chunk-WAVNKSSE.js";import{$a as Ee,_a as we}from"./chunk-DV5WIEGS.js";import"./chunk-ZITT4GJK.js";import"./chunk-2ZG44JU6.js";import"./chunk-Z44TXDGK.js";import"./chunk-CWWDVX6C.js";import"./chunk-IIHJNKC3.js";import"./chunk-3V6OPTHM.js";import"./chunk-LOQ4VVEN.js";import"./chunk-2UWBSJDH.js";import"./chunk-GUFBGYOC.js";import"./chunk-CK62QLTS.js";import"./chunk-WFWSBUYD.js";import{e as lt}from"./chunk-D76SO2ME.js";var T=Object.freeze({success:0,invocation:2,config:3,runtime:4,timeout:6,limit:7,internal:70,cancelled:130,brokenPipe:141}),m=class extends G{constructor(r,n,i){super(r,n,{code:`exec.${r}`,retryable:r==="runtime",...i});this.kind=r;this.name="TuiExecError"}};function De(e){switch(e.status){case"succeeded":return T.success;case"failed":return e.error?.category==="config"?T.config:e.error?.category==="internal"?T.internal:T.runtime;case"timeout":return T.timeout;case"cancelled":return T.cancelled;case"limit_exceeded":return T.limit}return T.internal}function L(e){return e instanceof m?T[e.kind]:T.internal}async function je(e,t){try{return Ee(e,t)}catch(r){let n=r instanceof we?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new m("config",n,{cause:r})}}function U(e){return e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"?M(e):e.kind==="runtime"?`The run failed: ${M(e)}. Retry after the connection recovers.`:`MCode encountered an internal error: ${M(e)}. Retry; if it keeps happening, report it through an available support channel.`}function Fe(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?`: ${M(e.error.message)}`:""}. Open MCode and run /doctor.`:e.error?.category==="internal"?`MCode encountered an internal error${e.error.message?`: ${M(e.error.message)}`:""}. Retry; if it keeps happening, report it through an available support channel.`:`The run failed${e.error?.message?`: ${M(e.error.message)}`:""}. Retry after the connection recovers.`}import{readFile as Ot,realpath as de,stat as Y}from"node:fs/promises";import{homedir as Be}from"node:os";import{basename as Je,dirname as _t,extname as Dt,isAbsolute as jt,resolve as K}from"node:path";var ae=lt(mt(),1);function ue(e,t){if(!t)return{ok:!0,value:e??null};if(!e?.trim())return{ok:!1,kind:"empty",message:"Structured output was empty."};let r;try{r=JSON.parse(e)}catch{return{ok:!1,kind:"invalid_json",message:"Structured output was not valid JSON."}}let n=new ae.Ajv({allErrors:!0,strict:!1}),i=n.compile(t);return i(r)?{ok:!0,value:r}:{ok:!1,kind:"schema_mismatch",message:`Structured output did not match --output-schema: ${n.errorsText(i.errors,{separator:"; "})}`}}function Ne(e,t){let r=e.status==="succeeded"?t.validation??ue(e.answer,t.outputSchema):void 0,n=ft(e,r);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:n.sessionId,turnId:n.turnId,status:n.status==="awaiting-user-continuation"?"failed":n.status,...n.status==="succeeded"&&r?.ok?{output:r.value}:{},...n.error?{error:{...n.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},durationMs:n.durationMs}}function $e(e){return J(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)&&pt(e.status)&>(e.model)&&yt(e.usage)&&ht(e.error):!1}function ft(e,t){return e.status==="awaiting-user-continuation"?{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:!1}}:e.status!=="succeeded"||!t||t.ok?e:{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:t.message,retryable:!0}}}function Le(e){new ae.Ajv({allErrors:!0,strict:!1}).compile(e)}function pt(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function gt(e){return e===void 0?!0:J(e)?typeof e.providerId=="string"&&typeof e.modelId=="string"&&q(e.variant)&&q(e.providerSource)&&q(e.providerKind)&&q(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict"):!1}function yt(e){return e===void 0?!0:J(e)?Object.values(e).every(t=>t===void 0||typeof t=="number"&&Number.isFinite(t)):!1}function ht(e){return e===void 0?!0:J(e)?(e.category==="config"||e.category==="runtime"||e.category==="internal")&&q(e.code)&&typeof e.message=="string"&&(e.retryable===void 0||typeof e.retryable=="boolean"):!1}function q(e){return e===void 0||typeof e=="string"}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHash as wt,randomUUID as Et}from"node:crypto";import{access as Tt,constants as xt,lstat as Ue,mkdir as vt,open as St,readdir as qe,rename as Rt,unlink as It,writeFile as bt}from"node:fs/promises";import{join as X,resolve as kt}from"node:path";var ce=256*1024,Pt=4*1024*1024,Mt=5e3;function He(e){return ve(e.replace(/("(?:authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"(?:\\.|[^"\\])*"/giu,'$1"[redacted]"'))}function At(e){if(e.length<=ce)return e;let t=Buffer.from(`
|
|
3
|
-
[diagnostic answer truncated: middle omitted]
|
|
4
|
-
`),r=Math.floor((ce-t.length)/2),n=r,i=e.length-r;for(;((e[n]??0)&192)===128;)n-=1;for(;((e[i]??0)&192)===128;)i+=1;return Buffer.concat([e.subarray(0,n),t,e.subarray(i)])}async function Ve(e,t){let r=kt(t,e);if(await vt(r,{recursive:!0,mode:448}),!(await Ue(r)).isDirectory())throw new Error("Diagnostics path must be a real directory.");if(await Tt(r,xt.W_OK),(await qe(r)).length>0)throw new Error("Diagnostics directory must be empty.");return r}function We(e){return e?wt("sha256").update(JSON.stringify(e)).digest("hex"):void 0}function H(e){return typeof e=="string"?He(e):Array.isArray(e)?e.map(H):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,/^(authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)$/iu.test(t)?"[redacted]":H(r)])):e}var z=class e{constructor(t,r,n){this.directory=t;this.warn=r;this.progressFile=n}pending=Promise.resolve();bytes=0;droppedEvents=0;closed=!1;failed=!1;static async create(t,r){if((await qe(t)).length>0)throw Object.assign(new Error("Diagnostics directory must be empty."),{code:"EEXIST"});let n=await St(X(t,"progress.jsonl"),"wx",384);return new e(t,r,n)}record(t){if(this.closed)return;let r=`${JSON.stringify(H({timestampMs:Date.now(),...t}))}
|
|
5
|
-
`,n=Buffer.byteLength(r);if(this.bytes+n>Pt){this.droppedEvents+=1;return}this.bytes+=n,this.enqueue(()=>this.progressFile.appendFile(r))}execution(t){this.json("execution.json",{schemaVersion:1,...t})}failure(t,r){let n=Buffer.from(He(t??"")),i=n.length>ce,s=At(n);this.json("failure.json",{schemaVersion:1,...r,answerBytes:Buffer.byteLength(t??""),savedBytes:s.length,truncated:i,redacted:!0}),this.enqueue(()=>this.replaceFile("failure-answer.txt",s))}async flush(t={}){this.enqueue(async()=>{let[i,s]=await Promise.all([Ue(X(this.directory,"progress.jsonl")),this.progressFile.stat()]);if(!i.isFile()||i.ino!==s.ino||i.dev!==s.dev)throw new Error("Diagnostics progress file was replaced.")}),this.enqueue(()=>this.progressFile.close()),this.enqueue(()=>this.replaceFile("diagnostics-status.json",`${JSON.stringify(H({...t,recoveryReady:t.recoveryReady===!0&&!this.failed,diagnosticsComplete:!this.failed,droppedEventCount:this.droppedEvents}),null,2)}
|
|
6
|
-
`));let r,n=await Promise.race([this.pending.then(()=>!0),new Promise(i=>{r=setTimeout(()=>i(!1),Mt)})]);return r&&clearTimeout(r),this.closed=!0,n||this.reportFailure("diagnostics flush deadline exceeded"),this.pending.finally(()=>this.progressFile.close()).catch(()=>{}),n&&!this.failed}json(t,r){let n=`${JSON.stringify(H(r),null,2)}
|
|
7
|
-
`;this.enqueue(()=>this.replaceFile(t,n))}async replaceFile(t,r){let n=X(this.directory,`.${t}.${Et()}.tmp`);try{await bt(n,r,{mode:384,flag:"wx"}),this.closed||await Rt(n,X(this.directory,t))}finally{await It(n).catch(()=>{})}}enqueue(t){this.closed||(this.pending=this.pending.then(async()=>{this.closed||await t()}).catch(()=>this.reportFailure("could not write execution diagnostics")))}reportFailure(t){this.failed||this.warn(`mcode diagnostics warning: ${t}
|
|
8
|
-
`),this.failed=!0}};var Ft={".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 Xe(e,t,r,n){if(_(n),t.review)return Nt(t,n);if(t.input!==void 0&&t.input!=="-")throw f('--input currently accepts only "-".');if(e!==void 0&&t.input!==void 0)throw f("The prompt argument and --input cannot be combined.");if(t.session&&t.continue)throw f("--session and --continue are mutually exclusive.");let i=O("--prompt-mode",t.promptMode??"tui",["tui","coding","work"]),s=O("--input-format",t.inputFormat??"text",["text","json"]),o=O("--output-format",t.outputFormat??"text",["text","json","stream-json"]),d=O("--permission",t.permission??"smart",["ask","smart","full","off"]);if(d==="ask")throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.");let c=d,g=await le(t.cwd??process.cwd(),"--cwd");_(n);let l=t.input==="-"?await r():e??"";_(n);let h=Ut(l,s),u=await Promise.all((t.file??[]).map(R=>Lt(R,g,n))),p=Ce(u);if(p==="count")throw f(`You can attach up to ${String(10)} files.`);if(p==="total-bytes")throw f("Attachments can total up to the 100 MB limit.");if(!h.trim()&&u.length===0)throw f("A prompt, --input -, or at least one --file is required.");let x=t.timeout===void 0?void 0:Ke(t.timeout,"--timeout"),a=t.maxSteps===void 0?void 0:Ye(t.maxSteps,"--max-steps"),S=t.config===void 0?void 0:await me(t.config,g,"--config"),P=t.outputSchema===void 0?void 0:await $t(t.outputSchema,g),I=t.outputLastMessage===void 0?void 0:await ze(t.outputLastMessage,g),A;if(t.diagnosticsDir!==void 0){if(!t.diagnosticsDir.trim())throw f("--diagnostics-dir cannot be empty.");try{A=await Ve(t.diagnosticsDir,g)}catch(R){throw f(`--diagnostics-dir is invalid: ${D(R)}`)}}return{prompt:h,promptMode:i,workspaceDir:g,attachments:u,...t.model?.trim()?{model:t.model.trim()}:{},...t.session?.trim()?{sessionId:t.session.trim()}:{},continueSession:t.continue===!0,...S?{configPath:S}:{},permission:c,...x===void 0?{}:{timeoutMs:x},...a===void 0?{}:{maxSteps:a},format:o,...P===void 0?{}:{outputSchema:P},...I===void 0?{}:{outputLastMessagePath:I},...A===void 0?{}:{diagnosticsDir:A}}}async function Nt(e,t){let r=O("--output-format",e.outputFormat??"text",["text","json","stream-json"]),n=O("--permission",e.permission??"smart",["ask","smart","full","off"]);if(n==="ask")throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.");let i=await le(e.cwd??process.cwd(),"--cwd");_(t);let s=e.timeout===void 0?void 0:Ke(e.timeout,"--timeout"),o=e.maxSteps===void 0?void 0:Ye(e.maxSteps,"--max-steps"),d=e.config===void 0?void 0:await me(e.config,i,"--config"),c=e.outputLastMessage===void 0?void 0:await ze(e.outputLastMessage,i);return{prompt:"Please review my uncommitted changes.",workspaceDir:i,attachments:[],...e.model?.trim()?{model:e.model.trim()}:{},continueSession:!1,...d?{configPath:d}:{},permission:n,...s===void 0?{}:{timeoutMs:s},...o===void 0?{}:{maxSteps:o},format:r,...c===void 0?{}:{outputLastMessagePath:c},reviewRequest:{scope:"local_changes"}}}async function $t(e,t){let r=e.trim();try{return Ge(r)}catch(i){if(r.startsWith("{")||r.startsWith("[")||!(i instanceof SyntaxError))throw f("--output-schema requires a JSON object.",i)}let n=await me(e,t,"--output-schema");try{return Ge(await Ot(n,"utf8"))}catch(i){throw f("--output-schema requires a JSON object.",i)}}function Ge(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 ze(e,t){let r=Q(e,t),n=await le(_t(r),"--output-last-message"),i=K(n,Je(r));if((await Y(i).catch(o=>{if(!(o&&typeof o=="object"&&"code"in o&&o.code==="ENOENT"))throw f(`--output-last-message is invalid: ${D(o)}`)}))?.isDirectory())throw f("--output-last-message must reference a file.");return i}async function Lt(e,t,r){_(r);let n=Q(e,t),i=await de(n).catch(c=>{throw f(`Cannot attach ${e}: ${D(c)}`)}),s=await Y(i).catch(c=>{throw f(`Cannot attach ${e}: ${D(c)}`)});if(_(r),!s.isFile())throw f(`Cannot attach ${e}: path is not a file.`);let o=Je(i),d=Ft[Dt(o).toLowerCase()]??Se(o)??"application/octet-stream";return{type:d.startsWith("image/")?"image":"file",filePath:i,fileName:o,mimeType:d,sizeBytes:s.size}}function _(e){if(e?.aborted)throw new m("cancelled","Invocation was cancelled.",{cause:e.reason})}async function le(e,t){let r=await de(Q(e,process.cwd())).catch(i=>{throw f(`${t} is invalid: ${D(i)}`)});if(!(await Y(r)).isDirectory())throw f(`${t} must reference a directory.`);return r}async function me(e,t,r){let n=await de(Q(e,t)).catch(s=>{throw f(`${r} is invalid: ${D(s)}`)});if(!(await Y(n)).isFile())throw f(`${r} must reference a file.`);return n}function Q(e,t){let r=e.trim();if(!r)throw f("Path value cannot be empty.");let n=r==="~"?Be():r.startsWith("~/")||r.startsWith("~\\")?K(Be(),r.slice(2)):r;return jt(n)?K(n):K(t,n)}function Ut(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 Ke(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]),i=r[2]?.toLowerCase()==="h"?36e5:r[2]?.toLowerCase()==="m"?6e4:r[2]?.toLowerCase()==="s"?1e3:1,s=n*i;if(!Number.isSafeInteger(s)||s<1)throw f(`${t} must resolve to a positive safe integer in milliseconds.`);return s}function Ye(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 O(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 D(e){return e instanceof Error?e.message:String(e)}import{resolve as nt}from"node:path";function Qe(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}import{randomUUID as Vt}from"node:crypto";import{rename as Wt,unlink as Bt,writeFile as Gt}from"node:fs/promises";import{basename as Jt,dirname as Xt,join as zt}from"node:path";var Z=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=qt(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 qt(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:Ze(r,t,n),completed:!1}))]}return e.type!=="message"||e.message.role!=="assistant"?[]:Ht(e.message)}function Ht(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:Ze(r,t,n),completed:!0}))]}function Ze(e,t,r){return{id:e.id??`${t}:tool:${String(r)}`,type:"tool_call",toolCall:e}}var V=class extends m{constructor(t,r){super("internal",t,r),this.name="HeadlessOutputError"}};function et(e,t,r={}){let n=!1;if(e==="stream-json"&&!r.eventProjector)throw new V("stream-json requires an Exec event projector.");return{async event(i){if(e==="stream-json")for(let s of r.eventProjector?.project(i)??[])await ee(t,`${JSON.stringify(s)}
|
|
9
|
-
`)},async result(i){if(n)throw new V("ExecResult was encoded more than once.");if(!$e(i))throw new V("Headless coordinator returned an invalid ExecResult.");if(n=!0,e==="stream-json"){for(let s of r.eventProjector?.complete(i)??[])await ee(t,`${JSON.stringify(s)}
|
|
10
|
-
`);return}if(e==="json"){await ee(t,`${JSON.stringify(i)}
|
|
11
|
-
`);return}if(i.status==="succeeded"){let s=Pe(i.output)?$(i.output):typeof i.output=="string"?Ie(i.output):JSON.stringify(i.output);await ee(t,`${s??""}
|
|
12
|
-
`)}}}}async function tt(e,t){let r=zt(Xt(e),`.${Jt(e)}.${process.pid}.${Vt()}.tmp`);try{await Gt(r,t,{encoding:"utf8",flag:"wx"}),await Wt(r,e)}catch(n){throw await Bt(r).catch(()=>{}),new m("internal",`Could not write --output-last-message: ${e}`,{cause:n})}}function fe(e){return t=>new Promise((r,n)=>{let i=!1,s=o=>{if(!i){if(i=!0,o.code==="EPIPE"){n(new m("brokenPipe","stdout pipe was closed.",{cause:o}));return}n(new m("internal",`stdout write failed: ${o.message}`,{cause:o}))}};e.once("error",s);try{e.write(t,o=>{if(o){s(o);return}i||(i=!0,e.off("error",s),r())})}catch(o){e.off("error",s),s(o)}})}async function ee(e,t){try{await e(t)}catch(r){if(r instanceof m)throw r;let n=r&&typeof r=="object"&&"code"in r?r.code:void 0;throw new m(n==="EPIPE"?"brokenPipe":"internal",n==="EPIPE"?"stdout pipe was closed.":"stdout writer failed.",{cause:r})}}var re=class{constructor(t,r={}){this.runtime=t;this.options=r}conversationPort(){return{sendMessage:(t,r)=>this.sendMessage(t,r),abortSession:t=>this.runtime.abortSession(t),steer:t=>this.runtime.steer(t)}}async*sendMessage(t,r){if(!t.turnId)throw te("EXEC_TURN_ID_REQUIRED","Exec requires a Turn id.");let n=t.turnId;r?.throwIfAborted();let i={seenMessageIds:new Set,seenCursors:new Set,sawEvent:!1,terminal:!1,heartbeatSeen:!1,doneSeen:!1},s=!0,o=0,d;for(;;){r?.throwIfAborted();let c=!1,g=!1;try{let h=s?this.runtime.sendMessage(t,r):this.runtime.watchSessionTurn(t.id,n,er(r),{...i.cursor?{afterCursor:i.cursor}:{},...!i.cursor&&i.afterMsgId?{afterMsgId:i.afterMsgId}:{}});s=!1;for await(let u of h){r?.throwIfAborted();let p=u.cursor?i.seenCursors.has(u.cursor):!1;u.cursor&&(i.cursor=u.cursor,p||(i.seenCursors.add(u.cursor),g=!0));let x=u.type==="message"&&u.message.id?i.seenMessageIds.has(u.message.id):!1,a=!u.cursor&&(u.type==="heartbeat"&&i.heartbeatSeen||u.type==="done"&&i.doneSeen);if(!(p||x||a)){if(u.type==="message"&&(g=!0),u.type==="heartbeat"&&(i.heartbeatSeen=!0),u.type==="done"&&(i.doneSeen=!0),!u.cursor&&u.type!=="message"&&(g=!i.sawEvent),i.sawEvent=!0,Yt(i,u),u.type==="resync-required"){c=!0,yield u;break}yield u,Zt(u)&&(i.terminal=!0)}}}catch(h){if(r?.aborted)throw r.reason??h;d=h}if(i.terminal)return;let l=yield*this.reconcile(t,n,i,c,r);if(l.terminal)return;if(!l.recoverable)throw d??te("EXEC_STREAM_ENDED_WITHOUT_TERMINAL","Runtime stream ended without a durable terminal fact.");if(o=g||l.progressed?0:o+1,o>(this.options.maxConsecutiveRecoveryAttempts??5))throw te("EXEC_STREAM_RECOVERY_EXHAUSTED","Runtime stream recovery was exhausted before a terminal fact arrived.",d);await(this.options.wait??tr)(this.options.reconnectDelayMs??100,r)}}async*reconcile(t,r,n,i,s){s?.throwIfAborted();let[o,d]=await Promise.all([this.runtime.getActiveRun(t.id),this.runtime.getSession(t.id)]),c=(o.state==="running"||o.state==="decision-blocked")&&(!o.turnId||o.turnId===r),g=i||!c||o.state==="idle",l=!1,h=!1;if(g){let u=await Kt(this.runtime,t.id,r);for(let p of u)p.id&&(n.afterMsgId=p.id),Qt(p)&&(l=!0),!(p.id&&n.seenMessageIds.has(p.id))&&(p.id&&n.seenMessageIds.add(p.id),n.sawEvent=!0,h=!0,yield{type:"message",message:p});i&&(n.cursor=void 0)}if(d.status==="error")return yield{type:"session-status",status:"error",turnId:r,message:d.errorMessage??"Runtime turn failed."},{progressed:h,recoverable:!1,terminal:!0};if(d.status==="aborted")return yield{type:"session-status",status:"aborted",turnId:r},{progressed:h,recoverable:!1,terminal:!0};if(d.status==="idle"&&l)return yield{type:"session-status",status:"finished",turnId:r},{progressed:h,recoverable:!1,terminal:!0};if(o.state==="decision-blocked")throw te("INTERACTION_NOT_AVAILABLE","Runtime is waiting for user interaction from a non-interactive Exec host.");return{progressed:h,recoverable:c||n.sawEvent,terminal:!1}}};async function Kt(e,t,r){let n=[],i=new Set,s;for(;;){let o=await e.listMessagePage(t,{limit:200,...s?{before:s}:{}});if(n.unshift(o.messages.filter(d=>d.turnId===r)),!o.hasMore||!o.nextCursor||i.has(o.nextCursor))break;i.add(o.nextCursor),s=o.nextCursor}return n.flat()}function Yt(e,t){t.type!=="message"||!t.message.id||(e.seenMessageIds.add(t.message.id),e.afterMsgId=t.message.id)}function Qt(e){return e.role==="assistant"&&(e.kind==="final"||e.finishReason==="stop"||e.finishReason==="end_turn"||e.finishReason==="stop_sequence")}function Zt(e){return e.type==="error"?!0:e.type==="session-status"&&(e.status==="finished"||e.status==="error"||e.status==="aborted"||e.status==="interrupted")}function er(e){return e??new AbortController().signal}async function tr(e,t){e<=0||await new Promise((r,n)=>{let s=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e),o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),n(t?.reason??new Error("Exec stream recovery was cancelled."))};if(t?.aborted){o();return}t?.addEventListener("abort",o,{once:!0})})}function te(e,t,r){return Object.assign(new Error(t,r===void 0?void 0:{cause:r}),{category:"runtime",code:e,retryable:!1})}import{performance as ne}from"node:perf_hooks";async function rt(e,t,r=5e3){let n=ne.now()+r;for(;ne.now()<n;){let i;try{let o=await Promise.race([e.getActiveRun(t),new Promise(d=>{i=setTimeout(()=>d(void 0),Math.max(0,n-ne.now()))})]);if(!o||o.sessionId!==t)return!1;if(o.state==="idle"||o.state==="terminal")return!0}catch{return!1}finally{i&&clearTimeout(i)}let s=n-ne.now();if(s<=0)return!1;await new Promise(o=>setTimeout(o,Math.min(50,s)))}return!1}import{performance as pe}from"node:perf_hooks";var ie=class{constructor(t){this.record=t}active=new Map;toolStates=new Map;modelSteps=0;toolCalls=0;lastActivityAt=Date.now();droppedOperations=0;observe(t){if(t.type==="delta"){(t.content||t.thinking||t.toolCalls?.length)&&(this.lastActivityAt=Date.now());for(let r of t.toolCalls??[])this.tool(r)}else if(t.type==="message")for(let r of t.message.toolCalls??[])this.tool(r);else if(t.type==="generic"&&t.eventType==="execution.diagnostic"){let{kind:r,operationId:n,modelId:i,protocol:s,finishReason:o}=t.data;if(typeof n!="string")return;if(r==="model_phase_started")this.modelSteps++,this.start(n,"model");else if(r==="model_phase_finished"||r==="model_phase_failed")this.end(n,{finishReason:typeof o=="string"?o:void 0});else return;this.record({kind:r,operationId:n,modelId:typeof i=="string"?i:void 0,protocol:typeof s=="string"?s:void 0})}}summary(){return{modelSteps:this.modelSteps,toolCalls:this.toolCalls,lastActivityAt:this.lastActivityAt,droppedOperations:this.droppedOperations,unfinishedOperations:[...this.active].map(([t,r])=>({operationId:t,kind:r.kind,startedAtMs:r.startedAtMs,elapsedMs:Math.max(0,pe.now()-r.startedAt)}))}}tool(t){if(!t.id)return;let r=String(t.status).toLowerCase(),n=["1","started","running","in_progress"].includes(r)?"started":["2","completed","succeeded","success"].includes(r)?"finished":["3","failed","error"].includes(r)?"failed":void 0;if(!(!n||this.toolStates.get(t.id)===n)){if(this.toolStates.size>=4096&&!this.toolStates.has(t.id)){this.droppedOperations++;return}this.toolStates.set(t.id,n),n==="started"?(this.toolCalls++,this.start(t.id,"tool"),this.record({kind:"tool_started",operationId:t.id,toolName:t.name})):this.end(t.id,{kind:`tool_${n}`,toolName:t.name})}}start(t,r){if(this.lastActivityAt=Date.now(),this.active.size>=256){this.droppedOperations++;return}this.active.set(t,{kind:r,startedAt:pe.now(),startedAtMs:this.lastActivityAt})}end(t,r){this.lastActivityAt=Date.now();let n=this.active.get(t);this.active.delete(t),this.record({kind:"operation_finished",operationId:t,...r,...n?{durationMs:Math.max(0,pe.now()-n.startedAt)}:{missingStart:!0}})}};async function at(e,t){let r=t.stdout??fe(process.stdout),n=t.stderr??fe(process.stderr),i=t.processRef??process,s=t.createTurnId??Qe,o=T.internal,d,c,g=[],l,h={},u={},p=!1,x,a=e.diagnosticsDir?new ie(y=>l?.record({...u,...y})):void 0,S=Date.now(),P=new re(t.runtime),I=new Me(P.conversationPort(),{...e.diagnosticsDir?{onAnswerSelection:y=>{h=y,l?.record(y)}}:{}}),A,R=()=>{I.abort()};i.once("SIGINT",R),i.once("SIGTERM",R),i.once("SIGHUP",R);try{e.diagnosticsDir&&(l=await z.create(e.diagnosticsDir,w=>g.push(w))),await Ae(t.runtime,e.sessionId);let y=await dr(e,t.runtime);await or(t.runtime,y);let b=e.model?mr(e.model):void 0,E=s(),C=`exec_${E}`;u={version:e.version,sessionId:y.sessionId,turnId:E,runId:C,startedAt:S,schemaHash:We(e.outputSchema)},l?.execution(u),l?.record({kind:"execution_started",sessionId:y.sessionId,turnId:E});let ge=et(e.format??"text",r,{...e.format==="stream-json"?{eventProjector:new Z({runId:C,sessionId:y.sessionId,turnId:E,resumed:!!(e.sessionId||e.continueSession)})}:{}}),ct=await I.execute({turnId:E,session:Promise.resolve(y),content:e.prompt,workspace:e.workspaceDir,version:e.version,...l?{executionDiagnostics:!0}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...b?{model:b}:{},...e.reviewRequest?{reviewRequest:e.reviewRequest}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.timeoutMs!==void 0||e.maxSteps!==void 0?{policy:{...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.maxSteps!==void 0?{maxSteps:e.maxSteps}:{},requireAnswer:!0}}:{policy:{requireAnswer:!0}}},async w=>{let B;w.type==="message"&&(B=be(w.message.origin),B&&(A={outcome:B,content:w.message.content??""})),a?.observe(w),w.type==="session-status"?l?.record({kind:"session_status",status:w.status}):w.type==="message"&&w.message.role==="assistant"&&l?.record({kind:"assistant_completed",messageId:w.message.id,finishReason:w.message.finishReason,requestDurationMs:w.message.usage?.requestDurationMs});try{await ge.event(nr(w,B))}catch(he){throw d??=he,I.abort(),he}});if(d)throw d;let v=ir(ct.outcome),j;if(e.reviewRequest&&v.status==="succeeded"){let w=rr(A);"error"in w?v={...v,status:"failed",answer:null,error:w.error}:j=w.result}x=v.answer;let F=v.status==="succeeded"?ue(v.answer,e.outputSchema):void 0,N=sr(e.format)||l?await ar(t.runtime,y.sessionId,E,v):{},dt={runId:C,...F?{validation:F}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...N.model?{model:{...N.model,...e.outputSchema&&v.status==="succeeded"?{structuredOutputMode:"native_strict"}:{}}}:{},...N.usage?{usage:N.usage}:{}},ye=Ne(v,dt),k=j?{...ye,output:j}:ye;l&&k.status==="timeout"&&(p=await rt(t.runtime,y.sessionId),l.record({kind:"stop_confirmed",stopped:p})),u={...u,model:N.model,status:k.status,durationMs:k.durationMs},k.status!=="succeeded"&&l?.failure(v.answer,{...a?.summary(),...h,error:k.error,status:k.status,...F&&!F.ok?{validationKind:F.kind}:{}}),c={encoder:ge,result:k,...k.status==="succeeded"&&e.outputLastMessagePath?{lastMessage:{filePath:e.outputLastMessagePath,answer:j?$(j):v.answer??""}}:{}}}catch(y){let b=ot(y);l?.failure(void 0,{error:{message:b.message},phase:"execution"}),o=L(b),o!==T.brokenPipe&&g.push(`mcode exec failed: ${U(b)}
|
|
13
|
-
`)}finally{i.off("SIGINT",R),i.off("SIGTERM",R),i.off("SIGHUP",R);let y,b=!1;try{await t.shutdown()===!0&&(y="Runtime shutdown did not complete cleanly.")}catch(E){y=xe(E,{summary:"mcode exec shutdown failed.",nextStep:"Verify no process is still running."})}if(c){if(y&&c.result.status==="succeeded"&&(c.result=it(c.result,"RUNTIME_SHUTDOWN_FAILED",y),b=!0),c.result.status==="succeeded"&&c.lastMessage)try{await tt(c.lastMessage.filePath,c.lastMessage.answer)}catch(E){c.result=it(c.result,"OUTPUT_LAST_MESSAGE_WRITE_FAILED",E instanceof Error?E.message:String(E))}try{c.result.status!=="succeeded"&&c.result.error?.category==="internal"&&l?.failure(x,{...h,status:c.result.status,error:c.result.error}),await c.encoder.result(c.result),o=De(c.result),c.result.status!=="succeeded"&&g.push(`mcode exec ${c.result.status}: ${Fe(c.result)}
|
|
14
|
-
`)}catch(E){let C=ot(E);o=L(C),o!==T.brokenPipe&&g.push(`mcode exec failed: ${U(C)}
|
|
15
|
-
`)}}else y&&o!==T.brokenPipe&&(o=T.internal);if(y&&!b&&g.push(`${y}
|
|
16
|
-
`),l?.execution({...u,endedAt:Date.now(),shutdownComplete:!y,exitCode:o}),l?.record({kind:"execution_finished",...u,exitCode:o,shutdownComplete:!y}),await l?.flush({version:e.version,runId:u.runId,sessionId:u.sessionId,turnId:u.turnId,...a?.summary(),exitCode:o,shutdownComplete:!y,recoveryReady:p&&!y}),o!==T.brokenPipe)for(let E of g)await fr(n,E)}return o}function rr(e){if(!e)return{error:{category:"runtime",code:"REVIEW_RESULT_MISSING",message:"Runtime completed without a validated code review result.",retryable:!0}};if(e.outcome==="failed")return{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:e.content.trim()||"Runtime rejected an invalid code review result.",retryable:!0}};let t=e.outcome==="pass"?ke(e.content):oe(e.content);return t?{result:t}:{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:"Runtime returned an invalid code review result.",retryable:!0}}}function nr(e,t){if(e.type!=="message"||t!=="needs_changes")return e;let r=oe(e.message.content??"");return{...e,message:{...e.message,content:r?$(r):"Runtime returned an invalid code review result."}}}function it(e,t,r){return{...e,status:"failed",output:void 0,error:{category:"internal",code:t,message:r,retryable:!1}}}function ir(e){return e.status!=="awaiting-user-continuation"?e:{...e,status:"failed",error:{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested user interaction from a non-interactive Exec host.",retryable:!1}}}async function or(e,t){let r=t.agentName??se,[n,i]=await Promise.all([e.getPendingQuestionnaire(r,t.sessionId),e.listPendingPermissions()]),s=i.some(d=>d.sessionId===t.sessionId);if(!n&&!s)return;let o=n?"a pending questionnaire":"a pending permission request";throw new m("runtime",`Session ${t.sessionId} has ${o} and requires an interactive host. Continue it in the TUI or ACP.`)}function sr(e){return e==="json"||e==="stream-json"}async function ar(e,t,r,n){let[i,s]=await Promise.all([e.getSessionUsage(t).catch(()=>{}),e.listModels(t).catch(()=>[])]),o=i?.rows?.filter(p=>p.turnId===r)??[],d=[...o].reverse().find(p=>p.model?.trim())?.model?.trim(),c=n.model?`${n.model.providerId}/${n.model.modelId}`:void 0,g=s.find(p=>p.selected===!0),l=g?`${g.providerId}/${g.modelId}`:void 0,h=ur(d??c??l,s,n.model?.variant),u=o.length>0?cr(o):n.usage;return{...h?{model:h}:{},...u?{usage:u}:{}}}function ur(e,t,r){let n=e?.indexOf("/")??-1;if(!e||n<=0||n===e.length-1)return;let i=e.slice(0,n),s=e.slice(n+1),o=t.find(d=>d.providerId===i&&d.modelId===s);return{providerId:i,modelId:s,...o?.variant!==void 0?{variant:o.variant}:r!==void 0?{variant:r}:{},...o?.providerSource?{providerSource:o.providerSource}:{},...o?.providerKind?{providerKind:o.providerKind}:{},...o?.apiFormat?{protocol:o.apiFormat}:{}}}function cr(e){let t={...W(e,"inputTokens"),...W(e,"outputTokens"),...W(e,"reasoningTokens"),...W(e,"cacheReadTokens"),...W(e,"cacheWriteTokens")},r=t.inputTokens,n=t.outputTokens;return Object.keys(t).length===0?void 0:{...t,...r!==void 0||n!==void 0?{totalTokens:(r??0)+(n??0)}:{}}}function W(e,t){let r=e.map(n=>n[t]).filter(n=>typeof n=="number"&&Number.isFinite(n));return r.length>0?{[t]:r.reduce((n,i)=>n+i,0)}:{}}function ot(e){if(e instanceof m)return e;if(e instanceof G){let r=e.category==="config"||e.category==="invocation"||e.category==="cancelled"||e.category==="brokenPipe"||e.category==="internal"?e.category:"runtime";return new m(r,e.message,{cause:e})}let t=e instanceof Error?e.message:String(e);return new m("runtime",t,{cause:e})}async function dr(e,t){if(e.sessionId){let r=await t.getSession(e.sessionId);return st(r,e.workspaceDir),r}if(e.continueSession){let r=await lr(t,e.workspaceDir);if(!r)throw new m("runtime",`No active Session exists for workspace ${e.workspaceDir}.`);return st(r,e.workspaceDir),r}return t.createSession({workspaceDir:e.workspaceDir,title:pr(e.prompt,e.attachments?.length??0)})}async function lr(e,t){let r;do{let n=await e.listSessionPage({agentName:se,cursor:r,limit:50,includeArchived:!1}),i=n.sessions.find(s=>s.archived!==!0&&s.workspaceDir!==void 0&&ut(s.workspaceDir,t));if(i)return i;r=n.hasMore?n.nextCursor:void 0}while(r)}function st(e,t){if(Re(e))throw new m("invocation","Sub-agent Sessions are internal and cannot be opened.");if(e.archived)throw new m("runtime",`Session is archived: ${e.sessionId}`);if(!e.workspaceDir||!ut(e.workspaceDir,t))throw new m("runtime",`Session workspace does not match --cwd: ${e.sessionId}`)}function ut(e,t){let r=nt(e),n=nt(t);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function mr(e){let t=e.indexOf("/");if(t<1||t===e.length-1)throw new m("invocation","--model must use provider/model or provider/model#variant.");let r=e.slice(0,t),n=e.slice(t+1),i=n.lastIndexOf("#"),s=i>0?n.slice(0,i):n,o=i>0?n.slice(i+1):void 0;if(!r||!s||i>0&&!o)throw new m("invocation","--model must use provider/model or provider/model#variant.");return{providerId:r,modelId:s,...o?{variant:o}:{}}}async function fr(e,t){try{await e(t)}catch{}}function pr(e,t){let r=e.replace(/\s+/g," ").trim();return r?r.length<=80?r:`${r.slice(0,77)}...`:t===1?"Attachment run":`${t} attachments`}async function On(e,t,r,n={}){let i=n.processRef??process,s=n.writeError??(a=>process.stderr.write(a)),o=n.resolveInvocation??Xe,d=n.resolveDataDir??Te,c=n.loadConfig??je,g=n.createRuntime??Oe,l=n.shutdownRuntime??_e,h=n.runExec??at,u=n.readStdin??yr,p=new AbortController,x=()=>p.abort();i.once("SIGINT",x),i.once("SIGTERM",x),i.once("SIGHUP",x);try{let a=await o(e,t,()=>u(p.signal),p.signal),S=await d(),P=a.configPath?await c(a.configPath,{dataDir:S}):void 0,I=await g({dataDir:S,workspaceDir:a.workspaceDir,version:r,...a.configPath?{configPath:a.configPath}:{},surface:"headless",promptMode:a.promptMode??"tui",permissionMode:gr(a.permission),...t.lane?{lane:t.lane}:{}},P?{getConfig:()=>P,configSource:"explicit"}:{});i.exitCode=await h({prompt:a.prompt,workspaceDir:a.workspaceDir,version:r,attachments:a.attachments,format:a.format,...a.model?{model:a.model}:{},...a.sessionId?{sessionId:a.sessionId}:{},continueSession:a.continueSession,permission:a.permission,...a.diagnosticsDir?{diagnosticsDir:a.diagnosticsDir}:{},...a.timeoutMs!==void 0?{timeoutMs:a.timeoutMs}:{},...a.maxSteps!==void 0?{maxSteps:a.maxSteps}:{},...a.outputSchema===void 0?{}:{outputSchema:a.outputSchema},...a.outputLastMessagePath===void 0?{}:{outputLastMessagePath:a.outputLastMessagePath},...a.reviewRequest?{reviewRequest:a.reviewRequest}:{}},{runtime:I.adapter,shutdown:()=>l(I)})}catch(a){let S=a instanceof m?a:new m("runtime",a instanceof Error?a.message:String(a),{cause:a});s(`mcode exec failed: ${U(S)}
|
|
17
|
-
`),i.exitCode=L(S)}finally{i.off("SIGINT",x),i.off("SIGTERM",x),i.off("SIGHUP",x)}}function gr(e){switch(e){case"smart":return"auto";case"full":return"bypassPermissions";case"off":return"off"}}async function yr(e,t=process.stdin){let r=[],n=t[Symbol.asyncIterator]();try{for(;;){let i=await hr(n,e);if(i.done)break;r.push(Buffer.isBuffer(i.value)?i.value:Buffer.from(i.value))}}finally{await n.return?.()}return Buffer.concat(r).toString("utf8")}function hr(e,t){return new Promise((r,n)=>{let i=()=>{n(new m("cancelled","stdin input was cancelled."))};if(t.aborted){i();return}t.addEventListener("abort",i,{once:!0}),e.next().then(s=>{t.removeEventListener("abort",i),r(s)},s=>{t.removeEventListener("abort",i),n(s)})})}export{yr as readTuiStdinToEnd,On as runTuiExecCommand};
|