@kaynooo/cli-wait 0.11.0 → 0.12.1
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 +3 -1
- package/dist/cli.js +281 -83
- package/dist/slot-cli.js +151 -45
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -21,7 +21,9 @@ waitfor task b92stimuo
|
|
|
21
21
|
- `--file` is read from its start, line by line as each is completed, colours stripped; it may not exist yet. A file that shrinks (rotated, truncated) is read again from its start.
|
|
22
22
|
- `--until <regex>` waits for a line of `--file` to match and prints it as `<file>:<line>: <text>`.
|
|
23
23
|
- `--fail <regex>` ends the wait on the first matching line of `--file`, printing the five lines on each side of it on stderr, as long as some condition is still unmet: a `--until` line before it in the same read wins.
|
|
24
|
-
- `--port <n>` waits for a TCP connection to `--host` (127.0.0.1) to be accepted, `--url <url>` for a 2xx answer, redirects followed. Each prints how long it took.
|
|
24
|
+
- `--port <n>` waits for a TCP connection to `--host` (127.0.0.1 or ::1) to be accepted, `--url <url>` for a 2xx answer, redirects followed. Each prints how long it took.
|
|
25
|
+
- `--port` and `--url` may be repeated: every one must be met (or the first with `--any`), each printed with how long it took, and `--json` adds `conditions: [{name, ms}]` for each one met. A timeout lists only the ones still pending.
|
|
26
|
+
- `--status <spec>` sets the status a `--url` must answer instead of any 2xx: `301`, `200-299`, `2xx` or a comma list (redirects are not followed when a 3xx is asked for). `--body <regex>` makes the first MiB of the body match too. With several `--url`, both apply to every one.
|
|
25
27
|
- `--pid <n>` waits for the process to exit, checked with signal 0, so it never matches its own shell the way a `while pgrep -f` loop does. A zombie counts as exited. A `--port` connection attempt is given up after 3 seconds and retried, so dropped packets do not hold a poll for minutes.
|
|
26
28
|
- `--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.
|
|
27
29
|
- `--any` is met by the first condition that is, not all of them: it takes two or more of `--until`, `--port`, `--url`, `--pid` and `--cmd`, prints the one that was met, and a timeout says none was and lists them all. A `--fail` line still ends the wait with 1.
|
package/dist/cli.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
5
|
import { existsSync as existsSync6 } from "fs";
|
|
6
|
-
import
|
|
6
|
+
import process20 from "process";
|
|
7
7
|
// ../kit/src/args.ts
|
|
8
8
|
import process9 from "process";
|
|
9
9
|
import { parseArgs } from "util";
|
|
@@ -469,24 +469,20 @@ function printJson(value) {
|
|
|
469
469
|
|
|
470
470
|
// ../kit/src/help.ts
|
|
471
471
|
import process8 from "process";
|
|
472
|
-
var OPTIONAL =
|
|
472
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
473
473
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
474
474
|
var FULL_STOP = /\.$/;
|
|
475
475
|
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
476
476
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
477
477
|
}
|
|
478
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
479
|
-
return [usageLine(usage, colors),
|
|
478
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
479
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
480
480
|
`);
|
|
481
481
|
}
|
|
482
482
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
483
483
|
if (exits.length === 0)
|
|
484
484
|
return [];
|
|
485
|
-
|
|
486
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
487
|
-
}
|
|
488
|
-
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
489
|
-
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
485
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
490
486
|
}
|
|
491
487
|
function wantsHelpJson(env = process8.env) {
|
|
492
488
|
return env.KIT_HELP === "json";
|
|
@@ -512,29 +508,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
512
508
|
return [];
|
|
513
509
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
514
510
|
}
|
|
511
|
+
var MAX_INLINE_CHOICES = 24;
|
|
515
512
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
516
513
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
517
514
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
518
|
-
const
|
|
515
|
+
const choices = option.choices?.join("|");
|
|
516
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
517
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
519
518
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
520
519
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
521
|
-
|
|
520
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
521
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
522
522
|
});
|
|
523
523
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
524
524
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
525
525
|
}
|
|
526
526
|
|
|
527
527
|
// ../kit/src/text.ts
|
|
528
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
529
528
|
function distance(a, b) {
|
|
530
|
-
|
|
531
|
-
|
|
529
|
+
const left = [...a];
|
|
530
|
+
const right = [...b];
|
|
531
|
+
let before = [];
|
|
532
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
533
|
+
for (const [i, x] of left.entries()) {
|
|
532
534
|
const current = [i + 1];
|
|
533
|
-
for (const [j,
|
|
534
|
-
|
|
535
|
+
for (const [j, y] of right.entries()) {
|
|
536
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
537
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
538
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
539
|
+
current.push(cost);
|
|
540
|
+
}
|
|
541
|
+
before = previous;
|
|
535
542
|
previous = current;
|
|
536
543
|
}
|
|
537
|
-
return previous[
|
|
544
|
+
return previous[right.length] ?? 0;
|
|
538
545
|
}
|
|
539
546
|
function closest(name, names) {
|
|
540
547
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -610,7 +617,7 @@ class Completing {
|
|
|
610
617
|
}
|
|
611
618
|
var completion = { active: false };
|
|
612
619
|
var OUTPUT_OPTIONS = {
|
|
613
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
620
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
614
621
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
615
622
|
};
|
|
616
623
|
function applyOutput(color, plain, env = process9.env) {
|
|
@@ -1074,31 +1081,109 @@ function interceptOutput(clear) {
|
|
|
1074
1081
|
// ../kit/src/cli.ts
|
|
1075
1082
|
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1076
1083
|
import { dirname as dirname3, join as join6 } from "path";
|
|
1077
|
-
import
|
|
1084
|
+
import process16 from "process";
|
|
1085
|
+
|
|
1086
|
+
// ../kit/src/completions.ts
|
|
1087
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1088
|
+
var FISH_FUNCTION = `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'
|
|
1089
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1090
|
+
set -l current (commandline -ct)
|
|
1091
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1092
|
+
if test "$line" = __files__
|
|
1093
|
+
__fish_complete_path $current
|
|
1094
|
+
else
|
|
1095
|
+
echo $line
|
|
1096
|
+
end
|
|
1097
|
+
end
|
|
1098
|
+
end`;
|
|
1099
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1100
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1101
|
+
local -a lines
|
|
1102
|
+
COMPREPLY=()
|
|
1103
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1104
|
+
for line in "\${lines[@]}"; do
|
|
1105
|
+
if [[ $line == __files__ ]]; then
|
|
1106
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1107
|
+
else
|
|
1108
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1109
|
+
fi
|
|
1110
|
+
done
|
|
1111
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1112
|
+
}`;
|
|
1113
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1114
|
+
local line
|
|
1115
|
+
local -a described plain
|
|
1116
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1117
|
+
if [[ $line == __files__ ]]; then
|
|
1118
|
+
_files
|
|
1119
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
1120
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1121
|
+
else
|
|
1122
|
+
plain+=("$line")
|
|
1123
|
+
fi
|
|
1124
|
+
done
|
|
1125
|
+
(( \${#described} )) && _describe -V value described
|
|
1126
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1127
|
+
return 0
|
|
1128
|
+
}`;
|
|
1129
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1130
|
+
if (shell === "fish")
|
|
1131
|
+
return `${header}
|
|
1132
|
+
${FISH_FUNCTION}
|
|
1133
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1134
|
+
`).join("")}`;
|
|
1135
|
+
if (shell === "bash")
|
|
1136
|
+
return `${header}
|
|
1137
|
+
${BASH_FUNCTION}
|
|
1138
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1139
|
+
`;
|
|
1140
|
+
return `${header}
|
|
1141
|
+
${ZSH_FUNCTION}
|
|
1142
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1143
|
+
`;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
// ../kit/src/notify.ts
|
|
1147
|
+
import process13 from "process";
|
|
1148
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
1149
|
+
var CANCELLED = 130;
|
|
1150
|
+
function base64(text) {
|
|
1151
|
+
return Buffer.from(text).toString("base64");
|
|
1152
|
+
}
|
|
1153
|
+
function notification(title, body, env = process13.env) {
|
|
1154
|
+
const id = `kit${process13.pid}`;
|
|
1155
|
+
const 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\\`];
|
|
1156
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1157
|
+
}
|
|
1158
|
+
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
1159
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1160
|
+
return;
|
|
1161
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1162
|
+
}
|
|
1078
1163
|
|
|
1079
1164
|
// ../kit/src/usage.ts
|
|
1080
1165
|
import { appendFileSync, mkdirSync } from "fs";
|
|
1081
1166
|
import { homedir as homedir4 } from "os";
|
|
1082
1167
|
import { dirname as dirname2, isAbsolute, join as join5 } from "path";
|
|
1083
|
-
import
|
|
1168
|
+
import process15 from "process";
|
|
1084
1169
|
|
|
1085
1170
|
// ../kit/src/logs.ts
|
|
1086
1171
|
import { lstatSync, openSync } from "fs";
|
|
1087
1172
|
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
1088
1173
|
import { homedir as homedir3, tmpdir } from "os";
|
|
1089
1174
|
import { join as join4 } from "path";
|
|
1090
|
-
import
|
|
1175
|
+
import process14 from "process";
|
|
1091
1176
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1092
1177
|
var CLI_FOLDER = "kaynooo-cli";
|
|
1093
1178
|
function isPrivateDirectory(path) {
|
|
1094
1179
|
try {
|
|
1095
1180
|
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
1096
|
-
return info !== undefined && info.isDirectory() && info.uid === (
|
|
1181
|
+
return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
1097
1182
|
} catch {
|
|
1098
1183
|
return false;
|
|
1099
1184
|
}
|
|
1100
1185
|
}
|
|
1101
|
-
async function privateLogDirectory(name, env =
|
|
1186
|
+
async function privateLogDirectory(name, env = process14.env) {
|
|
1102
1187
|
const runtime = env.XDG_RUNTIME_DIR;
|
|
1103
1188
|
const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
|
|
1104
1189
|
const path = join4(base, name);
|
|
@@ -1118,14 +1203,14 @@ var usageError;
|
|
|
1118
1203
|
function noteUsageError(message) {
|
|
1119
1204
|
usageError = message;
|
|
1120
1205
|
}
|
|
1121
|
-
function stateHome(env =
|
|
1206
|
+
function stateHome(env = process15.env) {
|
|
1122
1207
|
const dir = env.XDG_STATE_HOME;
|
|
1123
1208
|
return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
|
|
1124
1209
|
}
|
|
1125
|
-
function usagePath(env =
|
|
1210
|
+
function usagePath(env = process15.env) {
|
|
1126
1211
|
return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1127
1212
|
}
|
|
1128
|
-
function usageRecorded(env =
|
|
1213
|
+
function usageRecorded(env = process15.env) {
|
|
1129
1214
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1130
1215
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1131
1216
|
}
|
|
@@ -1139,7 +1224,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
1139
1224
|
usageError = undefined;
|
|
1140
1225
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1141
1226
|
}
|
|
1142
|
-
function recordUsage(entry, env =
|
|
1227
|
+
function recordUsage(entry, env = process15.env) {
|
|
1143
1228
|
if (!usageRecorded(env))
|
|
1144
1229
|
return;
|
|
1145
1230
|
try {
|
|
@@ -1155,10 +1240,14 @@ var LEVEL_OPTIONS = {
|
|
|
1155
1240
|
...OUTPUT_OPTIONS,
|
|
1156
1241
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1157
1242
|
};
|
|
1158
|
-
var TOP_OPTIONS = {
|
|
1243
|
+
var TOP_OPTIONS = {
|
|
1244
|
+
...LEVEL_OPTIONS,
|
|
1245
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1246
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1247
|
+
};
|
|
1159
1248
|
function printError(prefix, message, hint, cause) {
|
|
1160
|
-
const colors = paint(
|
|
1161
|
-
const styled = takesControlCodes(
|
|
1249
|
+
const colors = paint(process16.stderr);
|
|
1250
|
+
const styled = takesControlCodes(process16.stderr);
|
|
1162
1251
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1163
1252
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1164
1253
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1235,6 +1324,19 @@ async function leafCandidates(run, words) {
|
|
|
1235
1324
|
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1236
1325
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1237
1326
|
}
|
|
1327
|
+
var COMPLETIONS = "--completions";
|
|
1328
|
+
function flagValue([flag = "", ...rest]) {
|
|
1329
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1330
|
+
}
|
|
1331
|
+
function printCompletionScript(name, args) {
|
|
1332
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1333
|
+
if (shell === undefined || args.length !== 1) {
|
|
1334
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1335
|
+
return 2;
|
|
1336
|
+
}
|
|
1337
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1338
|
+
return 0;
|
|
1339
|
+
}
|
|
1238
1340
|
async function printCandidates(found) {
|
|
1239
1341
|
for (const line of await found)
|
|
1240
1342
|
console.log(line);
|
|
@@ -1258,16 +1360,20 @@ function packageVersion(entry = Bun.main) {
|
|
|
1258
1360
|
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1259
1361
|
if (argv[0] === COMPLETE)
|
|
1260
1362
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1363
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1364
|
+
return printCompletionScript(name, flagValue(argv));
|
|
1261
1365
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1262
1366
|
console.log(version ?? packageVersion());
|
|
1263
1367
|
return 0;
|
|
1264
1368
|
}
|
|
1265
1369
|
let code;
|
|
1370
|
+
const started = performance.now();
|
|
1266
1371
|
try {
|
|
1267
1372
|
code = await run(argv);
|
|
1268
1373
|
} catch (error) {
|
|
1269
1374
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1270
1375
|
}
|
|
1376
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1271
1377
|
if (usage !== false) {
|
|
1272
1378
|
try {
|
|
1273
1379
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1282,15 +1388,15 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
1282
1388
|
// ../kit/src/sessions.ts
|
|
1283
1389
|
import { homedir as homedir5 } from "os";
|
|
1284
1390
|
import { join as join7 } from "path";
|
|
1285
|
-
import
|
|
1391
|
+
import process17 from "process";
|
|
1286
1392
|
var {Glob } = globalThis.Bun;
|
|
1287
1393
|
var SESSION_FILES = new Glob("*.json");
|
|
1288
1394
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1289
1395
|
async function sessionDirs() {
|
|
1290
1396
|
const home = homedir5();
|
|
1291
1397
|
const dirs = new Set([join7(home, ".claude", "sessions")]);
|
|
1292
|
-
if (
|
|
1293
|
-
dirs.add(join7(
|
|
1398
|
+
if (process17.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
1399
|
+
dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR, "sessions"));
|
|
1294
1400
|
try {
|
|
1295
1401
|
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
|
|
1296
1402
|
dirs.add(dir);
|
|
@@ -1336,7 +1442,7 @@ async function liveSessions() {
|
|
|
1336
1442
|
}
|
|
1337
1443
|
async function currentSession(sessions) {
|
|
1338
1444
|
const byPid = new Map(sessions.map((session) => [session.pid, session]));
|
|
1339
|
-
let pid =
|
|
1445
|
+
let pid = process17.ppid;
|
|
1340
1446
|
for (let depth = 0;depth < 32 && pid > 1; depth++) {
|
|
1341
1447
|
const session = byPid.get(pid);
|
|
1342
1448
|
if (session !== undefined)
|
|
@@ -1462,11 +1568,58 @@ async function closeWhenConnected(attempt) {
|
|
|
1462
1568
|
(await attempt).end();
|
|
1463
1569
|
} catch {}
|
|
1464
1570
|
}
|
|
1465
|
-
|
|
1571
|
+
var STATUS_CLASS = /^([1-5])xx$/i;
|
|
1572
|
+
var STATUS_RANGE = /^(\d{3})(?:-(\d{3}))?$/;
|
|
1573
|
+
var BODY_BYTES = 1024 * 1024;
|
|
1574
|
+
function parseStatus(spec) {
|
|
1575
|
+
const tests = [];
|
|
1576
|
+
for (const part of spec.split(",").map((item) => item.trim())) {
|
|
1577
|
+
const klass = STATUS_CLASS.exec(part);
|
|
1578
|
+
const range = STATUS_RANGE.exec(part);
|
|
1579
|
+
if (klass !== null) {
|
|
1580
|
+
const hundred = Number(klass[1]);
|
|
1581
|
+
tests.push((status) => Math.floor(status / 100) === hundred);
|
|
1582
|
+
} else if (range !== null) {
|
|
1583
|
+
const low = Number(range[1]);
|
|
1584
|
+
const high = Number(range[2] ?? range[1]);
|
|
1585
|
+
tests.push((status) => status >= low && status <= high);
|
|
1586
|
+
} else {
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
return (status) => tests.some((test) => test(status));
|
|
1591
|
+
}
|
|
1592
|
+
async function readBody(response) {
|
|
1593
|
+
const reader = response.body?.getReader();
|
|
1594
|
+
if (reader === undefined)
|
|
1595
|
+
return "";
|
|
1596
|
+
const decoder = new TextDecoder;
|
|
1597
|
+
let text = "";
|
|
1598
|
+
let bytes = 0;
|
|
1599
|
+
while (bytes < BODY_BYTES) {
|
|
1600
|
+
const { done, value } = await reader.read();
|
|
1601
|
+
if (done)
|
|
1602
|
+
break;
|
|
1603
|
+
bytes += value?.length ?? 0;
|
|
1604
|
+
text += decoder.decode(value, { stream: true });
|
|
1605
|
+
}
|
|
1606
|
+
await reader.cancel();
|
|
1607
|
+
return text;
|
|
1608
|
+
}
|
|
1609
|
+
async function urlCheck(url, timeout, expect = {}) {
|
|
1466
1610
|
try {
|
|
1467
|
-
const
|
|
1468
|
-
await
|
|
1469
|
-
|
|
1611
|
+
const wantsRedirect = expect.status !== undefined && Array.from({ length: 100 }, (_, index) => 300 + index).some(expect.status.test);
|
|
1612
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(timeout), redirect: wantsRedirect ? "manual" : "follow" });
|
|
1613
|
+
const ok = expect.status === undefined ? response.ok : expect.status.test(response.status);
|
|
1614
|
+
if (!ok) {
|
|
1615
|
+
await response.body?.cancel();
|
|
1616
|
+
return { problem: expect.status === undefined ? `answered ${response.status}` : `answered ${response.status}, expected ${expect.status.spec}` };
|
|
1617
|
+
}
|
|
1618
|
+
if (expect.body === undefined) {
|
|
1619
|
+
await response.body?.cancel();
|
|
1620
|
+
return { status: response.status };
|
|
1621
|
+
}
|
|
1622
|
+
return expect.body.test(await readBody(response)) ? { status: response.status } : { problem: `answered ${response.status} but the body does not match ${expect.body}` };
|
|
1470
1623
|
} catch (error) {
|
|
1471
1624
|
return { problem: error instanceof Error ? error.message : String(error), isTimeout: error instanceof Error && error.name === "TimeoutError" };
|
|
1472
1625
|
}
|
|
@@ -1475,7 +1628,7 @@ async function urlCheck(url, timeout) {
|
|
|
1475
1628
|
// src/task.ts
|
|
1476
1629
|
import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
|
|
1477
1630
|
import { join as join8 } from "path";
|
|
1478
|
-
import
|
|
1631
|
+
import process19 from "process";
|
|
1479
1632
|
var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
|
|
1480
1633
|
var FAILURE = /\(fail\)|\berror:/i;
|
|
1481
1634
|
var TASK_ID = /^[\w-]+$/;
|
|
@@ -1483,9 +1636,9 @@ var TAIL_BYTES = 256;
|
|
|
1483
1636
|
var LONGEST_FAILURES = 30;
|
|
1484
1637
|
var CARRIAGE_RETURN2 = /\r$/;
|
|
1485
1638
|
function tasksRoot(env) {
|
|
1486
|
-
return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${
|
|
1639
|
+
return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process19.getuid?.() ?? 0}`);
|
|
1487
1640
|
}
|
|
1488
|
-
function taskFile(task, env =
|
|
1641
|
+
function taskFile(task, env = process19.env) {
|
|
1489
1642
|
if (task.includes("/") || task.endsWith(".output"))
|
|
1490
1643
|
return task;
|
|
1491
1644
|
if (!TASK_ID.test(task))
|
|
@@ -1518,7 +1671,7 @@ async function taskEnd(path, lines) {
|
|
|
1518
1671
|
}
|
|
1519
1672
|
function pidAlive(pid) {
|
|
1520
1673
|
try {
|
|
1521
|
-
|
|
1674
|
+
process19.kill(pid, 0);
|
|
1522
1675
|
} catch (error) {
|
|
1523
1676
|
return error.code === "EPERM";
|
|
1524
1677
|
}
|
|
@@ -1537,8 +1690,8 @@ function isZombie(pid) {
|
|
|
1537
1690
|
var USAGE = `waitfor [options]: waits until a file shows a line, a port listens, a URL answers 2xx, a process exits or a command exits 0
|
|
1538
1691
|
waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
|
|
1539
1692
|
|
|
1540
|
-
Every condition given must be met, or with --any the first of them to be. A --fail line in --file ends the wait at once. A timeout or a --fail line comes with an excerpt of what it saw last.
|
|
1541
|
-
--json prints {met, ms, line} once met or on a --fail line, line being the last --until line or the --fail one as {number, text} (null when none), and the progress lines go to stderr.`;
|
|
1693
|
+
Every condition given must be met, or with --any the first of them to be; --port and --url may be repeated, and --status and --body then apply to every --url. A --fail line in --file ends the wait at once. A timeout or a --fail line comes with an excerpt of what it saw last.
|
|
1694
|
+
--json prints {met, ms, line, conditions} once met or on a --fail line, conditions naming each one met as {name, ms}, line being the last --until line or the --fail one as {number, text} (null when none), and the progress lines go to stderr.`;
|
|
1542
1695
|
var TASK_USAGE = `waitfor task [options] <task id | file>: waits for a Claude Code background task to end, then prints its exit code, its last lines and the (fail) and error: lines above them
|
|
1543
1696
|
|
|
1544
1697
|
The task is the id a background Bash call returned, or the path of its .output file.
|
|
@@ -1556,9 +1709,11 @@ var OPTIONS = {
|
|
|
1556
1709
|
file: { type: "string", short: "f", description: "a log file to read, from its start, waiting for it to exist" },
|
|
1557
1710
|
until: { type: "string", short: "u", description: "a regular expression a line of --file must match" },
|
|
1558
1711
|
fail: { type: "string", short: "e", description: "a regular expression whose first matching line of --file is a failure" },
|
|
1559
|
-
port: { type: "string", short: "p", description: "a TCP port that must accept connections" },
|
|
1560
|
-
host: { type: "string", short: "H", description: "the host of --port (127.0.0.1)" },
|
|
1561
|
-
url: { type: "string", description: "a URL that must answer 2xx" },
|
|
1712
|
+
port: { type: "string", short: "p", multiple: true, description: "a TCP port that must accept connections, repeatable" },
|
|
1713
|
+
host: { type: "string", short: "H", description: "the host of --port (127.0.0.1 and ::1)" },
|
|
1714
|
+
url: { type: "string", multiple: true, description: "a URL that must answer 2xx (or --status), repeatable" },
|
|
1715
|
+
status: { type: "string", description: "the status a --url must answer instead of 2xx: 301, 200-299, 2xx or a comma list, for every --url" },
|
|
1716
|
+
body: { type: "string", description: "a regular expression the first MiB of a --url body must match, for every --url" },
|
|
1562
1717
|
pid: { type: "string", description: "a process id that must exit" },
|
|
1563
1718
|
cmd: { type: "string", short: "c", description: "a shell command that must exit 0, re-run every --interval" },
|
|
1564
1719
|
interval: { type: "string", description: "how long between two runs of --cmd (1s)" },
|
|
@@ -1609,7 +1764,7 @@ async function waitTask(args) {
|
|
|
1609
1764
|
const lines = wholeNumber(values.lines, "lines", 20);
|
|
1610
1765
|
const timeout = duration(values.timeout, "timeout", 5 * 60000);
|
|
1611
1766
|
const started = Date.now();
|
|
1612
|
-
const { dim } = paint(
|
|
1767
|
+
const { dim } = paint(process20.stderr);
|
|
1613
1768
|
const region = values.quiet === true ? undefined : liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
|
|
1614
1769
|
let code;
|
|
1615
1770
|
try {
|
|
@@ -1647,26 +1802,46 @@ async function main(args) {
|
|
|
1647
1802
|
fail(`unexpected argument ${positionals[0]}
|
|
1648
1803
|
|
|
1649
1804
|
${USAGE}`);
|
|
1650
|
-
|
|
1805
|
+
const portTexts = values.port ?? [];
|
|
1806
|
+
const urlTexts = values.url ?? [];
|
|
1807
|
+
if (values.until === undefined && portTexts.length === 0 && urlTexts.length === 0 && values.pid === undefined && values.cmd === undefined)
|
|
1651
1808
|
fail(`give --until with --file, --port, --url, --pid or --cmd
|
|
1652
1809
|
|
|
1653
1810
|
${USAGE}`);
|
|
1654
1811
|
if ((values.until !== undefined || values.fail !== undefined) !== (values.file !== undefined))
|
|
1655
1812
|
fail("--until and --fail read the --file lines, and --file needs one of them");
|
|
1656
|
-
if (values.host !== undefined &&
|
|
1813
|
+
if (values.host !== undefined && portTexts.length === 0)
|
|
1657
1814
|
fail("--host goes with --port");
|
|
1658
|
-
|
|
1815
|
+
if ((values.status !== undefined || values.body !== undefined) && urlTexts.length === 0)
|
|
1816
|
+
fail("--status and --body go with --url");
|
|
1817
|
+
const conditions = [values.until, ...portTexts, ...urlTexts, values.pid, values.cmd].filter((condition) => condition !== undefined).length;
|
|
1659
1818
|
if (values.any === true && conditions < 2)
|
|
1660
1819
|
fail("--any needs two or more of --until, --port, --url, --pid and --cmd");
|
|
1661
1820
|
if (values.interval !== undefined && values.cmd === undefined)
|
|
1662
1821
|
fail("--interval goes with --cmd");
|
|
1663
|
-
const
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1822
|
+
const ports = portTexts.map((text) => {
|
|
1823
|
+
const port = wholeNumber(text, "port", 0);
|
|
1824
|
+
if (port > 65535)
|
|
1825
|
+
fail(`--port takes a port up to 65535, not ${port}`);
|
|
1826
|
+
return { name: String(port), port, left: "not checked yet" };
|
|
1827
|
+
});
|
|
1828
|
+
for (const url of urlTexts) {
|
|
1829
|
+
if (!URL.canParse(url))
|
|
1830
|
+
fail(`--url ${url} is no URL`);
|
|
1831
|
+
}
|
|
1832
|
+
const statusTest = values.status === undefined ? undefined : parseStatus(values.status);
|
|
1833
|
+
if (values.status !== undefined && statusTest === undefined)
|
|
1834
|
+
fail(`--status takes a code, a range or a class such as 301, 200-299 or 2xx, not ${values.status}`);
|
|
1835
|
+
const expect = {};
|
|
1836
|
+
if (values.status !== undefined && statusTest !== undefined)
|
|
1837
|
+
expect.status = { test: statusTest, spec: values.status };
|
|
1838
|
+
const body = regex(values.body, "body");
|
|
1839
|
+
if (body !== undefined)
|
|
1840
|
+
expect.body = body;
|
|
1841
|
+
const urls = urlTexts.map((url) => ({ name: url, left: "not checked yet" }));
|
|
1842
|
+
const metAt = [];
|
|
1668
1843
|
const pid = values.pid === undefined ? undefined : wholeNumber(values.pid, "pid", 0);
|
|
1669
|
-
const
|
|
1844
|
+
const hosts = values.host === undefined ? ["127.0.0.1", "::1"] : [values.host];
|
|
1670
1845
|
const interval = duration(values.interval, "interval", 1000);
|
|
1671
1846
|
const isAny = values.any === true;
|
|
1672
1847
|
const timeout = duration(values.timeout, "timeout", 5 * 60000);
|
|
@@ -1675,18 +1850,16 @@ ${USAGE}`);
|
|
|
1675
1850
|
const json = values.json === true;
|
|
1676
1851
|
const say = json ? console.error : console.log;
|
|
1677
1852
|
let matched;
|
|
1678
|
-
let portLeft = port === undefined ? undefined : "not checked yet";
|
|
1679
|
-
let urlLeft = values.url === undefined ? undefined : "not checked yet";
|
|
1680
1853
|
let isPidLeft = pid !== undefined;
|
|
1681
1854
|
let cmdLeft = values.cmd === undefined ? undefined : "not run yet";
|
|
1682
1855
|
let cmdRanAt = 0;
|
|
1683
|
-
const { dim } = paint(
|
|
1856
|
+
const { dim } = paint(process20.stderr);
|
|
1684
1857
|
const region = values.quiet === true ? undefined : liveRegion((spinner) => {
|
|
1685
1858
|
const waited = dim(formatElapsed(Date.now() - started));
|
|
1686
1859
|
const left = [
|
|
1687
1860
|
watch === undefined || watch.done ? undefined : `${watch.path}: ${watch.exists ? "no --until line yet" : "does not exist yet"}`,
|
|
1688
|
-
|
|
1689
|
-
|
|
1861
|
+
...ports.filter((probe) => probe.left !== undefined).map((probe) => `${hosts[0]}:${probe.port}: ${probe.left}`),
|
|
1862
|
+
...urls.filter((probe) => probe.left !== undefined).map((probe) => `${probe.name}: ${probe.left}`),
|
|
1690
1863
|
isPidLeft ? `pid ${pid}: still running` : undefined,
|
|
1691
1864
|
cmdLeft === undefined ? undefined : `\`${values.cmd}\`: ${cmdLeft}`
|
|
1692
1865
|
];
|
|
@@ -1699,6 +1872,7 @@ ${USAGE}`);
|
|
|
1699
1872
|
if (event.kind === "until") {
|
|
1700
1873
|
say(`${watch.path}:${event.line.number}: ${truncate(event.line.text, WIDTH)}`);
|
|
1701
1874
|
matched = { number: event.line.number, text: event.line.text };
|
|
1875
|
+
metAt.push({ name: `${watch.path} --until`, ms: Date.now() - started });
|
|
1702
1876
|
continue;
|
|
1703
1877
|
}
|
|
1704
1878
|
problem(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now() - started)}
|
|
@@ -1708,24 +1882,42 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1708
1882
|
return 1;
|
|
1709
1883
|
}
|
|
1710
1884
|
}
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1885
|
+
for (const probe of ports) {
|
|
1886
|
+
if (probe.left === undefined)
|
|
1887
|
+
continue;
|
|
1888
|
+
for (const candidate of hosts) {
|
|
1889
|
+
const problem = await portProblem(candidate, probe.port ?? 0);
|
|
1890
|
+
if (candidate === hosts[0])
|
|
1891
|
+
probe.left = problem;
|
|
1892
|
+
if (problem === undefined) {
|
|
1893
|
+
const name = `${candidate.includes(":") ? `[${candidate}]` : candidate}:${probe.port}`;
|
|
1894
|
+
probe.left = undefined;
|
|
1895
|
+
probe.name = name;
|
|
1896
|
+
metAt.push({ name, ms: Date.now() - started });
|
|
1897
|
+
say(`${name} listening after ${formatDuration(Date.now() - started)}`);
|
|
1898
|
+
break;
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1715
1901
|
}
|
|
1716
|
-
|
|
1902
|
+
for (const probe of urls) {
|
|
1903
|
+
if (probe.left === undefined)
|
|
1904
|
+
continue;
|
|
1717
1905
|
const budget = Math.max(1, Math.min(URL_TIMEOUT, started + timeout - Date.now()));
|
|
1718
|
-
const check = await urlCheck(
|
|
1719
|
-
const isCutShort = "problem" in check && check.isTimeout === true && budget < URL_TIMEOUT &&
|
|
1906
|
+
const check = await urlCheck(probe.name, budget, expect);
|
|
1907
|
+
const isCutShort = "problem" in check && check.isTimeout === true && budget < URL_TIMEOUT && probe.left !== "not checked yet";
|
|
1720
1908
|
if (!isCutShort)
|
|
1721
|
-
|
|
1722
|
-
if ("status" in check)
|
|
1723
|
-
|
|
1909
|
+
probe.left = "problem" in check ? check.problem : undefined;
|
|
1910
|
+
if ("status" in check) {
|
|
1911
|
+
metAt.push({ name: probe.name, ms: Date.now() - started });
|
|
1912
|
+
say(`${probe.name} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
|
|
1913
|
+
}
|
|
1724
1914
|
}
|
|
1725
1915
|
if (pid !== undefined && isPidLeft) {
|
|
1726
1916
|
isPidLeft = pidAlive(pid);
|
|
1727
|
-
if (!isPidLeft)
|
|
1917
|
+
if (!isPidLeft) {
|
|
1918
|
+
metAt.push({ name: `pid ${pid}`, ms: Date.now() - started });
|
|
1728
1919
|
say(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
|
|
1920
|
+
}
|
|
1729
1921
|
}
|
|
1730
1922
|
if (values.cmd !== undefined && cmdLeft !== undefined && Date.now() - cmdRanAt >= interval) {
|
|
1731
1923
|
const budget = Math.max(1, Math.min(CMD_RUN_LIMIT, started + timeout - Date.now()));
|
|
@@ -1733,19 +1925,21 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1733
1925
|
if (!(problem?.startsWith("timed out") === true && budget < CMD_RUN_LIMIT && cmdLeft !== "not run yet"))
|
|
1734
1926
|
cmdLeft = problem;
|
|
1735
1927
|
cmdRanAt = Date.now();
|
|
1736
|
-
if (cmdLeft === undefined)
|
|
1928
|
+
if (cmdLeft === undefined) {
|
|
1929
|
+
metAt.push({ name: `\`${values.cmd}\``, ms: Date.now() - started });
|
|
1737
1930
|
say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now() - started)}`);
|
|
1931
|
+
}
|
|
1738
1932
|
}
|
|
1739
1933
|
const isMet = [
|
|
1740
1934
|
values.until !== undefined && (watch?.done ?? false),
|
|
1741
|
-
|
|
1742
|
-
|
|
1935
|
+
ports.some((probe) => probe.left === undefined),
|
|
1936
|
+
urls.some((probe) => probe.left === undefined),
|
|
1743
1937
|
pid !== undefined && !isPidLeft,
|
|
1744
1938
|
values.cmd !== undefined && cmdLeft === undefined
|
|
1745
1939
|
];
|
|
1746
|
-
if (isAny ? isMet.includes(true) : (watch?.done ?? true) &&
|
|
1940
|
+
if (isAny ? isMet.includes(true) : (watch?.done ?? true) && ports.every((probe) => probe.left === undefined) && urls.every((probe) => probe.left === undefined) && !isPidLeft && cmdLeft === undefined) {
|
|
1747
1941
|
if (json)
|
|
1748
|
-
printJson({ met: true, ms: Date.now() - started, line: matched ?? null });
|
|
1942
|
+
printJson({ met: true, ms: Date.now() - started, line: matched ?? null, conditions: metAt });
|
|
1749
1943
|
return 0;
|
|
1750
1944
|
}
|
|
1751
1945
|
if (Date.now() - started >= timeout && !(watch?.failing ?? false))
|
|
@@ -1758,10 +1952,14 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1758
1952
|
const missing = [];
|
|
1759
1953
|
if (watch !== undefined && !watch.done)
|
|
1760
1954
|
missing.push(watch.exists ? `no line of ${watch.path} matched --until` : `${watch.path} does not exist`);
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1955
|
+
for (const probe of ports) {
|
|
1956
|
+
if (probe.left !== undefined)
|
|
1957
|
+
missing.push(`${hosts[0]}:${probe.port} is not listening (${probe.left})`);
|
|
1958
|
+
}
|
|
1959
|
+
for (const probe of urls) {
|
|
1960
|
+
if (probe.left !== undefined)
|
|
1961
|
+
missing.push(`${probe.name} ${probe.left}`);
|
|
1962
|
+
}
|
|
1765
1963
|
if (isPidLeft)
|
|
1766
1964
|
missing.push(`pid ${pid} is still running`);
|
|
1767
1965
|
if (cmdLeft !== undefined)
|
|
@@ -1771,4 +1969,4 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1771
1969
|
last lines of ${watch?.path}:
|
|
1772
1970
|
${numbered(lines)}`}`);
|
|
1773
1971
|
}
|
|
1774
|
-
|
|
1972
|
+
process20.exitCode = await runMain({ name: "waitfor", run: main });
|
package/dist/slot-cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/slot-cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process21 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
7
|
import process9 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
@@ -468,24 +468,20 @@ function printJson(value) {
|
|
|
468
468
|
|
|
469
469
|
// ../kit/src/help.ts
|
|
470
470
|
import process8 from "process";
|
|
471
|
-
var OPTIONAL =
|
|
471
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
472
472
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
473
473
|
var FULL_STOP = /\.$/;
|
|
474
474
|
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
475
475
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
476
476
|
}
|
|
477
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
478
|
-
return [usageLine(usage, colors),
|
|
477
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
478
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
479
479
|
`);
|
|
480
480
|
}
|
|
481
481
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
482
482
|
if (exits.length === 0)
|
|
483
483
|
return [];
|
|
484
|
-
|
|
485
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
486
|
-
}
|
|
487
|
-
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
488
|
-
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
484
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
489
485
|
}
|
|
490
486
|
function wantsHelpJson(env = process8.env) {
|
|
491
487
|
return env.KIT_HELP === "json";
|
|
@@ -511,29 +507,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
511
507
|
return [];
|
|
512
508
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
513
509
|
}
|
|
510
|
+
var MAX_INLINE_CHOICES = 24;
|
|
514
511
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
515
512
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
516
513
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
517
|
-
const
|
|
514
|
+
const choices = option.choices?.join("|");
|
|
515
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
516
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
518
517
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
519
518
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
520
|
-
|
|
519
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
520
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
521
521
|
});
|
|
522
522
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
523
523
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
524
524
|
}
|
|
525
525
|
|
|
526
526
|
// ../kit/src/text.ts
|
|
527
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
528
527
|
function distance(a, b) {
|
|
529
|
-
|
|
530
|
-
|
|
528
|
+
const left = [...a];
|
|
529
|
+
const right = [...b];
|
|
530
|
+
let before = [];
|
|
531
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
532
|
+
for (const [i, x] of left.entries()) {
|
|
531
533
|
const current = [i + 1];
|
|
532
|
-
for (const [j,
|
|
533
|
-
|
|
534
|
+
for (const [j, y] of right.entries()) {
|
|
535
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
536
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
537
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
538
|
+
current.push(cost);
|
|
539
|
+
}
|
|
540
|
+
before = previous;
|
|
534
541
|
previous = current;
|
|
535
542
|
}
|
|
536
|
-
return previous[
|
|
543
|
+
return previous[right.length] ?? 0;
|
|
537
544
|
}
|
|
538
545
|
function closest(name, names) {
|
|
539
546
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -609,7 +616,7 @@ class Completing {
|
|
|
609
616
|
}
|
|
610
617
|
var completion = { active: false };
|
|
611
618
|
var OUTPUT_OPTIONS = {
|
|
612
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
619
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
613
620
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
614
621
|
};
|
|
615
622
|
function applyOutput(color, plain, env = process9.env) {
|
|
@@ -1073,31 +1080,109 @@ function interceptOutput(clear) {
|
|
|
1073
1080
|
// ../kit/src/cli.ts
|
|
1074
1081
|
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1075
1082
|
import { dirname as dirname3, join as join6 } from "path";
|
|
1076
|
-
import
|
|
1083
|
+
import process16 from "process";
|
|
1084
|
+
|
|
1085
|
+
// ../kit/src/completions.ts
|
|
1086
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1087
|
+
var FISH_FUNCTION = `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'
|
|
1088
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1089
|
+
set -l current (commandline -ct)
|
|
1090
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1091
|
+
if test "$line" = __files__
|
|
1092
|
+
__fish_complete_path $current
|
|
1093
|
+
else
|
|
1094
|
+
echo $line
|
|
1095
|
+
end
|
|
1096
|
+
end
|
|
1097
|
+
end`;
|
|
1098
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1099
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1100
|
+
local -a lines
|
|
1101
|
+
COMPREPLY=()
|
|
1102
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1103
|
+
for line in "\${lines[@]}"; do
|
|
1104
|
+
if [[ $line == __files__ ]]; then
|
|
1105
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1106
|
+
else
|
|
1107
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1108
|
+
fi
|
|
1109
|
+
done
|
|
1110
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1111
|
+
}`;
|
|
1112
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1113
|
+
local line
|
|
1114
|
+
local -a described plain
|
|
1115
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1116
|
+
if [[ $line == __files__ ]]; then
|
|
1117
|
+
_files
|
|
1118
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
1119
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1120
|
+
else
|
|
1121
|
+
plain+=("$line")
|
|
1122
|
+
fi
|
|
1123
|
+
done
|
|
1124
|
+
(( \${#described} )) && _describe -V value described
|
|
1125
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1126
|
+
return 0
|
|
1127
|
+
}`;
|
|
1128
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1129
|
+
if (shell === "fish")
|
|
1130
|
+
return `${header}
|
|
1131
|
+
${FISH_FUNCTION}
|
|
1132
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1133
|
+
`).join("")}`;
|
|
1134
|
+
if (shell === "bash")
|
|
1135
|
+
return `${header}
|
|
1136
|
+
${BASH_FUNCTION}
|
|
1137
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1138
|
+
`;
|
|
1139
|
+
return `${header}
|
|
1140
|
+
${ZSH_FUNCTION}
|
|
1141
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1142
|
+
`;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// ../kit/src/notify.ts
|
|
1146
|
+
import process13 from "process";
|
|
1147
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
1148
|
+
var CANCELLED = 130;
|
|
1149
|
+
function base64(text) {
|
|
1150
|
+
return Buffer.from(text).toString("base64");
|
|
1151
|
+
}
|
|
1152
|
+
function notification(title, body, env = process13.env) {
|
|
1153
|
+
const id = `kit${process13.pid}`;
|
|
1154
|
+
const 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\\`];
|
|
1155
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1156
|
+
}
|
|
1157
|
+
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
1158
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1159
|
+
return;
|
|
1160
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1161
|
+
}
|
|
1077
1162
|
|
|
1078
1163
|
// ../kit/src/usage.ts
|
|
1079
1164
|
import { appendFileSync, mkdirSync } from "fs";
|
|
1080
1165
|
import { homedir as homedir4 } from "os";
|
|
1081
1166
|
import { dirname as dirname2, isAbsolute, join as join5 } from "path";
|
|
1082
|
-
import
|
|
1167
|
+
import process15 from "process";
|
|
1083
1168
|
|
|
1084
1169
|
// ../kit/src/logs.ts
|
|
1085
1170
|
import { lstatSync, openSync } from "fs";
|
|
1086
1171
|
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
1087
1172
|
import { homedir as homedir3, tmpdir } from "os";
|
|
1088
1173
|
import { join as join4 } from "path";
|
|
1089
|
-
import
|
|
1174
|
+
import process14 from "process";
|
|
1090
1175
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1091
1176
|
var CLI_FOLDER = "kaynooo-cli";
|
|
1092
1177
|
function isPrivateDirectory(path) {
|
|
1093
1178
|
try {
|
|
1094
1179
|
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
1095
|
-
return info !== undefined && info.isDirectory() && info.uid === (
|
|
1180
|
+
return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
1096
1181
|
} catch {
|
|
1097
1182
|
return false;
|
|
1098
1183
|
}
|
|
1099
1184
|
}
|
|
1100
|
-
async function privateLogDirectory(name, env =
|
|
1185
|
+
async function privateLogDirectory(name, env = process14.env) {
|
|
1101
1186
|
const runtime = env.XDG_RUNTIME_DIR;
|
|
1102
1187
|
const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
|
|
1103
1188
|
const path = join4(base, name);
|
|
@@ -1117,14 +1202,14 @@ var usageError;
|
|
|
1117
1202
|
function noteUsageError(message) {
|
|
1118
1203
|
usageError = message;
|
|
1119
1204
|
}
|
|
1120
|
-
function stateHome(env =
|
|
1205
|
+
function stateHome(env = process15.env) {
|
|
1121
1206
|
const dir = env.XDG_STATE_HOME;
|
|
1122
1207
|
return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
|
|
1123
1208
|
}
|
|
1124
|
-
function usagePath(env =
|
|
1209
|
+
function usagePath(env = process15.env) {
|
|
1125
1210
|
return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1126
1211
|
}
|
|
1127
|
-
function usageRecorded(env =
|
|
1212
|
+
function usageRecorded(env = process15.env) {
|
|
1128
1213
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1129
1214
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1130
1215
|
}
|
|
@@ -1138,7 +1223,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
1138
1223
|
usageError = undefined;
|
|
1139
1224
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1140
1225
|
}
|
|
1141
|
-
function recordUsage(entry, env =
|
|
1226
|
+
function recordUsage(entry, env = process15.env) {
|
|
1142
1227
|
if (!usageRecorded(env))
|
|
1143
1228
|
return;
|
|
1144
1229
|
try {
|
|
@@ -1154,10 +1239,14 @@ var LEVEL_OPTIONS = {
|
|
|
1154
1239
|
...OUTPUT_OPTIONS,
|
|
1155
1240
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1156
1241
|
};
|
|
1157
|
-
var TOP_OPTIONS = {
|
|
1242
|
+
var TOP_OPTIONS = {
|
|
1243
|
+
...LEVEL_OPTIONS,
|
|
1244
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1245
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1246
|
+
};
|
|
1158
1247
|
function printError(prefix, message, hint, cause) {
|
|
1159
|
-
const colors = paint(
|
|
1160
|
-
const styled = takesControlCodes(
|
|
1248
|
+
const colors = paint(process16.stderr);
|
|
1249
|
+
const styled = takesControlCodes(process16.stderr);
|
|
1161
1250
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1162
1251
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1163
1252
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1234,6 +1323,19 @@ async function leafCandidates(run, words) {
|
|
|
1234
1323
|
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1235
1324
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1236
1325
|
}
|
|
1326
|
+
var COMPLETIONS = "--completions";
|
|
1327
|
+
function flagValue([flag = "", ...rest]) {
|
|
1328
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1329
|
+
}
|
|
1330
|
+
function printCompletionScript(name, args) {
|
|
1331
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1332
|
+
if (shell === undefined || args.length !== 1) {
|
|
1333
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1334
|
+
return 2;
|
|
1335
|
+
}
|
|
1336
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1337
|
+
return 0;
|
|
1338
|
+
}
|
|
1237
1339
|
async function printCandidates(found) {
|
|
1238
1340
|
for (const line of await found)
|
|
1239
1341
|
console.log(line);
|
|
@@ -1257,16 +1359,20 @@ function packageVersion(entry = Bun.main) {
|
|
|
1257
1359
|
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1258
1360
|
if (argv[0] === COMPLETE)
|
|
1259
1361
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1362
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1363
|
+
return printCompletionScript(name, flagValue(argv));
|
|
1260
1364
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1261
1365
|
console.log(version ?? packageVersion());
|
|
1262
1366
|
return 0;
|
|
1263
1367
|
}
|
|
1264
1368
|
let code;
|
|
1369
|
+
const started = performance.now();
|
|
1265
1370
|
try {
|
|
1266
1371
|
code = await run(argv);
|
|
1267
1372
|
} catch (error) {
|
|
1268
1373
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1269
1374
|
}
|
|
1375
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1270
1376
|
if (usage !== false) {
|
|
1271
1377
|
try {
|
|
1272
1378
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1281,15 +1387,15 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
1281
1387
|
// ../kit/src/sessions.ts
|
|
1282
1388
|
import { homedir as homedir5 } from "os";
|
|
1283
1389
|
import { join as join7 } from "path";
|
|
1284
|
-
import
|
|
1390
|
+
import process17 from "process";
|
|
1285
1391
|
var {Glob } = globalThis.Bun;
|
|
1286
1392
|
var SESSION_FILES = new Glob("*.json");
|
|
1287
1393
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1288
1394
|
async function sessionDirs() {
|
|
1289
1395
|
const home = homedir5();
|
|
1290
1396
|
const dirs = new Set([join7(home, ".claude", "sessions")]);
|
|
1291
|
-
if (
|
|
1292
|
-
dirs.add(join7(
|
|
1397
|
+
if (process17.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
1398
|
+
dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR, "sessions"));
|
|
1293
1399
|
try {
|
|
1294
1400
|
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
|
|
1295
1401
|
dirs.add(dir);
|
|
@@ -1335,7 +1441,7 @@ async function liveSessions() {
|
|
|
1335
1441
|
}
|
|
1336
1442
|
async function currentSession(sessions) {
|
|
1337
1443
|
const byPid = new Map(sessions.map((session) => [session.pid, session]));
|
|
1338
|
-
let pid =
|
|
1444
|
+
let pid = process17.ppid;
|
|
1339
1445
|
for (let depth = 0;depth < 32 && pid > 1; depth++) {
|
|
1340
1446
|
const session = byPid.get(pid);
|
|
1341
1447
|
if (session !== undefined)
|
|
@@ -1351,17 +1457,17 @@ async function currentSession(sessions) {
|
|
|
1351
1457
|
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync5, rmSync } from "fs";
|
|
1352
1458
|
import { availableParallelism } from "os";
|
|
1353
1459
|
import { join as join8 } from "path";
|
|
1354
|
-
import
|
|
1460
|
+
import process20 from "process";
|
|
1355
1461
|
|
|
1356
1462
|
// src/flock.ts
|
|
1357
1463
|
import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
|
|
1358
|
-
import
|
|
1464
|
+
import process19 from "process";
|
|
1359
1465
|
import { dlopen, FFIType } from "bun:ffi";
|
|
1360
1466
|
var LOCK_EX = 2;
|
|
1361
1467
|
var LOCK_NB = 4;
|
|
1362
1468
|
var flock;
|
|
1363
1469
|
function native() {
|
|
1364
|
-
flock ??= dlopen(
|
|
1470
|
+
flock ??= dlopen(process19.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
|
|
1365
1471
|
return flock;
|
|
1366
1472
|
}
|
|
1367
1473
|
function tryLock(path) {
|
|
@@ -1405,7 +1511,7 @@ function defaultSlots() {
|
|
|
1405
1511
|
return Math.max(1, Math.floor(availableParallelism() / 2));
|
|
1406
1512
|
}
|
|
1407
1513
|
async function stateDir() {
|
|
1408
|
-
const dir =
|
|
1514
|
+
const dir = process20.env.SLOT_DIR ?? await privateLogDirectory("slot");
|
|
1409
1515
|
for (const sub of ["slots", "locks", "waiters"])
|
|
1410
1516
|
mkdirSync2(join8(dir, sub), { recursive: true, mode: 448 });
|
|
1411
1517
|
return dir;
|
|
@@ -1447,7 +1553,7 @@ function waitingLine(dir, wanted) {
|
|
|
1447
1553
|
}
|
|
1448
1554
|
async function holderOf(command) {
|
|
1449
1555
|
const session = await currentSession(await liveSessions());
|
|
1450
|
-
return { pid:
|
|
1556
|
+
return { pid: process20.pid, command: command.join(" "), cwd: process20.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
|
|
1451
1557
|
}
|
|
1452
1558
|
var waiterCount = 0;
|
|
1453
1559
|
async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
@@ -1473,7 +1579,7 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
|
1473
1579
|
held.release();
|
|
1474
1580
|
const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
|
|
1475
1581
|
if (waiter === undefined) {
|
|
1476
|
-
const path = join8(dir, "waiters", `${
|
|
1582
|
+
const path = join8(dir, "waiters", `${process20.pid}-${waiterCount++}`);
|
|
1477
1583
|
const held = tryLock(path);
|
|
1478
1584
|
if (held !== undefined) {
|
|
1479
1585
|
writeHeld(held, JSON.stringify({ ...holder, resource }));
|
|
@@ -1514,7 +1620,7 @@ ${RUN_USAGE}`);
|
|
|
1514
1620
|
const count = wholeNumber(values.slots, "slots", defaultSlots());
|
|
1515
1621
|
const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
|
|
1516
1622
|
const deadline = Date.now() + timeoutMs;
|
|
1517
|
-
const holding = new Set((
|
|
1623
|
+
const holding = new Set((process20.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
|
|
1518
1624
|
const wanted = [...locks.filter((name) => !holding.has(`lock:${name}`)).map((name) => ({ kind: "lock", name, count })), ...values["no-slot"] === true || holding.has("slot") ? [] : [{ kind: "slot", name: "", count }]];
|
|
1519
1625
|
const signals = holdSignals(() => {
|
|
1520
1626
|
return;
|
|
@@ -1529,7 +1635,7 @@ ${RUN_USAGE}`);
|
|
|
1529
1635
|
const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
|
|
1530
1636
|
let child;
|
|
1531
1637
|
try {
|
|
1532
|
-
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...
|
|
1638
|
+
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process20.env, [HOLDING]: [...tokens].join(",") } });
|
|
1533
1639
|
} catch (error) {
|
|
1534
1640
|
fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
|
|
1535
1641
|
}
|
|
@@ -1572,11 +1678,11 @@ async function listSlots(args) {
|
|
|
1572
1678
|
printJson({ slots: count, busy, entries });
|
|
1573
1679
|
return 0;
|
|
1574
1680
|
}
|
|
1575
|
-
console.log(paint(
|
|
1681
|
+
console.log(paint(process20.stdout).bold(`slots: ${busy} of ${count} busy`));
|
|
1576
1682
|
if (entries.length > 0)
|
|
1577
|
-
console.log(table(entries.map((entry) => [badge(entry.state,
|
|
1683
|
+
console.log(table(entries.map((entry) => [badge(entry.state, process20.stdout), entry.resource, entry.session ?? `pid ${entry.pid}`, truncate(entry.command, COMMAND_WIDTH), entry.since === 0 ? "?" : formatAge(entry.since)])));
|
|
1578
1684
|
return 0;
|
|
1579
1685
|
}
|
|
1580
1686
|
|
|
1581
1687
|
// src/slot-cli.ts
|
|
1582
|
-
|
|
1688
|
+
process21.exitCode = await runMain({ name: "slot", run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-wait",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.12.1",
|
|
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",
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
"waitfor": "$npm_execpath src/cli.ts"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@kaynooo/cli-kit": "0.
|
|
41
|
+
"@kaynooo/cli-kit": "0.41.0"
|
|
42
42
|
}
|
|
43
43
|
}
|