@kaynooo/cli-wait 0.10.1 → 0.12.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 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 process18 from "process";
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 = /\[[^\]]+\]/g;
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 = [], replaces, exits = [] } = {}) {
479
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
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
- const width = Math.max(...exits.map(([code]) => String(code).length));
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 named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
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
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
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
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
531
- for (const [i, left] of [...a].entries()) {
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, right] of [...b].entries())
534
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
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[b.length] ?? 0;
544
+ return previous[right.length] ?? 0;
538
545
  }
539
546
  function closest(name, names) {
540
547
  const started = names.find((known) => known.startsWith(name));
@@ -782,12 +789,36 @@ function nearestOption(message, options, allowNegative) {
782
789
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
783
790
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
784
791
  }
792
+ // ../kit/src/argv.ts
793
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
794
+ import { resolve as resolve3 } from "path";
795
+ import process10 from "process";
796
+ function commandLine() {
797
+ try {
798
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
799
+ } catch {
800
+ return;
801
+ }
802
+ }
803
+ function realPath(word) {
804
+ try {
805
+ return realpathSync(resolve3(word));
806
+ } catch {
807
+ return;
808
+ }
809
+ }
810
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
811
+ const target = script === undefined ? undefined : realPath(script) ?? script;
812
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
813
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
814
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
815
+ }
785
816
  // ../kit/src/progress.ts
786
- import process11 from "process";
817
+ import process12 from "process";
787
818
 
788
819
  // ../kit/src/process.ts
789
820
  import { constants } from "os";
790
- import process10 from "process";
821
+ import process11 from "process";
791
822
  var KILL_GRACE_MS = 2000;
792
823
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
793
824
  function exitCodeOf(code, signal) {
@@ -809,7 +840,7 @@ function holdSignals(cleanup) {
809
840
  },
810
841
  release: () => {
811
842
  for (const signal of SIGNALS)
812
- process10.off(signal, onSignal);
843
+ process11.off(signal, onSignal);
813
844
  }
814
845
  };
815
846
  function onSignal(signal) {
@@ -822,10 +853,10 @@ function holdSignals(cleanup) {
822
853
  return;
823
854
  held.release();
824
855
  cleanup(signal);
825
- process10.kill(process10.pid, signal);
856
+ process11.kill(process11.pid, signal);
826
857
  }
827
858
  for (const signal of SIGNALS)
828
- process10.on(signal, onSignal);
859
+ process11.on(signal, onSignal);
829
860
  return held;
830
861
  }
831
862
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -839,7 +870,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
839
870
  return;
840
871
  try {
841
872
  if (grouped)
842
- process10.kill(-proc.pid, killing);
873
+ process11.kill(-proc.pid, killing);
843
874
  else
844
875
  proc.kill(killing);
845
876
  } catch {}
@@ -917,7 +948,7 @@ var RESET_STYLE = `${ESC}[0m`;
917
948
  var CTRL_C = 3;
918
949
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
919
950
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
920
- function liveRegion(render, stream = process11.stderr, env = process11.env) {
951
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
921
952
  if (!takesControlCodes(stream, env))
922
953
  return { redraw: () => {
923
954
  return;
@@ -964,11 +995,11 @@ function liveRegion(render, stream = process11.stderr, env = process11.env) {
964
995
  clear();
965
996
  restore();
966
997
  release();
967
- process11.off("exit", onExit);
998
+ process12.off("exit", onExit);
968
999
  signals.release();
969
1000
  }
970
1001
  timer.unref();
971
- process11.on("exit", onExit);
1002
+ process12.on("exit", onExit);
972
1003
  return {
973
1004
  redraw: draw,
974
1005
  print: (text) => {
@@ -1007,14 +1038,14 @@ function cutToWidth(line, width) {
1007
1038
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1008
1039
  }
1009
1040
  function swallowInput() {
1010
- const input = process11.stdin;
1041
+ const input = process12.stdin;
1011
1042
  if (!input.isTTY)
1012
1043
  return () => {
1013
1044
  return;
1014
1045
  };
1015
1046
  const onData = (data) => {
1016
1047
  if (data.includes(CTRL_C))
1017
- process11.kill(process11.pid, "SIGINT");
1048
+ process12.kill(process12.pid, "SIGINT");
1018
1049
  };
1019
1050
  input.setRawMode(true);
1020
1051
  input.on("data", onData);
@@ -1030,7 +1061,7 @@ function swallowInput() {
1030
1061
  };
1031
1062
  }
1032
1063
  function interceptOutput(clear) {
1033
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process11.stdout, "write"], [process11.stderr, "write"]];
1064
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1034
1065
  const wrapped = targets.map(([target, name]) => {
1035
1066
  const original = Reflect.get(target, name);
1036
1067
  const wrapper = (...args) => {
@@ -1048,33 +1079,51 @@ function interceptOutput(clear) {
1048
1079
  };
1049
1080
  }
1050
1081
  // ../kit/src/cli.ts
1051
- import { readFileSync as readFileSync3, realpathSync } from "fs";
1082
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1052
1083
  import { dirname as dirname3, join as join6 } from "path";
1053
- import process14 from "process";
1084
+ import process16 from "process";
1085
+
1086
+ // ../kit/src/notify.ts
1087
+ import process13 from "process";
1088
+ var NOTIFY_AFTER_MS = 1e4;
1089
+ var CANCELLED = 130;
1090
+ function base64(text) {
1091
+ return Buffer.from(text).toString("base64");
1092
+ }
1093
+ function notification(title, body, env = process13.env) {
1094
+ const id = `kit${process13.pid}`;
1095
+ 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\\`];
1096
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1097
+ }
1098
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1099
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1100
+ return;
1101
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1102
+ }
1054
1103
 
1055
1104
  // ../kit/src/usage.ts
1056
1105
  import { appendFileSync, mkdirSync } from "fs";
1057
1106
  import { homedir as homedir4 } from "os";
1058
1107
  import { dirname as dirname2, isAbsolute, join as join5 } from "path";
1059
- import process13 from "process";
1108
+ import process15 from "process";
1060
1109
 
1061
1110
  // ../kit/src/logs.ts
1062
1111
  import { lstatSync, openSync } from "fs";
1063
1112
  import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1064
1113
  import { homedir as homedir3, tmpdir } from "os";
1065
1114
  import { join as join4 } from "path";
1066
- import process12 from "process";
1115
+ import process14 from "process";
1067
1116
  var DAY_MS = 24 * 60 * 60 * 1000;
1068
1117
  var CLI_FOLDER = "kaynooo-cli";
1069
1118
  function isPrivateDirectory(path) {
1070
1119
  try {
1071
1120
  const info = lstatSync(path, { throwIfNoEntry: false });
1072
- return info !== undefined && info.isDirectory() && info.uid === (process12.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1121
+ return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1073
1122
  } catch {
1074
1123
  return false;
1075
1124
  }
1076
1125
  }
1077
- async function privateLogDirectory(name, env = process12.env) {
1126
+ async function privateLogDirectory(name, env = process14.env) {
1078
1127
  const runtime = env.XDG_RUNTIME_DIR;
1079
1128
  const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
1080
1129
  const path = join4(base, name);
@@ -1094,14 +1143,14 @@ var usageError;
1094
1143
  function noteUsageError(message) {
1095
1144
  usageError = message;
1096
1145
  }
1097
- function stateHome(env = process13.env) {
1146
+ function stateHome(env = process15.env) {
1098
1147
  const dir = env.XDG_STATE_HOME;
1099
1148
  return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
1100
1149
  }
1101
- function usagePath(env = process13.env) {
1150
+ function usagePath(env = process15.env) {
1102
1151
  return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
1103
1152
  }
1104
- function usageRecorded(env = process13.env) {
1153
+ function usageRecorded(env = process15.env) {
1105
1154
  const off = env.KAYNOOO_CLI_NO_USAGE;
1106
1155
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1107
1156
  }
@@ -1115,7 +1164,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1115
1164
  usageError = undefined;
1116
1165
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1117
1166
  }
1118
- function recordUsage(entry, env = process13.env) {
1167
+ function recordUsage(entry, env = process15.env) {
1119
1168
  if (!usageRecorded(env))
1120
1169
  return;
1121
1170
  try {
@@ -1133,8 +1182,8 @@ var LEVEL_OPTIONS = {
1133
1182
  };
1134
1183
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1135
1184
  function printError(prefix, message, hint, cause) {
1136
- const colors = paint(process14.stderr);
1137
- const styled = takesControlCodes(process14.stderr);
1185
+ const colors = paint(process16.stderr);
1186
+ const styled = takesControlCodes(process16.stderr);
1138
1187
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1139
1188
  const under = (label, text, tint) => text === undefined ? "" : `
1140
1189
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1178,24 +1227,24 @@ function candidateLine(candidate) {
1178
1227
  }
1179
1228
  function positionalBeingTyped(before, { options, positionals }) {
1180
1229
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1181
- let index = 0;
1230
+ const typed = [];
1182
1231
  let at = 0;
1183
1232
  while (at < before.length) {
1184
1233
  const word = before[at];
1185
1234
  if (word === "--") {
1186
- index += before.length - at - 1;
1235
+ typed.push(...before.slice(at + 1));
1187
1236
  break;
1188
1237
  }
1189
1238
  if (!word.startsWith("-"))
1190
- index++;
1239
+ typed.push(word);
1191
1240
  else if (takesValue(word))
1192
1241
  at++;
1193
1242
  at++;
1194
1243
  }
1195
1244
  const last = positionals.at(-1);
1196
- if (index < positionals.length)
1197
- return positionals[index];
1198
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1245
+ if (typed.length < positionals.length)
1246
+ return { name: positionals[typed.length], typed };
1247
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1199
1248
  }
1200
1249
  async function leafCandidates(run, words) {
1201
1250
  const completing = await completingOf(run);
@@ -1203,12 +1252,12 @@ async function leafCandidates(run, words) {
1203
1252
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1204
1253
  const flag = words.at(-2);
1205
1254
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1255
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1206
1256
  if (option?.type === "string") {
1207
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1257
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1208
1258
  return values === undefined ? [FILES] : values.map(candidateLine);
1209
1259
  }
1210
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1211
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1260
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1212
1261
  return values === undefined ? [FILES] : values.map(candidateLine);
1213
1262
  }
1214
1263
  async function printCandidates(found) {
@@ -1217,9 +1266,13 @@ async function printCandidates(found) {
1217
1266
  return 0;
1218
1267
  }
1219
1268
  function packageVersion(entry = Bun.main) {
1220
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1269
+ let resolved = entry;
1270
+ try {
1271
+ resolved = realpathSync2(entry);
1272
+ } catch {}
1273
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1221
1274
  try {
1222
- const { version } = JSON.parse(readFileSync3(join6(dir, "package.json"), "utf8"));
1275
+ const { version } = JSON.parse(readFileSync4(join6(dir, "package.json"), "utf8"));
1223
1276
  if (typeof version === "string")
1224
1277
  return version;
1225
1278
  } catch {}
@@ -1227,7 +1280,7 @@ function packageVersion(entry = Bun.main) {
1227
1280
  return "0.0.0";
1228
1281
  }
1229
1282
  }
1230
- async function runMain({ name, version, run, redact, usage }, argv = process14.argv.slice(2)) {
1283
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1231
1284
  if (argv[0] === COMPLETE)
1232
1285
  return printCandidates(leafCandidates(run, argv.slice(1)));
1233
1286
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1235,11 +1288,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process14.a
1235
1288
  return 0;
1236
1289
  }
1237
1290
  let code;
1291
+ const started = performance.now();
1238
1292
  try {
1239
1293
  code = await run(argv);
1240
1294
  } catch (error) {
1241
1295
  code = reportThrown(name, error, redact, wantsJson(argv));
1242
1296
  }
1297
+ notifyEnd(name, code, performance.now() - started);
1243
1298
  if (usage !== false) {
1244
1299
  try {
1245
1300
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1254,15 +1309,15 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
1254
1309
  // ../kit/src/sessions.ts
1255
1310
  import { homedir as homedir5 } from "os";
1256
1311
  import { join as join7 } from "path";
1257
- import process15 from "process";
1312
+ import process17 from "process";
1258
1313
  var {Glob } = globalThis.Bun;
1259
1314
  var SESSION_FILES = new Glob("*.json");
1260
1315
  var ACCOUNT_DIRS = new Glob("*/sessions");
1261
1316
  async function sessionDirs() {
1262
1317
  const home = homedir5();
1263
1318
  const dirs = new Set([join7(home, ".claude", "sessions")]);
1264
- if (process15.env.CLAUDE_CONFIG_DIR !== undefined)
1265
- dirs.add(join7(process15.env.CLAUDE_CONFIG_DIR, "sessions"));
1319
+ if (process17.env.CLAUDE_CONFIG_DIR !== undefined)
1320
+ dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR, "sessions"));
1266
1321
  try {
1267
1322
  for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1268
1323
  dirs.add(dir);
@@ -1308,7 +1363,7 @@ async function liveSessions() {
1308
1363
  }
1309
1364
  async function currentSession(sessions) {
1310
1365
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
1311
- let pid = process15.ppid;
1366
+ let pid = process17.ppid;
1312
1367
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
1313
1368
  const session = byPid.get(pid);
1314
1369
  if (session !== undefined)
@@ -1434,20 +1489,67 @@ async function closeWhenConnected(attempt) {
1434
1489
  (await attempt).end();
1435
1490
  } catch {}
1436
1491
  }
1437
- async function urlCheck(url, timeout) {
1492
+ var STATUS_CLASS = /^([1-5])xx$/i;
1493
+ var STATUS_RANGE = /^(\d{3})(?:-(\d{3}))?$/;
1494
+ var BODY_BYTES = 1024 * 1024;
1495
+ function parseStatus(spec) {
1496
+ const tests = [];
1497
+ for (const part of spec.split(",").map((item) => item.trim())) {
1498
+ const klass = STATUS_CLASS.exec(part);
1499
+ const range = STATUS_RANGE.exec(part);
1500
+ if (klass !== null) {
1501
+ const hundred = Number(klass[1]);
1502
+ tests.push((status) => Math.floor(status / 100) === hundred);
1503
+ } else if (range !== null) {
1504
+ const low = Number(range[1]);
1505
+ const high = Number(range[2] ?? range[1]);
1506
+ tests.push((status) => status >= low && status <= high);
1507
+ } else {
1508
+ return;
1509
+ }
1510
+ }
1511
+ return (status) => tests.some((test) => test(status));
1512
+ }
1513
+ async function readBody(response) {
1514
+ const reader = response.body?.getReader();
1515
+ if (reader === undefined)
1516
+ return "";
1517
+ const decoder = new TextDecoder;
1518
+ let text = "";
1519
+ let bytes = 0;
1520
+ while (bytes < BODY_BYTES) {
1521
+ const { done, value } = await reader.read();
1522
+ if (done)
1523
+ break;
1524
+ bytes += value?.length ?? 0;
1525
+ text += decoder.decode(value, { stream: true });
1526
+ }
1527
+ await reader.cancel();
1528
+ return text;
1529
+ }
1530
+ async function urlCheck(url, timeout, expect = {}) {
1438
1531
  try {
1439
- const response = await fetch(url, { signal: AbortSignal.timeout(timeout) });
1440
- await response.body?.cancel();
1441
- return response.ok ? { status: response.status } : { problem: `answered ${response.status}` };
1532
+ const wantsRedirect = expect.status !== undefined && Array.from({ length: 100 }, (_, index) => 300 + index).some(expect.status.test);
1533
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeout), redirect: wantsRedirect ? "manual" : "follow" });
1534
+ const ok = expect.status === undefined ? response.ok : expect.status.test(response.status);
1535
+ if (!ok) {
1536
+ await response.body?.cancel();
1537
+ return { problem: expect.status === undefined ? `answered ${response.status}` : `answered ${response.status}, expected ${expect.status.spec}` };
1538
+ }
1539
+ if (expect.body === undefined) {
1540
+ await response.body?.cancel();
1541
+ return { status: response.status };
1542
+ }
1543
+ return expect.body.test(await readBody(response)) ? { status: response.status } : { problem: `answered ${response.status} but the body does not match ${expect.body}` };
1442
1544
  } catch (error) {
1443
1545
  return { problem: error instanceof Error ? error.message : String(error), isTimeout: error instanceof Error && error.name === "TimeoutError" };
1444
1546
  }
1445
1547
  }
1446
1548
 
1447
1549
  // src/task.ts
1448
- import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync4, statSync as statSync3 } from "fs";
1550
+ import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
1449
1551
  import { join as join8 } from "path";
1450
- import process17 from "process";
1552
+ import process19 from "process";
1451
1553
  var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
1452
1554
  var FAILURE = /\(fail\)|\berror:/i;
1453
1555
  var TASK_ID = /^[\w-]+$/;
@@ -1455,9 +1557,9 @@ var TAIL_BYTES = 256;
1455
1557
  var LONGEST_FAILURES = 30;
1456
1558
  var CARRIAGE_RETURN2 = /\r$/;
1457
1559
  function tasksRoot(env) {
1458
- return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process17.getuid?.() ?? 0}`);
1560
+ return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process19.getuid?.() ?? 0}`);
1459
1561
  }
1460
- function taskFile(task, env = process17.env) {
1562
+ function taskFile(task, env = process19.env) {
1461
1563
  if (task.includes("/") || task.endsWith(".output"))
1462
1564
  return task;
1463
1565
  if (!TASK_ID.test(task))
@@ -1490,7 +1592,7 @@ async function taskEnd(path, lines) {
1490
1592
  }
1491
1593
  function pidAlive(pid) {
1492
1594
  try {
1493
- process17.kill(pid, 0);
1595
+ process19.kill(pid, 0);
1494
1596
  } catch (error) {
1495
1597
  return error.code === "EPERM";
1496
1598
  }
@@ -1498,7 +1600,7 @@ function pidAlive(pid) {
1498
1600
  }
1499
1601
  function isZombie(pid) {
1500
1602
  try {
1501
- const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1603
+ const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
1502
1604
  return stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z";
1503
1605
  } catch {
1504
1606
  return false;
@@ -1509,8 +1611,8 @@ function isZombie(pid) {
1509
1611
  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
1510
1612
  waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
1511
1613
 
1512
- 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.
1513
- --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.`;
1614
+ 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.
1615
+ --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.`;
1514
1616
  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
1515
1617
 
1516
1618
  The task is the id a background Bash call returned, or the path of its .output file.
@@ -1528,9 +1630,11 @@ var OPTIONS = {
1528
1630
  file: { type: "string", short: "f", description: "a log file to read, from its start, waiting for it to exist" },
1529
1631
  until: { type: "string", short: "u", description: "a regular expression a line of --file must match" },
1530
1632
  fail: { type: "string", short: "e", description: "a regular expression whose first matching line of --file is a failure" },
1531
- port: { type: "string", short: "p", description: "a TCP port that must accept connections" },
1532
- host: { type: "string", short: "H", description: "the host of --port (127.0.0.1)" },
1533
- url: { type: "string", description: "a URL that must answer 2xx" },
1633
+ port: { type: "string", short: "p", multiple: true, description: "a TCP port that must accept connections, repeatable" },
1634
+ host: { type: "string", short: "H", description: "the host of --port (127.0.0.1 and ::1)" },
1635
+ url: { type: "string", multiple: true, description: "a URL that must answer 2xx (or --status), repeatable" },
1636
+ status: { type: "string", description: "the status a --url must answer instead of 2xx: 301, 200-299, 2xx or a comma list, for every --url" },
1637
+ body: { type: "string", description: "a regular expression the first MiB of a --url body must match, for every --url" },
1534
1638
  pid: { type: "string", description: "a process id that must exit" },
1535
1639
  cmd: { type: "string", short: "c", description: "a shell command that must exit 0, re-run every --interval" },
1536
1640
  interval: { type: "string", description: "how long between two runs of --cmd (1s)" },
@@ -1581,7 +1685,7 @@ async function waitTask(args) {
1581
1685
  const lines = wholeNumber(values.lines, "lines", 20);
1582
1686
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
1583
1687
  const started = Date.now();
1584
- const { dim } = paint(process18.stderr);
1688
+ const { dim } = paint(process20.stderr);
1585
1689
  const region = values.quiet === true ? undefined : liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
1586
1690
  let code;
1587
1691
  try {
@@ -1619,26 +1723,46 @@ async function main(args) {
1619
1723
  fail(`unexpected argument ${positionals[0]}
1620
1724
 
1621
1725
  ${USAGE}`);
1622
- if (values.until === undefined && values.port === undefined && values.url === undefined && values.pid === undefined && values.cmd === undefined)
1726
+ const portTexts = values.port ?? [];
1727
+ const urlTexts = values.url ?? [];
1728
+ if (values.until === undefined && portTexts.length === 0 && urlTexts.length === 0 && values.pid === undefined && values.cmd === undefined)
1623
1729
  fail(`give --until with --file, --port, --url, --pid or --cmd
1624
1730
 
1625
1731
  ${USAGE}`);
1626
1732
  if ((values.until !== undefined || values.fail !== undefined) !== (values.file !== undefined))
1627
1733
  fail("--until and --fail read the --file lines, and --file needs one of them");
1628
- if (values.host !== undefined && values.port === undefined)
1734
+ if (values.host !== undefined && portTexts.length === 0)
1629
1735
  fail("--host goes with --port");
1630
- const conditions = [values.until, values.port, values.url, values.pid, values.cmd].filter((condition) => condition !== undefined).length;
1736
+ if ((values.status !== undefined || values.body !== undefined) && urlTexts.length === 0)
1737
+ fail("--status and --body go with --url");
1738
+ const conditions = [values.until, ...portTexts, ...urlTexts, values.pid, values.cmd].filter((condition) => condition !== undefined).length;
1631
1739
  if (values.any === true && conditions < 2)
1632
1740
  fail("--any needs two or more of --until, --port, --url, --pid and --cmd");
1633
1741
  if (values.interval !== undefined && values.cmd === undefined)
1634
1742
  fail("--interval goes with --cmd");
1635
- const port = values.port === undefined ? undefined : wholeNumber(values.port, "port", 0);
1636
- if (port !== undefined && port > 65535)
1637
- fail(`--port takes a port up to 65535, not ${port}`);
1638
- if (values.url !== undefined && !URL.canParse(values.url))
1639
- fail(`--url ${values.url} is no URL`);
1743
+ const ports = portTexts.map((text) => {
1744
+ const port = wholeNumber(text, "port", 0);
1745
+ if (port > 65535)
1746
+ fail(`--port takes a port up to 65535, not ${port}`);
1747
+ return { name: String(port), port, left: "not checked yet" };
1748
+ });
1749
+ for (const url of urlTexts) {
1750
+ if (!URL.canParse(url))
1751
+ fail(`--url ${url} is no URL`);
1752
+ }
1753
+ const statusTest = values.status === undefined ? undefined : parseStatus(values.status);
1754
+ if (values.status !== undefined && statusTest === undefined)
1755
+ fail(`--status takes a code, a range or a class such as 301, 200-299 or 2xx, not ${values.status}`);
1756
+ const expect = {};
1757
+ if (values.status !== undefined && statusTest !== undefined)
1758
+ expect.status = { test: statusTest, spec: values.status };
1759
+ const body = regex(values.body, "body");
1760
+ if (body !== undefined)
1761
+ expect.body = body;
1762
+ const urls = urlTexts.map((url) => ({ name: url, left: "not checked yet" }));
1763
+ const metAt = [];
1640
1764
  const pid = values.pid === undefined ? undefined : wholeNumber(values.pid, "pid", 0);
1641
- const host = values.host ?? "127.0.0.1";
1765
+ const hosts = values.host === undefined ? ["127.0.0.1", "::1"] : [values.host];
1642
1766
  const interval = duration(values.interval, "interval", 1000);
1643
1767
  const isAny = values.any === true;
1644
1768
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
@@ -1647,18 +1771,16 @@ ${USAGE}`);
1647
1771
  const json = values.json === true;
1648
1772
  const say = json ? console.error : console.log;
1649
1773
  let matched;
1650
- let portLeft = port === undefined ? undefined : "not checked yet";
1651
- let urlLeft = values.url === undefined ? undefined : "not checked yet";
1652
1774
  let isPidLeft = pid !== undefined;
1653
1775
  let cmdLeft = values.cmd === undefined ? undefined : "not run yet";
1654
1776
  let cmdRanAt = 0;
1655
- const { dim } = paint(process18.stderr);
1777
+ const { dim } = paint(process20.stderr);
1656
1778
  const region = values.quiet === true ? undefined : liveRegion((spinner) => {
1657
1779
  const waited = dim(formatElapsed(Date.now() - started));
1658
1780
  const left = [
1659
1781
  watch === undefined || watch.done ? undefined : `${watch.path}: ${watch.exists ? "no --until line yet" : "does not exist yet"}`,
1660
- portLeft === undefined ? undefined : `${host}:${port}: ${portLeft}`,
1661
- urlLeft === undefined ? undefined : `${values.url}: ${urlLeft}`,
1782
+ ...ports.filter((probe) => probe.left !== undefined).map((probe) => `${hosts[0]}:${probe.port}: ${probe.left}`),
1783
+ ...urls.filter((probe) => probe.left !== undefined).map((probe) => `${probe.name}: ${probe.left}`),
1662
1784
  isPidLeft ? `pid ${pid}: still running` : undefined,
1663
1785
  cmdLeft === undefined ? undefined : `\`${values.cmd}\`: ${cmdLeft}`
1664
1786
  ];
@@ -1671,6 +1793,7 @@ ${USAGE}`);
1671
1793
  if (event.kind === "until") {
1672
1794
  say(`${watch.path}:${event.line.number}: ${truncate(event.line.text, WIDTH)}`);
1673
1795
  matched = { number: event.line.number, text: event.line.text };
1796
+ metAt.push({ name: `${watch.path} --until`, ms: Date.now() - started });
1674
1797
  continue;
1675
1798
  }
1676
1799
  problem(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now() - started)}
@@ -1680,24 +1803,42 @@ ${numbered(event.excerpt, event.line)}`);
1680
1803
  return 1;
1681
1804
  }
1682
1805
  }
1683
- if (port !== undefined && portLeft !== undefined) {
1684
- portLeft = await portProblem(host, port);
1685
- if (portLeft === undefined)
1686
- say(`${host}:${port} listening after ${formatDuration(Date.now() - started)}`);
1806
+ for (const probe of ports) {
1807
+ if (probe.left === undefined)
1808
+ continue;
1809
+ for (const candidate of hosts) {
1810
+ const problem = await portProblem(candidate, probe.port ?? 0);
1811
+ if (candidate === hosts[0])
1812
+ probe.left = problem;
1813
+ if (problem === undefined) {
1814
+ const name = `${candidate.includes(":") ? `[${candidate}]` : candidate}:${probe.port}`;
1815
+ probe.left = undefined;
1816
+ probe.name = name;
1817
+ metAt.push({ name, ms: Date.now() - started });
1818
+ say(`${name} listening after ${formatDuration(Date.now() - started)}`);
1819
+ break;
1820
+ }
1821
+ }
1687
1822
  }
1688
- if (values.url !== undefined && urlLeft !== undefined) {
1823
+ for (const probe of urls) {
1824
+ if (probe.left === undefined)
1825
+ continue;
1689
1826
  const budget = Math.max(1, Math.min(URL_TIMEOUT, started + timeout - Date.now()));
1690
- const check = await urlCheck(values.url, budget);
1691
- const isCutShort = "problem" in check && check.isTimeout === true && budget < URL_TIMEOUT && urlLeft !== "not checked yet";
1827
+ const check = await urlCheck(probe.name, budget, expect);
1828
+ const isCutShort = "problem" in check && check.isTimeout === true && budget < URL_TIMEOUT && probe.left !== "not checked yet";
1692
1829
  if (!isCutShort)
1693
- urlLeft = "problem" in check ? check.problem : undefined;
1694
- if ("status" in check)
1695
- say(`${values.url} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
1830
+ probe.left = "problem" in check ? check.problem : undefined;
1831
+ if ("status" in check) {
1832
+ metAt.push({ name: probe.name, ms: Date.now() - started });
1833
+ say(`${probe.name} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
1834
+ }
1696
1835
  }
1697
1836
  if (pid !== undefined && isPidLeft) {
1698
1837
  isPidLeft = pidAlive(pid);
1699
- if (!isPidLeft)
1838
+ if (!isPidLeft) {
1839
+ metAt.push({ name: `pid ${pid}`, ms: Date.now() - started });
1700
1840
  say(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
1841
+ }
1701
1842
  }
1702
1843
  if (values.cmd !== undefined && cmdLeft !== undefined && Date.now() - cmdRanAt >= interval) {
1703
1844
  const budget = Math.max(1, Math.min(CMD_RUN_LIMIT, started + timeout - Date.now()));
@@ -1705,19 +1846,21 @@ ${numbered(event.excerpt, event.line)}`);
1705
1846
  if (!(problem?.startsWith("timed out") === true && budget < CMD_RUN_LIMIT && cmdLeft !== "not run yet"))
1706
1847
  cmdLeft = problem;
1707
1848
  cmdRanAt = Date.now();
1708
- if (cmdLeft === undefined)
1849
+ if (cmdLeft === undefined) {
1850
+ metAt.push({ name: `\`${values.cmd}\``, ms: Date.now() - started });
1709
1851
  say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now() - started)}`);
1852
+ }
1710
1853
  }
1711
1854
  const isMet = [
1712
1855
  values.until !== undefined && (watch?.done ?? false),
1713
- port !== undefined && portLeft === undefined,
1714
- values.url !== undefined && urlLeft === undefined,
1856
+ ports.some((probe) => probe.left === undefined),
1857
+ urls.some((probe) => probe.left === undefined),
1715
1858
  pid !== undefined && !isPidLeft,
1716
1859
  values.cmd !== undefined && cmdLeft === undefined
1717
1860
  ];
1718
- if (isAny ? isMet.includes(true) : (watch?.done ?? true) && portLeft === undefined && urlLeft === undefined && !isPidLeft && cmdLeft === undefined) {
1861
+ if (isAny ? isMet.includes(true) : (watch?.done ?? true) && ports.every((probe) => probe.left === undefined) && urls.every((probe) => probe.left === undefined) && !isPidLeft && cmdLeft === undefined) {
1719
1862
  if (json)
1720
- printJson({ met: true, ms: Date.now() - started, line: matched ?? null });
1863
+ printJson({ met: true, ms: Date.now() - started, line: matched ?? null, conditions: metAt });
1721
1864
  return 0;
1722
1865
  }
1723
1866
  if (Date.now() - started >= timeout && !(watch?.failing ?? false))
@@ -1730,10 +1873,14 @@ ${numbered(event.excerpt, event.line)}`);
1730
1873
  const missing = [];
1731
1874
  if (watch !== undefined && !watch.done)
1732
1875
  missing.push(watch.exists ? `no line of ${watch.path} matched --until` : `${watch.path} does not exist`);
1733
- if (portLeft !== undefined)
1734
- missing.push(`${host}:${port} is not listening (${portLeft})`);
1735
- if (urlLeft !== undefined)
1736
- missing.push(`${values.url} ${urlLeft}`);
1876
+ for (const probe of ports) {
1877
+ if (probe.left !== undefined)
1878
+ missing.push(`${hosts[0]}:${probe.port} is not listening (${probe.left})`);
1879
+ }
1880
+ for (const probe of urls) {
1881
+ if (probe.left !== undefined)
1882
+ missing.push(`${probe.name} ${probe.left}`);
1883
+ }
1737
1884
  if (isPidLeft)
1738
1885
  missing.push(`pid ${pid} is still running`);
1739
1886
  if (cmdLeft !== undefined)
@@ -1743,4 +1890,4 @@ ${numbered(event.excerpt, event.line)}`);
1743
1890
  last lines of ${watch?.path}:
1744
1891
  ${numbered(lines)}`}`);
1745
1892
  }
1746
- process18.exitCode = await runMain({ name: "waitfor", run: main });
1893
+ 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 process19 from "process";
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 = /\[[^\]]+\]/g;
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 = [], replaces, exits = [] } = {}) {
478
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
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
- const width = Math.max(...exits.map(([code]) => String(code).length));
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 named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
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
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
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
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
530
- for (const [i, left] of [...a].entries()) {
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, right] of [...b].entries())
533
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
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[b.length] ?? 0;
543
+ return previous[right.length] ?? 0;
537
544
  }
538
545
  function closest(name, names) {
539
546
  const started = names.find((known) => known.startsWith(name));
@@ -781,12 +788,36 @@ function nearestOption(message, options, allowNegative) {
781
788
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
782
789
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
783
790
  }
791
+ // ../kit/src/argv.ts
792
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
793
+ import { resolve as resolve3 } from "path";
794
+ import process10 from "process";
795
+ function commandLine() {
796
+ try {
797
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
798
+ } catch {
799
+ return;
800
+ }
801
+ }
802
+ function realPath(word) {
803
+ try {
804
+ return realpathSync(resolve3(word));
805
+ } catch {
806
+ return;
807
+ }
808
+ }
809
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
810
+ const target = script === undefined ? undefined : realPath(script) ?? script;
811
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
812
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
813
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
814
+ }
784
815
  // ../kit/src/progress.ts
785
- import process11 from "process";
816
+ import process12 from "process";
786
817
 
787
818
  // ../kit/src/process.ts
788
819
  import { constants } from "os";
789
- import process10 from "process";
820
+ import process11 from "process";
790
821
  var KILL_GRACE_MS = 2000;
791
822
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
792
823
  function exitCodeOf(code, signal) {
@@ -808,7 +839,7 @@ function holdSignals(cleanup) {
808
839
  },
809
840
  release: () => {
810
841
  for (const signal of SIGNALS)
811
- process10.off(signal, onSignal);
842
+ process11.off(signal, onSignal);
812
843
  }
813
844
  };
814
845
  function onSignal(signal) {
@@ -821,10 +852,10 @@ function holdSignals(cleanup) {
821
852
  return;
822
853
  held.release();
823
854
  cleanup(signal);
824
- process10.kill(process10.pid, signal);
855
+ process11.kill(process11.pid, signal);
825
856
  }
826
857
  for (const signal of SIGNALS)
827
- process10.on(signal, onSignal);
858
+ process11.on(signal, onSignal);
828
859
  return held;
829
860
  }
830
861
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -838,7 +869,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
838
869
  return;
839
870
  try {
840
871
  if (grouped)
841
- process10.kill(-proc.pid, killing);
872
+ process11.kill(-proc.pid, killing);
842
873
  else
843
874
  proc.kill(killing);
844
875
  } catch {}
@@ -916,7 +947,7 @@ var RESET_STYLE = `${ESC}[0m`;
916
947
  var CTRL_C = 3;
917
948
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
918
949
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
919
- function liveRegion(render, stream = process11.stderr, env = process11.env) {
950
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
920
951
  if (!takesControlCodes(stream, env))
921
952
  return { redraw: () => {
922
953
  return;
@@ -963,11 +994,11 @@ function liveRegion(render, stream = process11.stderr, env = process11.env) {
963
994
  clear();
964
995
  restore();
965
996
  release();
966
- process11.off("exit", onExit);
997
+ process12.off("exit", onExit);
967
998
  signals.release();
968
999
  }
969
1000
  timer.unref();
970
- process11.on("exit", onExit);
1001
+ process12.on("exit", onExit);
971
1002
  return {
972
1003
  redraw: draw,
973
1004
  print: (text) => {
@@ -1006,14 +1037,14 @@ function cutToWidth(line, width) {
1006
1037
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1007
1038
  }
1008
1039
  function swallowInput() {
1009
- const input = process11.stdin;
1040
+ const input = process12.stdin;
1010
1041
  if (!input.isTTY)
1011
1042
  return () => {
1012
1043
  return;
1013
1044
  };
1014
1045
  const onData = (data) => {
1015
1046
  if (data.includes(CTRL_C))
1016
- process11.kill(process11.pid, "SIGINT");
1047
+ process12.kill(process12.pid, "SIGINT");
1017
1048
  };
1018
1049
  input.setRawMode(true);
1019
1050
  input.on("data", onData);
@@ -1029,7 +1060,7 @@ function swallowInput() {
1029
1060
  };
1030
1061
  }
1031
1062
  function interceptOutput(clear) {
1032
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process11.stdout, "write"], [process11.stderr, "write"]];
1063
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1033
1064
  const wrapped = targets.map(([target, name]) => {
1034
1065
  const original = Reflect.get(target, name);
1035
1066
  const wrapper = (...args) => {
@@ -1047,33 +1078,51 @@ function interceptOutput(clear) {
1047
1078
  };
1048
1079
  }
1049
1080
  // ../kit/src/cli.ts
1050
- import { readFileSync as readFileSync3, realpathSync } from "fs";
1081
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1051
1082
  import { dirname as dirname3, join as join6 } from "path";
1052
- import process14 from "process";
1083
+ import process16 from "process";
1084
+
1085
+ // ../kit/src/notify.ts
1086
+ import process13 from "process";
1087
+ var NOTIFY_AFTER_MS = 1e4;
1088
+ var CANCELLED = 130;
1089
+ function base64(text) {
1090
+ return Buffer.from(text).toString("base64");
1091
+ }
1092
+ function notification(title, body, env = process13.env) {
1093
+ const id = `kit${process13.pid}`;
1094
+ 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\\`];
1095
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1096
+ }
1097
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1098
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1099
+ return;
1100
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1101
+ }
1053
1102
 
1054
1103
  // ../kit/src/usage.ts
1055
1104
  import { appendFileSync, mkdirSync } from "fs";
1056
1105
  import { homedir as homedir4 } from "os";
1057
1106
  import { dirname as dirname2, isAbsolute, join as join5 } from "path";
1058
- import process13 from "process";
1107
+ import process15 from "process";
1059
1108
 
1060
1109
  // ../kit/src/logs.ts
1061
1110
  import { lstatSync, openSync } from "fs";
1062
1111
  import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1063
1112
  import { homedir as homedir3, tmpdir } from "os";
1064
1113
  import { join as join4 } from "path";
1065
- import process12 from "process";
1114
+ import process14 from "process";
1066
1115
  var DAY_MS = 24 * 60 * 60 * 1000;
1067
1116
  var CLI_FOLDER = "kaynooo-cli";
1068
1117
  function isPrivateDirectory(path) {
1069
1118
  try {
1070
1119
  const info = lstatSync(path, { throwIfNoEntry: false });
1071
- return info !== undefined && info.isDirectory() && info.uid === (process12.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1120
+ return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1072
1121
  } catch {
1073
1122
  return false;
1074
1123
  }
1075
1124
  }
1076
- async function privateLogDirectory(name, env = process12.env) {
1125
+ async function privateLogDirectory(name, env = process14.env) {
1077
1126
  const runtime = env.XDG_RUNTIME_DIR;
1078
1127
  const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
1079
1128
  const path = join4(base, name);
@@ -1093,14 +1142,14 @@ var usageError;
1093
1142
  function noteUsageError(message) {
1094
1143
  usageError = message;
1095
1144
  }
1096
- function stateHome(env = process13.env) {
1145
+ function stateHome(env = process15.env) {
1097
1146
  const dir = env.XDG_STATE_HOME;
1098
1147
  return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
1099
1148
  }
1100
- function usagePath(env = process13.env) {
1149
+ function usagePath(env = process15.env) {
1101
1150
  return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
1102
1151
  }
1103
- function usageRecorded(env = process13.env) {
1152
+ function usageRecorded(env = process15.env) {
1104
1153
  const off = env.KAYNOOO_CLI_NO_USAGE;
1105
1154
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1106
1155
  }
@@ -1114,7 +1163,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1114
1163
  usageError = undefined;
1115
1164
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1116
1165
  }
1117
- function recordUsage(entry, env = process13.env) {
1166
+ function recordUsage(entry, env = process15.env) {
1118
1167
  if (!usageRecorded(env))
1119
1168
  return;
1120
1169
  try {
@@ -1132,8 +1181,8 @@ var LEVEL_OPTIONS = {
1132
1181
  };
1133
1182
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1134
1183
  function printError(prefix, message, hint, cause) {
1135
- const colors = paint(process14.stderr);
1136
- const styled = takesControlCodes(process14.stderr);
1184
+ const colors = paint(process16.stderr);
1185
+ const styled = takesControlCodes(process16.stderr);
1137
1186
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1138
1187
  const under = (label, text, tint) => text === undefined ? "" : `
1139
1188
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1177,24 +1226,24 @@ function candidateLine(candidate) {
1177
1226
  }
1178
1227
  function positionalBeingTyped(before, { options, positionals }) {
1179
1228
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1180
- let index = 0;
1229
+ const typed = [];
1181
1230
  let at = 0;
1182
1231
  while (at < before.length) {
1183
1232
  const word = before[at];
1184
1233
  if (word === "--") {
1185
- index += before.length - at - 1;
1234
+ typed.push(...before.slice(at + 1));
1186
1235
  break;
1187
1236
  }
1188
1237
  if (!word.startsWith("-"))
1189
- index++;
1238
+ typed.push(word);
1190
1239
  else if (takesValue(word))
1191
1240
  at++;
1192
1241
  at++;
1193
1242
  }
1194
1243
  const last = positionals.at(-1);
1195
- if (index < positionals.length)
1196
- return positionals[index];
1197
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1244
+ if (typed.length < positionals.length)
1245
+ return { name: positionals[typed.length], typed };
1246
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1198
1247
  }
1199
1248
  async function leafCandidates(run, words) {
1200
1249
  const completing = await completingOf(run);
@@ -1202,12 +1251,12 @@ async function leafCandidates(run, words) {
1202
1251
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1203
1252
  const flag = words.at(-2);
1204
1253
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1254
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1205
1255
  if (option?.type === "string") {
1206
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1256
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1207
1257
  return values === undefined ? [FILES] : values.map(candidateLine);
1208
1258
  }
1209
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1210
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1259
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1211
1260
  return values === undefined ? [FILES] : values.map(candidateLine);
1212
1261
  }
1213
1262
  async function printCandidates(found) {
@@ -1216,9 +1265,13 @@ async function printCandidates(found) {
1216
1265
  return 0;
1217
1266
  }
1218
1267
  function packageVersion(entry = Bun.main) {
1219
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1268
+ let resolved = entry;
1269
+ try {
1270
+ resolved = realpathSync2(entry);
1271
+ } catch {}
1272
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1220
1273
  try {
1221
- const { version } = JSON.parse(readFileSync3(join6(dir, "package.json"), "utf8"));
1274
+ const { version } = JSON.parse(readFileSync4(join6(dir, "package.json"), "utf8"));
1222
1275
  if (typeof version === "string")
1223
1276
  return version;
1224
1277
  } catch {}
@@ -1226,7 +1279,7 @@ function packageVersion(entry = Bun.main) {
1226
1279
  return "0.0.0";
1227
1280
  }
1228
1281
  }
1229
- async function runMain({ name, version, run, redact, usage }, argv = process14.argv.slice(2)) {
1282
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1230
1283
  if (argv[0] === COMPLETE)
1231
1284
  return printCandidates(leafCandidates(run, argv.slice(1)));
1232
1285
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1234,11 +1287,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process14.a
1234
1287
  return 0;
1235
1288
  }
1236
1289
  let code;
1290
+ const started = performance.now();
1237
1291
  try {
1238
1292
  code = await run(argv);
1239
1293
  } catch (error) {
1240
1294
  code = reportThrown(name, error, redact, wantsJson(argv));
1241
1295
  }
1296
+ notifyEnd(name, code, performance.now() - started);
1242
1297
  if (usage !== false) {
1243
1298
  try {
1244
1299
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1253,15 +1308,15 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
1253
1308
  // ../kit/src/sessions.ts
1254
1309
  import { homedir as homedir5 } from "os";
1255
1310
  import { join as join7 } from "path";
1256
- import process15 from "process";
1311
+ import process17 from "process";
1257
1312
  var {Glob } = globalThis.Bun;
1258
1313
  var SESSION_FILES = new Glob("*.json");
1259
1314
  var ACCOUNT_DIRS = new Glob("*/sessions");
1260
1315
  async function sessionDirs() {
1261
1316
  const home = homedir5();
1262
1317
  const dirs = new Set([join7(home, ".claude", "sessions")]);
1263
- if (process15.env.CLAUDE_CONFIG_DIR !== undefined)
1264
- dirs.add(join7(process15.env.CLAUDE_CONFIG_DIR, "sessions"));
1318
+ if (process17.env.CLAUDE_CONFIG_DIR !== undefined)
1319
+ dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR, "sessions"));
1265
1320
  try {
1266
1321
  for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1267
1322
  dirs.add(dir);
@@ -1307,7 +1362,7 @@ async function liveSessions() {
1307
1362
  }
1308
1363
  async function currentSession(sessions) {
1309
1364
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
1310
- let pid = process15.ppid;
1365
+ let pid = process17.ppid;
1311
1366
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
1312
1367
  const session = byPid.get(pid);
1313
1368
  if (session !== undefined)
@@ -1320,20 +1375,20 @@ async function currentSession(sessions) {
1320
1375
  return;
1321
1376
  }
1322
1377
  // src/slot.ts
1323
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync4, rmSync } from "fs";
1378
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync5, rmSync } from "fs";
1324
1379
  import { availableParallelism } from "os";
1325
1380
  import { join as join8 } from "path";
1326
- import process18 from "process";
1381
+ import process20 from "process";
1327
1382
 
1328
1383
  // src/flock.ts
1329
1384
  import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
1330
- import process17 from "process";
1385
+ import process19 from "process";
1331
1386
  import { dlopen, FFIType } from "bun:ffi";
1332
1387
  var LOCK_EX = 2;
1333
1388
  var LOCK_NB = 4;
1334
1389
  var flock;
1335
1390
  function native() {
1336
- flock ??= dlopen(process17.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
1391
+ flock ??= dlopen(process19.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
1337
1392
  return flock;
1338
1393
  }
1339
1394
  function tryLock(path) {
@@ -1377,14 +1432,14 @@ function defaultSlots() {
1377
1432
  return Math.max(1, Math.floor(availableParallelism() / 2));
1378
1433
  }
1379
1434
  async function stateDir() {
1380
- const dir = process18.env.SLOT_DIR ?? await privateLogDirectory("slot");
1435
+ const dir = process20.env.SLOT_DIR ?? await privateLogDirectory("slot");
1381
1436
  for (const sub of ["slots", "locks", "waiters"])
1382
1437
  mkdirSync2(join8(dir, sub), { recursive: true, mode: 448 });
1383
1438
  return dir;
1384
1439
  }
1385
1440
  function readHolder(path) {
1386
1441
  try {
1387
- const holder = JSON.parse(readFileSync4(path, "utf8"));
1442
+ const holder = JSON.parse(readFileSync5(path, "utf8"));
1388
1443
  return typeof holder.pid === "number" && typeof holder.command === "string" ? { pid: holder.pid, command: holder.command, cwd: holder.cwd ?? "", since: holder.since ?? 0, ...holder.session === undefined ? {} : { session: holder.session }, ...holder.resource === undefined ? {} : { resource: holder.resource } } : undefined;
1389
1444
  } catch {
1390
1445
  return;
@@ -1419,7 +1474,7 @@ function waitingLine(dir, wanted) {
1419
1474
  }
1420
1475
  async function holderOf(command) {
1421
1476
  const session = await currentSession(await liveSessions());
1422
- return { pid: process18.pid, command: command.join(" "), cwd: process18.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1477
+ return { pid: process20.pid, command: command.join(" "), cwd: process20.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1423
1478
  }
1424
1479
  var waiterCount = 0;
1425
1480
  async function acquire(dir, resources, holder, deadline, timeoutMs) {
@@ -1445,7 +1500,7 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
1445
1500
  held.release();
1446
1501
  const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
1447
1502
  if (waiter === undefined) {
1448
- const path = join8(dir, "waiters", `${process18.pid}-${waiterCount++}`);
1503
+ const path = join8(dir, "waiters", `${process20.pid}-${waiterCount++}`);
1449
1504
  const held = tryLock(path);
1450
1505
  if (held !== undefined) {
1451
1506
  writeHeld(held, JSON.stringify({ ...holder, resource }));
@@ -1486,7 +1541,7 @@ ${RUN_USAGE}`);
1486
1541
  const count = wholeNumber(values.slots, "slots", defaultSlots());
1487
1542
  const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
1488
1543
  const deadline = Date.now() + timeoutMs;
1489
- const holding = new Set((process18.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1544
+ const holding = new Set((process20.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1490
1545
  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 }]];
1491
1546
  const signals = holdSignals(() => {
1492
1547
  return;
@@ -1501,7 +1556,7 @@ ${RUN_USAGE}`);
1501
1556
  const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
1502
1557
  let child;
1503
1558
  try {
1504
- child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process18.env, [HOLDING]: [...tokens].join(",") } });
1559
+ child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process20.env, [HOLDING]: [...tokens].join(",") } });
1505
1560
  } catch (error) {
1506
1561
  fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
1507
1562
  }
@@ -1544,11 +1599,11 @@ async function listSlots(args) {
1544
1599
  printJson({ slots: count, busy, entries });
1545
1600
  return 0;
1546
1601
  }
1547
- console.log(paint(process18.stdout).bold(`slots: ${busy} of ${count} busy`));
1602
+ console.log(paint(process20.stdout).bold(`slots: ${busy} of ${count} busy`));
1548
1603
  if (entries.length > 0)
1549
- console.log(table(entries.map((entry) => [badge(entry.state, process18.stdout), entry.resource, entry.session ?? `pid ${entry.pid}`, truncate(entry.command, COMMAND_WIDTH), entry.since === 0 ? "?" : formatAge(entry.since)])));
1604
+ 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)])));
1550
1605
  return 0;
1551
1606
  }
1552
1607
 
1553
1608
  // src/slot-cli.ts
1554
- process19.exitCode = await runMain({ name: "slot", run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
1609
+ 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.10.1",
4
+ "version": "0.12.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",
@@ -38,6 +38,6 @@
38
38
  "waitfor": "$npm_execpath src/cli.ts"
39
39
  },
40
40
  "devDependencies": {
41
- "@kaynooo/cli-kit": "0.37.0"
41
+ "@kaynooo/cli-kit": "0.40.0"
42
42
  }
43
43
  }