@karmaniverous/stan-cli 0.13.1 → 0.14.0

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/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as t,existsSync as e,createWriteStream as n}from"node:fs";import{writeFile as r,readFile as a,appendFile as s,readdir as i,rm as o,mkdir as c}from"node:fs/promises";import{findConfigPathSync as l,DEFAULT_OPEN_COMMAND as u,prepareImports as d,createArchiveWithDependencyContext as p,createArchive as h,createArchiveDiffWithDependencyContext as f,createArchiveDiff as y,getPackagedSystemPromptPath as m,CORE_VERSION as g,ensureOutputDir as w}from"@karmaniverous/stan-core";import{z as b,ZodError as v}from"zod";import k from"yaml";import P,{resolve as S,delimiter as $,join as A,dirname as C}from"node:path";import E from"chalk";import{table as j}from"table";import I from"tree-kill";import{spawn as D}from"node:child_process";import{onExit as T}from"signal-exit";import{ensureDir as x}from"fs-extra";import{createHash as O}from"node:crypto";import{createRequire as R}from"node:module";import{fileURLToPath as N}from"node:url";import{packageDirectorySync as L}from"package-directory";import{emitKeypressEvents as M}from"node:readline";const K=b.union([b.boolean(),b.string(),b.number()]).transform(t=>{if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t;const e=t.trim().toLowerCase();return"1"===e||"true"===e||"0"!==e&&"false"!==e&&void 0}).optional(),U=b.object({script:b.string().min(1,{message:"script must be a non-empty string"}),warnPattern:b.string().min(1,{message:"warnPattern must be a non-empty string"}).optional().refine(t=>"string"!=typeof t||(t=>{try{return new RegExp(t),!0}catch{return!1}})(t),{message:"warnPattern: invalid regular expression"}),warnPatternFlags:b.string().optional().refine(t=>"string"!=typeof t||(t=>{try{return new RegExp("",t),!0}catch{return!1}})(t),{message:"warnPatternFlags: invalid regex flags"})}).strict(),_=b.record(b.string(),b.union([b.string().min(1),U])).default({}),B=b.object({archive:K,combine:K,keep:K,sequential:K,live:K,plan:K,facets:K,hangWarn:b.coerce.number().int().positive().optional(),hangKill:b.coerce.number().int().positive().optional(),hangKillGrace:b.coerce.number().int().positive().optional(),scripts:b.union([b.boolean(),b.array(b.string())]).optional(),prompt:b.string().optional(),context:K}).strict().optional(),G=b.object({file:b.string().optional()}).strict().optional(),q=b.object({stash:K}).strict().optional(),H=b.object({debug:K,boring:K,patch:G,run:B,snap:q}).strict().optional(),W=b.object({scripts:_,cliDefaults:H,patchOpenCommand:b.string().optional(),maxUndos:b.coerce.number().int().positive().optional(),devMode:K}).strict(),F=t=>{if(["archive","init"].filter(e=>Object.prototype.hasOwnProperty.call(t,e)).length>0)throw new Error('scripts: keys "archive" and "init" not allowed')},z=(t,e)=>t.endsWith(".json")?JSON.parse(e):k.parse(e),Q=(t,e)=>{if((()=>{try{return"1"===process.env.STAN_DEBUG}catch{return!1}})())try{console.error(`stan: debug: fallback: ${t}: ${e}`)}catch{}},J=t=>{try{"function"==typeof F&&F(t)}catch{}},Y=(t,e)=>{const n=t&&"object"==typeof t?t:{};let r;try{if(!("function"==typeof W.parse)){const t=n.scripts,e=t&&"object"==typeof t?t:{};J(e);const r=n.patchOpenCommand,a="string"==typeof r&&r.length>0?r:u;return{scripts:e,cliDefaults:n.cliDefaults,patchOpenCommand:a,maxUndos:n.maxUndos,devMode:n.devMode}}r=W.parse(n)}catch(t){const n=e.replace(/\\/g,"/");throw new Error(`stan-cli: invalid config in ${n}\n${(t=>t instanceof v?t.issues.map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("\n"):String(t))(t)}`)}return J(r.scripts),{scripts:r.scripts,cliDefaults:r.cliDefaults,patchOpenCommand:"string"==typeof r.patchOpenCommand&&r.patchOpenCommand.length>0?r.patchOpenCommand:u,maxUndos:r.maxUndos,devMode:r.devMode}},V=e=>{const n=l(e);if(!n)return{scripts:{},patchOpenCommand:u};const r=t(n,"utf8"),a=z(n,r),s=a&&"object"==typeof a?a:{};if(s["stan-cli"]&&"object"==typeof s["stan-cli"])return Y(s["stan-cli"],n);const i=(t=>{const e=["scripts","cliDefaults","patchOpenCommand","maxUndos","devMode"],n={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n})(s);if(Object.keys(i).length>0){if(!(()=>{try{const t=process.env.STAN_ACCEPT_LEGACY,e=("string"==typeof t?t:"").trim().toLowerCase();return"1"===e||"true"===e}catch{return!1}})()){const t=n.replace(/\\/g,"/");throw new Error([`stan-cli: legacy configuration detected in ${t} (missing top-level "stan-cli").`,'Run "stan init" to migrate your config (a .bak is written next to the file),',"or set STAN_ACCEPT_LEGACY=1 to temporarily accept legacy keys during the transition."].join(" "))}return Q("cli.config:loadSync",`using legacy top-level CLI keys from ${n.replace(/\\/g,"/")}; run "stan init" to migrate`),Object.prototype.hasOwnProperty.call(s,"stan-core")||Q("run.action:engine-legacy",`detected legacy root keys (no "stan-core") in ${n.replace(/\\/g,"/")}`),Y(i,n)}return{scripts:{},patchOpenCommand:u}},X=e=>{try{const n=V(e);let r=Object.keys(n.scripts);if(!r.length)try{const n=(e=>{try{const n=l(e??process.cwd());if(!n)return{};const r=t(n,"utf8"),a=z(n,r);return a&&"object"==typeof a?a:{}}catch{return{}}})(e),a=(t=>{const e=t["stan-cli"];return e&&"object"==typeof e?e:null})(n),s=(a&&"object"==typeof a.scripts?a.scripts:n.scripts)??{};r=Object.keys((t=>{const e={};if(!t||"object"!=typeof t)return e;for(const[n,r]of Object.entries(t))"string"==typeof r&&r.trim().length?e[n]=r:r&&"object"==typeof r&&"string"==typeof r.script&&(e[n]=String(r.script));return e})(s))}catch{}if(!r.length)return"";const a=r[0]||"lint";return["","Default: runs all scripts and writes archives.","","Available script keys:",` ${r.join(", ")}`,"","Examples:"," stan run # all scripts, with archives",` stan run -s ${a}`,` stan run -q -x ${a}`," stan run -A # no archives"," stan run -S -A -p # plan only, no scripts, no archives",` stan run -c -s ${a}`,""].join("\n")}catch(t){return"1"===process.env.STAN_DEBUG&&console.error("stan: unable to load config for help footer",t),""}},Z=()=>new Promise(t=>setImmediate(t));function tt(){const t=Boolean(process.stdout.isTTY);return"1"===process.env.STAN_BORING||"1"===process.env.NO_COLOR||"0"===process.env.FORCE_COLOR||!t}function et(t){return tt()?t:E.green(t)}function nt(t){return tt()?t:E.cyan(t)}function rt(t){return tt()?t:E.blue(t)}function at(t){return tt()?t:E.red(t)}function st(t){return tt()?t:E.black(t)}function it(t){return tt()?t:E.gray(t)}function ot(t){return tt()?t:E.hex("#FFA500")(t)}function ct(t){return tt()?t:E.bold(t)}function lt(t){return tt()?t:E.dim(t)}const ut=(t,e)=>{const{selection:n,config:r,mode:a,behavior:s}=e,i=null==n?Object.keys(r.scripts):n,o=P.join(r.stanPath,"output").replace(/\\/g,"/");return`stan:\n ${[tt()?"STAN run plan":ct("STAN run plan"),"mode: "+("sequential"===a?"sequential":"concurrent"),`output: ${o}/`,..."string"==typeof s.prompt&&s.prompt.trim().length?[`prompt: ${s.prompt}`]:[],`scripts: ${i.length?i.join(", "):"none"}`,"archive: "+(s.archive?"yes":"no"),"combine: "+(s.combine?"yes":"no"),"keep output dir: "+(s.keep?"yes":"no"),"context: "+(s.context?"yes":"no"),"live: "+(s.live?"yes":"no"),`hang warn: ${"number"==typeof s.hangWarn?s.hangWarn.toString():"n/a"}s`,`hang kill: ${"number"==typeof s.hangKill?s.hangKill.toString():"n/a"}s`,`hang kill grace: ${"number"==typeof s.hangKillGrace?s.hangKillGrace.toString():"n/a"}s`].join("\n ")}`},dt=t=>t.toString().padStart(2,"0"),pt=t=>{t<0&&(t=0);const e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return`${dt(n)}:${dt(r)}`},ht=t=>{if(tt()){if("warn"===t)return"[WARN]";switch(t){case"waiting":return"[WAIT]";case"run":return"[RUN]";case"ok":return"[OK]";case"error":return"[FAIL]";case"cancelled":return"[CANCELLED]";case"timeout":return"[TIMEOUT]";case"quiet":return"[QUIET]";case"stalled":return"[STALLED]";case"killed":return"[KILLED]";default:return""}}switch(t){case"warn":return ot("⚠︎ warn");case"waiting":return it("⏸︎ waiting");case"run":return rt("▶︎ run");case"ok":return et("✔︎ ok");case"error":return at("✖︎ fail");case"cancelled":return st("◼︎ cancelled");case"timeout":return at("⏱︎ timeout");case"quiet":return nt("⏱︎ quiet");case"stalled":return ot("⏱︎ stalled");case"killed":return at("◼︎ killed");default:return""}},ft=t=>t.replace(/\\/g,"/"),yt=(t,e)=>{if(!e)return"";const n=e;return P.isAbsolute(n)?ft(P.relative(t,n)):ft(n)},mt=t=>{const{state:e,cwd:n,now:r}=t,a=(t=>{switch(t.kind){case"warn":return"warn";case"waiting":default:return"waiting";case"running":return"run";case"quiet":return"quiet";case"stalled":return"stalled";case"done":return"ok";case"error":return"error";case"timedout":return"timeout";case"cancelled":return"cancelled";case"killed":return"killed"}})(e);let s="";if("running"===e.kind||"quiet"===e.kind||"stalled"===e.kind){const t="number"==typeof e.startedAt?e.startedAt:(r??Date.now)();s=pt(Math.max(0,(r??Date.now)()-t))}else"number"==typeof e.durationMs&&(s=pt(Math.max(0,e.durationMs)));const i="done"===e.kind||"warn"===e.kind||"error"===e.kind||"timedout"===e.kind||"cancelled"===e.kind||"killed"===e.kind?yt(n,e.outputPath):"";return{label:ht(a),time:s,output:i}},gt=t=>t.startsWith("script:")?{type:"script",item:t.slice(7)||"(unnamed)"}:t.startsWith("archive:")?{type:"archive",item:t.slice(8)||"(unnamed)"}:void 0,wt=t=>{const e={warn:0,waiting:0,running:0,quiet:0,stalled:0,ok:0,cancelled:0,fail:0,timeout:0};for(const{state:n}of t)"warn"===n.kind?e.warn+=1:"waiting"===n.kind?e.waiting+=1:"running"===n.kind?e.running+=1:"quiet"===n.kind?e.quiet+=1:"stalled"===n.kind?e.stalled+=1:"done"===n.kind?e.ok+=1:"timedout"===n.kind?e.timeout+=1:"cancelled"===n.kind?e.cancelled+=1:["error","killed"].includes(n.kind)&&(e.fail+=1);return e},bt=t=>{const{rows:e,startedAt:n,boring:r,uiId:a,includeHint:s}=t,i=["Type","Item","Status","Time","Output"].map(t=>ct(t)),o=[];if(o.push(i),0===e.length){const t=pt(Date.now()-n);o.push(["—","—",r?"[IDLE]":"idle",t,""])}else for(const t of e){const e=t.state,n=mt({state:e,cwd:process.cwd(),now:()=>Date.now()});o.push([t.type,t.item,n.label,n.time,n.output])}const c=(t=>j(t,{columnDefault:{paddingLeft:0,paddingRight:2},border:{topBody:"",topJoin:"",topLeft:"",topRight:"",bottomBody:"",bottomJoin:"",bottomLeft:"",bottomRight:"",bodyLeft:"",bodyRight:"",bodyJoin:"",joinBody:"",joinLeft:"",joinRight:"",joinJoin:""},drawHorizontalLine:()=>!1,columns:{0:{alignment:"left"},1:{alignment:"left"},2:{alignment:"left"},3:{alignment:"left"},4:{alignment:"left"}}}))(o),l=((t,e,n)=>n?[t,`waiting ${e.waiting.toString()}`,`running ${e.running.toString()}`,`quiet ${e.quiet.toString()}`,`stalled ${e.stalled.toString()}`,`timeout ${e.timeout.toString()}`,`ok ${e.ok.toString()}`,`warn ${e.warn.toString()}`,`fail ${e.fail.toString()}`,`cancelled ${e.cancelled.toString()}`].join(" • "):[t,it(`⏸︎ ${e.waiting.toString()}`),rt(`▶︎ ${e.running.toString()}`),nt(`⏱︎ ${e.quiet.toString()}`),ot(`⏱︎ ${e.stalled.toString()}`),at(`⏱︎ ${e.timeout.toString()}`),et(`✔︎ ${e.ok.toString()}`),ot(`⚠︎ ${e.warn.toString()}`),at(`✖︎ ${e.fail.toString()}`),st(`◼︎ ${e.cancelled.toString()}`)].join(" • "))(pt(Date.now()-n),wt(e.map(t=>({state:t.state}))),r),u=s?`\n${(t=>{const e="1"===process.env.STAN_TEST_UI_TAG?` UI#${t.toString()}`:"";return`${lt("Press")} ${ct("q")} ${lt("to cancel,")} ${ct("r")} ${lt("to restart")}${e}`})(a)}`:"",d=`\n${`${c.trimEnd()}\n\n${l}${u}`}\n`;if("1"===process.env.STAN_LIVE_DEBUG)try{const t=/(?:^|\n)Type\s+Item\s+Status\s+Time\s+Output(?:\n|$)/g,e=((t=>{try{return t.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g,"")}catch{return t}})(d).match(t)??[]).length;console.error("[stan:live:frame]",{headerMatches:e,includeHint:s})}catch{}return d},vt="[",kt=`${vt}?25l`,Pt=`${vt}?25h`,St=`${vt}K`,$t=t=>t>0?`${vt}${String(t)}F`:"",At=`${vt}1E`,Ct=()=>{const t=process.stdout;let e=0;return{start(){try{t.write(kt)}catch{}},write(n){try{const r=n.endsWith("\n")?n:`${n}\n`;(n=>{let r="";e>0&&(r+=$t(e));for(let t=0;t<n.length;t+=1){const a=n[t]??"";r+=0===e&&0===t&&""===a?"\n":`\r${St}${a}\n`}const a=e-n.length;for(let t=0;t<a;t+=1)r+=`\r${St}`,t<a-1&&(r+=At);t.write(r),e=n.length})(r.split("\n"))}catch{}},clear(){try{let n="";e>0&&(n+=$t(e));for(let t=0;t<e;t+=1)n+=`\r${St}\n`;t.write(n),e=0}catch{}},done(){try{t.write(Pt)}catch{}}}},Et=(()=>{try{return"1"===process.env.STAN_LIVE_DEBUG}catch{return!1}})(),jt=(t,e,n)=>{if(Et)try{n&&Object.keys(n).length>0?console.error(`[stan:live:${t}] ${e}`,n):console.error(`[stan:live:${t}] ${e}`)}catch{}},It={get enabled(){return Et},renderer:{start(t){jt("renderer","start()",t)},update(t){jt("renderer","update()",t)},render(t){jt("renderer","render()",t)},headerOnly(t){jt("renderer","render(header-only)",t)},flush(){jt("renderer","flush()")},clear(){jt("renderer","clear()")},stop(){jt("renderer","stop()")},done(){jt("renderer","stop():done()")}},ui:{start(){jt("UI","start()")},installCancellation(){jt("UI","installCancellation(): control.attach()")},onCancelled(t){jt("UI","onCancelled()",{mode:t})},stop(){jt("UI","stop() -> sink.stop()")}},session:{info(t,e){jt("session",t,e)},exitHook(){jt("session","exit hook fired: ui.stop + supervisor cancel + pause stdin")}}};let Dt=1;const Tt=()=>Date.now();class xt{rows=new Map;opts;frameNo=0;timer;startedAt=Tt();writer=null;uiId;constructor(t){this.opts={boring:Boolean(t?.boring),refreshMs:t?.refreshMs??1e3},this.uiId=Dt++}resetElapsed(){this.startedAt=Tt(),this.frameNo=0}finalize(){this.timer&&clearInterval(this.timer),this.timer=void 0,this.renderFinalNoHint(),It.renderer.stop(),It.renderer.done(),this.writer?.done()}flush(){It.renderer.flush(),this.render()}resetRows(){this.rows.clear()}start(){It.renderer.start({refreshMs:this.opts.refreshMs}),this.timer||(this.writer||(this.writer=Ct()),this.writer.start(),this.timer=setInterval(()=>{this.render()},this.opts.refreshMs))}clear(){It.renderer.clear(),this.writer?.clear()}stop(){It.renderer.stop(),this.timer&&clearInterval(this.timer),this.timer=void 0,It.renderer.done(),this.writer?.done()}update(t,e,n){const r=this.rows.get(t),a=n??gt(t)??(r?.type?{type:r.type,item:r.item}:void 0);if(!a){const n={type:"script",item:t};return void this.rows.set(t,{...n,state:{...r?.state??{},...e}})}this.rows.set(t,{...a,state:{...r?.state??{},...e}}),It.renderer.update({key:t,kind:e.kind,rowsSize:this.rows.size})}cancelPending(){const t=Tt();for(const[e,n]of this.rows.entries()){const r=n.state;switch(r.kind){case"waiting":this.update(e,{kind:"cancelled"});break;case"running":case"quiet":case"stalled":{const n="number"==typeof r.startedAt?r.startedAt:void 0,a="number"==typeof n?Math.max(0,t-n):0;this.update(e,{kind:"cancelled",durationMs:a});break}}}}renderFinalNoHint(){let t=bt({rows:Array.from(this.rows.values()),startedAt:this.startedAt,boring:this.opts.boring,uiId:this.uiId,includeHint:!1});t.endsWith("\n")||(t+="\n"),t+="\n",this.writer?.write(t)}render(){const t=bt({rows:Array.from(this.rows.values()),startedAt:this.startedAt,boring:this.opts.boring,uiId:this.uiId,includeHint:!0});if(this.frameNo+=1,It.enabled)try{const t=wt(this.rows.values()),e=Array.from(this.rows.keys()).slice(0,5);It.renderer.render({frameNo:this.frameNo,rowsSize:this.rows.size,keys:e,headerCount:1,hasHint:!0,counts:t})}catch{}this.writer?.write(t)}}class Ot{behavior;constructor(t){this.behavior=t}pids=new Map;lastCancelled=[];track(t,e){this.pids.set(t,e)}cancelAll(t){const e="number"==typeof this.behavior.hangKillGrace?this.behavior.hangKillGrace:10,n=t?.immediate?0:Math.max(0,1e3*e),r=Array.from(this.pids.entries()),a=Array.from(this.pids.values());this.lastCancelled=a;for(const[,t]of r)try{Number.isFinite(t)&&process.kill(t,"SIGTERM")}catch{}const s=()=>{for(const[,t]of r)try{Number.isFinite(t)&&I(t,"SIGKILL")}catch{}};n<=0?setTimeout(s,0):setTimeout(s,n),this.pids.clear()}async waitAll(t=2e3){const e=this.lastCancelled.length>0?[...this.lastCancelled]:Array.from(this.pids.values());if(0===e.length)return;const n=Date.now()+Math.max(0,t),r=t=>{try{return process.kill(t,0)}catch{return!1}};for(;Date.now()<n;){if(0===e.filter(t=>r(t)).length)break;await new Promise(t=>setTimeout(t,50))}this.lastCancelled=[]}}class Rt{ui;supervisor;cancelled=!1;restartRequested=!1;cancelledKeys=new Set;wake=null;waitP;constructor(t,e){this.ui=t,this.supervisor=e,this.waitP=new Promise(t=>this.wake=t)}markQueued(t){for(const e of t)this.cancelledKeys.add(`script:${e}`)}async wait(){await this.waitP}isCancelled(){return this.cancelled}isRestart(){return this.restartRequested}wasKeyCancelled(t){return this.cancelled&&this.cancelledKeys.has(`script:${t}`)}triggerCancel(){if(!this.cancelled){this.cancelled=!0;try{this.ui.onCancelled("cancel")}catch{}try{this.supervisor.cancelAll({immediate:!0})}catch{}try{process.exitCode=1,"test"!==process.env.NODE_ENV&&process.exit(1)}catch{}try{this.wake?.()}catch{}}}triggerRestart(){if(!this.restartRequested){this.restartRequested=!0,this.cancelled=!0;try{this.ui.onCancelled("restart")}catch{}try{this.supervisor.cancelAll({immediate:!0})}catch{}try{this.wake?.()}catch{}}}detachUiKeys(){try{It.session.info("restart: detach keys")}catch{}}}let Nt=null;function Lt(t){return Nt===t}const Mt=(t,n)=>{const r=n.PATH??n.Path??"",a=(t=>{const n=[];let r=t;for(;;){const t=A(r,"node_modules",".bin");try{e(t)&&n.push(t)}catch{}const a=C(r);if(a===r)break;r=a}return n})(t);return{...n,PATH:[...a,r].filter(Boolean).join($)}},Kt=async(t,e,r,i,o,c,l,u,d)=>{const p=S(e,`${i}.txt`),h=Date.now();l?.onStart?.(i);const f=n(p,{encoding:"utf8"}),y=D(o,{cwd:t,shell:!0,windowsHide:!0,env:Mt(t,process.env)}),m="1"===process.env.STAN_DEBUG;let g="";const w="number"==typeof u?.hangWarn&&u.hangWarn>0?u.hangWarn:0,b="number"==typeof u?.hangKill&&u.hangKill>0?u.hangKill:0,v="number"==typeof u?.hangKillGrace&&u.hangKillGrace>0?u.hangKillGrace:10;let k,P,$=Date.now(),A=!1,C=!1;try{"number"==typeof y.pid&&d&&d.track(`script:${i}`,y.pid)}catch{}y.stdout.on("data",t=>{f.write(t),g+=t.toString("utf8"),m&&process.stdout.write(t),$=Date.now()}),y.stderr.on("data",t=>{f.write(t),g+=t.toString("utf8"),m&&process.stderr.write(t),$=Date.now()}),(w>0||b>0)&&(k=setInterval(()=>{const t=Date.now()-$;if(!A&&w>0&&t>=1e3*w&&(A=!0,l?.onHangWarn?.(i,w)),!C&&b>0&&t>=1e3*b){C=!0;try{"number"==typeof y.pid&&process.kill(y.pid,"SIGTERM")}catch{}l?.onHangTimeout?.(i,b);const t=Math.max(0,1e3*v);P=setTimeout(()=>{try{"number"==typeof y.pid&&I(y.pid,"SIGKILL")}catch{}l?.onHangKilled?.(i,v)},t)}},1e3));const E=await new Promise((t,e)=>{y.on("error",t=>{e(t instanceof Error?t:new Error(String(t)))}),y.on("close",e=>{t(e??0)})});k&&clearInterval(k),P&&clearTimeout(P),f.end(),await(t=>new Promise((e,n)=>{t.on("close",()=>{e()}),t.on("error",t=>{n(t instanceof Error?t:new Error(String(t)))})}))(f);let j="ok";if("number"==typeof E&&0!==E)j="error";else if(u?.warnPatterns&&u.warnPatterns.length>0){const t=(t,e)=>t.some(t=>{try{return t.lastIndex=0,t.test(e)}catch{return!1}});let e=!1;if(g.length>0&&t(u.warnPatterns,g))e=!0;else try{const n=await a(p,"utf8");t(u.warnPatterns,n)&&(e=!0)}catch{}e&&(j="warn")}return l?.onEnd?.(i,p,h,Date.now(),E,j),c&&await s(c,i.slice(0,1).toUpperCase(),"utf8"),p},Ut=()=>{let t=0;return(()=>{try{const t=process.env.CI,e=("string"==typeof t?t:"").trim().toLowerCase();return""!==e&&"0"!==e&&"false"!==e}catch{return!1}})()&&(t+=25),"win32"!==process.platform&&(t+=10),25+t},_t=async(t,e,n,r,a,s,i,o,c,l,u)=>{const d=[],p=async n=>{try{if("function"==typeof l&&!l())return}catch{}const a=r.scripts[n],s="string"==typeof a?a:"object"==typeof a&&a&&"script"in a?a.script:"",p=a&&"object"==typeof a&&"warnPattern"in a?((t,e)=>{if("string"!=typeof t||!t.trim())return[];const n=t.trim(),r=[],a=(t,e)=>{try{r.push(new RegExp(t,e))}catch{}};if("string"==typeof e&&e.length>0){a(n,e);const t=n.replace(/\\\\/g,"\\");t!==n&&a(t,e)}else{a(n);const t=n.replace(/\\\\/g,"\\");t!==n&&a(t),a(n,"i")}return r})(a.warnPattern,a.warnPatternFlags):[],h=await Kt(t,e,0,n,s,i,o,{silent:o.silent,hangWarn:c?.hangWarn,hangKill:c?.hangKill,hangKillGrace:c?.hangKillGrace,warnPatterns:p},u);d.push(h)};if("sequential"===s)for(const t of a){const e=t=>new Promise(e=>setTimeout(e,t));if("function"==typeof l){if(!l())break;if(await Z(),!l())break;if(await e(Ut()),!l())break;if(await Z(),!l())break}if(await p(t),"function"==typeof l){if(await Z(),!l())break;if(await e(Math.max(5,Ut()/2)),!l())break;if(await Z(),!l())break}}else{const t="function"==typeof l?a.filter(()=>l()):a;await Promise.all(t.map(t=>p(t).then(()=>{})))}return d},Bt=async t=>{const{cwd:e,outAbs:n,outRel:r,config:a,toRun:s,mode:i,orderFile:o,ui:c,epoch:l,isActive:u,shouldContinue:d,supervisor:p,liveEnabled:h,hangWarn:f,hangKill:y,hangKillGrace:m}=t,g=[],w=_t(e,n,0,a,s,i,o,{onStart:t=>{u(l)&&c.onScriptStart(t)},onEnd:(t,n,r,a,s,i)=>{if(u(l)&&(c.onScriptEnd(t,n,e,r,a,s,i),"error"===i||"number"==typeof s&&0!==s))try{process.exitCode=1}catch{}},silent:!0,onHangWarn:(t,e)=>{u(l)&&(h||((t,e)=>{try{console.log(`stan: ⏱ stalled "${t}" after ${e.toString()}s of inactivity`)}catch{}})(t,e))},onHangTimeout:(t,e)=>{u(l)&&(h||((t,e)=>{try{console.log(`stan: ⏱ timeout "${t}" after ${e.toString()}s; sending SIGTERM`)}catch{}})(t,e))},onHangKilled:(t,e)=>{u(l)&&(h||((t,e)=>{try{console.log(`stan: ◼ killed "${t}" after ${e.toString()}s grace`)}catch{}})(t,e))}},{hangWarn:f,hangKill:y,hangKillGrace:m},d,p).then(t=>{g.push(...t)});return await w.catch(()=>{}),g};const Gt=(t,e)=>{try{It.session.info("install SIGINT handler"),process.on("SIGINT",t)}catch{}const n=(r=e,T(()=>{try{const t=r();t&&"function"==typeof t.then&&t.catch(()=>{})}catch{}}));var r;return()=>{try{It.session.info("detach SIGINT handler"),process.off("SIGINT",t)}catch{}try{It.session.info("uninstall exit hook"),n()}catch{}}},qt=(t,e)=>P.join(t,e,"system",".docs.meta.json"),Ht=async t=>O("sha256").update(await a(t)).digest("hex"),Wt=async(t,e,n)=>{const r=P.join(t,e,"imports");try{const t=await i(r,{withFileTypes:!0});await Promise.all(t.map(t=>o(S(r,t.name),{recursive:!0,force:!0})))}catch{}if(n&&"object"==typeof n)try{await d({cwd:t,stanPath:e,map:n})}catch{}},Ft=async t=>{try{const e=await i(t,{withFileTypes:!0}),n=new Set(["archive.tar","archive.diff.tar"]);await Promise.all(e.map(async e=>{n.has(e.name)||await o(S(t,e.name),{recursive:!0,force:!0})}))}catch{}},zt=async(t,e)=>{const n=P.join(t,e,"patch");try{const t=await i(n,{withFileTypes:!0});await Promise.all(t.map(t=>o(S(n,t.name),{recursive:!0,force:!0})))}catch{}},Qt=t=>"diff"===t?"archive (diff)":"archive";var Jt=Object.freeze({__proto__:null,archivePhase:async(t,e)=>{const{cwd:n,config:r,includeOutputs:a}=t,{dependency:s}=r,i=t=>{const{kind:e,counts:n,hasWarnings:r}=t,a=n,s=[`candidates ${String(a.candidates)}`,`selected ${String(a.selected)}`,`archived ${String(a.archived)}`];a.excludedBinaries>0&&s.push(`binaries ${String(a.excludedBinaries)}`),a.largeText>0&&s.push(`large ${String(a.largeText)}`);const i=r?" (warnings)":"",o="diff"===e?"diff":"meta"===e?"meta":"full";console.log(`stan: selection (${o}): ${s.join(", ")}${i}`)},c=Boolean(e?.silent),l=e?.which??"both",u=!1!==e?.stage,d=!1!==e?.cleanup,m=((t,e)=>{const n=P.join(t,e),r=P.join(n,"system");return{base:n,system:r,output:P.join(n,"output"),diff:P.join(n,"diff"),patch:P.join(n,"patch"),systemFile:P.join(r,"stan.system.md")}})(n,r.stanPath),g="function"==typeof e?.shouldContinue?e.shouldContinue:void 0,w=((t,e)=>{const n=Array.isArray(e)?e.filter(t=>"string"==typeof t&&t.length>0):[],r=(t=>{const e=(t=>{const e="string"==typeof t?t.trim():"",n=(r=e,r.replace(/\\+/g,"/")).replace(/\/+$/,"");var r;return n.length>0?n:e.startsWith("/")?"":".stan"})(t);return`${e}/imports/**`})(t);return n.includes(r)?n:[...n,r]})(r.stanPath,r.includes??[]);let b,v;c||"both"!==l&&"full"!==l||console.log(`stan: start "${nt("archive")}"`);try{if(u){if(g&&!g())return{archivePath:b,diffPath:v};await Wt(n,r.stanPath,r.imports)}if("both"===l||"full"===l){if(g&&!g())return{archivePath:b,diffPath:v};e?.progress?.start?.("full");const t=Date.now();if(s){b=(await p({cwd:n,stanPath:r.stanPath,dependency:s,archive:{includeOutputDir:a,includes:w,excludes:r.excludes??[],onSelectionReport:i}})).archivePath}else b=await h(n,r.stanPath,{includeOutputDir:a,includes:w,excludes:r.excludes??[],onSelectionReport:i});if(e?.progress?.done?.("full",b,t,Date.now()),g&&!g()){try{b&&await o(b,{force:!0})}catch{}return{archivePath:void 0,diffPath:v}}c||console.log(`stan: ${et("done")} "${nt("archive")}" -> ${nt(b?b.replace(/\\/g,"/"):"")}`)}if(c||"both"!==l&&"diff"!==l||console.log(`stan: start "${nt("archive (diff)")}"`),"both"===l||"diff"===l){if(g&&!g())return{archivePath:b,diffPath:v};e?.progress?.start?.("diff");const t=Date.now();let l;if(l=s?await f({cwd:n,stanPath:r.stanPath,dependency:s,diff:{baseName:"archive",includes:w,excludes:r.excludes??[],updateSnapshot:"createIfMissing",includeOutputDirInDiff:a,onSelectionReport:i}}):await y({cwd:n,stanPath:r.stanPath,baseName:"archive",includes:w,excludes:r.excludes??[],updateSnapshot:"createIfMissing",includeOutputDirInDiff:a,onSelectionReport:i}),v=l.diffPath,e?.progress?.done?.("diff",v,t,Date.now()),g&&!g()){try{await o(v,{force:!0})}catch{}return{archivePath:b,diffPath:void 0}}c||console.log(`stan: ${et("done")} "${nt("archive (diff)")}" -> ${nt(v.replace(/\\/g,"/"))}`)}}finally{}return d&&(a&&await Ft(m.output),await zt(n,r.stanPath)),{archivePath:b,diffPath:v}},archivePrintable:Qt,cleanupOutputsAfterCombine:Ft,cleanupPatchDirAfterArchive:zt,stageImports:Wt});const Yt=async t=>{const{cwd:e,stanPath:n,promptAbs:r}=t;let s,i=!1;try{r&&(s=await Ht(r))}catch{s=void 0}try{const t=await(async(t,e)=>{try{const n=await a(qt(t,e),"utf8"),r=JSON.parse(n);if(r&&"object"==typeof r)return r}catch{}return null})(e,n),r=t?.prompt&&"object"==typeof t.prompt?t.prompt.hash:void 0;r&&s?i=r!==s:r&&s||(i=!1)}catch{i=!1}return i},Vt=t=>P.join(t,"system","stan.system.md"),Xt=async t=>{const e=await a(t);return Buffer.from(e)},Zt=(t,n,r)=>{const a=P.join(t,Vt(n)),s=(()=>{try{const t=m();if(t&&e(t))return t}catch{}try{const t=R(import.meta.url).resolve("@karmaniverous/stan-core"),n=L({cwd:P.dirname(t)})??null;if(n){const t=P.join(n,"dist","stan.system.md");if(e(t))return t}}catch{}try{const t=R(import.meta.url).resolve("@karmaniverous/stan-core/dist/stan.system.md");if(t&&e(t))return t}catch{}return null})();if("local"===r){if(!e(a))throw new Error(`system prompt not found at ${P.join(n,"system","stan.system.md").replace(/\\/g,"/")}`);return{abs:a,display:P.join(n,"system","stan.system.md").replace(/\\/g,"/"),kind:"local"}}if("core"===r){if(!s||!e(s))throw new Error("packaged system prompt not found in @karmaniverous/stan-core");return{abs:s,display:`@karmaniverous/stan-core@${g}`,kind:"core"}}if("auto"===r){if(e(a))return{abs:a,display:P.join(n,"system","stan.system.md").replace(/\\/g,"/"),kind:"local"};if(s&&e(s))return{abs:s,display:`@karmaniverous/stan-core@${g}`,kind:"core"};try{const t=(()=>{try{const t=N(import.meta.url),n=L({cwd:P.dirname(t)})??null;if(n){const t=P.join(n,"dist","stan.system.md");if(e(t))return t}}catch{}return null})();if(t&&e(t))return{abs:t,display:t.replace(/\\/g,"/"),kind:"path"}}catch{}throw new Error("unable to resolve system prompt (auto: local and core unavailable)")}const i=P.isAbsolute(r)?r:P.join(t,r);if(!e(i))throw new Error(`system prompt not found at ${i.replace(/\\/g,"/")}`);return{abs:i,display:i.replace(/\\/g,"/"),kind:"path"}},te=async t=>{const{cwd:n,stanPath:a,promptAbs:s,promptDisplay:i}=t;try{const{restore:t}=await(async(t,n,a)=>{const s=P.join(t,Vt(n)),i=P.dirname(s),l=e(s);let u=null;if(l)try{u=await Xt(s)}catch{u=null}const d=await Xt(a.abs),p=l&&null!==u&&u.length===d.length&&u.equals(d);return p||(await c(i,{recursive:!0}),await r(s,d)),{changed:!p,restore:async()=>{if(!p)try{l&&null!==u?await r(s,u):await o(s,{force:!0})}catch{}}}})(n,a,{abs:s,display:i,kind:"path"});return t}catch(t){throw new Error(t instanceof Error?t.message:String(t))}},ee=async t=>{const{cwd:e,stanPath:n,behavior:r,promptAbs:a,promptDisplay:s,baseFull:i,baseDiff:o,archivePhase:c,stageImports:l,preparePrompt:u,prepareIfNeeded:d,shouldContinue:p,progress:h,ephemeral:f,includeOnChange:y,importsMap:m}=t,g=[],w=Boolean(r.combine);if(f&&"function"==typeof l){if("function"==typeof p&&!p())return g;await l(e,n,(t=>{if(!t)return t;const e={};for(const[n,r]of Object.entries(t))Array.isArray(r)&&(e[n]=r);return Object.keys(e).length?e:null})(m))}const b=async()=>{if("function"==typeof p&&!p())return;const t=!1===y?{...o,excludes:[...o.excludes??[],(r=`${n}/system/stan.system.md`,r.replace(/\\+/g,"/"))]}:o;var r;const a=await c({cwd:e,config:t,includeOutputs:w},{silent:!0,which:"diff",progress:h,shouldContinue:p});a.diffPath&&g.push(a.diffPath)},v=async()=>{if("function"==typeof p&&!p())return;const t=await c({cwd:e,config:i,includeOutputs:w},{silent:!0,which:"full",progress:h,shouldContinue:p});t.archivePath&&g.push(t.archivePath)};if(f){if(!a||"function"!=typeof u)return g;if(y){const t=await u({cwd:e,stanPath:n,promptAbs:a,promptDisplay:s});try{await b(),await v()}finally{await t().catch(()=>{})}return g}await b();const t=await u({cwd:e,stanPath:n,promptAbs:a,promptDisplay:s});try{await v()}finally{await t().catch(()=>{})}return g}const k="function"==typeof d?await d({cwd:e,stanPath:n,promptAbs:a,promptDisplay:s}):null;try{await b(),await v()}finally{await(k?.().catch(()=>{}))}return g};var ne=Object.freeze({__proto__:null,runArchiveStage:async t=>{const{cwd:e,config:n,behavior:s,ui:i,promptAbs:o,promptDisplay:c,promptSource:l}=t,u="function"==typeof t.shouldContinue?t.shouldContinue:()=>!0,d=[];if(!u())return{created:d,cancelled:!0};const p=(()=>{const t=Jt,e=t.archivePhase;if("function"==typeof e)return e;const n=t.default;if("function"==typeof n)return n;if(n&&"object"==typeof n){const t=n.archivePhase;if("function"==typeof t)return t;for(const t of Object.values(n))if("function"==typeof t)return t}if("function"==typeof Jt)return Jt;throw new Error("archivePhase not found")})(),h=(()=>{const t=Jt,e=t.stageImports;if("function"==typeof e)return e;const n=t.default;if("function"==typeof n)return n;if(n&&"object"==typeof n){const t=n.stageImports;if("function"==typeof t)return t;for(const t of Object.values(n))if("function"==typeof t)return t}if("function"==typeof Jt)return Jt;throw new Error("stageImports not found")})(),f=P.join(e,n.stanPath,"system","stan.system.md"),{full:y,diff:m}=(t=>({full:{stanPath:t.stanPath,includes:t.includes??[],excludes:t.excludes??[],imports:t.imports},diff:{stanPath:t.stanPath,includes:t.includes??[],excludes:t.excludes??[],imports:t.imports}}))(n),g=((t,e)=>({start:e=>{t.onArchiveStart(e)},done:(n,r,a,s)=>{t.onArchiveEnd(n,r,e,a,s)}}))(i,e),w=async()=>{try{if(!o||!l)return;const t=await Ht(o);await(async(t,e,n)=>{const s=qt(t,e);let i={};try{const t=await a(s,"utf8"),e=JSON.parse(t);e&&"object"==typeof e&&(i=e)}catch{i={}}const o={...i,prompt:{...i.prompt??{},...n}};await x(P.dirname(s)),await r(s,JSON.stringify(o,null,2),"utf8")})(e,n.stanPath,{source:l,hash:t,path:o})}catch{}},b=((t,e)=>{if(!e)return!1;try{return P.resolve(e)!==P.resolve(t)}catch{return!0}})(f,o);if(b){if(!u())return{created:d,cancelled:!0};let t=!0;try{t=await Yt({cwd:e,stanPath:n.stanPath,promptAbs:o})}catch{t=!0}try{const r=await ee({cwd:e,stanPath:n.stanPath,behavior:s,promptAbs:o,promptDisplay:c,baseFull:y,baseDiff:m,archivePhase:p,stageImports:async(t,e,n)=>{try{await h(t,e,n)}catch{}},preparePrompt:({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r})=>te({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r}),shouldContinue:u,progress:g,ephemeral:!0,includeOnChange:t,importsMap:n.imports});return d.push(...r),await w(),{created:d,cancelled:!1}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:String(t);console.error(`stan: error: failed to prepare system prompt (${e})`),console.log("");try{i.stop()}catch{}return{created:d,cancelled:!0}}}try{if(!u())return{created:d,cancelled:!0};const t=await ee({cwd:e,stanPath:n.stanPath,behavior:s,promptAbs:o,promptDisplay:c,baseFull:y,baseDiff:m,archivePhase:p,prepareIfNeeded:async({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r})=>n?te({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r}):null,shouldContinue:u,progress:g,ephemeral:!1});return d.push(...t),await w(),{created:d,cancelled:!1}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:String(t);console.error(`stan: error: failed to prepare system prompt (${e})`),console.log("");try{i.stop()}catch{}return{created:d,cancelled:!0}}}});const re=async t=>{const e=S(t,"archive.tar"),n=S(t,"archive.diff.tar");await Promise.allSettled([o(e,{force:!0}),o(n,{force:!0})])},ae=async t=>new Promise(e=>setTimeout(e,Math.max(0,t))),se=()=>"win32"===process.platform,ie=async t=>{const{created:n,ui:r,supervisor:a,detachSignals:s,liveEnabled:i,outAbs:o}=t,c=S(o,"archive.tar"),l=S(o,"archive.diff.tar"),u=()=>!e(c)&&!e(l),d=async()=>{await re(o).catch(()=>{})};if(await d(),!u()){const t=se()?10:6;for(let e=0;e<t&&(await ae(se()?200:40),await d(),!u());e+=1);try{await ae(se()?120:25)}catch{}}try{r.stop()}catch{}if(i)try{console.log("")}catch{}try{await a.waitAll(3e3)}catch{}(()=>{try{process.stdin.pause?.()}catch{}})();try{await ae(se()?160:40)}catch{}try{s()}catch{}return{created:n,cancelled:!0,restartRequested:!1}};async function oe(t,e){return t.isCancelled()&&!t.isRestart()?await ie(e):t.isRestart()?(t=>{try{t.detachSignals()}catch{}return{created:t.created,cancelled:!0,restartRequested:!0}})({created:e.created,detachSignals:e.detachSignals}):null}async function ce(t){const{cancelCtl:e,deps:n,cwd:r,config:a,behavior:s,ui:i,promptAbs:c,promptDisplay:l,supervisor:u}=t,d=await async function(t,e){try{await Z()}catch{}const n=await oe(t,e);if(n)return n;try{await ae(se()?300:30)}catch{}return oe(t,e)}(e,{created:n.created,ui:n.ui,supervisor:u,detachSignals:n.detachSignals,liveEnabled:!0,outAbs:n.outAbs});if(d)return{short:d};const p=(()=>{const t=ne,e=t.runArchiveStage,n=t.default?.runArchiveStage,r="function"==typeof e?e:"function"==typeof n?n:void 0;if(!r)throw new Error("runArchiveStage not found");return r})(),h=await p({cwd:r,config:a,behavior:s,ui:i,promptAbs:c,promptDisplay:l,shouldContinue:()=>!e.isCancelled()});if(h.cancelled)return{short:{created:n.created,cancelled:!0,restartRequested:!0}};if(e.isCancelled()&&!e.isRestart()){await Promise.all(h.created.map(t=>o(t,{force:!0}))).catch(()=>{}),await re(n.outAbs).catch(()=>{});try{n.detachSignals()}catch{}return{short:{created:n.created,cancelled:!0,restartRequested:!1}}}return{added:h.created}}async function le(t,e){const n=await oe(t,e);if(n)return n;const r=await async function(t,e){try{await Z()}catch{}return oe(t,e)}(t,e);if(r)return r;const a=await async function(t,e){try{await ae(se()?25:process.env.CI?20:10),await Z()}catch{}return oe(t,e)}(t,e);return a}function ue(t){const{cwd:e,config:n,selection:r,mode:a,behavior:s,ui:i,planBody:o,printPlan:c,promptChoice:l}=t;let u="",d=null,p=null;try{const t=((t,e,n)=>{const r=(n??"auto").trim(),a=Zt(t,e,r);return{display:"auto"===r?`auto → ${a.display}`:a.display,abs:a.abs,kind:a.kind}})(e,n.stanPath,l);u=t.display,d=t.abs,p=t.kind;try{if("1"===process.env.STAN_DEBUG){const e=t.kind||"path",n=(d||"").replace(/\\/g,"/");console.error(`stan: debug: prompt: ${e} ${n}`)}}catch{}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:String(t);console.error(`stan: warn: proceeding without resolved system prompt (${e})`),console.log(""),u="auto (unresolved)",d=null,p=null}if(c&&o)try{((t,e)=>{const{selection:n,config:r,mode:a,behavior:s,planBody:i,ui:o,promptDisplay:c}=e;try{const t=ut(0,{selection:n,config:r,mode:a,behavior:{...s,prompt:c}});o.onPlan(t)}catch{"string"==typeof i&&i.length&&o.onPlan(i)}console.log("")})(0,{selection:r,config:n,mode:a,behavior:s,planBody:o,ui:i,promptDisplay:u})}catch{}return{display:u,abs:d,source:p}}function de(t){const{ui:e,selection:n,config:r,includeArchives:a,cancelCtl:s}=t,i=((t,e,n,r)=>{const a=(e??[]).filter(t=>Object.prototype.hasOwnProperty.call(n.scripts,t));for(const e of a)try{t.onScriptQueued(e)}catch{}if(r){try{t.onArchiveQueued("full")}catch{}try{t.onArchiveQueued("diff")}catch{}}return a})(e,n,r,a);s.markQueued(i);try{const t=e.flushNow;"function"==typeof t&&t()}catch{}return i}const pe="test"===process.env.NODE_ENV||"1"===process.env.STAN_WRITE_ORDER,he=async t=>{const{cwd:e,config:n,selection:a,mode:s,behavior:i,liveEnabled:o,planBody:c,printPlan:l,ui:u,promptChoice:d}=t,p=function(){const t=Symbol("session-epoch");return Nt=t,t}(),h=S(e,n.stanPath,"output"),f=S(n.stanPath,"output").replace(/\\/g,"/"),y=await(async(t,e,n)=>{if(!t)return;const a=S(e,"order.txt");return n||await r(a,"","utf8"),a})(pe,h,Boolean(i.keep)),{display:m,abs:g}=ue({cwd:e,config:n,selection:a,mode:s,behavior:i,ui:u,planBody:c,printPlan:l,promptChoice:d});!function(t){t.start();try{const e=t.flushNow;"function"==typeof e&&e()}catch{}}(u);const w=new Ot({hangWarn:i.hangWarn,hangKill:i.hangKill,hangKillGrace:i.hangKillGrace}),b=new Rt(u,w);try{u.installCancellation(()=>{b.triggerCancel()},o?()=>{b.triggerRestart()}:void 0)}catch{}const v=Gt(()=>{b.triggerCancel()},async()=>{It.session.exitHook();try{u.stop()}catch{}try{w.cancelAll({immediate:!0})}catch{}try{await w.waitAll(3e3)}catch{}try{const t=process.stdin.pause;"function"==typeof t&&t()}catch{}});!function(t){try{const e=t.prepareForNewSession;"function"==typeof e&&e()}catch{}}(u);const k=de({ui:u,selection:a,config:n,includeArchives:Boolean(i.archive),cancelCtl:b}),P=[];if(k.length>0){const t=await Bt({cwd:e,outAbs:h,outRel:f,config:n,toRun:k,mode:s,orderFile:y,ui:u,epoch:p,isActive:Lt,shouldContinue:()=>!b.isCancelled(),supervisor:w,liveEnabled:o,hangWarn:i.hangWarn,hangKill:i.hangKill,hangKillGrace:i.hangKillGrace});P.push(...t)}const $={created:P,ui:u,supervisor:w,detachSignals:v,liveEnabled:o,outAbs:h},A=await le(b,$);if(A)return A;if(i.archive){const{short:t,added:r}=await ce({cancelCtl:b,deps:$,cwd:e,config:n,behavior:i,ui:u,promptAbs:g,promptDisplay:m,supervisor:w});if(t)return t;r?.length&&P.push(...r)}await(async()=>{try{const t="win32"===process.platform?140:process.env.CI?25:15;await new Promise(e=>setTimeout(e,t)),await Z()}catch{}})(),await(async t=>{try{await Z()}catch{}try{const e=t.flushNow;"function"==typeof e&&e()}catch{}})(u),It.session.info("normal path: detach signals, returning to caller");try{v()}catch{}return{created:P,cancelled:!1,restartRequested:!1}};class fe{onCancel;onRestart;attached=!1;keyHandler;dataHandler;constructor(t){this.onCancel=t.onCancel,this.onRestart=t.onRestart}attach(){if(this.attached)return;this.attached=!0;const t=process.stdin,e=Boolean(process.stdout.isTTY),n=Boolean(t.isTTY),r=e&&n;if(r)try{M(t);const e=t.setRawMode;"function"==typeof e&&e(!0);const n=t.resume;"function"==typeof n&&n()}catch{}if(this.keyHandler=(t,e)=>{const n=((e??{}).name??"").toLowerCase();"q"!==n?"r"===n&&this.onRestart?.():this.onCancel()},this.dataHandler=t=>{try{if("string"==typeof t){const e=t.toLowerCase();return void(""===e||"q"===e?this.onCancel():"r"===e&&this.onRestart?.())}if(Buffer.isBuffer(t)){if(t.includes(3))return void this.onCancel();const e=t.toString("utf8").toLowerCase();"q"===e?this.onCancel():"r"===e&&this.onRestart?.()}}catch{}},r){const e=t.on;"function"==typeof e&&e("keypress",this.keyHandler)}const a=t.on;"function"==typeof a&&a("data",this.dataHandler)}detach(){if(!this.attached)return;this.attached=!1;const t=process.stdin,e=t.off,n=t.removeListener,r="function"==typeof e?e.bind(t):"function"==typeof n?n.bind(t):null;try{r&&"function"==typeof this.keyHandler&&r("keypress",this.keyHandler),r&&"function"==typeof this.dataHandler&&r("data",this.dataHandler)}catch{}try{const e=t.setRawMode;"function"==typeof e&&e(!1);const n=t.pause;"function"==typeof n&&n()}catch{}}}class ye{rows=new Map;listeners=new Set;subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}clearAll(){this.rows.clear()}update(t,e,n){const r=this.rows.get(t),a=n??r?.meta;if(!a){const n=gt(t)??(t.startsWith("archive:")?{type:"archive",item:t.slice(8)||"(unnamed)"}:{type:"script",item:t.replace(/^script:/,"")||"(unnamed)"});return this.rows.set(t,{meta:n,state:e}),void this.emit(t,n,e)}this.rows.set(t,{meta:a,state:e}),this.emit(t,a,e)}emit(t,e,n){for(const r of this.listeners)try{r({key:t,meta:e,state:n})}catch{}}counts(){return wt(Array.from(this.rows.values()).map(t=>({state:t.state})))}}class me{model;constructor(t){this.model=t}unsub;subscribeModel(){this.unsub||(this.unsub=this.model.subscribe(t=>{try{this.onUpdate(t.key,t.meta,t.state)}catch{}}))}unsubscribeModel(){try{this.unsub?.()}catch{}this.unsub=void 0}}class ge extends me{opts;dbg(...t){try{"1"===process.env.STAN_LIVE_DEBUG&&console.error("[stan:live:sink]",...t)}catch{}}renderer=null;stopped=!1;constructor(t,e){super(t),this.opts=e}start(){this.stopped=!1,this.renderer?this.dbg("start() renderer=existing"):(this.dbg("start() renderer=create"),this.renderer=new xt({boring:Boolean(this.opts?.boring)}),this.renderer.start(),this.subscribeModel())}stop(){if(this.stopped)this.dbg("stop():already-stopped");else{this.stopped=!0;try{const t=this.renderer;t&&"function"==typeof t.finalize&&(this.dbg("stop() finalize(full)"),t.finalize())}catch{}this.unsubscribeModel()}}flushNow(){try{this.renderer&&this.renderer.flush()}catch{}}resetForRestart(){try{this.dbg("resetForRestart()");const t=this.renderer;t&&"function"==typeof t.resetRows&&t.resetRows()}catch{}}resetElapsed(){try{const t=this.renderer;t&&"function"==typeof t.resetElapsed&&t.resetElapsed()}catch{}}cancelPending(){this.dbg("cancelPending()");try{const t=this.renderer;t&&"function"==typeof t.cancelPending&&t.cancelPending()}catch{}}onUpdate(t,e,n){this.dbg("update",{key:t,type:e.type,item:e.item,kind:n.kind}),this.renderer&&this.renderer.update(`${e.type}:${e.item}`,n,e)}}class we extends me{cwd;constructor(t,e){super(t),this.cwd=e}start(){this.subscribeModel()}stop(){this.unsubscribeModel()}onUpdate(t,e,n){const r=e.item,a="archive"===e.type?Qt("diff"===r?"diff":"full"):r,s=mt({state:n,cwd:this.cwd});if("waiting"!==n.kind)if("running"!==n.kind)if("warn"!==n.kind){if("done"===n.kind||"error"===n.kind){const t="done"===n.kind,e=s.label,r=t?"":" (exit 1)",i=s.output||"";return void console.log(`stan: ${e} "${a}" -> ${i}${r}`)}}else console.log(`stan: ${s.label} "${a}" -> ${s.output}`);else console.log(`stan: ${s.label} "${a}"`);else console.log(`stan: ${s.label} "${a}"`)}}const be=(t,e)=>{t.update(`script:${e}`,{kind:"waiting"},{type:"script",item:e})},ve=(t,e)=>{t.update(`script:${e}`,{kind:"running",startedAt:Date.now()},{type:"script",item:e})},ke=(t,e)=>{const n="diff"===e?"diff":"full";t.update(`archive:${n}`,{kind:"running",startedAt:Date.now()},{type:"archive",item:n})},Pe=(t,e)=>{const n=Boolean(e?.useDurations);return{onScriptEnd:(e,r,a,s,i,o,c)=>{const l=yt(a,r);((t,e,n,r,a,s,i)=>{const o="number"==typeof r&&"number"==typeof a?Math.max(0,a-r):0,c="error"===i||"number"==typeof s&&0!==s?{kind:"error",durationMs:o,outputPath:n}:"warn"===i?{kind:"warn",durationMs:o,outputPath:n}:{kind:"done",durationMs:o,outputPath:n};t.update(`script:${e}`,c,{type:"script",item:e})})(t,e,l,n?s:void 0,n?i:void 0,n?o:void 0,c)},onArchiveEnd:(e,r,a,s,i)=>{const o=yt(a,r);((t,e,n,r,a)=>{const s="diff"===e?"diff":"full",i="number"==typeof r&&"number"==typeof a?Math.max(0,a-r):0;t.update(`archive:${s}`,{kind:"done",durationMs:i,outputPath:n},{type:"archive",item:s})})(t,e,o,n?s:void 0,n?i:void 0)}}};var Se=Object.freeze({__proto__:null,LiveUI:class{opts;renderer=null;control=null;model=new ye;sink;forwards=Pe(this.model,{useDurations:!0});stopped=!1;constructor(t){this.opts=t,this.sink=new ge(this.model,{boring:Boolean(t?.boring)})}start(){It.ui.start(),this.stopped=!1,this.renderer||(this.sink.start(),this.renderer=this.sink.renderer??null)}onPlan(t){console.log(t)}onScriptQueued(t){be(this.model,t)}onScriptStart(t){ve(this.model,t)}onScriptEnd(t,e,n,r,a,s,i){this.forwards.onScriptEnd(t,e,n,r,a,s,i)}onArchiveQueued(t){((t,e)=>{const n="diff"===e?"diff":"full";t.update(`archive:${n}`,{kind:"waiting"},{type:"archive",item:n})})(this.model,t)}onArchiveStart(t){ke(this.model,t)}onArchiveEnd(t,e,n,r,a){this.forwards.onArchiveEnd(t,e,n,r,a)}onCancelled(t="cancel"){It.ui.onCancelled(t);try{this.sink.cancelPending()}catch{}try{this.sink.resetElapsed()}catch{}try{if("restart"===t){It.session.info("restart: paint CANCELLED immediately; detach keys; table remains for overwrite");try{this.sink.flushNow()}catch{}try{const t=this.control;t&&t.detach()}catch{}finally{this.control=null}}else It.ui.stop(),this.sink.stop()}catch{}try{const t=this.control;t&&t.detach()}catch{}finally{this.control=null}}prepareForNewSession(){try{this.model.clearAll()}catch{}try{this.sink.resetElapsed()}catch{}try{this.sink.resetForRestart()}catch{}}flushNow(){try{this.sink.flushNow()}catch{}}installCancellation(t,e){try{this.control=new fe({onCancel:t,onRestart:e}),It.ui.installCancellation(),this.control.attach()}catch{this.control=null}}stop(){if(!this.stopped){this.stopped=!0,It.ui.stop();try{this.sink.stop()}catch{}try{const t=this.control;t&&t.detach()}catch{}this.control=null}}},LoggerUI:class{model=new ye;sink;forwards=null;constructor(){const t=process.cwd();let e=null;const n=we;if("function"==typeof n)try{e=new n(this.model,t)}catch{try{e=n(this.model,t)}catch{e=null}}if(!e)throw new Error("LoggerSink not available");this.sink=e,this.forwards=Pe(this.model,{useDurations:!1})}start(){this.sink.start()}onPlan(t){console.log(t)}onScriptQueued(t){be(this.model,t)}onScriptStart(t){ve(this.model,t)}onScriptEnd(t,e,n,r,a,s,i){this.forwards?.onScriptEnd(t,e,n,void 0,void 0,void 0,i)}onArchiveQueued(){}onArchiveStart(t){ke(this.model,t)}onArchiveEnd(t,e,n){this.forwards?.onArchiveEnd(t,e,n,void 0,void 0)}onCancelled(){}installCancellation(){}stop(){this.sink.stop()}}});const $e=async(t,n,r=null,a="concurrent",s,i)=>{const c=s??{};await w(t,n.stanPath,Boolean(c.keep));const l=ut(0,{selection:r,config:n,mode:a,behavior:c}),u=process.stdout,d=Boolean(u.isTTY),p=(c.live??!0)&&d,h=null==r?Object.keys(n.scripts):r,{LiveUICtor:f,LoggerUICtor:y}=(()=>{const t=Se;return{LiveUICtor:"function"==typeof t.LiveUI?t.LiveUI:"function"==typeof t.default?.LiveUI?t.default.LiveUI:void 0,LoggerUICtor:"function"==typeof t.LoggerUI?t.LoggerUI:"function"==typeof t.default?.LoggerUI?t.default.LoggerUI:void 0}})(),m=p&&"function"==typeof f?new f({boring:"1"===process.env.STAN_BORING}):"function"==typeof y?new y:{start(){},onPlan(){},onScriptQueued(){},onScriptStart(){},onScriptEnd(){},onArchiveQueued(){},onArchiveStart(){},onArchiveEnd(){},onCancelled(){},installCancellation(){},stop(){}};let g=!1;for(;;){const{created:r,cancelled:s,restartRequested:u}=await he({cwd:t,config:n,selection:h,mode:a,behavior:c,liveEnabled:p,planBody:l,printPlan:!g&&!1!==c.plan,ui:m,promptChoice:i});if(g=!0,!u){if(s){const a=P.join(t,n.stanPath,"output"),s=P.join(a,"archive.tar"),i=P.join(a,"archive.diff.tar"),c=async t=>new Promise(e=>setTimeout(e,t)),l=()=>!e(s)&&!e(i),u=async()=>{await Promise.allSettled([o(s,{force:!0}),o(i,{force:!0})])},d=8;for(let t=0;t<d;t+=1){try{await u()}catch{}if(l())break;const t="win32"===process.platform;await c(t?200:40)}try{await new Promise(t=>setTimeout(t,"win32"===process.platform?100:25))}catch{}try{const t="win32"===process.platform?30:process.env.CI?20:15;await new Promise(e=>setTimeout(e,t))}catch{}return r}try{try{await Z()}catch{}const t=m.flushNow;if("function"==typeof t)try{t()}catch{}m.stop()}catch{}try{const t="win32"===process.platform?30:process.env.CI?20:15;await new Promise(e=>setTimeout(e,t))}catch{}return r}}};export{X as renderAvailableScriptsHelp,$e as runSelected};
1
+ import{readFileSync as t,existsSync as e,createWriteStream as n}from"node:fs";import{writeFile as r,readFile as a,appendFile as s,readdir as i,rm as o,copyFile as c,rename as l,mkdir as u}from"node:fs/promises";import{findConfigPathSync as p,DEFAULT_OPEN_COMMAND as d,prepareImports as h,createMetaArchive as f,createContextArchiveWithDependencyContext as m,createArchive as y,createContextArchiveDiffWithDependencyContext as w,createArchiveDiff as g,getPackagedSystemPromptPath as b,CORE_VERSION as v,ensureOutputDir as k}from"@karmaniverous/stan-core";import{z as P,ZodError as $}from"zod";import S from"yaml";import A,{resolve as D,delimiter as j,join as C,dirname as E}from"node:path";import x from"chalk";import{table as I}from"table";import O from"tree-kill";import{spawn as T}from"node:child_process";import{onExit as N}from"signal-exit";import{ensureDir as M,exists as K}from"fs-extra";import{createHash as _}from"node:crypto";import{createRequire as L}from"node:module";import{fileURLToPath as B}from"node:url";import{packageDirectorySync as G}from"package-directory";const R=P.union([P.boolean(),P.string(),P.number()]).transform(t=>{if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t;const e=t.trim().toLowerCase();return"1"===e||"true"===e||"0"!==e&&"false"!==e&&void 0}).optional(),U=P.object({script:P.string().min(1,{message:"script must be a non-empty string"}),warnPattern:P.string().min(1,{message:"warnPattern must be a non-empty string"}).optional().refine(t=>"string"!=typeof t||(t=>{try{return new RegExp(t),!0}catch{return!1}})(t),{message:"warnPattern: invalid regular expression"}),warnPatternFlags:P.string().optional().refine(t=>"string"!=typeof t||(t=>{try{return new RegExp("",t),!0}catch{return!1}})(t),{message:"warnPatternFlags: invalid regex flags"})}).strict(),W=P.record(P.string(),P.union([P.string().min(1),U])).default({}),F=P.object({archive:R,combine:R,keep:R,sequential:R,live:R,plan:R,facets:R,hangWarn:P.coerce.number().int().positive().optional(),hangKill:P.coerce.number().int().positive().optional(),hangKillGrace:P.coerce.number().int().positive().optional(),scripts:P.union([P.boolean(),P.array(P.string())]).optional(),prompt:P.string().optional(),context:R}).strict().optional(),q=P.object({file:P.string().optional()}).strict().optional(),H=P.object({stash:R}).strict().optional(),z=P.object({debug:R,boring:R,patch:q,run:F,snap:H}).strict().optional(),Q=P.object({scripts:W,cliDefaults:z,patchOpenCommand:P.string().optional(),maxUndos:P.coerce.number().int().positive().optional(),devMode:R}).strict(),J=t=>{if(["archive","init"].filter(e=>Object.prototype.hasOwnProperty.call(t,e)).length>0)throw new Error('scripts: keys "archive" and "init" not allowed')},V=(t,e)=>t.endsWith(".json")?JSON.parse(e):S.parse(e),Y=(t,e)=>{if((()=>{try{return"1"===process.env.STAN_DEBUG}catch{return!1}})())try{console.error(`stan: debug: fallback: ${t}: ${e}`)}catch{}},X=t=>{try{"function"==typeof J&&J(t)}catch{}},Z=(t,e)=>{const n=t&&"object"==typeof t?t:{};let r;try{if(!("function"==typeof Q.parse)){const t=n.scripts,e=t&&"object"==typeof t?t:{};X(e);const r=n.patchOpenCommand,a="string"==typeof r&&r.length>0?r:d;return{scripts:e,cliDefaults:n.cliDefaults,patchOpenCommand:a,maxUndos:n.maxUndos,devMode:n.devMode}}r=Q.parse(n)}catch(t){const n=e.replace(/\\/g,"/");throw new Error(`stan-cli: invalid config in ${n}\n${(t=>t instanceof $?t.issues.map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("\n"):String(t))(t)}`)}return X(r.scripts),{scripts:r.scripts,cliDefaults:r.cliDefaults,patchOpenCommand:"string"==typeof r.patchOpenCommand&&r.patchOpenCommand.length>0?r.patchOpenCommand:d,maxUndos:r.maxUndos,devMode:r.devMode}},tt=e=>{const n=p(e);if(!n)return{scripts:{},patchOpenCommand:d};const r=t(n,"utf8"),a=V(n,r),s=a&&"object"==typeof a?a:{};if(s["stan-cli"]&&"object"==typeof s["stan-cli"])return Z(s["stan-cli"],n);const i=(t=>{const e=["scripts","cliDefaults","patchOpenCommand","maxUndos","devMode"],n={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n})(s);if(Object.keys(i).length>0){if(!(()=>{try{const t=process.env.STAN_ACCEPT_LEGACY,e=("string"==typeof t?t:"").trim().toLowerCase();return"1"===e||"true"===e}catch{return!1}})()){const t=n.replace(/\\/g,"/");throw new Error([`stan-cli: legacy configuration detected in ${t} (missing top-level "stan-cli").`,'Run "stan init" to migrate your config (a .bak is written next to the file),',"or set STAN_ACCEPT_LEGACY=1 to temporarily accept legacy keys during the transition."].join(" "))}return Y("cli.config:loadSync",`using legacy top-level CLI keys from ${n.replace(/\\/g,"/")}; run "stan init" to migrate`),Object.prototype.hasOwnProperty.call(s,"stan-core")||Y("run.action:engine-legacy",`detected legacy root keys (no "stan-core") in ${n.replace(/\\/g,"/")}`),Z(i,n)}return{scripts:{},patchOpenCommand:d}},et=e=>{try{const n=tt(e);let r=Object.keys(n.scripts);if(!r.length)try{const n=(e=>{try{const n=p(e??process.cwd());if(!n)return{};const r=t(n,"utf8"),a=V(n,r);return a&&"object"==typeof a?a:{}}catch{return{}}})(e),a=(t=>{const e=t["stan-cli"];return e&&"object"==typeof e?e:null})(n),s=(a&&"object"==typeof a.scripts?a.scripts:n.scripts)??{};r=Object.keys((t=>{const e={};if(!t||"object"!=typeof t)return e;for(const[n,r]of Object.entries(t))"string"==typeof r&&r.trim().length?e[n]=r:r&&"object"==typeof r&&"string"==typeof r.script&&(e[n]=String(r.script));return e})(s))}catch{}if(!r.length)return"";const a=r[0]||"lint";return["","Default: runs all scripts and writes archives.","","Available script keys:",` ${r.join(", ")}`,"","Examples:"," stan run # all scripts, with archives",` stan run -s ${a}`,` stan run -q -x ${a}`," stan run -A # no archives"," stan run -S -A -p # plan only, no scripts, no archives",` stan run -c -s ${a}`,""].join("\n")}catch(t){return"1"===process.env.STAN_DEBUG&&console.error("stan: unable to load config for help footer",t),""}},nt=(t,e)=>{try{if(null==t)return;return t[e]}catch{return}};function rt(t,e,n){const r="number"==typeof n?.maxDefaultDepth&&n.maxDefaultDepth>=0?n.maxDefaultDepth:3,a=!0===n?.allowDefaultCallable,s=!0===n?.allowModuleCallable,i=!0===n?.scanDefaultObject,o=[],c=new Set,l=t=>{(t=>"function"==typeof t)(t)&&(c.has(t)||(c.add(t),o.push(t)))};l(nt(t,e));const u=nt(t,"default");l(nt(u,e)),a&&l(u),s&&l(t);const p=new Set;let d=u;for(let t=0;t<r&&(d&&!p.has(d));t+=1){p.add(d);const t=nt(d,"default");l(nt(t,e)),a&&l(t),d=t}if(i&&u&&"object"==typeof u)try{for(const t of Object.values(u))l(t)}catch{}if(o.length>0)return o[0];const h=e.trim().length?e.trim():"(unnamed)";throw new Error(`resolveCallableExport: ${h} not found`)}function at(t,e,n){try{return rt(t,e,n)}catch{return null}}const st=()=>new Promise(t=>setImmediate(t));function it(){const t=Boolean(process.stdout.isTTY);return"1"===process.env.STAN_BORING||"1"===process.env.NO_COLOR||"0"===process.env.FORCE_COLOR||!t}function ot(t){return it()?t:x.green(t)}function ct(t){return it()?t:x.cyan(t)}function lt(t){return it()?t:x.blue(t)}function ut(t){return it()?t:x.red(t)}function pt(t){return it()?t:x.black(t)}function dt(t){return it()?t:x.gray(t)}function ht(t){return it()?t:x.hex("#FFA500")(t)}function ft(t){return it()?t:x.bold(t)}function mt(t){return it()?t:x.dim(t)}const yt=(t,e)=>{const{selection:n,config:r,mode:a,behavior:s}=e,i=null==n?Object.keys(r.scripts):n,o=A.join(r.stanPath,"output").replace(/\\/g,"/");return`stan:\n ${[it()?"STAN run plan":ft("STAN run plan"),"mode: "+("sequential"===a?"sequential":"concurrent"),`output: ${o}/`,..."string"==typeof s.prompt&&s.prompt.trim().length?[`prompt: ${s.prompt}`]:[],`scripts: ${i.length?i.join(", "):"none"}`,"archive: "+(s.archive?"yes":"no"),"combine: "+(s.combine?"yes":"no"),"keep output dir: "+(s.keep?"yes":"no"),"context: "+(s.context?"yes":"no"),"live: "+(s.live?"yes":"no"),`hang warn: ${"number"==typeof s.hangWarn?s.hangWarn.toString():"n/a"}s`,`hang kill: ${"number"==typeof s.hangKill?s.hangKill.toString():"n/a"}s`,`hang kill grace: ${"number"==typeof s.hangKillGrace?s.hangKillGrace.toString():"n/a"}s`].join("\n ")}`},wt=t=>t.toString().padStart(2,"0"),gt=t=>{t<0&&(t=0);const e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return`${wt(n)}:${wt(r)}`},bt=t=>{if(it()){if("warn"===t)return"[WARN]";switch(t){case"waiting":return"[WAIT]";case"run":return"[RUN]";case"ok":return"[OK]";case"error":return"[FAIL]";case"cancelled":return"[CANCELLED]";case"timeout":return"[TIMEOUT]";case"quiet":return"[QUIET]";case"stalled":return"[STALLED]";case"killed":return"[KILLED]";default:return""}}switch(t){case"warn":return ht("⚠︎ warn");case"waiting":return dt("⏸︎ waiting");case"run":return lt("▶︎ run");case"ok":return ot("✔︎ ok");case"error":return ut("✖︎ fail");case"cancelled":return pt("◼︎ cancelled");case"timeout":return ut("⏱︎ timeout");case"quiet":return ct("⏱︎ quiet");case"stalled":return ht("⏱︎ stalled");case"killed":return ut("◼︎ killed");default:return""}},vt=t=>t.replace(/\\/g,"/"),kt=(t,e)=>{if(!e)return"";const n=e;return A.isAbsolute(n)?vt(A.relative(t,n)):vt(n)},Pt=t=>{const{state:e,cwd:n,now:r}=t,a=(t=>{switch(t.kind){case"warn":return"warn";case"waiting":default:return"waiting";case"running":return"run";case"quiet":return"quiet";case"stalled":return"stalled";case"done":return"ok";case"error":return"error";case"timedout":return"timeout";case"cancelled":return"cancelled";case"killed":return"killed"}})(e);let s="";if("running"===e.kind||"quiet"===e.kind||"stalled"===e.kind){const t="number"==typeof e.startedAt?e.startedAt:(r??Date.now)();s=gt(Math.max(0,(r??Date.now)()-t))}else"number"==typeof e.durationMs&&(s=gt(Math.max(0,e.durationMs)));const i="done"===e.kind||"warn"===e.kind||"error"===e.kind||"timedout"===e.kind||"cancelled"===e.kind||"killed"===e.kind?kt(n,e.outputPath):"";return{label:bt(a),time:s,output:i}},$t=t=>t.startsWith("script:")?{type:"script",item:t.slice(7)||"(unnamed)"}:t.startsWith("archive:")?{type:"archive",item:t.slice(8)||"(unnamed)"}:void 0,St=t=>{const e={warn:0,waiting:0,running:0,quiet:0,stalled:0,ok:0,cancelled:0,fail:0,timeout:0};for(const{state:n}of t)"warn"===n.kind?e.warn+=1:"waiting"===n.kind?e.waiting+=1:"running"===n.kind?e.running+=1:"quiet"===n.kind?e.quiet+=1:"stalled"===n.kind?e.stalled+=1:"done"===n.kind?e.ok+=1:"timedout"===n.kind?e.timeout+=1:"cancelled"===n.kind?e.cancelled+=1:["error","killed"].includes(n.kind)&&(e.fail+=1);return e},At=t=>{const{rows:e,startedAt:n,boring:r,uiId:a,includeHint:s}=t,i=["Type","Item","Status","Time","Output"].map(t=>ft(t)),o=[];if(o.push(i),0===e.length){const t=gt(Date.now()-n);o.push(["—","—",r?"[IDLE]":"idle",t,""])}else for(const t of e){const e=t.state,n=Pt({state:e,cwd:process.cwd(),now:()=>Date.now()});o.push([t.type,t.item,n.label,n.time,n.output])}const c=(t=>I(t,{columnDefault:{paddingLeft:0,paddingRight:2},border:{topBody:"",topJoin:"",topLeft:"",topRight:"",bottomBody:"",bottomJoin:"",bottomLeft:"",bottomRight:"",bodyLeft:"",bodyRight:"",bodyJoin:"",joinBody:"",joinLeft:"",joinRight:"",joinJoin:""},drawHorizontalLine:()=>!1,columns:{0:{alignment:"left"},1:{alignment:"left"},2:{alignment:"left"},3:{alignment:"left"},4:{alignment:"left"}}}))(o),l=((t,e,n)=>n?[t,`waiting ${e.waiting.toString()}`,`running ${e.running.toString()}`,`quiet ${e.quiet.toString()}`,`stalled ${e.stalled.toString()}`,`timeout ${e.timeout.toString()}`,`ok ${e.ok.toString()}`,`warn ${e.warn.toString()}`,`fail ${e.fail.toString()}`,`cancelled ${e.cancelled.toString()}`].join(" • "):[t,dt(`⏸︎ ${e.waiting.toString()}`),lt(`▶︎ ${e.running.toString()}`),ct(`⏱︎ ${e.quiet.toString()}`),ht(`⏱︎ ${e.stalled.toString()}`),ut(`⏱︎ ${e.timeout.toString()}`),ot(`✔︎ ${e.ok.toString()}`),ht(`⚠︎ ${e.warn.toString()}`),ut(`✖︎ ${e.fail.toString()}`),pt(`◼︎ ${e.cancelled.toString()}`)].join(" • "))(gt(Date.now()-n),St(e.map(t=>({state:t.state}))),r),u=s?`\n${(t=>{const e="1"===process.env.STAN_TEST_UI_TAG?` UI#${t.toString()}`:"";return`${mt("Press")} ${ft("Ctrl-C")} ${mt("to cancel")}${e}`})(a)}`:"",p=`\n${`${c.trimEnd()}\n\n${l}${u}`}\n`;if("1"===process.env.STAN_LIVE_DEBUG)try{const t=/(?:^|\n)Type\s+Item\s+Status\s+Time\s+Output(?:\n|$)/g,e=((t=>{try{return t.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g,"")}catch{return t}})(p).match(t)??[]).length;console.error("[stan:live:frame]",{headerMatches:e,includeHint:s})}catch{}return p},Dt="[",jt=`${Dt}?25l`,Ct=`${Dt}?25h`,Et=`${Dt}K`,xt=t=>t>0?`${Dt}${String(t)}F`:"",It=`${Dt}1E`,Ot=()=>{const t=process.stdout;let e=0;return{start(){try{t.write(jt)}catch{}},write(n){try{const r=n.endsWith("\n")?n:`${n}\n`;(n=>{let r="";e>0&&(r+=xt(e));for(let t=0;t<n.length;t+=1){const a=n[t]??"";r+=0===e&&0===t&&""===a?"\n":`\r${Et}${a}\n`}const a=e-n.length;for(let t=0;t<a;t+=1)r+=`\r${Et}`,t<a-1&&(r+=It);t.write(r),e=n.length})(r.split("\n"))}catch{}},clear(){try{let n="";e>0&&(n+=xt(e));for(let t=0;t<e;t+=1)n+=`\r${Et}\n`;t.write(n),e=0}catch{}},done(){try{t.write(Ct)}catch{}}}},Tt=(()=>{try{return"1"===process.env.STAN_LIVE_DEBUG}catch{return!1}})(),Nt=(t,e,n)=>{if(Tt)try{n&&Object.keys(n).length>0?console.error(`[stan:live:${t}] ${e}`,n):console.error(`[stan:live:${t}] ${e}`)}catch{}},Mt={get enabled(){return Tt},renderer:{start(t){Nt("renderer","start()",t)},update(t){Nt("renderer","update()",t)},render(t){Nt("renderer","render()",t)},headerOnly(t){Nt("renderer","render(header-only)",t)},flush(){Nt("renderer","flush()")},clear(){Nt("renderer","clear()")},stop(){Nt("renderer","stop()")},done(){Nt("renderer","stop():done()")}},ui:{start(){Nt("UI","start()")},onCancelled(){Nt("UI","onCancelled()")},stop(){Nt("UI","stop() -> sink.stop()")}},session:{info(t,e){Nt("session",t,e)},exitHook(){Nt("session","exit hook fired: ui.stop + supervisor cancel + pause stdin")}}};let Kt=1;const _t=()=>Date.now();class Lt{rows=new Map;opts;frameNo=0;timer;startedAt=_t();writer=null;uiId;constructor(t){this.opts={boring:Boolean(t?.boring),refreshMs:t?.refreshMs??1e3},this.uiId=Kt++}resetElapsed(){this.startedAt=_t(),this.frameNo=0}finalize(){this.timer&&clearInterval(this.timer),this.timer=void 0,this.renderFinalNoHint(),Mt.renderer.stop(),Mt.renderer.done(),this.writer?.done()}flush(){Mt.renderer.flush(),this.render()}resetRows(){this.rows.clear()}start(){Mt.renderer.start({refreshMs:this.opts.refreshMs}),this.timer||(this.writer||(this.writer=Ot()),this.writer.start(),this.timer=setInterval(()=>{this.render()},this.opts.refreshMs))}clear(){Mt.renderer.clear(),this.writer?.clear()}stop(){Mt.renderer.stop(),this.timer&&clearInterval(this.timer),this.timer=void 0,Mt.renderer.done(),this.writer?.done()}update(t,e,n){const r=this.rows.get(t),a=n??$t(t)??(r?.type?{type:r.type,item:r.item}:void 0);if(!a){const n={type:"script",item:t};return void this.rows.set(t,{...n,state:{...r?.state??{},...e}})}this.rows.set(t,{...a,state:{...r?.state??{},...e}}),Mt.renderer.update({key:t,kind:e.kind,rowsSize:this.rows.size})}cancelPending(){const t=_t();for(const[e,n]of this.rows.entries()){const r=n.state;switch(r.kind){case"waiting":this.update(e,{kind:"cancelled"});break;case"running":case"quiet":case"stalled":{const n="number"==typeof r.startedAt?r.startedAt:void 0,a="number"==typeof n?Math.max(0,t-n):0;this.update(e,{kind:"cancelled",durationMs:a});break}}}}renderFinalNoHint(){let t=At({rows:Array.from(this.rows.values()),startedAt:this.startedAt,boring:this.opts.boring,uiId:this.uiId,includeHint:!1});t.endsWith("\n")||(t+="\n"),t+="\n",this.writer?.write(t)}render(){const t=At({rows:Array.from(this.rows.values()),startedAt:this.startedAt,boring:this.opts.boring,uiId:this.uiId,includeHint:!0});if(this.frameNo+=1,Mt.enabled)try{const t=St(this.rows.values()),e=Array.from(this.rows.keys()).slice(0,5);Mt.renderer.render({frameNo:this.frameNo,rowsSize:this.rows.size,keys:e,headerCount:1,hasHint:!0,counts:t})}catch{}this.writer?.write(t)}}class Bt{behavior;constructor(t){this.behavior=t}pids=new Map;lastCancelled=[];track(t,e){this.pids.set(t,e)}cancelAll(t){const e="number"==typeof this.behavior.hangKillGrace?this.behavior.hangKillGrace:10,n=t?.immediate?0:Math.max(0,1e3*e),r=Array.from(this.pids.entries()),a=Array.from(this.pids.values());this.lastCancelled=a;for(const[,t]of r)try{Number.isFinite(t)&&process.kill(t,"SIGTERM")}catch{}const s=()=>{for(const[,t]of r)try{Number.isFinite(t)&&O(t,"SIGKILL")}catch{}};n<=0?setTimeout(s,0):setTimeout(s,n),this.pids.clear()}async waitAll(t=2e3){const e=this.lastCancelled.length>0?[...this.lastCancelled]:Array.from(this.pids.values());if(0===e.length)return;const n=Date.now()+Math.max(0,t),r=t=>{try{return process.kill(t,0)}catch{return!1}};for(;Date.now()<n;){if(0===e.filter(t=>r(t)).length)break;await new Promise(t=>setTimeout(t,50))}this.lastCancelled=[]}}class Gt{ui;supervisor;cancelled=!1;cancelledKeys=new Set;wake=null;waitP;constructor(t,e){this.ui=t,this.supervisor=e,this.waitP=new Promise(t=>this.wake=t)}markQueued(t){for(const e of t)this.cancelledKeys.add(`script:${e}`)}async wait(){await this.waitP}isCancelled(){return this.cancelled}wasKeyCancelled(t){return this.cancelled&&this.cancelledKeys.has(`script:${t}`)}triggerCancel(){if(!this.cancelled){this.cancelled=!0;try{this.ui.onCancelled()}catch{}try{this.supervisor.cancelAll({immediate:!0})}catch{}try{process.exitCode=1,"test"!==process.env.NODE_ENV&&process.exit(1)}catch{}try{this.wake?.()}catch{}}}}let Rt=null;function Ut(t){return Rt===t}const Wt=(t,n)=>{const r=n.PATH??n.Path??"",a=(t=>{const n=[];let r=t;for(;;){const t=C(r,"node_modules",".bin");try{e(t)&&n.push(t)}catch{}const a=E(r);if(a===r)break;r=a}return n})(t);return{...n,PATH:[...a,r].filter(Boolean).join(j)}},Ft=async(t,e,r,i,o,c,l,u,p)=>{const d=D(e,`${i}.txt`),h=Date.now();l?.onStart?.(i);const f=n(d,{encoding:"utf8"}),m=T(o,{cwd:t,shell:!0,windowsHide:!0,env:Wt(t,process.env)}),y="1"===process.env.STAN_DEBUG;let w="";const g="number"==typeof u?.hangWarn&&u.hangWarn>0?u.hangWarn:0,b="number"==typeof u?.hangKill&&u.hangKill>0?u.hangKill:0,v="number"==typeof u?.hangKillGrace&&u.hangKillGrace>0?u.hangKillGrace:10;let k,P,$=Date.now(),S=!1,A=!1;try{"number"==typeof m.pid&&p&&p.track(`script:${i}`,m.pid)}catch{}m.stdout.on("data",t=>{f.write(t),w+=t.toString("utf8"),y&&process.stdout.write(t),$=Date.now()}),m.stderr.on("data",t=>{f.write(t),w+=t.toString("utf8"),y&&process.stderr.write(t),$=Date.now()}),(g>0||b>0)&&(k=setInterval(()=>{const t=Date.now()-$;if(!S&&g>0&&t>=1e3*g&&(S=!0,l?.onHangWarn?.(i,g)),!A&&b>0&&t>=1e3*b){A=!0;try{"number"==typeof m.pid&&process.kill(m.pid,"SIGTERM")}catch{}l?.onHangTimeout?.(i,b);const t=Math.max(0,1e3*v);P=setTimeout(()=>{try{"number"==typeof m.pid&&O(m.pid,"SIGKILL")}catch{}l?.onHangKilled?.(i,v)},t)}},1e3));const j=await new Promise((t,e)=>{m.on("error",t=>{e(t instanceof Error?t:new Error(String(t)))}),m.on("close",e=>{t(e??0)})});k&&clearInterval(k),P&&clearTimeout(P),f.end(),await(t=>new Promise((e,n)=>{t.on("close",()=>{e()}),t.on("error",t=>{n(t instanceof Error?t:new Error(String(t)))})}))(f);let C="ok";if("number"==typeof j&&0!==j)C="error";else if(u?.warnPatterns&&u.warnPatterns.length>0){const t=(t,e)=>t.some(t=>{try{return t.lastIndex=0,t.test(e)}catch{return!1}});let e=!1;if(w.length>0&&t(u.warnPatterns,w))e=!0;else try{const n=await a(d,"utf8");t(u.warnPatterns,n)&&(e=!0)}catch{}e&&(C="warn")}return l?.onEnd?.(i,d,h,Date.now(),j,C),c&&await s(c,i.slice(0,1).toUpperCase(),"utf8"),d},qt=()=>{let t=0;return(()=>{try{const t=process.env.CI,e=("string"==typeof t?t:"").trim().toLowerCase();return""!==e&&"0"!==e&&"false"!==e}catch{return!1}})()&&(t+=25),"win32"!==process.platform&&(t+=10),25+t},Ht=async(t,e,n,r,a,s,i,o,c,l,u)=>{const p=[],d=async n=>{try{if("function"==typeof l&&!l())return}catch{}const a=r.scripts[n],s="string"==typeof a?a:"object"==typeof a&&a&&"script"in a?a.script:"",d=a&&"object"==typeof a&&"warnPattern"in a?((t,e)=>{if("string"!=typeof t||!t.trim())return[];const n=t.trim(),r=[],a=(t,e)=>{try{r.push(new RegExp(t,e))}catch{}};if("string"==typeof e&&e.length>0){a(n,e);const t=n.replace(/\\\\/g,"\\");t!==n&&a(t,e)}else{a(n);const t=n.replace(/\\\\/g,"\\");t!==n&&a(t),a(n,"i")}return r})(a.warnPattern,a.warnPatternFlags):[],h=await Ft(t,e,0,n,s,i,o,{silent:o.silent,hangWarn:c?.hangWarn,hangKill:c?.hangKill,hangKillGrace:c?.hangKillGrace,warnPatterns:d},u);p.push(h)};if("sequential"===s)for(const t of a){const e=t=>new Promise(e=>setTimeout(e,t));if("function"==typeof l){if(!l())break;if(await st(),!l())break;if(await e(qt()),!l())break;if(await st(),!l())break}if(await d(t),"function"==typeof l){if(await st(),!l())break;if(await e(Math.max(5,qt()/2)),!l())break;if(await st(),!l())break}}else{const t="function"==typeof l?a.filter(()=>l()):a;await Promise.all(t.map(t=>d(t).then(()=>{})))}return p},zt=async t=>{const{cwd:e,outAbs:n,outRel:r,config:a,toRun:s,mode:i,orderFile:o,ui:c,epoch:l,isActive:u,shouldContinue:p,supervisor:d,liveEnabled:h,hangWarn:f,hangKill:m,hangKillGrace:y}=t,w=[],g=Ht(e,n,0,a,s,i,o,{onStart:t=>{u(l)&&c.onScriptStart(t)},onEnd:(t,n,r,a,s,i)=>{if(u(l)&&(c.onScriptEnd(t,n,e,r,a,s,i),"error"===i||"number"==typeof s&&0!==s))try{process.exitCode=1}catch{}},silent:!0,onHangWarn:(t,e)=>{u(l)&&(h||((t,e)=>{try{console.log(`stan: ⏱ stalled "${t}" after ${e.toString()}s of inactivity`)}catch{}})(t,e))},onHangTimeout:(t,e)=>{u(l)&&(h||((t,e)=>{try{console.log(`stan: ⏱ timeout "${t}" after ${e.toString()}s; sending SIGTERM`)}catch{}})(t,e))},onHangKilled:(t,e)=>{u(l)&&(h||((t,e)=>{try{console.log(`stan: ◼ killed "${t}" after ${e.toString()}s grace`)}catch{}})(t,e))}},{hangWarn:f,hangKill:m,hangKillGrace:y},p,d).then(t=>{w.push(...t)});return await g.catch(()=>{}),w};const Qt=(t,e)=>{try{Mt.session.info("install SIGINT handler"),process.on("SIGINT",t)}catch{}const n=(r=e,N(()=>{try{const t=r();t&&"function"==typeof t.then&&t.catch(()=>{})}catch{}}));var r;return()=>{try{Mt.session.info("detach SIGINT handler"),process.off("SIGINT",t)}catch{}try{Mt.session.info("uninstall exit hook"),n()}catch{}}},Jt=(t,e)=>A.join(t,e,"system",".docs.meta.json"),Vt=async t=>_("sha256").update(await a(t)).digest("hex"),Yt=async(t,e,n)=>{const r=A.join(t,e,"imports");try{const t=await i(r,{withFileTypes:!0});await Promise.all(t.map(t=>o(D(r,t.name),{recursive:!0,force:!0})))}catch{}if(n&&"object"==typeof n)try{await h({cwd:t,stanPath:e,map:n})}catch{}},Xt=async t=>{try{const e=await i(t,{withFileTypes:!0}),n=new Set(["archive.tar","archive.diff.tar"]);await Promise.all(e.map(async e=>{n.has(e.name)||await o(D(t,e.name),{recursive:!0,force:!0})}))}catch{}},Zt=async(t,e)=>{const n=A.join(t,e,"patch");try{const t=await i(n,{withFileTypes:!0});await Promise.all(t.map(t=>o(D(n,t.name),{recursive:!0,force:!0})))}catch{}},te=t=>{if(e=t,!Boolean(e)||"object"!=typeof e)return[];var e;const n=t.i;return Array.isArray(n)?n:[]},ee=t=>"string"==typeof t?t:Array.isArray(t)&&"string"==typeof t[0]?t[0]:null,ne=t=>"diff"===t?"archive (diff)":"meta"===t?"archive (meta)":"archive";var re=Object.freeze({__proto__:null,archivePhase:async(t,e)=>{const{cwd:n,config:r,includeOutputs:a}=t,{dependency:s}=r,i=t=>{const{kind:e,counts:n,hasWarnings:r}=t,a=n,s=[`candidates ${String(a.candidates)}`,`selected ${String(a.selected)}`,`archived ${String(a.archived)}`];a.excludedBinaries>0&&s.push(`binaries ${String(a.excludedBinaries)}`),a.largeText>0&&s.push(`large ${String(a.largeText)}`);const i=r?" (warnings)":"",o="diff"===e?"diff":"meta"===e?"meta":"full";console.log(`stan: selection (${o}): ${s.join(", ")}${i}`)},u=Boolean(e?.silent),p=e?.which??"both",d=!1!==e?.stage,h=!1!==e?.cleanup,b=((t,e)=>{const n=A.join(t,e),r=A.join(n,"system");return{base:n,system:r,output:A.join(n,"output"),diff:A.join(n,"diff"),patch:A.join(n,"patch"),systemFile:A.join(r,"stan.system.md")}})(n,r.stanPath),v="function"==typeof e?.shouldContinue?e.shouldContinue:void 0,k=((t,e)=>{const n=Array.isArray(e)?e.filter(t=>"string"==typeof t&&t.length>0):[],r=(t=>{const e=(t=>{const e="string"==typeof t?t.trim():"",n=(r=e,r.replace(/\\+/g,"/")).replace(/\/+$/,"");var r;return n.length>0?n:e.startsWith("/")?"":".stan"})(t);return`${e}/imports/**`})(t);return n.includes(r)?n:[...n,r]})(r.stanPath,r.includes??[]),P=r.excludes??[],$=s&&!((t,e)=>{const n=`${e}/context/npm/`,r=`${e}/context/abs/`;for(const e of te(t)){const t=ee(e);if(t&&(t.startsWith(n)||t.startsWith(r)))return!0}return!1})(s.state,r.stanPath)?(S=[...P,...(D=r.stanPath,[`${D}/context/npm/**`,`${D}/context/abs/**`])],Array.from(new Set(S))):P;var S,D;let j,C;u||"both"!==p&&"full"!==p||console.log(`stan: start "${ct("archive")}"`);try{if(d){if(v&&!v())return{archivePath:j,diffPath:C};await Yt(n,r.stanPath,r.imports)}if("both"===p||"full"===p){if(v&&!v())return{archivePath:j,diffPath:C};const t=r.meta?"meta":"full";e?.progress?.start?.(t);const p=Date.now();if(r.meta){const t=A.join(n,r.stanPath,"output"),e=A.join(t,"archive.tar"),s=A.join(n,r.stanPath,"diff","archive.prev.tar");await K(e)&&await c(e,s);const o=await f(n,r.stanPath,{includes:k,excludes:P},{includeOutputDir:a,onSelectionReport:i});await l(o,e),j=e}else if(s){j=(await m({cwd:n,stanPath:r.stanPath,dependency:s,selection:{includes:k,excludes:$},archive:{includeOutputDir:!1,onSelectionReport:i}})).archivePath}else j=await y(n,r.stanPath,{includeOutputDir:a,includes:k,excludes:P,onSelectionReport:i});if(e?.progress?.done?.(t,j,p,Date.now()),v&&!v()){try{j&&await o(j,{force:!0})}catch{}return{archivePath:void 0,diffPath:C}}u||console.log(`stan: ${ot("done")} "${ct("archive")}" -> ${ct(j?j.replace(/\\/g,"/"):"")}`)}if(u||"both"!==p&&"diff"!==p||console.log(`stan: start "${ct("archive (diff)")}"`),"both"===p||"diff"===p){if(v&&!v())return{archivePath:j,diffPath:C};e?.progress?.start?.("diff");const t=Date.now();let c;if(c=s?await w({cwd:n,stanPath:r.stanPath,dependency:s,selection:{includes:k,excludes:$},diff:{onSelectionReport:i,baseName:"archive",updateSnapshot:"createIfMissing",includeOutputDirInDiff:!1,snapshotFileName:".archive.snapshot.context.json"}}):await g({cwd:n,stanPath:r.stanPath,baseName:"archive",includes:k,excludes:P,updateSnapshot:"createIfMissing",includeOutputDirInDiff:a,onSelectionReport:i}),C=c.diffPath,e?.progress?.done?.("diff",C,t,Date.now()),v&&!v()){try{await o(C,{force:!0})}catch{}return{archivePath:j,diffPath:void 0}}u||console.log(`stan: ${ot("done")} "${ct("archive (diff)")}" -> ${ct(C.replace(/\\/g,"/"))}`)}}finally{}return h&&(a&&(s?u||console.log(`stan: ${ct("warn")} combine mode (-b) ignored in context mode`):await Xt(b.output)),await Zt(n,r.stanPath)),{archivePath:j,diffPath:C}},archivePrintable:ne,cleanupOutputsAfterCombine:Xt,cleanupPatchDirAfterArchive:Zt,stageImports:Yt});const ae=t=>rt(re,t,{allowDefaultCallable:!0,allowModuleCallable:!0,scanDefaultObject:!0,maxDefaultDepth:3}),se=async t=>{const{cwd:e,stanPath:n,promptAbs:r}=t;let s,i=!1;try{r&&(s=await Vt(r))}catch{s=void 0}try{const t=await(async(t,e)=>{try{const n=await a(Jt(t,e),"utf8"),r=JSON.parse(n);if(r&&"object"==typeof r)return r}catch{}return null})(e,n),r=t?.prompt&&"object"==typeof t.prompt?t.prompt.hash:void 0;r&&s?i=r!==s:r&&s||(i=!1)}catch{i=!1}return i},ie=t=>A.join(t,"system","stan.system.md"),oe=async t=>{const e=await a(t);return Buffer.from(e)},ce=(t,n,r)=>{const a=A.join(t,ie(n)),s=(()=>{try{const t=b();if(t&&e(t))return t}catch{}try{const t=L(import.meta.url).resolve("@karmaniverous/stan-core"),n=G({cwd:A.dirname(t)})??null;if(n){const t=A.join(n,"dist","stan.system.md");if(e(t))return t}}catch{}try{const t=L(import.meta.url).resolve("@karmaniverous/stan-core/dist/stan.system.md");if(t&&e(t))return t}catch{}return null})();if("local"===r){if(!e(a))throw new Error(`system prompt not found at ${A.join(n,"system","stan.system.md").replace(/\\/g,"/")}`);return{abs:a,display:A.join(n,"system","stan.system.md").replace(/\\/g,"/"),kind:"local"}}if("core"===r){if(!s||!e(s))throw new Error("packaged system prompt not found in @karmaniverous/stan-core");return{abs:s,display:`@karmaniverous/stan-core@${v}`,kind:"core"}}if("auto"===r){if(e(a))return{abs:a,display:A.join(n,"system","stan.system.md").replace(/\\/g,"/"),kind:"local"};if(s&&e(s))return{abs:s,display:`@karmaniverous/stan-core@${v}`,kind:"core"};try{const t=(()=>{try{const t=B(import.meta.url),n=G({cwd:A.dirname(t)})??null;if(n){const t=A.join(n,"dist","stan.system.md");if(e(t))return t}}catch{}return null})();if(t&&e(t))return{abs:t,display:t.replace(/\\/g,"/"),kind:"path"}}catch{}throw new Error("unable to resolve system prompt (auto: local and core unavailable)")}const i=A.isAbsolute(r)?r:A.join(t,r);if(!e(i))throw new Error(`system prompt not found at ${i.replace(/\\/g,"/")}`);return{abs:i,display:i.replace(/\\/g,"/"),kind:"path"}},le=async t=>{const{cwd:n,stanPath:a,promptAbs:s,promptDisplay:i}=t;try{const{restore:t}=await(async(t,n,a)=>{const s=A.join(t,ie(n)),i=A.dirname(s),c=e(s);let l=null;if(c)try{l=await oe(s)}catch{l=null}const p=await oe(a.abs),d=c&&null!==l&&l.length===p.length&&l.equals(p);return d||(await u(i,{recursive:!0}),await r(s,p)),{changed:!d,restore:async()=>{if(!d)try{c&&null!==l?await r(s,l):await o(s,{force:!0})}catch{}}}})(n,a,{abs:s,display:i,kind:"path"});return t}catch(t){throw new Error(t instanceof Error?t.message:String(t))}},ue=async t=>{const{cwd:e,stanPath:n,behavior:r,promptAbs:a,promptDisplay:s,baseFull:i,baseDiff:o,archivePhase:c,stageImports:l,preparePrompt:u,prepareIfNeeded:p,shouldContinue:d,progress:h,ephemeral:f,includeOnChange:m,importsMap:y}=t,w=[],g=Boolean(r.combine);if(f&&"function"==typeof l){if("function"==typeof d&&!d())return w;await l(e,n,(t=>{if(!t)return t;const e={};for(const[n,r]of Object.entries(t))Array.isArray(r)&&(e[n]=r);return Object.keys(e).length?e:null})(y))}const b=async()=>{if("function"==typeof d&&!d())return;const t=!1===m?{...o,excludes:[...o.excludes??[],(a=`${n}/system/stan.system.md`,a.replace(/\\+/g,"/"))]}:o;var a;if(r.meta)return;const s=await c({cwd:e,config:t,includeOutputs:g},{silent:!0,which:"diff",progress:h,shouldContinue:d});s.diffPath&&w.push(s.diffPath)},v=async()=>{if("function"==typeof d&&!d())return;const t=await c({cwd:e,config:i,includeOutputs:g},{silent:!0,which:"full",progress:h,shouldContinue:d});t.archivePath&&w.push(t.archivePath)};if(f){if(!a||"function"!=typeof u)return w;if(m){const t=await u({cwd:e,stanPath:n,promptAbs:a,promptDisplay:s});try{await b(),await v()}finally{await t().catch(()=>{})}return w}await b();const t=await u({cwd:e,stanPath:n,promptAbs:a,promptDisplay:s});try{await v()}finally{await t().catch(()=>{})}return w}const k="function"==typeof p?await p({cwd:e,stanPath:n,promptAbs:a,promptDisplay:s}):null;try{await b(),await v()}finally{await(k?.().catch(()=>{}))}return w};var pe=Object.freeze({__proto__:null,runArchiveStage:async t=>{const{cwd:e,config:n,behavior:s,ui:i,promptAbs:o,promptDisplay:c,promptSource:l}=t,u="function"==typeof t.shouldContinue?t.shouldContinue:()=>!0,p=[];if(!u())return{created:p,cancelled:!0};const d=ae("archivePhase"),h=ae("stageImports"),f=A.join(e,n.stanPath,"system","stan.system.md"),{full:m,diff:y}=((t,e)=>{const n=t=>t.replace(/\\/g,"/"),r=[n(`${t.stanPath}/context/dependency.meta.json`),n(`${t.stanPath}/context/dependency.state.json`)],a=e.context?[]:r,s=e.context?[n(`${t.stanPath}/context/dependency.meta.json`),n(`${t.stanPath}/context/dependency.state.json`)]:[];return{full:{stanPath:t.stanPath,includes:[...t.includes??[],...s],excludes:[...t.excludes??[],...a],imports:t.imports,meta:e.meta,dependency:t.dependency},diff:{stanPath:t.stanPath,includes:[...t.includes??[],...s],excludes:[...t.excludes??[],...a],imports:t.imports,dependency:t.dependency}}})(n,s),w=((t,e)=>({start:e=>{t.onArchiveStart(e)},done:(n,r,a,s)=>{t.onArchiveEnd(n,r,e,a,s)}}))(i,e),g=async()=>{try{if(!o||!l)return;const t=await Vt(o);await(async(t,e,n)=>{const s=Jt(t,e);let i={};try{const t=await a(s,"utf8"),e=JSON.parse(t);e&&"object"==typeof e&&(i=e)}catch{i={}}const o={...i,prompt:{...i.prompt??{},...n}};await M(A.dirname(s)),await r(s,JSON.stringify(o,null,2),"utf8")})(e,n.stanPath,{source:l,hash:t,path:o})}catch{}},b=((t,e)=>{if(!e)return!1;try{return A.resolve(e)!==A.resolve(t)}catch{return!0}})(f,o);if(b){if(!u())return{created:p,cancelled:!0};let t=!0;try{t=await se({cwd:e,stanPath:n.stanPath,promptAbs:o})}catch{t=!0}try{const r=await ue({cwd:e,stanPath:n.stanPath,behavior:s,promptAbs:o,promptDisplay:c,baseFull:m,baseDiff:y,archivePhase:d,stageImports:async(t,e,n)=>{try{await h(t,e,n)}catch{}},preparePrompt:({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r})=>le({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r}),shouldContinue:u,progress:w,ephemeral:!0,includeOnChange:t,importsMap:n.imports});return p.push(...r),await g(),{created:p,cancelled:!1}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:String(t);console.error(`stan: error: failed to prepare system prompt (${e})`),console.log("");try{i.stop()}catch{}return{created:p,cancelled:!0}}}try{if(!u())return{created:p,cancelled:!0};const t=await ue({cwd:e,stanPath:n.stanPath,behavior:s,promptAbs:o,promptDisplay:c,baseFull:m,baseDiff:y,archivePhase:d,prepareIfNeeded:async({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r})=>n?le({cwd:t,stanPath:e,promptAbs:n,promptDisplay:r}):null,shouldContinue:u,progress:w,ephemeral:!1});return p.push(...t),await g(),{created:p,cancelled:!1}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:String(t);console.error(`stan: error: failed to prepare system prompt (${e})`),console.log("");try{i.stop()}catch{}return{created:p,cancelled:!0}}}});const de=async t=>{const e=D(t,"archive.tar"),n=D(t,"archive.diff.tar");await Promise.allSettled([o(e,{force:!0}),o(n,{force:!0})])},he=async t=>new Promise(e=>setTimeout(e,Math.max(0,t))),fe=()=>"win32"===process.platform,me=async t=>{const{created:n,ui:r,supervisor:a,detachSignals:s,liveEnabled:i,outAbs:o}=t,c=D(o,"archive.tar"),l=D(o,"archive.diff.tar"),u=()=>!e(c)&&!e(l),p=async()=>{await de(o).catch(()=>{})};if(await p(),!u()){const t=fe()?10:6;for(let e=0;e<t&&(await he(fe()?200:40),await p(),!u());e+=1);try{await he(fe()?120:25)}catch{}}try{r.stop()}catch{}if(i)try{console.log("")}catch{}try{await a.waitAll(3e3)}catch{}(()=>{try{process.stdin.pause?.()}catch{}})();try{await he(fe()?160:40)}catch{}try{s()}catch{}return{created:n,cancelled:!0}};async function ye(t,e){return t.isCancelled()?await me(e):null}async function we(t){const{cancelCtl:e,deps:n,cwd:r,config:a,behavior:s,ui:i,promptAbs:c,promptDisplay:l,supervisor:u}=t,p=await async function(t,e){try{await st()}catch{}const n=await ye(t,e);if(n)return n;try{await he(fe()?300:30)}catch{}return ye(t,e)}(e,{created:n.created,ui:n.ui,supervisor:u,detachSignals:n.detachSignals,liveEnabled:!0,outAbs:n.outAbs});if(p)return{short:p};const d=rt(pe,"runArchiveStage",{maxDefaultDepth:2}),h=await d({cwd:r,config:a,behavior:s,ui:i,promptAbs:c,promptDisplay:l,shouldContinue:()=>!e.isCancelled()});if(h.cancelled||e.isCancelled()){await Promise.all(h.created.map(t=>o(t,{force:!0}))).catch(()=>{}),await de(n.outAbs).catch(()=>{});try{n.detachSignals()}catch{}return{short:{created:n.created,cancelled:!0}}}return{added:h.created}}async function ge(t,e){const n=await ye(t,e);if(n)return n;const r=await async function(t,e){try{await st()}catch{}return ye(t,e)}(t,e);if(r)return r;const a=await async function(t,e){try{await he(fe()?25:process.env.CI?20:10),await st()}catch{}return ye(t,e)}(t,e);return a}function be(t){const{cwd:e,config:n,selection:r,mode:a,behavior:s,ui:i,planBody:o,printPlan:c,promptChoice:l}=t;let u="",p=null,d=null;try{const t=((t,e,n)=>{const r=(n??"auto").trim(),a=ce(t,e,r);return{display:"auto"===r?`auto → ${a.display}`:a.display,abs:a.abs,kind:a.kind}})(e,n.stanPath,l);u=t.display,p=t.abs,d=t.kind;try{if("1"===process.env.STAN_DEBUG){const e=t.kind||"path",n=(p||"").replace(/\\/g,"/");console.error(`stan: debug: prompt: ${e} ${n}`)}}catch{}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:String(t);console.error(`stan: warn: proceeding without resolved system prompt (${e})`),console.log(""),u="auto (unresolved)",p=null,d=null}if(c&&o)try{((t,e)=>{const{selection:n,config:r,mode:a,behavior:s,planBody:i,ui:o,promptDisplay:c}=e;try{const t=yt(0,{selection:n,config:r,mode:a,behavior:{...s,prompt:c}});o.onPlan(t)}catch{"string"==typeof i&&i.length&&o.onPlan(i)}console.log("")})(0,{selection:r,config:n,mode:a,behavior:s,planBody:o,ui:i,promptDisplay:u})}catch{}return{display:u,abs:p,source:d}}function ve(t){const{ui:e,selection:n,config:r,includeArchives:a,primaryArchiveKind:s,skipDiff:i,cancelCtl:o}=t,c=((t,e,n,r,a)=>{const s=(e??[]).filter(t=>Object.prototype.hasOwnProperty.call(n.scripts,t)),i=a?.primaryArchiveKind??"full",o=Boolean(a?.skipDiff);for(const e of s)try{t.onScriptQueued(e)}catch{}if(r){try{t.onArchiveQueued(i)}catch{}if(!o)try{t.onArchiveQueued("diff")}catch{}}return s})(e,n,r,a,{primaryArchiveKind:s,skipDiff:i});o.markQueued(c);try{const t=e.flushNow;"function"==typeof t&&t()}catch{}return c}const ke="test"===process.env.NODE_ENV||"1"===process.env.STAN_WRITE_ORDER,Pe=async t=>{const{cwd:e,config:n,selection:a,mode:s,behavior:i,liveEnabled:o,planBody:c,printPlan:l,ui:u,promptChoice:p}=t,d=function(){const t=Symbol("session-epoch");return Rt=t,t}(),h=D(e,n.stanPath,"output"),f=D(n.stanPath,"output").replace(/\\/g,"/"),m=await(async(t,e,n)=>{if(!t)return;const a=D(e,"order.txt");return n||await r(a,"","utf8"),a})(ke,h,Boolean(i.keep)),{display:y,abs:w}=be({cwd:e,config:n,selection:a,mode:s,behavior:i,ui:u,planBody:c,printPlan:l,promptChoice:p});!function(t){t.start();try{const e=t.flushNow;"function"==typeof e&&e()}catch{}}(u);const g=new Bt({hangWarn:i.hangWarn,hangKill:i.hangKill,hangKillGrace:i.hangKillGrace}),b=new Gt(u,g),v=Qt(()=>{b.triggerCancel()},async()=>{Mt.session.exitHook();try{u.stop()}catch{}try{g.cancelAll({immediate:!0})}catch{}try{await g.waitAll(3e3)}catch{}try{const t=process.stdin.pause;"function"==typeof t&&t()}catch{}});!function(t){try{const e=t.prepareForNewSession;"function"==typeof e&&e()}catch{}}(u);const k=ve({ui:u,selection:a,config:n,includeArchives:Boolean(i.archive),primaryArchiveKind:i.meta?"meta":"full",skipDiff:Boolean(i.meta),cancelCtl:b}),P=[];if(k.length>0){const t=await zt({cwd:e,outAbs:h,outRel:f,config:n,toRun:k,mode:s,orderFile:m,ui:u,epoch:d,isActive:Ut,shouldContinue:()=>!b.isCancelled(),supervisor:g,liveEnabled:o,hangWarn:i.hangWarn,hangKill:i.hangKill,hangKillGrace:i.hangKillGrace});P.push(...t)}const $={created:P,ui:u,supervisor:g,detachSignals:v,liveEnabled:o,outAbs:h},S=await ge(b,$);if(S)return S;if(i.archive){const{short:t,added:r}=await we({cancelCtl:b,deps:$,cwd:e,config:n,behavior:i,ui:u,promptAbs:w,promptDisplay:y,supervisor:g});if(t)return t;r?.length&&P.push(...r)}await(async()=>{try{const t="win32"===process.platform?140:process.env.CI?25:15;await new Promise(e=>setTimeout(e,t)),await st()}catch{}})(),await(async t=>{try{await st()}catch{}try{const e=t.flushNow;"function"==typeof e&&e()}catch{}})(u),Mt.session.info("normal path: detach signals, returning to caller");try{v()}catch{}return{created:P,cancelled:!1}};class $e{rows=new Map;listeners=new Set;subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}clearAll(){this.rows.clear()}update(t,e,n){const r=this.rows.get(t),a=n??r?.meta;if(!a){const n=$t(t)??(t.startsWith("archive:")?{type:"archive",item:t.slice(8)||"(unnamed)"}:{type:"script",item:t.replace(/^script:/,"")||"(unnamed)"});return this.rows.set(t,{meta:n,state:e}),void this.emit(t,n,e)}this.rows.set(t,{meta:a,state:e}),this.emit(t,a,e)}emit(t,e,n){for(const r of this.listeners)try{r({key:t,meta:e,state:n})}catch{}}counts(){return St(Array.from(this.rows.values()).map(t=>({state:t.state})))}}class Se{model;constructor(t){this.model=t}unsub;subscribeModel(){this.unsub||(this.unsub=this.model.subscribe(t=>{try{this.onUpdate(t.key,t.meta,t.state)}catch{}}))}unsubscribeModel(){try{this.unsub?.()}catch{}this.unsub=void 0}}class Ae extends Se{opts;dbg(...t){try{"1"===process.env.STAN_LIVE_DEBUG&&console.error("[stan:live:sink]",...t)}catch{}}renderer=null;stopped=!1;constructor(t,e){super(t),this.opts=e}start(){this.stopped=!1,this.renderer?this.dbg("start() renderer=existing"):(this.dbg("start() renderer=create"),this.renderer=new Lt({boring:Boolean(this.opts?.boring)}),this.renderer.start(),this.subscribeModel())}stop(){if(this.stopped)this.dbg("stop():already-stopped");else{this.stopped=!0;try{const t=this.renderer;t&&"function"==typeof t.finalize&&(this.dbg("stop() finalize(full)"),t.finalize())}catch{}this.unsubscribeModel()}}flushNow(){try{this.renderer&&this.renderer.flush()}catch{}}resetForRestart(){try{this.dbg("resetForRestart()");const t=this.renderer;t&&"function"==typeof t.resetRows&&t.resetRows()}catch{}}resetElapsed(){try{const t=this.renderer;t&&"function"==typeof t.resetElapsed&&t.resetElapsed()}catch{}}cancelPending(){this.dbg("cancelPending()");try{const t=this.renderer;t&&"function"==typeof t.cancelPending&&t.cancelPending()}catch{}}onUpdate(t,e,n){this.dbg("update",{key:t,type:e.type,item:e.item,kind:n.kind}),this.renderer&&this.renderer.update(`${e.type}:${e.item}`,n,e)}}class De extends Se{cwd;constructor(t,e){super(t),this.cwd=e}start(){this.subscribeModel()}stop(){this.unsubscribeModel()}onUpdate(t,e,n){const r=e.item,a="archive"===e.type?ne("diff"===r?"diff":"meta"===r?"meta":"full"):r,s=Pt({state:n,cwd:this.cwd});if("waiting"!==n.kind)if("running"!==n.kind)if("warn"!==n.kind){if("done"===n.kind||"error"===n.kind){const t="done"===n.kind,e=s.label,r=t?"":" (exit 1)",i=s.output||"";return void console.log(`stan: ${e} "${a}" -> ${i}${r}`)}}else console.log(`stan: ${s.label} "${a}" -> ${s.output}`);else console.log(`stan: ${s.label} "${a}"`);else console.log(`stan: ${s.label} "${a}"`)}}const je=(t,e)=>{t.update(`script:${e}`,{kind:"waiting"},{type:"script",item:e})},Ce=(t,e)=>{t.update(`script:${e}`,{kind:"running",startedAt:Date.now()},{type:"script",item:e})},Ee=(t,e)=>{const n=e;t.update(`archive:${n}`,{kind:"running",startedAt:Date.now()},{type:"archive",item:n})},xe=(t,e)=>{const n=Boolean(e?.useDurations);return{onScriptEnd:(e,r,a,s,i,o,c)=>{const l=kt(a,r);((t,e,n,r,a,s,i)=>{const o="number"==typeof r&&"number"==typeof a?Math.max(0,a-r):0,c="error"===i||"number"==typeof s&&0!==s?{kind:"error",durationMs:o,outputPath:n}:"warn"===i?{kind:"warn",durationMs:o,outputPath:n}:{kind:"done",durationMs:o,outputPath:n};t.update(`script:${e}`,c,{type:"script",item:e})})(t,e,l,n?s:void 0,n?i:void 0,n?o:void 0,c)},onArchiveEnd:(e,r,a,s,i)=>{const o=kt(a,r);((t,e,n,r,a)=>{const s=e,i="number"==typeof r&&"number"==typeof a?Math.max(0,a-r):0;t.update(`archive:${s}`,{kind:"done",durationMs:i,outputPath:n},{type:"archive",item:s})})(t,e,o,n?s:void 0,n?i:void 0)}}};var Ie=Object.freeze({__proto__:null,LiveUI:class{opts;renderer=null;model=new $e;sink;forwards=xe(this.model,{useDurations:!0});stopped=!1;constructor(t){this.opts=t,this.sink=new Ae(this.model,{boring:Boolean(t?.boring)})}start(){Mt.ui.start(),this.stopped=!1,this.renderer||(this.sink.start(),this.renderer=this.sink.renderer??null)}onPlan(t){console.log(t)}onScriptQueued(t){je(this.model,t)}onScriptStart(t){Ce(this.model,t)}onScriptEnd(t,e,n,r,a,s,i){this.forwards.onScriptEnd(t,e,n,r,a,s,i)}onArchiveQueued(t){((t,e)=>{const n=e;t.update(`archive:${n}`,{kind:"waiting"},{type:"archive",item:n})})(this.model,t)}onArchiveStart(t){Ee(this.model,t)}onArchiveEnd(t,e,n,r,a){this.forwards.onArchiveEnd(t,e,n,r,a)}onCancelled(){Mt.ui.onCancelled();try{this.sink.cancelPending()}catch{}Mt.ui.stop(),this.sink.stop()}prepareForNewSession(){try{this.model.clearAll()}catch{}try{this.sink.resetElapsed()}catch{}}flushNow(){try{this.sink.flushNow()}catch{}}stop(){if(!this.stopped){this.stopped=!0,Mt.ui.stop();try{this.sink.stop()}catch{}}}},LoggerUI:class{model=new $e;sink;forwards=null;constructor(){const t=process.cwd();let e=null;const n=De;if("function"==typeof n)try{e=new n(this.model,t)}catch{try{e=n(this.model,t)}catch{e=null}}if(!e)throw new Error("LoggerSink not available");this.sink=e,this.forwards=xe(this.model,{useDurations:!1})}start(){this.sink.start()}onPlan(t){console.log(t)}onScriptQueued(t){je(this.model,t)}onScriptStart(t){Ce(this.model,t)}onScriptEnd(t,e,n,r,a,s,i){this.forwards?.onScriptEnd(t,e,n,void 0,void 0,void 0,i)}onArchiveQueued(){}onArchiveStart(t){Ee(this.model,t)}onArchiveEnd(t,e,n){this.forwards?.onArchiveEnd(t,e,n,void 0,void 0)}onCancelled(){}stop(){this.sink.stop()}}});const Oe=async(t,n,r=null,a="concurrent",s,i)=>{const c=s??{};await k(t,n.stanPath,Boolean(c.keep));const l=yt(0,{selection:r,config:n,mode:a,behavior:c}),u=process.stdout,p=Boolean(u.isTTY),d=(c.live??!0)&&p,h=null==r?Object.keys(n.scripts):r,{LiveUICtor:f,LoggerUICtor:m}={LiveUICtor:at(Ie,"LiveUI",{maxDefaultDepth:2})??void 0,LoggerUICtor:at(Ie,"LoggerUI",{maxDefaultDepth:2})??void 0},y=d&&"function"==typeof f?new f({boring:"1"===process.env.STAN_BORING}):"function"==typeof m?new m:{start(){},onPlan(){},onScriptQueued(){},onScriptStart(){},onScriptEnd(){},onArchiveQueued(){},onArchiveStart(){},onArchiveEnd(){},onCancelled(){},installCancellation(){},stop(){}},{created:w,cancelled:g}=await Pe({cwd:t,config:n,selection:h,mode:a,behavior:c,liveEnabled:d,planBody:l,printPlan:!1!==c.plan,ui:y,promptChoice:i});if(g){const r=A.join(t,n.stanPath,"output"),a=A.join(r,"archive.tar"),s=A.join(r,"archive.diff.tar"),i=async t=>new Promise(e=>setTimeout(e,t)),c=()=>!e(a)&&!e(s),l=async()=>{await Promise.allSettled([o(a,{force:!0}),o(s,{force:!0})])},u=8;for(let t=0;t<u;t+=1){try{await l()}catch{}if(c())break;const t="win32"===process.platform;await i(t?200:40)}try{await new Promise(t=>setTimeout(t,"win32"===process.platform?100:25))}catch{}try{const t="win32"===process.platform?30:process.env.CI?20:15;await new Promise(e=>setTimeout(e,t))}catch{}return w}try{try{await st()}catch{}const t=y.flushNow;if("function"==typeof t)try{t()}catch{}y.stop()}catch{}try{const t="win32"===process.platform?30:process.env.CI?20:15;await new Promise(e=>setTimeout(e,t))}catch{}return w};export{et as renderAvailableScriptsHelp,Oe as runSelected};
@@ -44,7 +44,6 @@ type ExecutionMode = 'concurrent' | 'sequential';
44
44
 
45
45
  /**
46
46
  * Return type helper for dependency graph build (internal).
47
- * @hidden
48
47
  */
49
48
  type DependencyMetaResult = Awaited<ReturnType<typeof buildDependencyMeta>>;
50
49
  /** Dependency context object passed to the runner for context-aware archiving. */
@@ -93,6 +92,8 @@ type RunBehavior = {
93
92
  keep?: boolean;
94
93
  /** Enable context mode (dependency graph & staged imports). */
95
94
  context?: boolean;
95
+ /** Create a meta archive (archive.tar = system+context) instead of full source. Requires context. */
96
+ meta?: boolean;
96
97
  /** Create archive.tar and archive.diff.tar. */
97
98
  archive?: boolean;
98
99
  /** Enable the live TTY UI when available. */
@@ -130,4 +131,4 @@ type RunBehavior = {
130
131
  declare const runSelected: (cwd: string, config: RunnerConfig, selection?: string[] | null, mode?: ExecutionMode, behaviorMaybe?: RunBehavior, promptChoice?: string) => Promise<string[]>;
131
132
 
132
133
  export { renderAvailableScriptsHelp, runSelected };
133
- export type { DependencyContext, ExecutionMode, RunBehavior, RunnerConfig, ScriptEntry, ScriptMap, ScriptObject, Selection };
134
+ export type { DependencyContext, DependencyMetaResult, ExecutionMode, RunBehavior, RunnerConfig, ScriptEntry, ScriptMap, ScriptObject, Selection };
package/package.json CHANGED
@@ -14,14 +14,14 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@karmaniverous/stan-context": "^0.6.0",
17
- "@karmaniverous/stan-core": "^0.8.1",
17
+ "@karmaniverous/stan-core": "^0.10.1",
18
18
  "@vitest/eslint-plugin": "^1.6.6",
19
19
  "chalk": "^5.6.2",
20
20
  "clipboardy": "^5.1.0",
21
21
  "commander": "^14.0.2",
22
22
  "fast-glob": "^3.3.3",
23
23
  "fs-extra": "^11.3.3",
24
- "inquirer": "^13.2.1",
24
+ "inquirer": "^13.2.2",
25
25
  "package-directory": "^8.1.0",
26
26
  "signal-exit": "^4.1.0",
27
27
  "table": "^6.9.0",
@@ -42,7 +42,7 @@
42
42
  "@rollup/plugin-typescript": "^12.3.0",
43
43
  "@types/eslint-config-prettier": "^6.11.3",
44
44
  "@types/fs-extra": "^11.0.4",
45
- "@types/node": "^25.0.10",
45
+ "@types/node": "^25.1.0",
46
46
  "@vitest/coverage-v8": "^4.0.18",
47
47
  "auto-changelog": "^2.5.0",
48
48
  "cross-env": "^10.1.0",
@@ -52,14 +52,14 @@
52
52
  "eslint-plugin-prettier": "^5.5.5",
53
53
  "eslint-plugin-simple-import-sort": "^12.1.1",
54
54
  "eslint-plugin-tsdoc": "^0.5.0",
55
- "happy-dom": "^20.3.7",
55
+ "happy-dom": "^20.4.0",
56
56
  "jsonc-eslint-parser": "^2.4.2",
57
57
  "knip": "^5.82.1",
58
- "lefthook": "^2.0.15",
58
+ "lefthook": "^2.0.16",
59
59
  "prettier": "^3.8.1",
60
60
  "release-it": "^19.2.4",
61
61
  "rimraf": "^6.1.2",
62
- "rollup": "^4.56.0",
62
+ "rollup": "^4.57.0",
63
63
  "rollup-plugin-dts": "^6.3.0",
64
64
  "tslib": "^2.8.1",
65
65
  "tsx": "^4.21.0",
@@ -67,7 +67,7 @@
67
67
  "typedoc-plugin-mdn-links": "^5.1.1",
68
68
  "typedoc-plugin-replace-text": "^4.2.0",
69
69
  "typedoc-plugin-zod": "^1.4.3",
70
- "typescript-eslint": "^8.53.1",
70
+ "typescript-eslint": "^8.54.0",
71
71
  "vitest": "^4.0.18"
72
72
  },
73
73
  "engines": {
@@ -159,5 +159,5 @@
159
159
  },
160
160
  "type": "module",
161
161
  "types": "dist/types/index.d.ts",
162
- "version": "0.13.1"
162
+ "version": "0.14.0"
163
163
  }