@kaynooo/cli-wait 0.13.0 → 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/README.md +6 -3
- package/dist/{chunk-mqe2vjsz.js → chunk-18nqpwfh.js} +5 -3
- package/dist/cli.js +9 -9
- package/dist/slot-cli.js +2 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -8,7 +8,9 @@ Waits for a background build or server for Claude Code, where a session would ot
|
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
10
|
waitfor --file server.log --until 'Listening on' --fail 'Error|FATAL' --timeout 2m
|
|
11
|
+
waitfor --file out.bin --idle 2s
|
|
11
12
|
waitfor --port 5432
|
|
13
|
+
waitfor --port-free 8000
|
|
12
14
|
waitfor --url http://localhost:8000/health
|
|
13
15
|
waitfor --pid 4242
|
|
14
16
|
waitfor --cmd 'curl -fs localhost:8000/health'
|
|
@@ -21,12 +23,13 @@ waitfor task b92stimuo
|
|
|
21
23
|
- `--file` is read from its start, line by line as each is completed, colours stripped; it may not exist yet. A file that shrinks (rotated, truncated) is read again from its start.
|
|
22
24
|
- `--until <regex>` waits for a line of `--file` to match and prints it as `<file>:<line>: <text>`.
|
|
23
25
|
- `--fail <regex>` ends the wait on the first matching line of `--file`, printing the five lines on each side of it on stderr, as long as some condition is still unmet: a `--until` line before it in the same read wins.
|
|
24
|
-
- `--
|
|
25
|
-
- `--port
|
|
26
|
+
- `--idle <duration>` waits until `--file` exists and its size and mtime stay unchanged for that duration (`500ms`, `2s`, …), without requiring `--until` or `--fail` (and may be combined with `--fail` or `--until`).
|
|
27
|
+
- `--port <n>` waits for a TCP connection to `--host` (127.0.0.1 or ::1) to be accepted, `--port-free <n>` waits until the port stops accepting connections (when `--host` is omitted, neither 127.0.0.1 nor ::1 may accept connections), and `--url <url>` waits for a 2xx answer, redirects followed. Each prints how long it took.
|
|
28
|
+
- `--port`, `--port-free` and `--url` may be repeated: every one must be met (or the first with `--any`), each printed with how long it took, and `--json` adds `conditions: [{name, ms}]` for each one met. A timeout lists only the ones still pending.
|
|
26
29
|
- `--status <spec>` sets the status a `--url` must answer instead of any 2xx: `301`, `200-299`, `2xx` or a comma list (redirects are not followed when a 3xx is asked for). `--body <regex>` makes the first MiB of the body match too. With several `--url`, both apply to every one.
|
|
27
30
|
- `--pid <n>` waits for the process to exit, checked with signal 0, so it never matches its own shell the way a `while pgrep -f` loop does. A zombie counts as exited. A `--port` connection attempt is given up after 3 seconds and retried, so dropped packets do not hold a poll for minutes.
|
|
28
31
|
- `--cmd <command>` runs the command through `sh -c` and waits for it to exit 0, re-running it every `--interval` (1s, `-t` bounds each run to the time left, 30s at most); a timeout names its last exit code and last output line.
|
|
29
|
-
- `--any` is met by the first condition that is, not all of them: it takes two or more of `--until`, `--port`, `--url`, `--pid` and `--cmd`, prints the one that was met, and a timeout says none was and lists them all. A `--fail` line still ends the wait with 1.
|
|
32
|
+
- `--any` is met by the first condition that is, not all of them: it takes two or more of `--until`, `--idle`, `--port`, `--port-free`, `--url`, `--healthy`, `--pid` and `--cmd`, prints the one that was met, and a timeout says none was and lists them all. A `--fail` line still ends the wait with 1.
|
|
30
33
|
- `waitfor task <id | file>` waits for a Claude Code background Bash task to end, its id found under `$CLAUDE_CODE_TMPDIR` (or `$TMPDIR`, `/tmp`) in `claude-<uid>/*/*/tasks/<id>.output`, then prints its exit code, its last 20 lines (`-n`) and the `(fail)` and `error:` lines above them, the last 30. It exits 0 when the task exited 0, 1 on another code, 2 on a timeout with the last lines; a path that does not exist fails at once with 2, and a subagent's id is refused, its notification reporting its end. `--json` prints `{task, path, code, ms, failures, tail}`, each line as `{number, text}`.
|
|
31
34
|
- `--json` prints `{met, ms, line}` once met, or on a `--fail` line with `met` false, `line` being the last `--until` line or the `--fail` one as `{number, text}`; the progress lines go to stderr. `--quiet` drops the live progress line, on `waitfor task` too.
|
|
32
35
|
- Every condition given must be met: `--port 8000 --file server.log --fail Error` waits for the port and gives up early when the log shows an error.
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import process8 from"process";import{parseArgs}from"util";import process6 from"process";var Nt=/\s+\S*$/,Y=/\s/;function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t));import process from"process";var MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"];function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}import process5 from"process";var G2=/^[a-f0-9]+$/i;function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}var B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var o=Fe();import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";var FILE_CACHE=new Map;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function userConfigReadPath(bin,legacy=[],where={}){if(bin==="config")return mainConfigPath(where);let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}function readUserConfig(bin,where={},legacy=[]){if(bin==="config")return readMainConfig(where);let fileData=readCachedObject(userConfigReadPath(bin,legacy,where)),section=readMainConfig(where)[bin];return isRecord(section)?{...fileData,...section}:fileData}function configuredNumber(bin,key,fallback,where={},legacy=[]){let value=readUserConfig(bin,where,legacy)[key];return typeof value==="number"&&Number.isInteger(value)&&value>0?value:fallback}var DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,MAX_FILE_BYTES=65536,SPACES=/\s+/;function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}var CUBE=[0,95,135,175,215,255];function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}var warned=new Set;function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}var current,currentKey="";function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function problem(text,detail){console.error(marked("problem",text,process5.stderr,detail))}var STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])));function statusOf(word){return STATUS_OF.get(word.toLowerCase())}function badge(word,stream,env=process5.env){let status=statusOf(word);if(status===void 0||!takesControlCodes(stream,env))return word;let{theme}=activeTheme();return tinted(paint(stream,env),theme.colors[status],env)(`${theme.glyphs[status]} ${word}`)}function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`;function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var UNITS=[["d",86400],["h",3600],["m",60],["s",1]];function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function formatElapsed(ms){return formatSeconds(Math.floor(Math.max(0,ms)/1000))}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function formatAge(date,now=Date.now()){let at=typeof date==="number"?date:Date.parse(date);if(Number.isNaN(at))return"-";let seconds=(now-at)/1000;return seconds<60?"just now":`${upTo(formatSeconds(seconds)," ")} ago`}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}var LINE_BREAKS=/\s*\n\s*/g;function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
|
|
2
|
+
import process8 from"process";import{parseArgs}from"util";import process6 from"process";var Nt=/\s+\S*$/,Y=/\s/;function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t));import process from"process";var MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"];function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}import process5 from"process";var G2=/^[a-f0-9]+$/i;function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}var B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var o=Fe();import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";var FILE_CACHE=new Map;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function userConfigReadPath(bin,legacy=[],where={}){if(bin==="config")return mainConfigPath(where);let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}function readUserConfig(bin,where={},legacy=[]){if(bin==="config")return readMainConfig(where);let fileData=readCachedObject(userConfigReadPath(bin,legacy,where)),section=readMainConfig(where)[bin];return isRecord(section)?{...fileData,...section}:fileData}function configuredNumber(bin,key,fallback,where={},legacy=[]){let value=readUserConfig(bin,where,legacy)[key];return typeof value==="number"&&Number.isInteger(value)&&value>0?value:fallback}var DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,MAX_FILE_BYTES=65536,SPACES=/\s+/;function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}var CUBE=[0,95,135,175,215,255];function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}var warned=new Set;function warnOnce(message){if(warned.has(message))return;warned.add(message),process4.stderr.write(`warning: theme ${message}
|
|
3
|
+
`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}var current,currentKey="";function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function writeErr(text=""){process5.stderr.write(`${text}
|
|
4
|
+
`)}function problem(text,detail){writeErr(marked("problem",text,process5.stderr,detail))}var STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])));function statusOf(word){return STATUS_OF.get(word.toLowerCase())}function badge(word,stream,env=process5.env){let status=statusOf(word);if(status===void 0||!takesControlCodes(stream,env))return word;let{theme}=activeTheme();return tinted(paint(stream,env),theme.colors[status],env)(`${theme.glyphs[status]} ${word}`)}var GRAPHEMES=new Intl.Segmenter;function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`;function wrapToWidth(text,width){let lines=[],current="";for(let word of text.split(" "))if(current!==""&&Bun.stringWidth(current)+1+Bun.stringWidth(word)>width)lines.push(current),current=word;else current=current===""?word:`${current} ${word}`;return current===""?lines:[...lines,current]}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var UNITS=[["d",86400],["h",3600],["m",60],["s",1]];function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function formatElapsed(ms){return formatSeconds(Math.floor(Math.max(0,ms)/1000))}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function formatAge(date,now=Date.now()){let at=typeof date==="number"?date:Date.parse(date);if(Number.isNaN(at))return"-";let seconds=(now-at)/1000;return seconds<60?"just now":`${upTo(formatSeconds(seconds)," ")} ago`}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}var LINE_BREAKS=/\s*\n\s*/g;function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
|
|
3
5
|
`);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
|
|
4
6
|
`)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}import process7 from"process";var OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
5
7
|
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
6
8
|
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
7
9
|
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process7.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
8
10
|
`)}function exitRows(exits,colors=paint(process7.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process7.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
9
|
-
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}var MAX_AGENT_EXAMPLES=2;function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}var MAX_INLINE_CHOICES=24;function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var WHOLE=/^\d+$/;function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}var BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000};function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var DASHES=/^-+/;function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}var EXIT=Symbol.for("@kaynooo/cli-kit/Exit");class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}}function badUsage(message){throw new UsageError(message)}class HelpShown extends Exit{constructor(){super("help shown",0)}}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}var completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};function applyOutput(color,plain,env=process8.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process8.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process8.stdout)?process8.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}var UNKNOWN_OPTION=/^unknown option '(-[^']+)'/;function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process9 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process9.argv.slice(2),cmdline=commandLine(),script=process9.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}import process11 from"process";import{readFileSync as readFileSync4}from"fs";import{constants}from"os";import process10 from"process";var KILL_GRACE_MS=2000,SIGNALS=["SIGINT","SIGTERM","SIGHUP"],GROUP_SIGNALS=new Set(["SIGINT","SIGHUP"]);function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}function groupsOf(pid){try{let stat=readFileSync4(`/proc/${pid}/stat`,"utf8"),fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");return{group:Number(fields[2]),foreground:Number(fields[5])}}catch{return}}function heardTheTerminal(child){if(child.pid===void 0)return!1;let own=groupsOf("self");return own!==void 0&&own.group===own.foreground&&groupsOf(child.pid)?.group===own.group}function holdSignals(cleanup){let received,child,held={get signal(){return received},forward:(to)=>{child=to},release:()=>{for(let signal of SIGNALS)process10.off(signal,onSignal)}};function onSignal(signal){if(received=signal,child!==void 0){if(!GROUP_SIGNALS.has(signal)||!heardTheTerminal(child))child.kill(signal);return}if(cleanup===void 0)return;held.release(),cleanup(signal),process10.kill(process10.pid,signal)}for(let signal of SIGNALS)process10.on(signal,onSignal);return held}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process10.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],FRAME_MS=200;var CLEAR_BELOW="\r\x1B[J",CTRL_C=3,CONSOLE_METHODS=["log","info","warn","error","debug","dir","dirxml","table","trace","group","groupCollapsed","count","timeEnd","timeLog","assert"];function liveRegion(render,stream=process11.stderr,env=process11.env){if(!takesControlCodes(stream,env))return{redraw:()=>{return},print:(text)=>void stream.write(`${text}
|
|
11
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}var MAX_AGENT_EXAMPLES=2;function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}var MAX_INLINE_CHOICES=24;function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapToWidth(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var WHOLE=/^\d+$/;function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}var BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000};function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var DASHES=/^-+/;function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}var EXIT=Symbol.for("@kaynooo/cli-kit/Exit");class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}}function badUsage(message){throw new UsageError(message)}class HelpShown extends Exit{constructor(){super("help shown",0)}}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}var completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};function applyOutput(color,plain,env=process8.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process8.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process8.stdout)?process8.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}var UNKNOWN_OPTION=/^unknown option '(-[^']+)'/;function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process9 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process9.argv.slice(2),cmdline=commandLine(),script=process9.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}import process11 from"process";import{readFileSync as readFileSync4}from"fs";import{constants}from"os";import process10 from"process";var KILL_GRACE_MS=2000,SIGNALS=["SIGINT","SIGTERM","SIGHUP"],GROUP_SIGNALS=new Set(["SIGINT","SIGHUP"]);function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}function groupsOf(pid){try{let stat=readFileSync4(`/proc/${pid}/stat`,"utf8"),fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");return{group:Number(fields[2]),foreground:Number(fields[5])}}catch{return}}function heardTheTerminal(child){if(child.pid===void 0)return!1;let own=groupsOf("self");return own!==void 0&&own.group===own.foreground&&groupsOf(child.pid)?.group===own.group}function holdSignals(cleanup){let received,child,held={get signal(){return received},forward:(to)=>{child=to},release:()=>{for(let signal of SIGNALS)process10.off(signal,onSignal)}};function onSignal(signal){if(received=signal,child!==void 0){if(!GROUP_SIGNALS.has(signal)||!heardTheTerminal(child))child.kill(signal);return}if(cleanup===void 0)return;held.release(),cleanup(signal),process10.kill(process10.pid,signal)}for(let signal of SIGNALS)process10.on(signal,onSignal);return held}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process10.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],FRAME_MS=200;var CLEAR_BELOW="\r\x1B[J",CTRL_C=3,CONSOLE_METHODS=["log","info","warn","error","debug","dir","dirxml","table","trace","group","groupCollapsed","count","timeEnd","timeLog","assert"];function liveRegion(render,stream=process11.stderr,env=process11.env){if(!takesControlCodes(stream,env))return{redraw:()=>{return},print:(text)=>void stream.write(`${text}
|
|
10
12
|
`),stop:()=>{return},pause:()=>()=>{return}};let write=stream.write.bind(stream),frame=0,drawn=!1,paused=!1,stopped=!1,columns=()=>{let now=stream.getWindowSize?.()[0]??stream.columns;return now===void 0||now===0?80:now},clear=()=>{if(drawn)write(CLEAR_BELOW);drawn=!1},draw=()=>{if(paused)return;let width=columns()-1,height=stream.rows===void 0||stream.rows===0?24:stream.rows,lines=render(FRAMES[frame++%FRAMES.length]).slice(0,Math.max(1,height-1)).map((line)=>cutToWidth(line,width));if(lines.length===0){clear();return}write(`${CLEAR_BELOW}${lines.join(`
|
|
11
13
|
`)}${lines.length>1?`\x1B[${lines.length-1}A`:""}\r`),drawn=!0},timer=setInterval(draw,FRAME_MS);stream.on?.("resize",draw);let restore=interceptOutput(clear),release=swallowInput(),onExit=()=>{clear(),release()},signals=holdSignals(stop);function stop(){stopped=!0,clearInterval(timer),stream.off?.("resize",draw),clear(),restore(),release(),process11.off("exit",onExit),signals.release()}function pause(){if(paused||stopped)return()=>{return};return paused=!0,clearInterval(timer),stream.off?.("resize",draw),clear(),restore(),release(),()=>{if(!paused||stopped)return;paused=!1,timer=setInterval(draw,FRAME_MS),timer.unref(),stream.on?.("resize",draw),restore=interceptOutput(clear),release=swallowInput(),draw()}}return timer.unref(),process11.on("exit",onExit),{redraw:draw,print:(text)=>{clear(),write(`${text}
|
|
12
14
|
`),draw()},stop,pause}}function swallowInput(){let input=process11.stdin;if(!input.isTTY)return()=>{return};let onData=(data)=>{if(data.includes(CTRL_C))process11.kill(process11.pid,"SIGINT")};input.setRawMode(!0),input.on("data",onData),input.resume();let released=!1;return()=>{if(released)return;released=!0,input.off("data",onData),input.pause(),input.setRawMode(!1)}}function interceptOutput(clear){let wrapped=[...CONSOLE_METHODS.map((name)=>[console,name]),[process11.stdout,"write"],[process11.stderr,"write"]].map(([target,name])=>{let original=Reflect.get(target,name),wrapper=(...args)=>(clear(),original.apply(target,args));return Reflect.set(target,name,wrapper),{target,name,original,wrapper}});return()=>{for(let{target,name,original,wrapper}of wrapped)if(Reflect.get(target,name)===wrapper)Reflect.set(target,name,original)}}import{readFileSync as readFileSync6,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join6}from"path";import process16 from"process";import process12 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process12.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process12.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
@@ -71,4 +73,4 @@ __kaynooo_cli_bins+=(${bins.join(" ")})
|
|
|
71
73
|
`)}
|
|
72
74
|
`,temp=`${path}.${process15.pid}.tmp`;writeFileSync2(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process15.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync2(dirname3(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
73
75
|
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};function printError(prefix,message,hint,cause){let colors=paint(process16.stderr),styled=takesControlCodes(process16.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
74
|
-
${styled?tint(label):`${label}:`} ${text}`;
|
|
76
|
+
${styled?tint(label):`${label}:`} ${text}`;writeErr(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){writeErr(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync6(join6(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv),printError);if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();heading.bin={name,version:()=>version??packageVersion()};try{code=await run(argv)}catch(error){meta=error instanceof HelpShown,code=reportThrown(name,error,redact,wantsJson(argv))}finally{heading.bin=void 0}if(notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);import{homedir as homedir5}from"os";import{join as join7}from"path";import process17 from"process";var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");async function sessionDirs(){let home=process17.env.HOME??homedir5(),dirs=new Set([join7(home,".claude","sessions")]);if(process17.env.CLAUDE_CONFIG_DIR!==void 0)dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR,"sessions"));try{for await(let dir of ACCOUNT_DIRS.scan({cwd:join7(home,".claude-accounts"),onlyFiles:!1,absolute:!0}))dirs.add(dir)}catch{}return[...dirs]}async function procStat(pid){try{let stat=await Bun.file(`/proc/${pid}/stat`).text();return stat.slice(stat.lastIndexOf(")")+2).split(" ")}catch{return}}async function isAlive(pid,procStart){let stat=await procStat(pid);if(stat===void 0)return!1;return procStart===void 0||stat[19]===procStart}async function liveSessions(){let sessions=new Map;for(let dir of await sessionDirs()){let files;try{files=await Array.fromAsync(SESSION_FILES.scan({cwd:dir,absolute:!0}))}catch{continue}for(let file of files){let entry;try{entry=await Bun.file(file).json()}catch{continue}if(entry.name===void 0||entry.pid===void 0||sessions.has(entry.pid)||!await isAlive(entry.pid,entry.procStart))continue;sessions.set(entry.pid,{name:entry.name,pid:entry.pid,status:entry.status??"unknown",cwd:entry.cwd??""})}}return[...sessions.values()]}async function currentSession(sessions){let byPid=new Map(sessions.map((session)=>[session.pid,session])),pid=process17.ppid;for(let depth=0;depth<32&&pid>1;depth++){let session=byPid.get(pid);if(session!==void 0)return session;let parent=Number((await procStat(pid))?.[1]);if(!Number.isInteger(parent))return;pid=parent}return}import{basename,dirname as dirname5,join as join8,relative,sep}from"path";var PARENT=`..${sep}`;export{configuredNumber,paint,writeErr,problem,badge,formatDuration,formatElapsed,formatAge,truncate,table,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,exitCodeOf,holdSignals,runCommand,liveRegion,privateLogDirectory,runMain,liveSessions,currentSession};
|
package/dist/cli.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{configuredNumber,paint,problem,formatDuration,formatElapsed,truncate,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,runCommand,liveRegion,runMain}from"./chunk-
|
|
4
|
-
`);return this.partial=(pieces.pop()??"").slice(0,MAX_LINE),pieces.map((text)=>({number:++this.number,text:Bun.stripANSI(text.slice(0,MAX_LINE).replace(CARRIAGE_RETURN,""))}))}async slice(end){try{return await Bun.file(this.path).slice(this.offset,end).bytes()}catch(error){return badUsage(`--file ${this.path} cannot be read (${error.code??String(error)})`)}}}async function portProblem(host,port,timeoutMs=PORT_TIMEOUT_MS){let attempt=Bun.connect({hostname:host,port,socket:{data:(socket)=>void socket.end()}}),timer;try{let socket=await Promise.race([attempt,new Promise((resolve)=>{timer=setTimeout(resolve,timeoutMs,"timeout")})]);if(socket==="timeout")return closeWhenConnected(attempt),"ETIMEDOUT";socket.end();return}catch(error){return error instanceof Error?error.code??error.message:String(error)}finally{clearTimeout(timer)}}async function closeWhenConnected(attempt){try{(await attempt).end()}catch{}}var STATUS_CLASS=/^([1-5])xx$/i,STATUS_RANGE=/^(\d{3})(?:-(\d{3}))?$/,BODY_BYTES=1048576;function parseStatus(spec){let tests=[];for(let part of spec.split(",").map((item)=>item.trim())){let klass=STATUS_CLASS.exec(part),range=STATUS_RANGE.exec(part);if(klass!==null){let hundred=Number(klass[1]);tests.push((status)=>Math.floor(status/100)===hundred)}else if(range!==null){let low=Number(range[1]),high=Number(range[2]??range[1]);tests.push((status)=>status>=low&&status<=high)}else return}return(status)=>tests.some((test)=>test(status))}async function healthyProblem(service){if(Bun.which("docker")===null)return"docker is not installed";let compose=await runCommand(["docker","compose","ps","--format","json",service]);if(compose.code===0&&compose.stdout.trim()!==""){let rows=compose.stdout.trim().split(`
|
|
3
|
+
import{configuredNumber,paint,writeErr,problem,formatDuration,formatElapsed,truncate,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,runCommand,liveRegion,runMain}from"./chunk-18nqpwfh.js";import{existsSync as existsSync3}from"fs";import process2 from"process";import{existsSync,statSync}from"fs";var TAIL=configuredNumber("wait","tail",20),AROUND=configuredNumber("wait","around",5),CARRIAGE_RETURN=/\r$/,SLICE_BYTES=1048576,MAX_LINE=1e4,PORT_TIMEOUT_MS=configuredNumber("wait","portTimeoutMs",3000);class FileWatch{path;until;failOn;offset=0;decoder=new TextDecoder;partial="";identity;number=0;recent=[];failure;matched=!1;constructor(path,until,failOn,fromEnd=!1){this.path=path;this.until=until;this.failOn=failOn;if(fromEnd&&existsSync(path)){let stats=statSync(path);if(stats.isDirectory())badUsage(`--file ${path} is a folder, not a log file`);this.offset=stats.size,this.identity={dev:stats.dev,ino:stats.ino}}}get done(){return this.until===void 0||this.matched}get failing(){return this.failure!==void 0}get failsFirst(){return this.failure?.isFirst===!0}get exists(){return existsSync(this.path)}async poll(){let events=[];for(let lines=await this.nextLines();lines!==void 0;lines=await this.nextLines())for(let line of lines){if(this.failure!==void 0){if(this.failure.after.length<AROUND)this.failure.after.push(line);continue}if(this.failOn?.test(line.text)===!0){this.failure={before:this.recent.slice(-AROUND),line,after:[],waited:!1,isFirst:!this.matched};continue}if(this.recent.push(line),this.recent.length>TAIL)this.recent.shift();if(!this.matched&&this.until?.test(line.text)===!0)this.matched=!0,events.push({kind:"until",line})}if(this.failure!==void 0&&!this.failure.waited&&this.failure.after.length<AROUND)this.failure.waited=!0;else if(this.failure!==void 0)events.push({kind:"fail",line:this.failure.line,excerpt:[...this.failure.before,this.failure.line,...this.failure.after]});return events}excerpt(){return this.recent}async nextLines(){if(!existsSync(this.path))return;let stats=statSync(this.path);if(stats.isDirectory())badUsage(`--file ${this.path} is a folder, not a log file`);let{size,dev,ino}=stats,replaced=this.identity!==void 0&&(this.identity.dev!==dev||this.identity.ino!==ino);if(this.identity={dev,ino},size<this.offset||replaced)this.offset=0,this.decoder=new TextDecoder,this.partial="",this.number=0,this.recent=[];if(size===this.offset)return;let end=Math.min(size,this.offset+SLICE_BYTES),chunk=this.decoder.decode(await this.slice(end),{stream:!0});this.offset=end;let pieces=(this.partial+chunk).split(`
|
|
4
|
+
`);return this.partial=(pieces.pop()??"").slice(0,MAX_LINE),pieces.map((text)=>({number:++this.number,text:Bun.stripANSI(text.slice(0,MAX_LINE).replace(CARRIAGE_RETURN,""))}))}async slice(end){try{return await Bun.file(this.path).slice(this.offset,end).bytes()}catch(error){return badUsage(`--file ${this.path} cannot be read (${error.code??String(error)})`)}}}class IdleWatch{path;durationMs;last;stableSince;matched=!1;lastNow=Date.now();constructor(path,durationMs){this.path=path;this.durationMs=durationMs}get done(){return this.matched}get exists(){return this.last!==void 0}get stableFor(){return this.stableSince===void 0?0:Math.max(0,this.lastNow-this.stableSince)}poll(now=Date.now()){if(this.lastNow=now,this.matched)return!1;let stats;try{stats=statSync(this.path,{bigint:!0,throwIfNoEntry:!1})}catch(error){let code=error.code;if(code==="ENOTDIR")return this.last=void 0,this.stableSince=void 0,!1;badUsage(`--file ${this.path} cannot be stat'd (${code??String(error)})`)}if(stats===void 0)return this.last=void 0,this.stableSince=void 0,!1;if(stats.isDirectory())badUsage(`--file ${this.path} is a folder, not a file`);let current={size:stats.size,mtimeNs:stats.mtimeNs,dev:stats.dev,ino:stats.ino};if(this.last===void 0||this.last.size!==current.size||this.last.mtimeNs!==current.mtimeNs||this.last.dev!==current.dev||this.last.ino!==current.ino)return this.last=current,this.stableSince=now,!1;if(this.stableSince!==void 0&&now-this.stableSince>=this.durationMs)return this.matched=!0,!0;return!1}}async function portProblem(host,port,timeoutMs=PORT_TIMEOUT_MS){let attempt=Bun.connect({hostname:host,port,socket:{data:(socket)=>void socket.end()}}),timer;try{let socket=await Promise.race([attempt,new Promise((resolve)=>{timer=setTimeout(resolve,timeoutMs,"timeout")})]);if(socket==="timeout")return closeWhenConnected(attempt),"ETIMEDOUT";socket.end();return}catch(error){return error instanceof Error?error.code??error.message:String(error)}finally{clearTimeout(timer)}}async function portFreeHost(hosts,port,timeoutMs=PORT_TIMEOUT_MS){for(let host of hosts)if(await portProblem(host,port,timeoutMs)===void 0)return host;return}async function closeWhenConnected(attempt){try{(await attempt).end()}catch{}}var STATUS_CLASS=/^([1-5])xx$/i,STATUS_RANGE=/^(\d{3})(?:-(\d{3}))?$/,BODY_BYTES=1048576;function parseStatus(spec){let tests=[];for(let part of spec.split(",").map((item)=>item.trim())){let klass=STATUS_CLASS.exec(part),range=STATUS_RANGE.exec(part);if(klass!==null){let hundred=Number(klass[1]);tests.push((status)=>Math.floor(status/100)===hundred)}else if(range!==null){let low=Number(range[1]),high=Number(range[2]??range[1]);tests.push((status)=>status>=low&&status<=high)}else return}return(status)=>tests.some((test)=>test(status))}async function healthyProblem(service){if(Bun.which("docker")===null)return"docker is not installed";let compose=await runCommand(["docker","compose","ps","--format","json",service]);if(compose.code===0&&compose.stdout.trim()!==""){let rows=compose.stdout.trim().split(`
|
|
5
5
|
`).flatMap((line)=>{try{let parsed=JSON.parse(line);return Array.isArray(parsed)?parsed:[parsed]}catch{return[]}});if(rows.length>0){let states=rows.map((row)=>String(row.Health??row.State??row.Status??"unknown").toLowerCase());return states.every((state)=>state==="healthy"||state.includes("(healthy)"))?void 0:states.join(", ")}}let inspected=await runCommand(["docker","inspect","--format","{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",service]);if(inspected.code!==0)return"container not found";let status=inspected.stdout.trim().toLowerCase();return status==="healthy"?void 0:status||"unknown"}async function readBody(response){let reader=response.body?.getReader();if(reader===void 0)return"";let decoder=new TextDecoder,text="",bytes=0;while(bytes<BODY_BYTES){let{done,value}=await reader.read();if(done)break;bytes+=value?.length??0,text+=decoder.decode(value,{stream:!0})}return await reader.cancel(),text}async function urlCheck(url,timeout,expect={}){try{let wantsRedirect=expect.status!==void 0&&Array.from({length:100},(_,index)=>300+index).some(expect.status.test),init={signal:AbortSignal.timeout(timeout),redirect:wantsRedirect?"manual":"follow",...expect.headers===void 0?{}:{headers:expect.headers},...expect.insecure===!0?{tls:{rejectUnauthorized:!1}}:{}},response=await fetch(url,init);if(!(expect.status===void 0?response.ok:expect.status.test(response.status)))return await response.body?.cancel(),{problem:expect.status===void 0?`answered ${response.status}`:`answered ${response.status}, expected ${expect.status.spec}`};if(expect.body===void 0)return await response.body?.cancel(),{status:response.status};return expect.body.test(await readBody(response))?{status:response.status}:{problem:`answered ${response.status} but the body does not match ${expect.body}`}}catch(error){return{problem:error instanceof Error?error.message:String(error),isTimeout:error instanceof Error&&error.name==="TimeoutError"}}}import{existsSync as existsSync2,lstatSync,readFileSync,statSync as statSync2}from"fs";import{join}from"path";import process from"process";var EXITED=/(?:^|\n)\[exited with code (-?\d+)\]\n*$/,FAILURE=/\(fail\)|\berror:/i,TASK_ID=/^[\w-]+$/,TAIL_BYTES=256,LONGEST_FAILURES=30,CARRIAGE_RETURN2=/\r$/;function tasksRoot(env){return join(env.CLAUDE_CODE_TMPDIR??env.TMPDIR??"/tmp",`claude-${process.getuid?.()??0}`)}function taskFile(task,env=process.env){if(task.includes("/")||task.endsWith(".output"))return task;if(!TASK_ID.test(task))return;let root=tasksRoot(env),found=existsSync2(root)?[...new Bun.Glob(`*/*/tasks/${task}.output`).scanSync({cwd:root,onlyFiles:!1})]:[];return found.length===0?void 0:join(root,found[0]??"")}function isTranscript(path){return existsSync2(path)&&lstatSync(path).isSymbolicLink()&&path.endsWith(".output")}async function exitCode(path){if(!existsSync2(path))return;let size=statSync2(path).size,found=EXITED.exec(await Bun.file(path).slice(Math.max(0,size-TAIL_BYTES),size).text());return found===null?void 0:Number(found[1])}async function taskEnd(path,lines){if(!existsSync2(path))return{failures:[],tail:[]};let all=(await Bun.file(path).text()).replace(EXITED,"").split(`
|
|
6
|
-
`).map((line,i)=>({number:i+1,text:Bun.stripANSI(line.replace(CARRIAGE_RETURN2,""))}));while(all.at(-1)?.text.trim()==="")all.pop();let tail=all.slice(-lines),first=tail[0]?.number??1/0;return{failures:all.filter((line)=>line.number<first&&FAILURE.test(line.text)).slice(-LONGEST_FAILURES),tail}}function pidAlive(pid){try{process.kill(pid,0)}catch(error){return error.code==="EPERM"}return!isZombie(pid)}function isZombie(pid){try{let stat=readFileSync(`/proc/${pid}/stat`,"utf8");return stat.slice(stat.lastIndexOf(")")+2,stat.lastIndexOf(")")+3)==="Z"}catch{return!1}}var USAGE=`waitfor [options]: waits until a file shows a line, a port listens, a URL answers 2xx, a Docker service is healthy, a process exits or a command exits 0
|
|
6
|
+
`).map((line,i)=>({number:i+1,text:Bun.stripANSI(line.replace(CARRIAGE_RETURN2,""))}));while(all.at(-1)?.text.trim()==="")all.pop();let tail=all.slice(-lines),first=tail[0]?.number??1/0;return{failures:all.filter((line)=>line.number<first&&FAILURE.test(line.text)).slice(-LONGEST_FAILURES),tail}}function pidAlive(pid){try{process.kill(pid,0)}catch(error){return error.code==="EPERM"}return!isZombie(pid)}function isZombie(pid){try{let stat=readFileSync(`/proc/${pid}/stat`,"utf8");return stat.slice(stat.lastIndexOf(")")+2,stat.lastIndexOf(")")+3)==="Z"}catch{return!1}}var USAGE=`waitfor [options]: waits until a file shows a line or goes idle, a port listens or frees up, a URL answers 2xx, a Docker service is healthy, a process exits or a command exits 0
|
|
7
7
|
waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
|
|
8
8
|
|
|
9
|
-
All conditions are polled in parallel every tick. Every condition given must be met, or with --any the first of them; --port, --url and --healthy may be repeated. A --fail line in --file or a --while-pid process exiting ends the wait immediately with exit 1.`,TASK_USAGE=`waitfor task [options] <task id | file>: waits for a Claude Code background task to end, then prints its exit code, its last lines and the (fail) and error: lines above them
|
|
9
|
+
All conditions are polled in parallel every tick. Every condition given must be met, or with --any the first of them; --port, --port-free, --url and --healthy may be repeated. A --fail line in --file or a --while-pid process exiting ends the wait immediately with exit 1.`,TASK_USAGE=`waitfor task [options] <task id | file>: waits for a Claude Code background task to end, then prints its exit code, its last lines and the (fail) and error: lines above them
|
|
10
10
|
|
|
11
11
|
The task is the id a background Bash call returned, or the path of its .output file.
|
|
12
|
-
--json prints {task, path, code, ms, failures, tail}, each line as {number, text}.`,TIMEOUT_EXIT=124,EXITS=[[0,"every condition was met"],[1,"a --fail line showed up or --while-pid exited"],[124,"it timed out"],[2,"a usage error"]],TASK_EXITS=[[0,"the task exited 0"],[1,"it exited with another code"],[124,"it timed out"],[2,"a usage error"]],TIMEOUT={type:"string",short:"t",description:"how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds"},TASK_OPTIONS={lines:{type:"string",short:"n",description:"how many of its last lines to print (20)"},timeout:TIMEOUT,json:jsonOption(),quiet:{type:"boolean",short:"q",description:"no live progress line"}},OPTIONS={file:{type:"string",short:"f",description:"a
|
|
12
|
+
--json prints {task, path, code, ms, failures, tail}, each line as {number, text}.`,TIMEOUT_EXIT=124,EXITS=[[0,"every condition was met"],[1,"a --fail line showed up or --while-pid exited"],[124,"it timed out"],[2,"a usage error"]],TASK_EXITS=[[0,"the task exited 0"],[1,"it exited with another code"],[124,"it timed out"],[2,"a usage error"]],TIMEOUT={type:"string",short:"t",description:"how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds"},TASK_OPTIONS={lines:{type:"string",short:"n",description:"how many of its last lines to print (20)"},timeout:TIMEOUT,json:jsonOption(),quiet:{type:"boolean",short:"q",description:"no live progress line"}},OPTIONS={file:{type:"string",short:"f",description:"a file to read or watch, waiting for it to exist"},"from-end":{type:"boolean",description:"with --file, start reading from the current end of the file (ignore existing lines)"},until:{type:"string",short:"u",description:"a regular expression a line of --file must match"},fail:{type:"string",short:"e",description:"a regular expression whose first matching line of --file is a failure"},idle:{type:"string",description:"with --file, wait until its size and mtime stay unchanged for this duration (e.g. 2s)"},port:{type:"string",short:"p",multiple:!0,description:"a TCP port that must accept connections, repeatable"},"port-free":{type:"string",multiple:!0,description:"a TCP port that must stop accepting connections, repeatable"},host:{type:"string",description:"the host of --port and --port-free (127.0.0.1 and ::1)"},url:{type:"string",multiple:!0,description:"a URL that must answer 2xx (or --status), repeatable"},header:{type:"string",short:"H",multiple:!0,description:'"Name: value" header sent with every --url request, repeatable'},insecure:{type:"boolean",short:"k",description:"with --url, ignore untrusted TLS certificates"},status:{type:"string",description:"the status a --url must answer instead of 2xx: 301, 200-299, 2xx or a comma list, for every --url"},body:{type:"string",description:"a regular expression the first MiB of a --url body must match, for every --url"},healthy:{type:"string",multiple:!0,description:"a Docker Compose service or container that must report healthy, repeatable"},pid:{type:"string",description:"a process id that must exit"},"while-pid":{type:"string",description:"abort immediately with exit 1 if this process exits before conditions are met"},cmd:{type:"string",short:"c",description:"a shell command that must exit 0, re-run every --interval"},interval:{type:"string",description:"how long between two runs of --cmd (1s)"},any:{type:"boolean",description:"met by the first condition that is, not all of them (needs two)"},timeout:TIMEOUT,json:jsonOption("{met, ms, line, conditions: [{name, ms}]}, line being the last --until line or the --fail one as {number, text}; the progress lines go to stderr"),quiet:{type:"boolean",short:"q",description:"no live progress line: only what was met and the failure"}},POLL=250,URL_TIMEOUT=5000,WIDTH=400,CMD_RUN_LIMIT=30000,LAST_LINE=/[^\n]+(?=\n*$)/,HEADER_LINE=/^[\w!#$%&'*+.^`|~-]+:/;function regex(source,name){if(source===void 0)return;try{return new RegExp(source)}catch(error){fail(`--${name} is no valid regular expression: ${error instanceof Error?error.message:String(error)}`)}}function numbered(lines,marked){let width=String(lines.at(-1)?.number??0).length;return lines.map((line)=>`${line===marked?">":" "} ${String(line.number).padStart(width)} ${truncate(line.text,WIDTH)}`).join(`
|
|
13
13
|
`)}async function cmdProblem(command,timeoutMs){try{let ran=await runCommand(["sh","-c",command],{timeoutMs});if(ran.code===0&&!ran.timedOut)return;let last=LAST_LINE.exec(ran.text)?.[0];return`${ran.timedOut?"timed out":`exited ${ran.code}`}${last===void 0?"":` (${truncate(last,WIDTH)})`}`}catch(error){return`could not run: ${error instanceof Error?error.message:String(error)}`}}async function waitTask(args){let{values,positionals:[task]}=parse(args,TASK_USAGE,TASK_OPTIONS,{positionals:["<task>"],exits:TASK_EXITS}),path=taskFile(task);if(path===void 0)fail(`no background task ${task}: give the id a background Bash call returned, or the path of its .output file`);if(!existsSync3(path))fail(`no output file ${path}: ${task} is no background task of this machine`);if(isTranscript(path))fail(`${task} is a subagent, whose end its notification reports: waitfor task waits on a background Bash task`);let lines=wholeNumber(values.lines,"lines",20),timeout=duration(values.timeout,"timeout",300000),started=Date.now(),{dim}=paint(process2.stderr),region=values.quiet===!0?void 0:liveRegion((spinner)=>[`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now()-started))}`]),code;try{for(;;){if(code=await exitCode(path),code!==void 0||Date.now()-started>=timeout)break;await Bun.sleep(POLL)}}finally{region?.stop()}let{failures,tail}=await taskEnd(path,lines),last=tail.length===0?"":`
|
|
14
14
|
last lines of ${path}:
|
|
15
15
|
${numbered(tail)}`;if(code===void 0)fail(`gave up after ${formatDuration(timeout)}: task ${task} is still running${last}`,TIMEOUT_EXIT);if(values.json===!0)return printJson({task,path,code,ms:Date.now()-started,failures,tail}),code===0?0:1;let failed=failures.length===0?"":`
|
|
16
16
|
(fail) and error: lines above them:
|
|
17
|
-
${numbered(failures)}`;return console.log(`task ${task} exited with code ${code}, waited ${formatDuration(Date.now()-started)}${failed}${last}`),code===0?0:1}async function main(args){if(args[0]==="task")return waitTask(args.slice(1));let parsed=parse(args,USAGE,OPTIONS,{exits:EXITS,replaces:"sleep loops, tail -f and until ! pgrep -f",examples:[['waitfor --file dev.log --from-end --until "ready in" --fail error',"a dev server up from new log lines, or its first error"],["waitfor --port 5432 --while-pid 1234 -t 2m","Postgres accepting connections while its launcher is alive"]]}),{values,positionals}=parsed;if(positionals.length>0)fail(`unexpected argument ${positionals[0]}
|
|
17
|
+
${numbered(failures)}`;return console.log(`task ${task} exited with code ${code}, waited ${formatDuration(Date.now()-started)}${failed}${last}`),code===0?0:1}function hostPort(host,port){return`${host.includes(":")?`[${host}]`:host}:${port}`}async function main(args){if(args[0]==="task")return waitTask(args.slice(1));let parsed=parse(args,USAGE,OPTIONS,{exits:EXITS,replaces:"sleep loops, tail -f and until ! pgrep -f",examples:[['waitfor --file dev.log --from-end --until "ready in" --fail error',"a dev server up from new log lines, or its first error"],["waitfor --port 5432 --while-pid 1234 -t 2m","Postgres accepting connections while its launcher is alive"],["waitfor --port-free 8000","old server has released port 8000"],["waitfor --file out.bin --idle 2s","file finished writing and stayed unchanged for 2s"]]}),{values,positionals}=parsed;if(positionals.length>0)fail(`unexpected argument ${positionals[0]}
|
|
18
18
|
|
|
19
|
-
${USAGE}`);let portTexts=values.port??[],urlTexts=values.url??[],healthyTexts=values.healthy??[];if(values.until===void 0&&portTexts.length===0&&urlTexts.length===0&&healthyTexts.length===0&&values.pid===void 0&&values.cmd===void 0)fail(`give --until with --file, --port, --url, --healthy, --pid or --cmd
|
|
19
|
+
${USAGE}`);let portTexts=values.port??[],portFreeTexts=values["port-free"]??[],urlTexts=values.url??[],healthyTexts=values.healthy??[];if(values.until===void 0&&values.idle===void 0&&portTexts.length===0&&portFreeTexts.length===0&&urlTexts.length===0&&healthyTexts.length===0&&values.pid===void 0&&values.cmd===void 0)fail(`give --until or --idle with --file, --port, --port-free, --url, --healthy, --pid or --cmd
|
|
20
20
|
|
|
21
|
-
${USAGE}`);if((values.until!==void 0||values.fail!==void 0)!==(values.file!==void 0))fail("--until and --
|
|
22
|
-
${numbered(event.excerpt,event.line)}`),json)printJson({met:!1,ms:Date.now()-started,line:{number:event.line.number,text:event.line.text}});return 1}if(pid!==void 0&&isPidLeft){if(isPidLeft=pidAlive(pid),!isPidLeft)metAt.push({name:`pid ${pid}`,ms:Date.now()-started}),say(`pid ${pid} exited after ${formatDuration(Date.now()-started)}`)}let isMet=[values.until!==void 0&&(watch?.done??!1),ports.some((probe)=>probe.left===void 0),urls.some((probe)=>probe.left===void 0),services.some((probe)=>probe.left===void 0),pid!==void 0&&!isPidLeft,values.cmd!==void 0&&cmdLeft===void 0],isAllMet=(watch?.done??!0)&&ports.every((probe)=>probe.left===void 0)&&urls.every((probe)=>probe.left===void 0)&&services.every((probe)=>probe.left===void 0)&&!isPidLeft&&cmdLeft===void 0;if((isAny?isMet.includes(!0):isAllMet)&&!(watch?.failsFirst??!1)){if(json)printJson({met:!0,ms:Date.now()-started,line:matched??null,conditions:metAt});return 0}if(Date.now()-started>=timeout&&!(watch?.failing??!1))break;await Bun.sleep(POLL)}}finally{region?.stop()}let missing=[];if(watch!==void 0&&!watch.done)missing.push(watch.exists?`no line of ${watch.path} matched --until`:`${watch.path} does not exist`);for(let probe of ports)if(probe.left!==void 0)missing.push(`${hosts[0]
|
|
21
|
+
${USAGE}`);if((values.until!==void 0||values.fail!==void 0||values.idle!==void 0)!==(values.file!==void 0))fail("--until, --fail and --idle work with --file, and --file needs one of them");if(values["from-end"]===!0&&values.file===void 0)fail("--from-end goes with --file");if(values.host!==void 0&&portTexts.length===0&&portFreeTexts.length===0)fail("--host goes with --port or --port-free");if((values.status!==void 0||values.body!==void 0||(values.header?.length??0)>0||values.insecure===!0)&&urlTexts.length===0)fail("--status, --body, --header and --insecure go with --url");let conditions=[values.until,values.idle,...portTexts,...portFreeTexts,...urlTexts,...healthyTexts,values.pid,values.cmd].filter((condition)=>condition!==void 0).length;if(values.any===!0&&conditions<2)fail("--any needs two or more of --until, --idle, --port, --port-free, --url, --healthy, --pid and --cmd");if(values.interval!==void 0&&values.cmd===void 0)fail("--interval goes with --cmd");let hosts=values.host===void 0?["127.0.0.1","::1"]:[values.host],ports=portTexts.map((text)=>{let port=wholeNumber(text,"port",0);if(port>65535)fail(`--port takes a port up to 65535, not ${port}`);return{name:String(port),port,left:"not checked yet"}}),freePorts=portFreeTexts.map((text)=>{let port=wholeNumber(text,"port-free",0);if(port>65535)fail(`--port-free takes a port up to 65535, not ${port}`);return{name:hostPort(hosts[0],port),port,left:"not checked yet"}});for(let url of urlTexts)if(!URL.canParse(url))fail(`--url ${url} is no URL`);let headers={};for(let entry of values.header??[]){if(!HEADER_LINE.test(entry))fail(`-H takes "Name: value", not ${entry}`);let at=entry.indexOf(":");headers[entry.slice(0,at).trim()]=entry.slice(at+1).trim()}let statusTest=values.status===void 0?void 0:parseStatus(values.status);if(values.status!==void 0&&statusTest===void 0)fail(`--status takes a code, a range or a class such as 301, 200-299 or 2xx, not ${values.status}`);let expect={...values.status!==void 0&&statusTest!==void 0?{status:{test:statusTest,spec:values.status}}:{},...Object.keys(headers).length===0?{}:{headers},...values.insecure===!0?{insecure:!0}:{}},body=regex(values.body,"body");if(body!==void 0)expect.body=body;let urls=urlTexts.map((url)=>({name:url,left:"not checked yet"})),services=healthyTexts.map((service)=>({name:service,left:"not checked yet"})),metAt=[],pid=values.pid===void 0?void 0:wholeNumber(values.pid,"pid",0),whilePid=values["while-pid"]===void 0?void 0:wholeNumber(values["while-pid"],"while-pid",0),idleMs=values.idle===void 0?void 0:duration(values.idle,"idle",0),interval=duration(values.interval,"interval",1000),isAny=values.any===!0,timeout=duration(values.timeout,"timeout",300000),watch=values.file!==void 0&&(values.until!==void 0||values.fail!==void 0)?new FileWatch(values.file,regex(values.until,"until"),regex(values.fail,"fail"),values["from-end"]===!0):void 0,idle=values.file!==void 0&&idleMs!==void 0?new IdleWatch(values.file,idleMs):void 0,started=Date.now(),json=values.json===!0,say=json?writeErr:console.log,matched,isPidLeft=pid!==void 0,cmdLeft=values.cmd===void 0?void 0:"not run yet",cmdRanAt=0,{dim}=paint(process2.stderr),region=values.quiet===!0?void 0:liveRegion((spinner)=>{let waited=dim(formatElapsed(Date.now()-started));return[watch===void 0||watch.done?void 0:`${watch.path}: ${watch.exists?"no --until line yet":"does not exist yet"}`,idle===void 0||idle.done?void 0:`${idle.path}: ${idle.exists?`idle ${formatDuration(idle.stableFor)} / ${formatDuration(idle.durationMs)}`:"does not exist yet"}`,...ports.filter((probe)=>probe.left!==void 0).map((probe)=>`${hostPort(hosts[0],probe.port??0)}: ${probe.left}`),...freePorts.filter((probe)=>probe.left!==void 0).map((probe)=>`${probe.name}: ${probe.left}`),...urls.filter((probe)=>probe.left!==void 0).map((probe)=>`${probe.name}: ${probe.left}`),...services.filter((probe)=>probe.left!==void 0).map((probe)=>`service ${probe.name}: ${probe.left}`),isPidLeft?`pid ${pid}: still running`:void 0,cmdLeft===void 0?void 0:`\`${values.cmd}\`: ${cmdLeft}`].filter((line)=>line!==void 0).map((line)=>`${spinner} ${line} ${waited}`)});try{for(;;){if(whilePid!==void 0&&!pidAlive(whilePid)){if(problem(`waitfor: --while-pid ${whilePid} exited after ${formatDuration(Date.now()-started)} before conditions were met`),json)printJson({met:!1,ms:Date.now()-started,reason:`pid ${whilePid} exited`,line:null,conditions:metAt});return 1}let[fileEvents]=await Promise.all([watch===void 0?Promise.resolve([]):watch.poll(),Promise.all(ports.filter((probe)=>probe.left!==void 0).map(async(probe)=>{for(let candidate of hosts){let prob=await portProblem(candidate,probe.port??0);if(candidate===hosts[0])probe.left=prob;if(prob===void 0){let name=hostPort(candidate,probe.port??0);probe.left=void 0,probe.name=name,metAt.push({name,ms:Date.now()-started}),say(`${name} listening after ${formatDuration(Date.now()-started)}`);return}}})),Promise.all(freePorts.filter((probe)=>probe.left!==void 0).map(async(probe)=>{let busy=await portFreeHost(hosts,probe.port??0);if(busy!==void 0){probe.name=hostPort(busy,probe.port??0),probe.left="still listening";return}let name=hostPort(hosts[0],probe.port??0);probe.left=void 0,probe.name=name,metAt.push({name:`port-free:${name}`,ms:Date.now()-started}),say(`${name} free after ${formatDuration(Date.now()-started)}`)})),Promise.all(urls.filter((probe)=>probe.left!==void 0).map(async(probe)=>{let budget=Math.max(1,Math.min(URL_TIMEOUT,started+timeout-Date.now())),check=await urlCheck(probe.name,budget,expect);if(!(("problem"in check)&&check.isTimeout===!0&&budget<URL_TIMEOUT&&probe.left!=="not checked yet"))probe.left="problem"in check?check.problem:void 0;if("status"in check)metAt.push({name:probe.name,ms:Date.now()-started}),say(`${probe.name} answered ${check.status} after ${formatDuration(Date.now()-started)}`)})),Promise.all(services.filter((probe)=>probe.left!==void 0).map(async(probe)=>{let prob=await healthyProblem(probe.name);if(probe.left=prob,prob===void 0)metAt.push({name:`healthy:${probe.name}`,ms:Date.now()-started}),say(`${probe.name} healthy after ${formatDuration(Date.now()-started)}`)})),(async()=>{if(values.cmd!==void 0&&cmdLeft!==void 0&&Date.now()-cmdRanAt>=interval){let budget=Math.max(1,Math.min(CMD_RUN_LIMIT,started+timeout-Date.now())),prob=await cmdProblem(values.cmd,budget);if(!(prob?.startsWith("timed out")===!0&&budget<CMD_RUN_LIMIT&&cmdLeft!=="not run yet"))cmdLeft=prob;if(cmdRanAt=Date.now(),cmdLeft===void 0)metAt.push({name:`\`${values.cmd}\``,ms:Date.now()-started}),say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now()-started)}`)}})()]);for(let event of fileEvents){if(event.kind==="until"){say(`${watch.path}:${event.line.number}: ${truncate(event.line.text,WIDTH)}`),matched={number:event.line.number,text:event.line.text},metAt.push({name:`${watch.path} --until`,ms:Date.now()-started});continue}if(problem(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now()-started)}
|
|
22
|
+
${numbered(event.excerpt,event.line)}`),json)printJson({met:!1,ms:Date.now()-started,line:{number:event.line.number,text:event.line.text}});return 1}if(idle!==void 0&&!idle.done&&idle.poll())metAt.push({name:`${idle.path} --idle`,ms:Date.now()-started}),say(`${idle.path} idle for ${formatDuration(idle.durationMs)} after ${formatDuration(Date.now()-started)}`);if(pid!==void 0&&isPidLeft){if(isPidLeft=pidAlive(pid),!isPidLeft)metAt.push({name:`pid ${pid}`,ms:Date.now()-started}),say(`pid ${pid} exited after ${formatDuration(Date.now()-started)}`)}let isMet=[values.until!==void 0&&(watch?.done??!1),idle!==void 0&&idle.done,ports.some((probe)=>probe.left===void 0),freePorts.some((probe)=>probe.left===void 0),urls.some((probe)=>probe.left===void 0),services.some((probe)=>probe.left===void 0),pid!==void 0&&!isPidLeft,values.cmd!==void 0&&cmdLeft===void 0],isAllMet=(watch?.done??!0)&&(idle?.done??!0)&&ports.every((probe)=>probe.left===void 0)&&freePorts.every((probe)=>probe.left===void 0)&&urls.every((probe)=>probe.left===void 0)&&services.every((probe)=>probe.left===void 0)&&!isPidLeft&&cmdLeft===void 0;if((isAny?isMet.includes(!0):isAllMet)&&!(watch?.failsFirst??!1)){if(json)printJson({met:!0,ms:Date.now()-started,line:matched??null,conditions:metAt});return 0}if(Date.now()-started>=timeout&&!(watch?.failing??!1))break;await Bun.sleep(POLL)}}finally{region?.stop()}let missing=[];if(watch!==void 0&&!watch.done)missing.push(watch.exists?`no line of ${watch.path} matched --until`:`${watch.path} does not exist`);if(idle!==void 0&&!idle.done)if(!idle.exists){if(watch===void 0||watch.done||watch.exists)missing.push(`${idle.path} does not exist`)}else missing.push(`${idle.path} has not been idle for ${formatDuration(idle.durationMs)} (stable ${formatDuration(idle.stableFor)})`);for(let probe of ports)if(probe.left!==void 0)missing.push(`${hostPort(hosts[0],probe.port??0)} is not listening (${probe.left})`);for(let probe of freePorts)if(probe.left!==void 0)missing.push(probe.left==="still listening"?`${probe.name} is still listening`:`${probe.name} is not free (${probe.left})`);for(let probe of urls)if(probe.left!==void 0)missing.push(`${probe.name} ${probe.left}`);for(let probe of services)if(probe.left!==void 0)missing.push(`service ${probe.name} is not healthy (${probe.left})`);if(isPidLeft)missing.push(`pid ${pid} is still running`);if(cmdLeft!==void 0)missing.push(`\`${values.cmd}\` ${cmdLeft}`);let lines=watch?.excerpt()??[];fail(`gave up after ${formatDuration(timeout)}${isAny?", none met":""}: ${missing.join(", ")}${lines.length===0?"":`
|
|
23
23
|
last lines of ${watch?.path}:
|
|
24
24
|
${numbered(lines)}`}`,TIMEOUT_EXIT)}process2.exitCode=await runMain({name:"waitfor",run:main});
|
package/dist/slot-cli.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{configuredNumber,paint,badge,formatDuration,formatElapsed,formatAge,truncate,table,printJson,wholeNumber,duration,jsonOption,fail,parse,exitCodeOf,holdSignals,liveRegion,privateLogDirectory,runMain,liveSessions,currentSession}from"./chunk-
|
|
3
|
+
import{configuredNumber,paint,writeErr,badge,formatDuration,formatElapsed,formatAge,truncate,table,printJson,wholeNumber,duration,jsonOption,fail,parse,exitCodeOf,holdSignals,liveRegion,privateLogDirectory,runMain,liveSessions,currentSession}from"./chunk-18nqpwfh.js";import process3 from"process";import{existsSync,mkdirSync,readdirSync,readFileSync,rmSync}from"fs";import{availableParallelism}from"os";import{join}from"path";import process2 from"process";import{closeSync,constants,ftruncateSync,openSync,writeSync}from"fs";import process from"process";import{dlopen,FFIType}from"bun:ffi";var LOCK_EX=2,LOCK_NB=4,flock;function native(){return flock??=dlopen(process.platform==="darwin"?"libSystem.B.dylib":"libc.so.6",{flock:{args:[FFIType.i32,FFIType.i32],returns:FFIType.i32}}).symbols.flock,flock}function tryLock(path){let fd=openSync(path,constants.O_RDWR|constants.O_CREAT,384);if(native()(fd,LOCK_EX|LOCK_NB)!==0){closeSync(fd);return}return{fd,release:()=>closeSync(fd)}}function writeHeld(held,text){ftruncateSync(held.fd),writeSync(held.fd,text,0)}var RUN_USAGE=`slot [options] -- <cmd>...: waits in FIFO order for free machine-wide slots, then runs the command and exits with its code
|
|
4
4
|
slot ls [--json]: lists who holds a slot or a lock and who waits for one (slot ls --help)
|
|
5
5
|
|
|
6
6
|
Slots and locks are shared across sessions, worktrees and shells of this user; one is freed the moment its holder ends, SIGKILL included.
|
|
7
7
|
A slotted command running slot again does not wait for a second slot, preventing deadlock. Use --weight <k> to reserve k slots at once or --exclusive to hold all slots. Pass \`slot -- ls\` to run the ls command.`,RUN_EXITS=[[0,"the command did"],["its own","the code of a command that failed"],[2,"it timed out waiting for the slot or a usage error"],[127,"the command cannot be started"]],LS_USAGE=`slot ls [options]: lists the slots and locks held, with the session, the command and how long ago it started, then who waits for one
|
|
8
8
|
|
|
9
|
-
--json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`,SLOTS={type:"string",short:"n",description:"how many commands may hold a slot at once (config.jsonc#slot.slots, else half CPU count)"},RUN_OPTIONS={lock:{type:"string",short:"l",multiple:!0,description:"a named lock to hold as well, for what must not run twice at once (shop-test-db)"},"no-slot":{type:"boolean",description:"take the --lock alone, without a slot"},weight:{type:"string",short:"w",description:"how many slots this command reserves at once (1)"},exclusive:{type:"boolean",short:"x",description:"reserve all slots at once (same as --weight <slots>)"},slots:SLOTS,timeout:{type:"string",short:"t",description:"how long to wait before giving up (30s, 5m, 1h, a bare number in seconds), forever by default"}},LS_OPTIONS={slots:SLOTS,json:jsonOption()},POLL=250,COMMAND_WIDTH=60,LOCK_NAME=/^\w[\w.-]*$/,HOLDING="SLOT_HOLDING";function defaultSlots(){return configuredNumber("slot","slots",Math.max(1,Math.floor(availableParallelism()/2)))}async function stateDir(){let dir=process2.env.SLOT_DIR??await privateLogDirectory("slot");for(let sub of["slots","locks","waiters"])mkdirSync(join(dir,sub),{recursive:!0,mode:448});return dir}function readHolder(path){try{let holder=JSON.parse(readFileSync(path,"utf8"));return typeof holder.pid==="number"&&typeof holder.command==="string"?{pid:holder.pid,command:holder.command,cwd:holder.cwd??"",since:holder.since??0,...holder.session===void 0?{}:{session:holder.session},...holder.resource===void 0?{}:{resource:holder.resource}}:void 0}catch{return}}function pathOf(dir,kind,name){return join(dir,kind==="slot"?"slots":"locks",name)}function candidates(dir,{kind,name,count}){if(kind==="lock")return[{path:pathOf(dir,"lock",name),resource:`lock ${name}`}];return Array.from({length:count},(_,index)=>({path:pathOf(dir,"slot",String(index)),resource:`slot ${index+1}`}))}function attempt(dir,wanted){let taken=[];for(let{path,resource}of candidates(dir,wanted)){let held=tryLock(path);if(held!==void 0){if(taken.push({held,resource}),taken.length===wanted.weight)return taken}}for(let{held}of taken)held.release();return}function who(holder){return`${holder.session??`pid ${holder.pid}`} running ${truncate(holder.command,COMMAND_WIDTH)} for ${formatDuration(Date.now()-holder.since)}`}function waitingLine(dir,wanted){let holders=candidates(dir,wanted).map(({path})=>readHolder(path)).filter((holder)=>holder!==void 0).sort((a,b)=>a.since-b.since),oldest=holders[0],by=oldest===void 0?"another process":who(oldest);if(wanted.kind==="lock")return`slot: waiting for lock ${wanted.name}, held by ${by}`;return`slot: waiting for ${wanted.weight>1?`${wanted.weight} slots`:"a slot"} (${holders.length} of ${wanted.count} busy), the oldest held by ${by}`}async function holderOf(command){let session=await currentSession(await liveSessions());return{pid:process2.pid,command:command.join(" "),cwd:process2.cwd(),since:Date.now(),...session===void 0?{}:{session:session.name}}}var waiterCount=0;function resourceLabel(wanted){return wanted.kind==="lock"?`lock ${wanted.name}`:"slot"}function hasOlderWaiter(dir,myName,resources){let folder=join(dir,"waiters");if(!existsSync(folder))return!1;let wantedLabels=new Set(resources.map(resourceLabel));for(let name of readdirSync(folder).sort()){if(myName!==void 0&&name>=myName)break;let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){rmSync(path,{force:!0}),probe.release();continue}let holder=readHolder(path);if(holder===void 0||holder.resource===void 0||wantedLabels.has(holder.resource))return!0}return!1}async function acquire(dir,resources,holder,deadline,timeoutMs){let waiter,region,currentBusy=resources[0],started=Date.now(),{dim}=paint(process2.stderr);try{for(;;){let blockedByQueue=hasOlderWaiter(dir,waiter?.name,resources),taken=[],busy=blockedByQueue?resources[0]:void 0;if(!blockedByQueue)for(let wanted of resources){let got=attempt(dir,wanted);if(got===void 0){busy=wanted;break}taken.push(...got)}if(busy===void 0){for(let{held}of taken)writeHeld(held,JSON.stringify(holder));return taken}for(let{held}of taken)held.release();currentBusy=busy;let resource=resourceLabel(busy);if(waiter===void 0){let name=`${String(Date.now()).padStart(15,"0")}-${String(process2.pid).padStart(8,"0")}-${waiterCount++}`,path=join(dir,"waiters",name),held=tryLock(path);if(held!==void 0)writeHeld(held,JSON.stringify({...holder,resource})),waiter={held,path,name,resource};if(process2.stderr.isTTY)region=liveRegion((spinner)=>[`${spinner} ${waitingLine(dir,currentBusy)} ${dim(formatElapsed(Date.now()-started))}`]);else
|
|
9
|
+
--json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`,SLOTS={type:"string",short:"n",description:"how many commands may hold a slot at once (config.jsonc#slot.slots, else half CPU count)"},RUN_OPTIONS={lock:{type:"string",short:"l",multiple:!0,description:"a named lock to hold as well, for what must not run twice at once (shop-test-db)"},"no-slot":{type:"boolean",description:"take the --lock alone, without a slot"},weight:{type:"string",short:"w",description:"how many slots this command reserves at once (1)"},exclusive:{type:"boolean",short:"x",description:"reserve all slots at once (same as --weight <slots>)"},slots:SLOTS,timeout:{type:"string",short:"t",description:"how long to wait before giving up (30s, 5m, 1h, a bare number in seconds), forever by default"}},LS_OPTIONS={slots:SLOTS,json:jsonOption()},POLL=250,COMMAND_WIDTH=60,LOCK_NAME=/^\w[\w.-]*$/,HOLDING="SLOT_HOLDING";function defaultSlots(){return configuredNumber("slot","slots",Math.max(1,Math.floor(availableParallelism()/2)))}async function stateDir(){let dir=process2.env.SLOT_DIR??await privateLogDirectory("slot");for(let sub of["slots","locks","waiters"])mkdirSync(join(dir,sub),{recursive:!0,mode:448});return dir}function readHolder(path){try{let holder=JSON.parse(readFileSync(path,"utf8"));return typeof holder.pid==="number"&&typeof holder.command==="string"?{pid:holder.pid,command:holder.command,cwd:holder.cwd??"",since:holder.since??0,...holder.session===void 0?{}:{session:holder.session},...holder.resource===void 0?{}:{resource:holder.resource}}:void 0}catch{return}}function pathOf(dir,kind,name){return join(dir,kind==="slot"?"slots":"locks",name)}function candidates(dir,{kind,name,count}){if(kind==="lock")return[{path:pathOf(dir,"lock",name),resource:`lock ${name}`}];return Array.from({length:count},(_,index)=>({path:pathOf(dir,"slot",String(index)),resource:`slot ${index+1}`}))}function attempt(dir,wanted){let taken=[];for(let{path,resource}of candidates(dir,wanted)){let held=tryLock(path);if(held!==void 0){if(taken.push({held,resource}),taken.length===wanted.weight)return taken}}for(let{held}of taken)held.release();return}function who(holder){return`${holder.session??`pid ${holder.pid}`} running ${truncate(holder.command,COMMAND_WIDTH)} for ${formatDuration(Date.now()-holder.since)}`}function waitingLine(dir,wanted){let holders=candidates(dir,wanted).map(({path})=>readHolder(path)).filter((holder)=>holder!==void 0).sort((a,b)=>a.since-b.since),oldest=holders[0],by=oldest===void 0?"another process":who(oldest);if(wanted.kind==="lock")return`slot: waiting for lock ${wanted.name}, held by ${by}`;return`slot: waiting for ${wanted.weight>1?`${wanted.weight} slots`:"a slot"} (${holders.length} of ${wanted.count} busy), the oldest held by ${by}`}async function holderOf(command){let session=await currentSession(await liveSessions());return{pid:process2.pid,command:command.join(" "),cwd:process2.cwd(),since:Date.now(),...session===void 0?{}:{session:session.name}}}var waiterCount=0;function resourceLabel(wanted){return wanted.kind==="lock"?`lock ${wanted.name}`:"slot"}function hasOlderWaiter(dir,myName,resources){let folder=join(dir,"waiters");if(!existsSync(folder))return!1;let wantedLabels=new Set(resources.map(resourceLabel));for(let name of readdirSync(folder).sort()){if(myName!==void 0&&name>=myName)break;let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){rmSync(path,{force:!0}),probe.release();continue}let holder=readHolder(path);if(holder===void 0||holder.resource===void 0||wantedLabels.has(holder.resource))return!0}return!1}async function acquire(dir,resources,holder,deadline,timeoutMs){let waiter,region,currentBusy=resources[0],started=Date.now(),{dim}=paint(process2.stderr);try{for(;;){let blockedByQueue=hasOlderWaiter(dir,waiter?.name,resources),taken=[],busy=blockedByQueue?resources[0]:void 0;if(!blockedByQueue)for(let wanted of resources){let got=attempt(dir,wanted);if(got===void 0){busy=wanted;break}taken.push(...got)}if(busy===void 0){for(let{held}of taken)writeHeld(held,JSON.stringify(holder));return taken}for(let{held}of taken)held.release();currentBusy=busy;let resource=resourceLabel(busy);if(waiter===void 0){let name=`${String(Date.now()).padStart(15,"0")}-${String(process2.pid).padStart(8,"0")}-${waiterCount++}`,path=join(dir,"waiters",name),held=tryLock(path);if(held!==void 0)writeHeld(held,JSON.stringify({...holder,resource})),waiter={held,path,name,resource};if(process2.stderr.isTTY)region=liveRegion((spinner)=>[`${spinner} ${waitingLine(dir,currentBusy)} ${dim(formatElapsed(Date.now()-started))}`]);else writeErr(waitingLine(dir,busy))}else if(waiter.resource!==resource)writeHeld(waiter.held,JSON.stringify({...holder,resource})),waiter.resource=resource;if(Date.now()>=deadline)fail(`gave up after ${formatDuration(timeoutMs)} waiting for ${busy.kind==="lock"?`lock ${busy.name}`:"a slot"}`);await Bun.sleep(POLL)}}finally{if(region?.stop(),waiter!==void 0)rmSync(waiter.path,{force:!0}),waiter.held.release()}}function withSeparator(args){let takesValue=(word)=>Object.entries(RUN_OPTIONS).some(([name,option])=>option.type==="string"&&(word===`--${name}`||("short"in option)&&word===`-${option.short}`));for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")return args;if(!word.startsWith("-"))return[...args.slice(0,at),"--",...args.slice(at)];if(takesValue(word))at++}return args}async function runSlotted(given){let args=withSeparator(given),parsed=parse(args,RUN_USAGE,RUN_OPTIONS,{rest:!0,exits:RUN_EXITS,replaces:"flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database",examples:[["slot -- bunx vue-tsc","wait for a free slot, then type-check"],["slot --lock shop-test-db -- vendor/bin/phpunit","one phpunit at a time on the shared test database"],["slot -w 2 -- bun test","reserve 2 slots for a heavy test run"],"slot ls"]}),{values,rest}=parsed;if(rest===void 0||rest.length===0)fail(`give the command after --
|
|
10
10
|
|
|
11
11
|
${RUN_USAGE}`);let locks=[...new Set(values.lock??[])].sort();for(let name of locks)if(!LOCK_NAME.test(name))fail(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);if(values["no-slot"]===!0&&locks.length===0)fail("--no-slot takes the --lock alone, and none is given");if(values["no-slot"]===!0&&(values.weight!==void 0||values.exclusive===!0))fail("--weight and --exclusive cannot be used with --no-slot");if(values.weight!==void 0&&values.exclusive===!0)fail("give either --weight or --exclusive, not both");let count=wholeNumber(values.slots,"slots",defaultSlots()),weight=values.exclusive===!0?count:wholeNumber(values.weight,"weight",1,1);if(weight>count)fail(`--weight ${weight} exceeds total slots (${count})`);let timeoutMs=duration(values.timeout,"timeout",Number.POSITIVE_INFINITY),deadline=Date.now()+timeoutMs,holding=new Set((process2.env[HOLDING]??"").split(",").filter((token)=>token!=="")),wanted=[...locks.filter((name)=>!holding.has(`lock:${name}`)).map((name)=>({kind:"lock",name,count,weight:1})),...values["no-slot"]===!0||holding.has("slot")?[]:[{kind:"slot",name:"",count,weight}]],signals=holdSignals(()=>{return}),taken=[];try{if(wanted.length>0){let dir=await stateDir(),holder=await holderOf(rest);taken.push(...await acquire(dir,wanted,holder,deadline,timeoutMs))}let tokens=new Set([...holding,...locks.map((name)=>`lock:${name}`),...wanted.some((resource)=>resource.kind==="slot")?["slot"]:[]]),child;try{child=Bun.spawn(rest,{stdio:["inherit","inherit","inherit"],env:{...process2.env,[HOLDING]:[...tokens].join(",")}})}catch(error){fail(`cannot run ${rest[0]}: ${error instanceof Error?error.message:String(error)}`,127)}return signals.forward(child),await child.exited,exitCodeOf(child.exitCode,child.signalCode)}finally{signals.release();for(let{held}of taken)held.release()}}function scan(dir,state,kind){let folder=join(dir,kind),entries=[];for(let name of existsSync(folder)?readdirSync(folder):[]){let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){if(kind==="waiters")rmSync(path,{force:!0});probe.release();continue}let holder=readHolder(path),resource=kind==="waiters"?holder?.resource??"slot":`${kind==="slots"?"slot":"lock"} ${kind==="slots"?Number(name)+1:name}`;entries.push({state,resource,pid:holder?.pid??0,command:holder?.command??"?",cwd:holder?.cwd??"",since:holder?.since??0,...holder?.session===void 0?{}:{session:holder.session}})}return entries}async function listSlots(args){let{values}=parse(args,LS_USAGE,LS_OPTIONS,{exits:[[0,"it listed them"],[2,"a usage error"]],examples:["slot ls","slot ls --json"]}),count=wholeNumber(values.slots,"slots",defaultSlots()),dir=await stateDir(),holding=[...scan(dir,"holding","slots"),...scan(dir,"holding","locks")].sort((a,b)=>a.since-b.since),waiting=scan(dir,"waiting","waiters").sort((a,b)=>a.since-b.since),entries=[...holding,...waiting],busy=holding.filter((entry)=>entry.resource.startsWith("slot ")).length;if(values.json===!0)return printJson({slots:count,busy,entries}),0;if(console.log(paint(process2.stdout).bold(`slots: ${busy} of ${count} busy`)),entries.length>0)console.log(table(entries.map((entry)=>[badge(entry.state,process2.stdout),entry.resource,entry.session??`pid ${entry.pid}`,truncate(entry.command,COMMAND_WIDTH),entry.since===0?"?":formatAge(entry.since)])));return 0}process3.exitCode=await runMain({name:"slot",run:async(args)=>args[0]==="ls"?listSlots(args.slice(1)):runSlotted(args)});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-wait",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.14.0",
|
|
5
5
|
"description": "waitfor and slot: waits for a log line, a listening port or a URL answering, and queues heavy commands behind machine-wide slots and named locks, for Claude Code, instead of sleep and polling loops.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -35,6 +35,6 @@
|
|
|
35
35
|
"waitfor": "$npm_execpath src/cli.ts"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@kaynooo/cli-kit": "0.
|
|
38
|
+
"@kaynooo/cli-kit": "0.52.1"
|
|
39
39
|
}
|
|
40
40
|
}
|