@kaynooo/cli-wait 0.14.0 → 0.16.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 +26 -22
- package/dist/chunk-90ewdkej.js +2 -0
- package/dist/chunk-cwtbc9w7.js +16 -0
- package/dist/chunk-k8551tyv.js +4 -0
- package/dist/chunk-q23bt6dr.js +66 -0
- package/dist/cli.js +16 -18
- package/dist/slot-cli.js +4 -6
- package/package.json +2 -2
- package/dist/chunk-18nqpwfh.js +0 -76
package/README.md
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
# waitfor and slot
|
|
2
2
|
|
|
3
|
-
Two
|
|
3
|
+
Two bins in one package: [`waitfor`](#waitfor) waits for something to happen, [`slot`](#slot) queues heavy commands in FIFO order. Install both with `bun install -g @kaynooo/cli-wait`.
|
|
4
4
|
|
|
5
5
|
# waitfor
|
|
6
6
|
|
|
7
7
|
Waits for a background build or server for Claude Code, where a session would otherwise `sleep 30; tail -c 2000 build.log` or hand-write an `until` loop: `waitfor` returns as soon as the log line shows, the port listens or the URL answers, and stops early on an error line.
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
waitfor --file server.log --until 'Listening on' --fail 'Error|FATAL' --timeout 2m
|
|
10
|
+
waitfor --file server.log --from-end --until 'Listening on' --fail 'Error|FATAL' --timeout 2m
|
|
11
11
|
waitfor --file out.bin --idle 2s
|
|
12
|
-
waitfor --port 5432
|
|
12
|
+
waitfor --port 5432 --while-pid 1234
|
|
13
13
|
waitfor --port-free 8000
|
|
14
|
-
waitfor --url http://localhost:8000/health
|
|
14
|
+
waitfor --url http://localhost:8000/health -H 'Authorization: Bearer ...'
|
|
15
|
+
waitfor --healthy db
|
|
15
16
|
waitfor --pid 4242
|
|
16
17
|
waitfor --cmd 'curl -fs localhost:8000/health'
|
|
17
18
|
waitfor --any --port 5432 --cmd 'test -f ready' -t 1m
|
|
@@ -20,30 +21,33 @@ waitfor task b92stimuo
|
|
|
20
21
|
|
|
21
22
|
## Behaviour
|
|
22
23
|
|
|
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.
|
|
24
|
+
- `--file` is read from its start (or from the current end with `--from-end`), 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.
|
|
24
25
|
- `--until <regex>` waits for a line of `--file` to match and prints it as `<file>:<line>: <text>`.
|
|
25
26
|
- `--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.
|
|
26
27
|
- `--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
28
|
- `--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 `--
|
|
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`,
|
|
30
|
-
- `--
|
|
29
|
+
- `--port`, `--port-free`, `--url` and `--healthy` 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.
|
|
30
|
+
- `--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, `-H` / `--header "Name: value"` adds repeatable request headers, and `-k` / `--insecure` ignores untrusted TLS certificates. With several `--url`, all apply to every one.
|
|
31
|
+
- `--healthy <service>` waits until a Docker Compose service or container reports `healthy`.
|
|
32
|
+
- `--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. `--while-pid <n>` aborts immediately with exit 1 if that process exits before the conditions are met. A `--port` connection attempt is given up after 3 seconds and retried, so dropped packets do not hold a poll for minutes.
|
|
31
33
|
- `--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.
|
|
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.
|
|
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,
|
|
34
|
-
- `--json` prints `{met, ms, line}`
|
|
34
|
+
- `--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 or `--while-pid` exit still ends the wait with 1.
|
|
35
|
+
- `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, 124 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 `{met, task, path, code, ms, failures, tail, reason?}`, each line as `{number, text}`.
|
|
36
|
+
- `--json` prints `{met, ms, line, conditions, reason?, pending?}` on stdout on success (`met: true`, exit 0), `--fail` or `--while-pid` (`met: false`, exit 1), and timeout (`met: false, reason: "timeout"`, exit 124); progress lines go to stderr. `--quiet` drops the live progress line, on `waitfor task` too.
|
|
35
37
|
- 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.
|
|
36
|
-
- `--timeout` takes `30s`, `5m`, `1h` or a bare number of seconds, 5 minutes by default. On a timeout stderr names what is still missing (the file absent, the connection error, the status answered) and the file's last 20 lines.
|
|
37
|
-
- Exit codes: 0 every condition met, 1 a `--fail` line,
|
|
38
|
+
- `--timeout` takes `30s`, `5m`, `1h` or a bare number of seconds, 5 minutes by default. On a timeout stderr names what is still missing (the file absent, the connection error, the status answered) and the file's last 20 lines (unless `--json` is passed).
|
|
39
|
+
- Exit codes: 0 every condition met, 1 a `--fail` line or `--while-pid` exit, 124 a timeout, 2 a usage error.
|
|
38
40
|
- Named `waitfor` so as not to shadow the shell's `wait`.
|
|
39
41
|
|
|
40
42
|
# slot
|
|
41
43
|
|
|
42
|
-
Heavy commands from parallel Claude Code sessions (phpunit, playwright, vue-tsc, eslint) queue behind a machine-wide set of slots instead of overloading the machine, and a named lock keeps two runs off one shared resource such as a test database.
|
|
44
|
+
Heavy commands from parallel Claude Code sessions (phpunit, playwright, vue-tsc, eslint) queue in FIFO order behind a machine-wide set of slots instead of overloading the machine, and a named lock keeps two runs off one shared resource such as a test database.
|
|
43
45
|
|
|
44
46
|
```sh
|
|
45
47
|
slot -- bunx vue-tsc
|
|
46
48
|
slot --lock shop-test-db -- vendor/bin/phpunit
|
|
49
|
+
slot -w 2 -- bun test
|
|
50
|
+
slot --exclusive -- bun run build
|
|
47
51
|
slot -n 6 -t 10m -- bun test
|
|
48
52
|
slot ls
|
|
49
53
|
check --slot
|
|
@@ -51,16 +55,16 @@ check --slot
|
|
|
51
55
|
|
|
52
56
|
## Behaviour
|
|
53
57
|
|
|
54
|
-
- `slot -- <cmd>` waits for
|
|
55
|
-
- `--
|
|
56
|
-
-
|
|
58
|
+
- `slot -- <cmd>` waits in FIFO order for free slots, runs the command with the terminal's stdin, stdout and stderr and exits with its code (a signal's `128 + n`, 127 when it cannot start). The slots are shared by every session, worktree and shell of the user; there are half as many as CPUs by default (`config.jsonc#slot.slots` overrides it), and `-n` / `--slots` sets the count.
|
|
59
|
+
- `--weight <k>` (`-w`) reserves `k` slots at once for heavy workloads; `--exclusive` (`-x`) reserves all slots at once.
|
|
60
|
+
- `--lock <name>` (`-l`) also holds a named lock, repeatable, across sessions and worktrees. The locks and the slots are taken all together or not at all: a command waiting for one gives back what it got and registers a FIFO waiter ticket so earlier waiters are served before later arrivals. `--no-slot` takes the locks alone.
|
|
61
|
+
- Slots, locks and FIFO waiter tickets are `flock`s on files, called through `bun:ffi`: the kernel drops one with its holder, so a `slot` killed with SIGKILL frees what it held immediately and stale waiters are cleaned automatically. The command it started is not killed with it: it keeps running with its slot and lock already freed, so the lock no longer protects it.
|
|
57
62
|
- A `slot` inside a slotted command does not wait for another slot or for a lock the outer one holds (the `SLOT_HOLDING` variable lists them), so a script and the commands it runs may both be wrapped, and `check --slot` over a script calling `slot --lock` cannot deadlock against a session waiting for a slot while it holds that lock, since a waiter holds nothing.
|
|
58
|
-
- When it has to wait, stderr
|
|
59
|
-
- `slot ls` lists the holders (`slot 2`, `lock shop-test-db`) and the waiters with their session (
|
|
60
|
-
- `slot ls` is the listing even as a first word, `slot -- ls` being read as `slot ls` because Bun drops a leading `--`: write `slot -n 4 -- ls` for the command.
|
|
63
|
+
- When it has to wait, a human terminal shows a live spinner on stderr; pipes, CI and agents (even on a PTY) get a single diagnostic line naming who holds what it needs: the session, the command and for how long. `--timeout` (`-t`, `30s`, `5m`, a bare number of seconds) gives up with exit `124`; it waits forever by default.
|
|
64
|
+
- `slot ls` (alias `slot list`) lists the holders (`slot 2`, `lock shop-test-db`) and the waiters with their session (through `~/.claude/sessions`), command and age, `--json` as `{slots, busy, entries}`. Pass `slot -- ls` to run the `ls` command itself.
|
|
61
65
|
- State lives in `$XDG_RUNTIME_DIR/kaynooo-cli/slot` (`~/.cache/kaynooo-cli/slot` without it), only the user can enter it; `$SLOT_DIR` points elsewhere.
|
|
62
|
-
- Exit codes: the command's,
|
|
66
|
+
- Exit codes: the command's own, 124 on a timeout, 2 on a usage error, 127 when the command cannot start.
|
|
63
67
|
|
|
64
68
|
## Config
|
|
65
69
|
|
|
66
|
-
`~/.config/kaynooo-cli/wait.json` (`$XDG_CONFIG_HOME/kaynooo-cli/` when set) takes positive whole numbers: `tail` (20, the lines of a file kept for a timeout excerpt), `around` (5, the lines kept on each side of a failure line) and `portTimeoutMs` (3000, how long one port probe waits).
|
|
70
|
+
`~/.config/kaynooo-cli/wait.json` (`$XDG_CONFIG_HOME/kaynooo-cli/` when set) takes positive whole numbers: `tail` (20, the lines of a file kept for a timeout excerpt), `around` (5, the lines kept on each side of a failure line) and `portTimeoutMs` (3000, how long one port probe waits). `slot.slots` in `config.jsonc` (or `slot.json`) sets the default slot count.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{AsyncLocalStorage}from"async_hooks";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"}function isHumanTerminal(stream=process.stdout,env=process.env){return outputMode(stream,env)==="terminal"}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:"#7dd3fc",id:"#ecd8a6",path:"#93c5fd",label:"#9aa5b4",value:"bold",hairline:"#7e8a9c",ok:"#7ee787",warn:"#f2cc60",problem:"#ff8b8b",note:"#9aa5b4",plan:"#c4b5fd",passed:"#7ee787",failed:"#ff8b8b",running:"#7dd3fc",queued:"#f2cc60",skipped:"#9aa5b4"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",halfBar:"\u2578",track:"\u2500",rule:"\u2500",corner:"\u256D",head:"\u25B8",branch:"\u251C",last:"\u2514",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["#7dd3fc","#c4b5fd","#7ee787","#93c5fd","#f2cc60","#ff8b8b"],bins:{},gradient:["#a5b4fc","#7dd3fc"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",hairline:"white",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",hairline:"#a1a1aa",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",hairline:"dim",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:"#",halfBar:"#",track:"-",rule:"-",corner:"+",head:">",branch:"+",last:"+",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);if(!takesControlCodes(stream,env))return`${MARK_WORDS[mark]} ${text}${detail===void 0?"":` ${detail}`}`;let{theme}=activeTheme(),head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark]),tail=detail===void 0?"":` ${tinted(colors,theme.colors.label,env)(detail)}`;return`${head} ${text}${tail}`}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(`
|
|
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());if(!header||!takesControlCodes(stream,env))return lines.join(`
|
|
6
|
+
`);let{theme}=activeTheme(),headerTint=tinted(colors,theme.colors.label,env),ruleText=widths.map((width)=>theme.glyphs.rule.repeat(width)).join(" ").trimEnd(),rule=lines.length>1&&ruleText!==""?[tinted(colors,theme.colors.hairline,env)(ruleText)]:[];return lines.flatMap((line,index)=>index===0?[headerTint(line),...rule]:[line]).join(`
|
|
7
|
+
`)}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(`
|
|
8
|
+
`),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(`
|
|
9
|
+
`)}`,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(`
|
|
10
|
+
`)}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(`
|
|
11
|
+
`)}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 describeOptions(options){return Object.entries(options).map(([name,{type,short,description:text,choices,multiple}])=>({name,type,...short===void 0?{}:{short},...text===void 0?{}:{description:text},...choices===void 0?{}:{choices:[...choices]},...multiple===!0?{multiple:!0}:{}}))}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
12
|
+
`),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:describeOptions(options)}}}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},parseContext=new AsyncLocalStorage,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,ctx=parseContext.getStore();if(ctx!==void 0)ctx.options=all,ctx.json=void 0;let 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(ctx!==void 0)ctx.json=values.json===!0;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}from"fs";import{constants}from"os";import process9 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=readFileSync3(`/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)process9.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),process9.kill(process9.pid,signal)}for(let signal of SIGNALS)process9.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)process9.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()}}}import process10 from"process";var FRAME_MS=160;var GRAPHEMES2=new Intl.Segmenter,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 liveRegion2(render,stream=process10.stderr,env=process10.env){if(!takesControlCodes(stream,env))return{redraw:()=>{return},print:(text)=>void stream.write(`${text}
|
|
13
|
+
`),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,head=activeTheme().theme.glyphs.head,lines=render(head,frame++).slice(0,Math.max(1,height-1)).map((line)=>cutToWidth(line,width));if(lines.length===0){clear();return}write(`${CLEAR_BELOW}${lines.join(`
|
|
14
|
+
`)}${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(),process10.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(),process10.on("exit",onExit),{redraw:draw,print:(text)=>{clear(),write(`${text}
|
|
15
|
+
`),draw()},stop,pause}}function swallowInput(){let input=process10.stdin;if(!input.isTTY)return()=>{return};let onData=(data)=>{if(data.includes(CTRL_C))process10.kill(process10.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]),[process10.stdout,"write"],[process10.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)}}
|
|
16
|
+
export{outputMode,isHumanTerminal,xdgFolder,configuredNumber,tinted,activeTheme,takesControlCodes,paint,writeErr,problem,badge,closest,formatDuration,formatElapsed,formatAge,truncate,table,printJson,usageLine,wantsHelpJson,description,exampleRows,optionRows,wholeNumber,duration,jsonOption,Exit,fail,UsageError,badUsage,HelpShown,Completing,completion,parseContext,OUTPUT_OPTIONS,applyOutput,parse,exitCodeOf,holdSignals,runCommand,liveRegion2};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import process from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process.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)}
|
|
3
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process.stdout.write(`${answer}
|
|
4
|
+
`),0}export{askpassClient};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{outputMode,xdgFolder,tinted,activeTheme,takesControlCodes,paint,writeErr,closest,formatDuration,usageLine,wantsHelpJson,description,exampleRows,optionRows,Exit,UsageError,HelpShown,Completing,completion,parseContext,OUTPUT_OPTIONS,applyOutput}from"./chunk-cwtbc9w7.js";import{readFileSync,realpathSync}from"fs";import{resolve}from"path";import process from"process";function commandLine(){try{return readFileSync("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve(word))}catch{return}}function scriptArgs(argv=process.argv.slice(2),cmdline=commandLine(),script=process.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&&(resolve(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{readFileSync as readFileSync3,realpathSync as realpathSync2}from"fs";import{dirname as dirname2,join as join3}from"path";import process5 from"process";var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
3
|
+
functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
4
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
5
|
+
set -l current (commandline -ct)
|
|
6
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
7
|
+
if test "$line" = __files__
|
|
8
|
+
__fish_complete_path $current
|
|
9
|
+
else
|
|
10
|
+
echo $line
|
|
11
|
+
end
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
15
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
16
|
+
__kaynooo_cli_complete() {
|
|
17
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
18
|
+
local -a lines
|
|
19
|
+
COMPREPLY=()
|
|
20
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
21
|
+
for line in "\${lines[@]}"; do
|
|
22
|
+
if [[ $line == __files__ ]]; then
|
|
23
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
24
|
+
else
|
|
25
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
26
|
+
fi
|
|
27
|
+
done
|
|
28
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
29
|
+
}
|
|
30
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
31
|
+
`;return`${header}
|
|
32
|
+
__kaynooo_cli_complete() {
|
|
33
|
+
local line
|
|
34
|
+
local -a described plain
|
|
35
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
36
|
+
if [[ $line == __files__ ]]; then
|
|
37
|
+
_files
|
|
38
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
39
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
40
|
+
else
|
|
41
|
+
plain+=("$line")
|
|
42
|
+
fi
|
|
43
|
+
done
|
|
44
|
+
(( \${#described} )) && _describe -V value described
|
|
45
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
46
|
+
return 0
|
|
47
|
+
}
|
|
48
|
+
__kaynooo_cli_register() {
|
|
49
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
50
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
51
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
52
|
+
}
|
|
53
|
+
autoload -Uz add-zsh-hook
|
|
54
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
55
|
+
typeset -gaU __kaynooo_cli_bins
|
|
56
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
57
|
+
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";function shown(commands){return Object.fromEntries(Object.entries(commands).filter(([,{hidden}])=>hidden!==!0))}async function resolveSummary(summary){return typeof summary==="string"?summary:summary()}function lookup({commands,aliases},word){let name=aliases!==void 0&&Object.hasOwn(aliases,word)?aliases[word]??word:word;return Object.hasOwn(commands,name)?commands[name]:void 0}function scopeOf(commands,extra,aliases){return{commands:typeof commands==="function"?{}:commands,lazy:[...typeof commands==="function"?[commands]:[],...extra===void 0?[]:[extra]],aliases}}async function expand(scope,words){if(scope.lazy.length===0)return scope;let commands={...scope.commands};for(let added of await Promise.all(scope.lazy.map(async(lazy)=>lazy(words))))for(let[name,command]of Object.entries(added))commands[name]??=command;return{...scope,commands,lazy:[]}}async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}async function optionsOf(run){return(await completingOf(run)).options}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}async function candidates(scope,defaultCommand,words,before=[]){let[word="",...rest]=words,listing=rest.length===0&&!word.startsWith("-"),{commands}=scope,command=lookup(scope,word);if(listing||command===void 0){let expanded=await expand(scope,[...before,...words]);commands=expanded.commands,command=lookup(expanded,word)}if(listing){let own=await Promise.all(Object.entries(shown(commands)).map(async([name,{summary}])=>`${name} ${await resolveSummary(summary)}`)),fallback=defaultCommand===void 0?void 0:commands[defaultCommand],values=fallback!==void 0&&"run"in fallback?await leafCandidates(fallback.run,[word]):[],valueOf=(line)=>line.slice(0,line.includes("\t")?line.indexOf("\t"):void 0);return[...own,...values.filter((line)=>line!==FILES&&!Object.hasOwn(commands,valueOf(line)))]}if(command===void 0){let fallback=defaultCommand===void 0?void 0:commands[defaultCommand];return fallback!==void 0&&"run"in fallback?leafCandidates(fallback.run,words):[]}return"commands"in command?candidates(scopeOf(command.commands,command.extraCommands,command.aliases),command.defaultCommand,rest,[...before,word]):leafCandidates(command.run,rest)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}import process2 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process2.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process2.pid}`,codes=[`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`,`\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process2.stderr,env=process2.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}import{appendFileSync,mkdirSync,readFileSync as readFileSync2,renameSync,statSync,writeFileSync}from"fs";import{homedir as homedir2}from"os";import{dirname,join as join2}from"path";import process4 from"process";import{lstatSync,openSync}from"fs";import{mkdir,mkdtemp,readdir,rm,stat}from"fs/promises";import{homedir,tmpdir}from"os";import{join}from"path";import process3 from"process";var CLI_FOLDER="kaynooo-cli";function isPrivateDirectory(path){try{let info=lstatSync(path,{throwIfNoEntry:!1});return info!==void 0&&info.isDirectory()&&info.uid===(process3.getuid?.()??info.uid)&&(info.mode&63)===0}catch{return!1}}async function privateLogDirectory(name,env=process3.env){let path=join(xdgFolder(env.XDG_RUNTIME_DIR,join(homedir(),".cache")),CLI_FOLDER,name);try{if(await mkdir(path,{recursive:!0,mode:448}),isPrivateDirectory(path))return path}catch{}return mkdtemp(join(tmpdir(),`${name.replaceAll("/","-")}-`))}var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process4.env){return xdgFolder(env.XDG_STATE_HOME,join2(homedir2(),".local","state"))}function usagePath(env=process4.env){return join2(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process4.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,mode,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)},...mode===void 0?{}:{mode}}}function trimUsage(path,maxBytes){let info=statSync(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync2(path,"utf8").split(`
|
|
58
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
59
|
+
`)}
|
|
60
|
+
`,temp=`${path}.${process4.pid}.tmp`;writeFileSync(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process4.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync(dirname(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
61
|
+
`,{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"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let label=group===void 0?"Commands:":`${group}:`,rows=groups.get(label)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(label,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([label,rows],index)=>[...index===0?[]:[""],colors.bold(label),...rows])}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function help({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream,json=!1){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(json||wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
|
|
62
|
+
`)}var HINT_CODE=/`[^`\n]+`/g;function styleHint(text,accent){return text.replaceAll(HINT_CODE,(match)=>accent(match))}function printError(prefix,message,hint,cause){if(!takesControlCodes(process5.stderr)){let causeLine=cause===void 0?"":`
|
|
63
|
+
cause: ${cause}`,hintLine=hint===void 0?"":`
|
|
64
|
+
hint: ${hint}`;writeErr(`error: ${prefix}: ${message}${causeLine}${hintLine}`);return}let colors=paint(process5.stderr),{theme}=activeTheme(),mark=tinted(colors.bold,theme.colors.problem)(theme.glyphs.problem),muted=tinted(colors,theme.colors.label),warn=tinted(colors,theme.colors.warn),accent=tinted(colors,theme.colors.accent),causeLine=cause===void 0?"":`
|
|
65
|
+
${muted("cause")} ${cause}`,hintLine=hint===void 0?"":`
|
|
66
|
+
${warn("hint")} ${styleHint(hint,accent)}`;writeErr(`${mark} ${colors.bold(prefix)}${muted(":")} ${message}${causeLine}${hintLine}`)}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}}))}var LEVEL_VALUE_FLAGS=new Set(["--color","--completions"]);function wantsJson(argv,options){let json=!1;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--")break;if(arg==="--json"){json=!0;continue}if(arg==="--no-json"){json=!1;continue}if(LEVEL_VALUE_FLAGS.has(arg)){i++;continue}if(options!==void 0&&arg.startsWith("-")&&!arg.includes("=")){if(Object.entries(options).some(([name,{short,type}])=>type==="string"&&(arg===`--${name}`||arg===`-${short}`))&&argv[i+1]!==void 0&&!(argv[i+1]==="--json"&&Object.hasOwn(options,"json")))i++}}return json}async function maybeAskpass(argv){if(process5.env.KAYNOOO_ASKPASS_SOCKET===void 0)return;let{askpassClient}=await import("./chunk-k8551tyv.js");return askpassClient(argv)}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}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),currentPath=level.path.length>1?level.path.slice(1).join(" "):void 0,argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error,redact,wantsJson(typed)),meta:!1,command:currentPath}}let[name,...args]=argv,defaultName=level.defaultCommand,fallback=defaultName===void 0?void 0:level.commands[defaultName];if(name===void 0&&level.runBare&&defaultName!==void 0&&fallback===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),fallback=level.commands[defaultName];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback&&defaultName!==void 0){let resolved=[...level.path.slice(1),defaultName].join(" ");return parseContext.run({},async()=>{try{return{code:await fallback.run([]),meta:!1,command:resolved}}catch(error){return{code:reportThrown(`${prefix} ${defaultName}`,error,redact,!1),meta:error instanceof HelpShown,command:resolved}}})}if(name===void 0&&level.path.length>1)return writeErr(await help(await expand(level,[...level.path.slice(1),...argv]),process5.stderr)),{code:2,meta:!0,command:currentPath};if(name==="help"&&args.length>0&&args[0]!=="--json")return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h"||name==="--help=json")return console.log(await help(await expand(level,[...level.path.slice(1),...argv]),process5.stdout,wantsHelpJson(process5.env,argv))),{code:0,meta:!0,command:currentPath};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0,command:void 0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands))),hint=meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`;if(wantsJson(argv))printJsonError(`no command ${name}`,hint,void 0,{code:2,command:prefix});else printError(prefix,`no command ${name}`,hint);return{code:2,meta:!1,command:currentPath}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,ran],header:(colors,text)=>`${colors.bold(`${prefix} ${ran}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:command.defaultCommand,runBare:command.runBare===!0,examples:command.examples,replaces:void 0},rest,{version,redact})}let resolved=[...level.path.slice(1),ran].join(" "),leaf=command;return parseContext.run({},async()=>{try{return{code:await leaf.run(rest),meta:!1,command:resolved}}catch(error){let ctx=parseContext.getStore(),json=ctx?.json??wantsJson(rest,ctx?.options);return{code:reportThrown(`${prefix} ${ran}`,error,redact,json),meta:error instanceof HelpShown,command:resolved}}})}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname2(resolved);;dir=dirname2(dir)){try{let{version}=JSON.parse(readFileSync3(join3(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname2(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await maybeAskpass(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv),printError);let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta,command}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact});if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}import{homedir as homedir3}from"os";import{join as join4}from"path";import process6 from"process";var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");async function sessionDirs(){let home=process6.env.HOME??homedir3(),dirs=new Set([join4(home,".claude","sessions")]);if(process6.env.CLAUDE_CONFIG_DIR!==void 0)dirs.add(join4(process6.env.CLAUDE_CONFIG_DIR,"sessions"));try{for await(let dir of ACCOUNT_DIRS.scan({cwd:join4(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=process6.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 dirname3,join as join5,relative,sep}from"path";var PARENT=`..${sep}`;export{privateLogDirectory,runCli,liveSessions,currentSession};
|
package/dist/cli.js
CHANGED
|
@@ -1,24 +1,22 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{configuredNumber,paint,writeErr,problem,formatDuration,formatElapsed,truncate,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,runCommand,
|
|
4
|
-
`)
|
|
5
|
-
`)
|
|
6
|
-
`).
|
|
7
|
-
waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
|
|
3
|
+
import{configuredNumber,paint,writeErr,problem,formatDuration,formatElapsed,truncate,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,runCommand,liveRegion2}from"./chunk-cwtbc9w7.js";import{runCli}from"./chunk-q23bt6dr.js";import{existsSync as existsSync3}from"fs";import process3 from"process";import{existsSync,lstatSync,readFileSync,statSync}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_RETURN=/\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=existsSync(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 existsSync(path)&&lstatSync(path).isSymbolicLink()&&path.endsWith(".output")}async function exitCode(path){if(!existsSync(path))return;let size=statSync(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(!existsSync(path))return{failures:[],tail:[]};let all=(await Bun.file(path).text()).replace(EXITED,"").split(`
|
|
4
|
+
`).map((line,i)=>({number:i+1,text:Bun.stripANSI(line.replace(CARRIAGE_RETURN,""))}));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}}import process2 from"process";import{existsSync as existsSync2,statSync as statSync2}from"fs";var TAIL=configuredNumber("wait","tail",20),AROUND=configuredNumber("wait","around",5),CARRIAGE_RETURN2=/\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&&existsSync2(path)){let stats=statSync2(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 existsSync2(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(!existsSync2(this.path))return;let stats=statSync2(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(`
|
|
5
|
+
`);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_RETURN2,""))}))}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=statSync2(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(`
|
|
6
|
+
`).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"}}}var TIMEOUT_EXIT=124,POLL_MS=250,WIDTH=400,URL_TIMEOUT_MS=5000,CMD_RUN_LIMIT_MS=30000,LAST_LINE=/[^\n]+(?=\n*$)/,HEADER_LINE=/^[\w!#$%&'*+.^`|~-]+:/,TIMEOUT_OPTION={type:"string",short:"t",description:"how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds"},WAIT_USAGE=`waitfor [options]
|
|
8
7
|
|
|
9
|
-
|
|
8
|
+
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.
|
|
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.`,WAIT_EXITS=[[0,"every condition was met (or one with --any)"],[1,"a --fail line showed up or --while-pid exited"],[124,"it timed out"],[2,"a usage error"]],WAIT_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_OPTION,json:jsonOption("{met, ms, line, conditions: [{name, ms}], reason?, pending?}"),quiet:{type:"boolean",short:"q",description:"no live progress line: only what was met and the failure"}};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(`
|
|
10
|
+
`)}function hostPort(host,port){return`${host.includes(":")?`[${host}]`:host}:${port}`}function compileRegex(source,name){if(source===void 0)return;try{return new RegExp(source)}catch(error){return badUsage(`--${name} is no valid regular expression: ${error instanceof Error?error.message:String(error)}`)}}function parsePorts(texts,flag,defaultHost){return texts.map((text)=>{let port=wholeNumber(text,flag,0);if(port>65535)badUsage(`--${flag} takes a port up to 65535, not ${port}`);return{name:flag==="port-free"?hostPort(defaultHost,port):String(port),port,left:"not checked yet"}})}function parseHeaders(entries){let headers={};for(let entry of entries){if(!HEADER_LINE.test(entry))badUsage(`-H takes "Name: value", not ${entry}`);let at=entry.indexOf(":");headers[entry.slice(0,at).trim()]=entry.slice(at+1).trim()}return headers}function parseWaitSpec(args){let parsed=parse(args,WAIT_USAGE,WAIT_OPTIONS,{exits:WAIT_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)badUsage(`unexpected argument ${positionals[0]}`);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)badUsage("give --until or --idle with --file, --port, --port-free, --url, --healthy, --pid or --cmd");if((values.until!==void 0||values.fail!==void 0||values.idle!==void 0)!==(values.file!==void 0))badUsage("--until, --fail and --idle work with --file, and --file needs one of them");if(values["from-end"]===!0&&values.file===void 0)badUsage("--from-end goes with --file");if(values.host!==void 0&&portTexts.length===0&&portFreeTexts.length===0)badUsage("--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)badUsage("--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)badUsage("--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)badUsage("--interval goes with --cmd");let hosts=values.host===void 0?["127.0.0.1","::1"]:[values.host],ports=parsePorts(portTexts,"port",hosts[0]),freePorts=parsePorts(portFreeTexts,"port-free",hosts[0]);for(let url of urlTexts)if(!URL.canParse(url))badUsage(`--url ${url} is no URL`);let headers=parseHeaders(values.header??[]),statusTest=values.status===void 0?void 0:parseStatus(values.status);if(values.status!==void 0&&statusTest===void 0)badUsage(`--status takes a code, a range or a class such as 301, 200-299 or 2xx, not ${values.status}`);let body=compileRegex(values.body,"body"),urlExpect={...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===void 0?{}:{body}},idleMs=values.idle===void 0?void 0:duration(values.idle,"idle",0);return{hosts,ports,freePorts,urls:urlTexts.map((url)=>({name:url,left:"not checked yet"})),urlExpect,services:healthyTexts.map((service)=>({name:service,left:"not checked yet"})),watch:values.file!==void 0&&(values.until!==void 0||values.fail!==void 0)?new FileWatch(values.file,compileRegex(values.until,"until"),compileRegex(values.fail,"fail"),values["from-end"]===!0):void 0,hasUntil:values.until!==void 0,idle:values.file!==void 0&&idleMs!==void 0?new IdleWatch(values.file,idleMs):void 0,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),cmd:values.cmd,interval:duration(values.interval,"interval",1000),isAny:values.any===!0,timeout:duration(values.timeout,"timeout",300000),json:values.json===!0,quiet:values.quiet===!0}}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 pollPort(probe,hosts,state,say){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,state.metAt.push({name,ms:Date.now()-state.started}),say(`${name} listening after ${formatDuration(Date.now()-state.started)}`);return}}}async function pollFreePort(probe,hosts,state,say){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,state.metAt.push({name:`port-free:${name}`,ms:Date.now()-state.started}),say(`${name} free after ${formatDuration(Date.now()-state.started)}`)}async function pollUrl(probe,spec,state,say){let budget=Math.max(1,Math.min(URL_TIMEOUT_MS,state.started+spec.timeout-Date.now())),check=await urlCheck(probe.name,budget,spec.urlExpect);if(!(("problem"in check)&&check.isTimeout===!0&&budget<URL_TIMEOUT_MS&&probe.left!=="not checked yet"))probe.left="problem"in check?check.problem:void 0;if("status"in check)state.metAt.push({name:probe.name,ms:Date.now()-state.started}),say(`${probe.name} answered ${check.status} after ${formatDuration(Date.now()-state.started)}`)}async function pollService(probe,state,say){let prob=await healthyProblem(probe.name);if(probe.left=prob,prob===void 0)state.metAt.push({name:`healthy:${probe.name}`,ms:Date.now()-state.started}),say(`${probe.name} healthy after ${formatDuration(Date.now()-state.started)}`)}async function pollCmd(spec,state,say){if(spec.cmd===void 0||state.cmdLeft===void 0||Date.now()-state.cmdRanAt<spec.interval)return;let budget=Math.max(1,Math.min(CMD_RUN_LIMIT_MS,state.started+spec.timeout-Date.now())),prob=await cmdProblem(spec.cmd,budget);if(!(prob?.startsWith("timed out")===!0&&budget<CMD_RUN_LIMIT_MS&&state.cmdLeft!=="not run yet"))state.cmdLeft=prob;if(state.cmdRanAt=Date.now(),state.cmdLeft===void 0)state.metAt.push({name:`\`${spec.cmd}\``,ms:Date.now()-state.started}),say(`\`${spec.cmd}\` exited 0 after ${formatDuration(Date.now()-state.started)}`)}function progressLines(spec,state,spinner,dim){let waited=dim(formatElapsed(Date.now()-state.started));return[spec.watch===void 0||spec.watch.done?void 0:`${spec.watch.path}: ${spec.watch.exists?"no --until line yet":"does not exist yet"}`,spec.idle===void 0||spec.idle.done?void 0:`${spec.idle.path}: ${spec.idle.exists?`idle ${formatDuration(spec.idle.stableFor)} / ${formatDuration(spec.idle.durationMs)}`:"does not exist yet"}`,...spec.ports.filter((probe)=>probe.left!==void 0).map((probe)=>`${hostPort(spec.hosts[0],probe.port??0)}: ${probe.left}`),...spec.freePorts.filter((probe)=>probe.left!==void 0).map((probe)=>`${probe.name}: ${probe.left}`),...spec.urls.filter((probe)=>probe.left!==void 0).map((probe)=>`${probe.name}: ${probe.left}`),...spec.services.filter((probe)=>probe.left!==void 0).map((probe)=>`service ${probe.name}: ${probe.left}`),state.isPidLeft?`pid ${spec.pid}: still running`:void 0,state.cmdLeft===void 0?void 0:`\`${spec.cmd}\`: ${state.cmdLeft}`].filter((line)=>line!==void 0).map((line)=>`${spinner} ${line} ${waited}`)}function isSatisfied(spec,state){if(spec.watch?.failsFirst===!0)return!1;if(spec.isAny)return spec.hasUntil&&(spec.watch?.done??!1)||spec.idle!==void 0&&spec.idle.done||spec.ports.some((probe)=>probe.left===void 0)||spec.freePorts.some((probe)=>probe.left===void 0)||spec.urls.some((probe)=>probe.left===void 0)||spec.services.some((probe)=>probe.left===void 0)||spec.pid!==void 0&&!state.isPidLeft||spec.cmd!==void 0&&state.cmdLeft===void 0;return(spec.watch?.done??!0)&&(spec.idle?.done??!0)&&spec.ports.every((probe)=>probe.left===void 0)&&spec.freePorts.every((probe)=>probe.left===void 0)&&spec.urls.every((probe)=>probe.left===void 0)&&spec.services.every((probe)=>probe.left===void 0)&&!state.isPidLeft&&state.cmdLeft===void 0}function missingReasons(spec,state){let missing=[];if(spec.watch!==void 0&&!spec.watch.done)missing.push(spec.watch.exists?`no line of ${spec.watch.path} matched --until`:`${spec.watch.path} does not exist`);if(spec.idle!==void 0&&!spec.idle.done)if(!spec.idle.exists){if(spec.watch===void 0||spec.watch.done||spec.watch.exists)missing.push(`${spec.idle.path} does not exist`)}else missing.push(`${spec.idle.path} has not been idle for ${formatDuration(spec.idle.durationMs)} (stable ${formatDuration(spec.idle.stableFor)})`);for(let probe of spec.ports)if(probe.left!==void 0)missing.push(`${hostPort(spec.hosts[0],probe.port??0)} is not listening (${probe.left})`);for(let probe of spec.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 spec.urls)if(probe.left!==void 0)missing.push(`${probe.name} ${probe.left}`);for(let probe of spec.services)if(probe.left!==void 0)missing.push(`service ${probe.name} is not healthy (${probe.left})`);if(state.isPidLeft)missing.push(`pid ${spec.pid} is still running`);if(state.cmdLeft!==void 0)missing.push(`\`${spec.cmd}\` ${state.cmdLeft}`);return missing}async function waitConditions(args){let spec=parseWaitSpec(args),state={started:Date.now(),metAt:[],matched:void 0,isPidLeft:spec.pid!==void 0,cmdLeft:spec.cmd===void 0?void 0:"not run yet",cmdRanAt:0},say=spec.json?writeErr:console.log,{dim}=paint(process2.stderr),region=spec.quiet?void 0:liveRegion2((spinner)=>progressLines(spec,state,spinner,dim));try{for(;;){if(spec.whilePid!==void 0&&!pidAlive(spec.whilePid)){let ms=Date.now()-state.started;if(spec.json)printJson({met:!1,ms,reason:`pid ${spec.whilePid} exited`,line:null,conditions:state.metAt});else problem(`waitfor: --while-pid ${spec.whilePid} exited after ${formatDuration(ms)} before conditions were met`);return 1}let[fileEvents]=await Promise.all([spec.watch===void 0?Promise.resolve([]):spec.watch.poll(),Promise.all(spec.ports.filter((probe)=>probe.left!==void 0).map(async(probe)=>pollPort(probe,spec.hosts,state,say))),Promise.all(spec.freePorts.filter((probe)=>probe.left!==void 0).map(async(probe)=>pollFreePort(probe,spec.hosts,state,say))),Promise.all(spec.urls.filter((probe)=>probe.left!==void 0).map(async(probe)=>pollUrl(probe,spec,state,say))),Promise.all(spec.services.filter((probe)=>probe.left!==void 0).map(async(probe)=>pollService(probe,state,say))),pollCmd(spec,state,say)]);for(let event of fileEvents){if(event.kind==="until"){say(`${spec.watch.path}:${event.line.number}: ${truncate(event.line.text,WIDTH)}`),state.matched={number:event.line.number,text:event.line.text},state.metAt.push({name:`${spec.watch.path} --until`,ms:Date.now()-state.started});continue}let ms=Date.now()-state.started;if(spec.json)printJson({met:!1,ms,reason:"fail",line:{number:event.line.number,text:event.line.text},conditions:state.metAt});else problem(`waitfor: ${spec.watch.path}:${event.line.number} matched --fail after ${formatDuration(ms)}
|
|
11
|
+
${numbered(event.excerpt,event.line)}`);return 1}if(spec.idle!==void 0&&!spec.idle.done&&spec.idle.poll())state.metAt.push({name:`${spec.idle.path} --idle`,ms:Date.now()-state.started}),say(`${spec.idle.path} idle for ${formatDuration(spec.idle.durationMs)} after ${formatDuration(Date.now()-state.started)}`);if(spec.pid!==void 0&&state.isPidLeft){if(state.isPidLeft=pidAlive(spec.pid),!state.isPidLeft)state.metAt.push({name:`pid ${spec.pid}`,ms:Date.now()-state.started}),say(`pid ${spec.pid} exited after ${formatDuration(Date.now()-state.started)}`)}if(isSatisfied(spec,state)){if(spec.json)printJson({met:!0,ms:Date.now()-state.started,line:state.matched??null,conditions:state.metAt});return 0}if(Date.now()-state.started>=spec.timeout&&!(spec.watch?.failing??!1))break;await Bun.sleep(POLL_MS)}}finally{region?.stop()}let missing=missingReasons(spec,state);if(spec.json)return printJson({met:!1,ms:Date.now()-state.started,reason:"timeout",line:state.matched??null,conditions:state.metAt,pending:missing}),TIMEOUT_EXIT;let lines=spec.watch?.excerpt()??[];fail(`gave up after ${formatDuration(spec.timeout)}${spec.isAny?", none met":""}: ${missing.join(", ")}${lines.length===0?"":`
|
|
12
|
+
last lines of ${spec.watch?.path}:
|
|
13
|
+
${numbered(lines)}`}`,TIMEOUT_EXIT)}var TASK_USAGE=`waitfor task [options] <task id | file>
|
|
10
14
|
|
|
11
|
-
|
|
12
|
-
|
|
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?"":`
|
|
15
|
+
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.
|
|
16
|
+
The task is the id a background Bash call returned, or the path of its .output file.`,TASK_EXITS=[[0,"the task exited 0"],[1,"it exited with another code"],[124,"it timed out"],[2,"a usage error"]],TASK_OPTIONS={lines:{type:"string",short:"n",description:"how many of its last lines to print (20)"},timeout:TIMEOUT_OPTION,json:jsonOption("{met, task, path, code, ms, failures, tail, reason?}"),quiet:{type:"boolean",short:"q",description:"no live progress line"}};async function waitTask(args){let{values,positionals:[task]}=parse(args,TASK_USAGE,TASK_OPTIONS,{positionals:["<task>"],exits:TASK_EXITS,examples:["waitfor task b92stimuo","waitfor task /tmp/claude/tasks/b92.output -n 40"]}),path=taskFile(task);if(path===void 0)badUsage(`no background task ${task}: give the id a background Bash call returned, or the path of its .output file`);if(!existsSync3(path))badUsage(`no output file ${path}: ${task} is no background task of this machine`);if(isTranscript(path))badUsage(`${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(process3.stderr),region=values.quiet===!0?void 0:liveRegion2((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_MS)}}finally{region?.stop()}let{failures,tail}=await taskEnd(path,lines),ms=Date.now()-started;if(code===void 0){if(values.json===!0)return printJson({met:!1,reason:"timeout",task,path,code:null,ms,failures,tail}),TIMEOUT_EXIT;let last=tail.length===0?"":`
|
|
14
17
|
last lines of ${path}:
|
|
15
|
-
${numbered(tail)}`;
|
|
18
|
+
${numbered(tail)}`;fail(`gave up after ${formatDuration(timeout)}: task ${task} is still running${last}`,TIMEOUT_EXIT)}if(values.json===!0)return printJson({met:!0,task,path,code,ms,failures,tail}),code===0?0:1;let last=tail.length===0?"":`
|
|
19
|
+
last lines of ${path}:
|
|
20
|
+
${numbered(tail)}`,failed=failures.length===0?"":`
|
|
16
21
|
(fail) and error: lines above them:
|
|
17
|
-
${numbered(failures)}`;return console.log(`task ${task} exited with code ${code}, waited ${formatDuration(
|
|
18
|
-
|
|
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
|
-
|
|
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
|
-
last lines of ${watch?.path}:
|
|
24
|
-
${numbered(lines)}`}`,TIMEOUT_EXIT)}process2.exitCode=await runMain({name:"waitfor",run:main});
|
|
22
|
+
${numbered(failures)}`;return console.log(`task ${task} exited with code ${code}, waited ${formatDuration(ms)}${failed}${last}`),code===0?0:1}process3.exitCode=await runCli({name:"waitfor",about:"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",replaces:"sleep loops, tail -f and until ! pgrep -f",defaultCommand:"wait",runBare:!0,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"],["waitfor task b92stimuo","wait for a Claude Code background Bash task to finish"]],commands:{wait:{run:waitConditions,summary:"wait for file, port, URL, Docker health, pid or command conditions"},task:{run:waitTask,summary:"wait for a Claude Code background Bash task to end"}}});
|
package/dist/slot-cli.js
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
import{configuredNumber,paint,writeErr,badge,formatDuration,formatElapsed,formatAge,truncate,table,printJson,wholeNumber,duration,jsonOption,fail,parse,exitCodeOf,holdSignals,
|
|
4
|
-
slot ls [--json]: lists who holds a slot or a lock and who waits for one (slot ls --help)
|
|
3
|
+
import{isHumanTerminal,configuredNumber,paint,writeErr,badge,formatDuration,formatElapsed,formatAge,truncate,table,printJson,wholeNumber,duration,jsonOption,fail,badUsage,OUTPUT_OPTIONS,parse,exitCodeOf,holdSignals,liveRegion2}from"./chunk-cwtbc9w7.js";import{privateLogDirectory,runCli,liveSessions,currentSession}from"./chunk-q23bt6dr.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 TIMEOUT_EXIT=124,RUN_USAGE=`slot [options] -- <cmd>...
|
|
5
4
|
|
|
5
|
+
Waits in FIFO order for free machine-wide slots, then runs the command and exits with its code.
|
|
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
|
-
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
|
|
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 succeeded"],["its own","the exit code of the command"],[124,"it timed out waiting for the slot or lock"],[2,"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 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
|
-
|
|
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)});
|
|
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(isHumanTerminal(process2.stderr))region=liveRegion2((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"}`,TIMEOUT_EXIT);await Bun.sleep(POLL)}}finally{if(region?.stop(),waiter!==void 0)rmSync(waiter.path,{force:!0}),waiter.held.release()}}function withSeparator(args){let allOptions={...RUN_OPTIONS,...OUTPUT_OPTIONS},takesValue=(word)=>!word.includes("=")&&Object.entries(allOptions).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)badUsage("give the command after --");let locks=[...new Set(values.lock??[])].sort();for(let name of locks)if(!LOCK_NAME.test(name))badUsage(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);if(values["no-slot"]===!0&&locks.length===0)badUsage("--no-slot takes the --lock alone, and none is given");if(values["no-slot"]===!0&&(values.weight!==void 0||values.exclusive===!0))badUsage("--weight and --exclusive cannot be used with --no-slot");if(values.weight!==void 0&&values.exclusive===!0)badUsage("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)badUsage(`--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 runCli({name:"slot",about:"waits in FIFO order for free machine-wide slots, then runs the command and exits with its code",replaces:"flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database",defaultCommand:"run",runBare:!0,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","list active holders and waiters"]],commands:{run:{run:runSlotted,summary:"wait for free slots/locks and run a command after --"},ls:{run:listSlots,summary:"list who holds a slot or lock and who waits for one"}},aliases:{list:"ls"}});
|
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.16.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.54.0"
|
|
39
39
|
}
|
|
40
40
|
}
|
package/dist/chunk-18nqpwfh.js
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
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),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(`
|
|
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(`
|
|
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(`
|
|
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(`
|
|
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(`
|
|
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(`
|
|
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(`
|
|
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}
|
|
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(`
|
|
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}
|
|
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)}
|
|
15
|
-
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process12.stdout.write(`${answer}
|
|
16
|
-
`),0}var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
17
|
-
functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
18
|
-
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
19
|
-
set -l current (commandline -ct)
|
|
20
|
-
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
21
|
-
if test "$line" = __files__
|
|
22
|
-
__fish_complete_path $current
|
|
23
|
-
else
|
|
24
|
-
echo $line
|
|
25
|
-
end
|
|
26
|
-
end
|
|
27
|
-
end
|
|
28
|
-
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
29
|
-
`).join("")}`;if(shell==="bash")return`${header}
|
|
30
|
-
__kaynooo_cli_complete() {
|
|
31
|
-
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
32
|
-
local -a lines
|
|
33
|
-
COMPREPLY=()
|
|
34
|
-
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
35
|
-
for line in "\${lines[@]}"; do
|
|
36
|
-
if [[ $line == __files__ ]]; then
|
|
37
|
-
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
38
|
-
else
|
|
39
|
-
words+="\${line%%$'\\t'*}"$'\\n'
|
|
40
|
-
fi
|
|
41
|
-
done
|
|
42
|
-
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
43
|
-
}
|
|
44
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
45
|
-
`;return`${header}
|
|
46
|
-
__kaynooo_cli_complete() {
|
|
47
|
-
local line
|
|
48
|
-
local -a described plain
|
|
49
|
-
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
50
|
-
if [[ $line == __files__ ]]; then
|
|
51
|
-
_files
|
|
52
|
-
elif [[ $line == *$'\\t'* ]]; then
|
|
53
|
-
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
54
|
-
else
|
|
55
|
-
plain+=("$line")
|
|
56
|
-
fi
|
|
57
|
-
done
|
|
58
|
-
(( \${#described} )) && _describe -V value described
|
|
59
|
-
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
60
|
-
return 0
|
|
61
|
-
}
|
|
62
|
-
__kaynooo_cli_register() {
|
|
63
|
-
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
64
|
-
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
65
|
-
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
66
|
-
}
|
|
67
|
-
autoload -Uz add-zsh-hook
|
|
68
|
-
add-zsh-hook precmd __kaynooo_cli_register
|
|
69
|
-
typeset -gaU __kaynooo_cli_bins
|
|
70
|
-
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
71
|
-
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}import process13 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process13.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process13.pid}`,codes=[`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`,`\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process13.stderr,env=process13.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}import{appendFileSync,mkdirSync as mkdirSync2,readFileSync as readFileSync5,renameSync,statSync as statSync3,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir4}from"os";import{dirname as dirname3,join as join5}from"path";import process15 from"process";import{lstatSync,openSync}from"fs";import{mkdir,mkdtemp,readdir,rm,stat}from"fs/promises";import{homedir as homedir3,tmpdir}from"os";import{join as join4}from"path";import process14 from"process";var CLI_FOLDER="kaynooo-cli";function isPrivateDirectory(path){try{let info=lstatSync(path,{throwIfNoEntry:!1});return info!==void 0&&info.isDirectory()&&info.uid===(process14.getuid?.()??info.uid)&&(info.mode&63)===0}catch{return!1}}async function privateLogDirectory(name,env=process14.env){let path=join4(xdgFolder(env.XDG_RUNTIME_DIR,join4(homedir3(),".cache")),CLI_FOLDER,name);try{if(await mkdir(path,{recursive:!0,mode:448}),isPrivateDirectory(path))return path}catch{}return mkdtemp(join4(tmpdir(),`${name.replaceAll("/","-")}-`))}var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process15.env){return xdgFolder(env.XDG_STATE_HOME,join5(homedir4(),".local","state"))}function usagePath(env=process15.env){return join5(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process15.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,mode,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)},...mode===void 0?{}:{mode}}}function trimUsage(path,maxBytes){let info=statSync3(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync5(path,"utf8").split(`
|
|
72
|
-
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
73
|
-
`)}
|
|
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)}
|
|
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?"":`
|
|
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};
|