@kaynooo/cli-wait 0.11.0 → 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 +3 -1
- package/dist/cli.js +200 -81
- package/dist/slot-cli.js +70 -43
- 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));
|
|
@@ -1074,31 +1081,49 @@ 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/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
|
+
}
|
|
1078
1103
|
|
|
1079
1104
|
// ../kit/src/usage.ts
|
|
1080
1105
|
import { appendFileSync, mkdirSync } from "fs";
|
|
1081
1106
|
import { homedir as homedir4 } from "os";
|
|
1082
1107
|
import { dirname as dirname2, isAbsolute, join as join5 } from "path";
|
|
1083
|
-
import
|
|
1108
|
+
import process15 from "process";
|
|
1084
1109
|
|
|
1085
1110
|
// ../kit/src/logs.ts
|
|
1086
1111
|
import { lstatSync, openSync } from "fs";
|
|
1087
1112
|
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
1088
1113
|
import { homedir as homedir3, tmpdir } from "os";
|
|
1089
1114
|
import { join as join4 } from "path";
|
|
1090
|
-
import
|
|
1115
|
+
import process14 from "process";
|
|
1091
1116
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1092
1117
|
var CLI_FOLDER = "kaynooo-cli";
|
|
1093
1118
|
function isPrivateDirectory(path) {
|
|
1094
1119
|
try {
|
|
1095
1120
|
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
1096
|
-
return info !== undefined && info.isDirectory() && info.uid === (
|
|
1121
|
+
return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
1097
1122
|
} catch {
|
|
1098
1123
|
return false;
|
|
1099
1124
|
}
|
|
1100
1125
|
}
|
|
1101
|
-
async function privateLogDirectory(name, env =
|
|
1126
|
+
async function privateLogDirectory(name, env = process14.env) {
|
|
1102
1127
|
const runtime = env.XDG_RUNTIME_DIR;
|
|
1103
1128
|
const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
|
|
1104
1129
|
const path = join4(base, name);
|
|
@@ -1118,14 +1143,14 @@ var usageError;
|
|
|
1118
1143
|
function noteUsageError(message) {
|
|
1119
1144
|
usageError = message;
|
|
1120
1145
|
}
|
|
1121
|
-
function stateHome(env =
|
|
1146
|
+
function stateHome(env = process15.env) {
|
|
1122
1147
|
const dir = env.XDG_STATE_HOME;
|
|
1123
1148
|
return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
|
|
1124
1149
|
}
|
|
1125
|
-
function usagePath(env =
|
|
1150
|
+
function usagePath(env = process15.env) {
|
|
1126
1151
|
return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1127
1152
|
}
|
|
1128
|
-
function usageRecorded(env =
|
|
1153
|
+
function usageRecorded(env = process15.env) {
|
|
1129
1154
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1130
1155
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1131
1156
|
}
|
|
@@ -1139,7 +1164,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
1139
1164
|
usageError = undefined;
|
|
1140
1165
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1141
1166
|
}
|
|
1142
|
-
function recordUsage(entry, env =
|
|
1167
|
+
function recordUsage(entry, env = process15.env) {
|
|
1143
1168
|
if (!usageRecorded(env))
|
|
1144
1169
|
return;
|
|
1145
1170
|
try {
|
|
@@ -1157,8 +1182,8 @@ var LEVEL_OPTIONS = {
|
|
|
1157
1182
|
};
|
|
1158
1183
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
1159
1184
|
function printError(prefix, message, hint, cause) {
|
|
1160
|
-
const colors = paint(
|
|
1161
|
-
const styled = takesControlCodes(
|
|
1185
|
+
const colors = paint(process16.stderr);
|
|
1186
|
+
const styled = takesControlCodes(process16.stderr);
|
|
1162
1187
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1163
1188
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1164
1189
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1263,11 +1288,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
|
|
|
1263
1288
|
return 0;
|
|
1264
1289
|
}
|
|
1265
1290
|
let code;
|
|
1291
|
+
const started = performance.now();
|
|
1266
1292
|
try {
|
|
1267
1293
|
code = await run(argv);
|
|
1268
1294
|
} catch (error) {
|
|
1269
1295
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1270
1296
|
}
|
|
1297
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1271
1298
|
if (usage !== false) {
|
|
1272
1299
|
try {
|
|
1273
1300
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1282,15 +1309,15 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
1282
1309
|
// ../kit/src/sessions.ts
|
|
1283
1310
|
import { homedir as homedir5 } from "os";
|
|
1284
1311
|
import { join as join7 } from "path";
|
|
1285
|
-
import
|
|
1312
|
+
import process17 from "process";
|
|
1286
1313
|
var {Glob } = globalThis.Bun;
|
|
1287
1314
|
var SESSION_FILES = new Glob("*.json");
|
|
1288
1315
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1289
1316
|
async function sessionDirs() {
|
|
1290
1317
|
const home = homedir5();
|
|
1291
1318
|
const dirs = new Set([join7(home, ".claude", "sessions")]);
|
|
1292
|
-
if (
|
|
1293
|
-
dirs.add(join7(
|
|
1319
|
+
if (process17.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
1320
|
+
dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR, "sessions"));
|
|
1294
1321
|
try {
|
|
1295
1322
|
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
|
|
1296
1323
|
dirs.add(dir);
|
|
@@ -1336,7 +1363,7 @@ async function liveSessions() {
|
|
|
1336
1363
|
}
|
|
1337
1364
|
async function currentSession(sessions) {
|
|
1338
1365
|
const byPid = new Map(sessions.map((session) => [session.pid, session]));
|
|
1339
|
-
let pid =
|
|
1366
|
+
let pid = process17.ppid;
|
|
1340
1367
|
for (let depth = 0;depth < 32 && pid > 1; depth++) {
|
|
1341
1368
|
const session = byPid.get(pid);
|
|
1342
1369
|
if (session !== undefined)
|
|
@@ -1462,11 +1489,58 @@ async function closeWhenConnected(attempt) {
|
|
|
1462
1489
|
(await attempt).end();
|
|
1463
1490
|
} catch {}
|
|
1464
1491
|
}
|
|
1465
|
-
|
|
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 = {}) {
|
|
1466
1531
|
try {
|
|
1467
|
-
const
|
|
1468
|
-
await
|
|
1469
|
-
|
|
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}` };
|
|
1470
1544
|
} catch (error) {
|
|
1471
1545
|
return { problem: error instanceof Error ? error.message : String(error), isTimeout: error instanceof Error && error.name === "TimeoutError" };
|
|
1472
1546
|
}
|
|
@@ -1475,7 +1549,7 @@ async function urlCheck(url, timeout) {
|
|
|
1475
1549
|
// src/task.ts
|
|
1476
1550
|
import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
|
|
1477
1551
|
import { join as join8 } from "path";
|
|
1478
|
-
import
|
|
1552
|
+
import process19 from "process";
|
|
1479
1553
|
var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
|
|
1480
1554
|
var FAILURE = /\(fail\)|\berror:/i;
|
|
1481
1555
|
var TASK_ID = /^[\w-]+$/;
|
|
@@ -1483,9 +1557,9 @@ var TAIL_BYTES = 256;
|
|
|
1483
1557
|
var LONGEST_FAILURES = 30;
|
|
1484
1558
|
var CARRIAGE_RETURN2 = /\r$/;
|
|
1485
1559
|
function tasksRoot(env) {
|
|
1486
|
-
return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${
|
|
1560
|
+
return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process19.getuid?.() ?? 0}`);
|
|
1487
1561
|
}
|
|
1488
|
-
function taskFile(task, env =
|
|
1562
|
+
function taskFile(task, env = process19.env) {
|
|
1489
1563
|
if (task.includes("/") || task.endsWith(".output"))
|
|
1490
1564
|
return task;
|
|
1491
1565
|
if (!TASK_ID.test(task))
|
|
@@ -1518,7 +1592,7 @@ async function taskEnd(path, lines) {
|
|
|
1518
1592
|
}
|
|
1519
1593
|
function pidAlive(pid) {
|
|
1520
1594
|
try {
|
|
1521
|
-
|
|
1595
|
+
process19.kill(pid, 0);
|
|
1522
1596
|
} catch (error) {
|
|
1523
1597
|
return error.code === "EPERM";
|
|
1524
1598
|
}
|
|
@@ -1537,8 +1611,8 @@ function isZombie(pid) {
|
|
|
1537
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
|
|
1538
1612
|
waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
|
|
1539
1613
|
|
|
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.`;
|
|
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.`;
|
|
1542
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
|
|
1543
1617
|
|
|
1544
1618
|
The task is the id a background Bash call returned, or the path of its .output file.
|
|
@@ -1556,9 +1630,11 @@ var OPTIONS = {
|
|
|
1556
1630
|
file: { type: "string", short: "f", description: "a log file to read, from its start, waiting for it to exist" },
|
|
1557
1631
|
until: { type: "string", short: "u", description: "a regular expression a line of --file must match" },
|
|
1558
1632
|
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" },
|
|
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" },
|
|
1562
1638
|
pid: { type: "string", description: "a process id that must exit" },
|
|
1563
1639
|
cmd: { type: "string", short: "c", description: "a shell command that must exit 0, re-run every --interval" },
|
|
1564
1640
|
interval: { type: "string", description: "how long between two runs of --cmd (1s)" },
|
|
@@ -1609,7 +1685,7 @@ async function waitTask(args) {
|
|
|
1609
1685
|
const lines = wholeNumber(values.lines, "lines", 20);
|
|
1610
1686
|
const timeout = duration(values.timeout, "timeout", 5 * 60000);
|
|
1611
1687
|
const started = Date.now();
|
|
1612
|
-
const { dim } = paint(
|
|
1688
|
+
const { dim } = paint(process20.stderr);
|
|
1613
1689
|
const region = values.quiet === true ? undefined : liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
|
|
1614
1690
|
let code;
|
|
1615
1691
|
try {
|
|
@@ -1647,26 +1723,46 @@ async function main(args) {
|
|
|
1647
1723
|
fail(`unexpected argument ${positionals[0]}
|
|
1648
1724
|
|
|
1649
1725
|
${USAGE}`);
|
|
1650
|
-
|
|
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)
|
|
1651
1729
|
fail(`give --until with --file, --port, --url, --pid or --cmd
|
|
1652
1730
|
|
|
1653
1731
|
${USAGE}`);
|
|
1654
1732
|
if ((values.until !== undefined || values.fail !== undefined) !== (values.file !== undefined))
|
|
1655
1733
|
fail("--until and --fail read the --file lines, and --file needs one of them");
|
|
1656
|
-
if (values.host !== undefined &&
|
|
1734
|
+
if (values.host !== undefined && portTexts.length === 0)
|
|
1657
1735
|
fail("--host goes with --port");
|
|
1658
|
-
|
|
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;
|
|
1659
1739
|
if (values.any === true && conditions < 2)
|
|
1660
1740
|
fail("--any needs two or more of --until, --port, --url, --pid and --cmd");
|
|
1661
1741
|
if (values.interval !== undefined && values.cmd === undefined)
|
|
1662
1742
|
fail("--interval goes with --cmd");
|
|
1663
|
-
const
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
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 = [];
|
|
1668
1764
|
const pid = values.pid === undefined ? undefined : wholeNumber(values.pid, "pid", 0);
|
|
1669
|
-
const
|
|
1765
|
+
const hosts = values.host === undefined ? ["127.0.0.1", "::1"] : [values.host];
|
|
1670
1766
|
const interval = duration(values.interval, "interval", 1000);
|
|
1671
1767
|
const isAny = values.any === true;
|
|
1672
1768
|
const timeout = duration(values.timeout, "timeout", 5 * 60000);
|
|
@@ -1675,18 +1771,16 @@ ${USAGE}`);
|
|
|
1675
1771
|
const json = values.json === true;
|
|
1676
1772
|
const say = json ? console.error : console.log;
|
|
1677
1773
|
let matched;
|
|
1678
|
-
let portLeft = port === undefined ? undefined : "not checked yet";
|
|
1679
|
-
let urlLeft = values.url === undefined ? undefined : "not checked yet";
|
|
1680
1774
|
let isPidLeft = pid !== undefined;
|
|
1681
1775
|
let cmdLeft = values.cmd === undefined ? undefined : "not run yet";
|
|
1682
1776
|
let cmdRanAt = 0;
|
|
1683
|
-
const { dim } = paint(
|
|
1777
|
+
const { dim } = paint(process20.stderr);
|
|
1684
1778
|
const region = values.quiet === true ? undefined : liveRegion((spinner) => {
|
|
1685
1779
|
const waited = dim(formatElapsed(Date.now() - started));
|
|
1686
1780
|
const left = [
|
|
1687
1781
|
watch === undefined || watch.done ? undefined : `${watch.path}: ${watch.exists ? "no --until line yet" : "does not exist yet"}`,
|
|
1688
|
-
|
|
1689
|
-
|
|
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}`),
|
|
1690
1784
|
isPidLeft ? `pid ${pid}: still running` : undefined,
|
|
1691
1785
|
cmdLeft === undefined ? undefined : `\`${values.cmd}\`: ${cmdLeft}`
|
|
1692
1786
|
];
|
|
@@ -1699,6 +1793,7 @@ ${USAGE}`);
|
|
|
1699
1793
|
if (event.kind === "until") {
|
|
1700
1794
|
say(`${watch.path}:${event.line.number}: ${truncate(event.line.text, WIDTH)}`);
|
|
1701
1795
|
matched = { number: event.line.number, text: event.line.text };
|
|
1796
|
+
metAt.push({ name: `${watch.path} --until`, ms: Date.now() - started });
|
|
1702
1797
|
continue;
|
|
1703
1798
|
}
|
|
1704
1799
|
problem(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now() - started)}
|
|
@@ -1708,24 +1803,42 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1708
1803
|
return 1;
|
|
1709
1804
|
}
|
|
1710
1805
|
}
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
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
|
+
}
|
|
1715
1822
|
}
|
|
1716
|
-
|
|
1823
|
+
for (const probe of urls) {
|
|
1824
|
+
if (probe.left === undefined)
|
|
1825
|
+
continue;
|
|
1717
1826
|
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 &&
|
|
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";
|
|
1720
1829
|
if (!isCutShort)
|
|
1721
|
-
|
|
1722
|
-
if ("status" in check)
|
|
1723
|
-
|
|
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
|
+
}
|
|
1724
1835
|
}
|
|
1725
1836
|
if (pid !== undefined && isPidLeft) {
|
|
1726
1837
|
isPidLeft = pidAlive(pid);
|
|
1727
|
-
if (!isPidLeft)
|
|
1838
|
+
if (!isPidLeft) {
|
|
1839
|
+
metAt.push({ name: `pid ${pid}`, ms: Date.now() - started });
|
|
1728
1840
|
say(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
|
|
1841
|
+
}
|
|
1729
1842
|
}
|
|
1730
1843
|
if (values.cmd !== undefined && cmdLeft !== undefined && Date.now() - cmdRanAt >= interval) {
|
|
1731
1844
|
const budget = Math.max(1, Math.min(CMD_RUN_LIMIT, started + timeout - Date.now()));
|
|
@@ -1733,19 +1846,21 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1733
1846
|
if (!(problem?.startsWith("timed out") === true && budget < CMD_RUN_LIMIT && cmdLeft !== "not run yet"))
|
|
1734
1847
|
cmdLeft = problem;
|
|
1735
1848
|
cmdRanAt = Date.now();
|
|
1736
|
-
if (cmdLeft === undefined)
|
|
1849
|
+
if (cmdLeft === undefined) {
|
|
1850
|
+
metAt.push({ name: `\`${values.cmd}\``, ms: Date.now() - started });
|
|
1737
1851
|
say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now() - started)}`);
|
|
1852
|
+
}
|
|
1738
1853
|
}
|
|
1739
1854
|
const isMet = [
|
|
1740
1855
|
values.until !== undefined && (watch?.done ?? false),
|
|
1741
|
-
|
|
1742
|
-
|
|
1856
|
+
ports.some((probe) => probe.left === undefined),
|
|
1857
|
+
urls.some((probe) => probe.left === undefined),
|
|
1743
1858
|
pid !== undefined && !isPidLeft,
|
|
1744
1859
|
values.cmd !== undefined && cmdLeft === undefined
|
|
1745
1860
|
];
|
|
1746
|
-
if (isAny ? isMet.includes(true) : (watch?.done ?? true) &&
|
|
1861
|
+
if (isAny ? isMet.includes(true) : (watch?.done ?? true) && ports.every((probe) => probe.left === undefined) && urls.every((probe) => probe.left === undefined) && !isPidLeft && cmdLeft === undefined) {
|
|
1747
1862
|
if (json)
|
|
1748
|
-
printJson({ met: true, ms: Date.now() - started, line: matched ?? null });
|
|
1863
|
+
printJson({ met: true, ms: Date.now() - started, line: matched ?? null, conditions: metAt });
|
|
1749
1864
|
return 0;
|
|
1750
1865
|
}
|
|
1751
1866
|
if (Date.now() - started >= timeout && !(watch?.failing ?? false))
|
|
@@ -1758,10 +1873,14 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1758
1873
|
const missing = [];
|
|
1759
1874
|
if (watch !== undefined && !watch.done)
|
|
1760
1875
|
missing.push(watch.exists ? `no line of ${watch.path} matched --until` : `${watch.path} does not exist`);
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
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
|
+
}
|
|
1765
1884
|
if (isPidLeft)
|
|
1766
1885
|
missing.push(`pid ${pid} is still running`);
|
|
1767
1886
|
if (cmdLeft !== undefined)
|
|
@@ -1771,4 +1890,4 @@ ${numbered(event.excerpt, event.line)}`);
|
|
|
1771
1890
|
last lines of ${watch?.path}:
|
|
1772
1891
|
${numbered(lines)}`}`);
|
|
1773
1892
|
}
|
|
1774
|
-
|
|
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
|
|
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));
|
|
@@ -1073,31 +1080,49 @@ 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/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
|
+
}
|
|
1077
1102
|
|
|
1078
1103
|
// ../kit/src/usage.ts
|
|
1079
1104
|
import { appendFileSync, mkdirSync } from "fs";
|
|
1080
1105
|
import { homedir as homedir4 } from "os";
|
|
1081
1106
|
import { dirname as dirname2, isAbsolute, join as join5 } from "path";
|
|
1082
|
-
import
|
|
1107
|
+
import process15 from "process";
|
|
1083
1108
|
|
|
1084
1109
|
// ../kit/src/logs.ts
|
|
1085
1110
|
import { lstatSync, openSync } from "fs";
|
|
1086
1111
|
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
1087
1112
|
import { homedir as homedir3, tmpdir } from "os";
|
|
1088
1113
|
import { join as join4 } from "path";
|
|
1089
|
-
import
|
|
1114
|
+
import process14 from "process";
|
|
1090
1115
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1091
1116
|
var CLI_FOLDER = "kaynooo-cli";
|
|
1092
1117
|
function isPrivateDirectory(path) {
|
|
1093
1118
|
try {
|
|
1094
1119
|
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
1095
|
-
return info !== undefined && info.isDirectory() && info.uid === (
|
|
1120
|
+
return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
1096
1121
|
} catch {
|
|
1097
1122
|
return false;
|
|
1098
1123
|
}
|
|
1099
1124
|
}
|
|
1100
|
-
async function privateLogDirectory(name, env =
|
|
1125
|
+
async function privateLogDirectory(name, env = process14.env) {
|
|
1101
1126
|
const runtime = env.XDG_RUNTIME_DIR;
|
|
1102
1127
|
const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
|
|
1103
1128
|
const path = join4(base, name);
|
|
@@ -1117,14 +1142,14 @@ var usageError;
|
|
|
1117
1142
|
function noteUsageError(message) {
|
|
1118
1143
|
usageError = message;
|
|
1119
1144
|
}
|
|
1120
|
-
function stateHome(env =
|
|
1145
|
+
function stateHome(env = process15.env) {
|
|
1121
1146
|
const dir = env.XDG_STATE_HOME;
|
|
1122
1147
|
return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
|
|
1123
1148
|
}
|
|
1124
|
-
function usagePath(env =
|
|
1149
|
+
function usagePath(env = process15.env) {
|
|
1125
1150
|
return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1126
1151
|
}
|
|
1127
|
-
function usageRecorded(env =
|
|
1152
|
+
function usageRecorded(env = process15.env) {
|
|
1128
1153
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1129
1154
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1130
1155
|
}
|
|
@@ -1138,7 +1163,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
1138
1163
|
usageError = undefined;
|
|
1139
1164
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1140
1165
|
}
|
|
1141
|
-
function recordUsage(entry, env =
|
|
1166
|
+
function recordUsage(entry, env = process15.env) {
|
|
1142
1167
|
if (!usageRecorded(env))
|
|
1143
1168
|
return;
|
|
1144
1169
|
try {
|
|
@@ -1156,8 +1181,8 @@ var LEVEL_OPTIONS = {
|
|
|
1156
1181
|
};
|
|
1157
1182
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
1158
1183
|
function printError(prefix, message, hint, cause) {
|
|
1159
|
-
const colors = paint(
|
|
1160
|
-
const styled = takesControlCodes(
|
|
1184
|
+
const colors = paint(process16.stderr);
|
|
1185
|
+
const styled = takesControlCodes(process16.stderr);
|
|
1161
1186
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1162
1187
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1163
1188
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1262,11 +1287,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
|
|
|
1262
1287
|
return 0;
|
|
1263
1288
|
}
|
|
1264
1289
|
let code;
|
|
1290
|
+
const started = performance.now();
|
|
1265
1291
|
try {
|
|
1266
1292
|
code = await run(argv);
|
|
1267
1293
|
} catch (error) {
|
|
1268
1294
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1269
1295
|
}
|
|
1296
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1270
1297
|
if (usage !== false) {
|
|
1271
1298
|
try {
|
|
1272
1299
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1281,15 +1308,15 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
1281
1308
|
// ../kit/src/sessions.ts
|
|
1282
1309
|
import { homedir as homedir5 } from "os";
|
|
1283
1310
|
import { join as join7 } from "path";
|
|
1284
|
-
import
|
|
1311
|
+
import process17 from "process";
|
|
1285
1312
|
var {Glob } = globalThis.Bun;
|
|
1286
1313
|
var SESSION_FILES = new Glob("*.json");
|
|
1287
1314
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1288
1315
|
async function sessionDirs() {
|
|
1289
1316
|
const home = homedir5();
|
|
1290
1317
|
const dirs = new Set([join7(home, ".claude", "sessions")]);
|
|
1291
|
-
if (
|
|
1292
|
-
dirs.add(join7(
|
|
1318
|
+
if (process17.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
1319
|
+
dirs.add(join7(process17.env.CLAUDE_CONFIG_DIR, "sessions"));
|
|
1293
1320
|
try {
|
|
1294
1321
|
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
|
|
1295
1322
|
dirs.add(dir);
|
|
@@ -1335,7 +1362,7 @@ async function liveSessions() {
|
|
|
1335
1362
|
}
|
|
1336
1363
|
async function currentSession(sessions) {
|
|
1337
1364
|
const byPid = new Map(sessions.map((session) => [session.pid, session]));
|
|
1338
|
-
let pid =
|
|
1365
|
+
let pid = process17.ppid;
|
|
1339
1366
|
for (let depth = 0;depth < 32 && pid > 1; depth++) {
|
|
1340
1367
|
const session = byPid.get(pid);
|
|
1341
1368
|
if (session !== undefined)
|
|
@@ -1351,17 +1378,17 @@ async function currentSession(sessions) {
|
|
|
1351
1378
|
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync5, rmSync } from "fs";
|
|
1352
1379
|
import { availableParallelism } from "os";
|
|
1353
1380
|
import { join as join8 } from "path";
|
|
1354
|
-
import
|
|
1381
|
+
import process20 from "process";
|
|
1355
1382
|
|
|
1356
1383
|
// src/flock.ts
|
|
1357
1384
|
import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
|
|
1358
|
-
import
|
|
1385
|
+
import process19 from "process";
|
|
1359
1386
|
import { dlopen, FFIType } from "bun:ffi";
|
|
1360
1387
|
var LOCK_EX = 2;
|
|
1361
1388
|
var LOCK_NB = 4;
|
|
1362
1389
|
var flock;
|
|
1363
1390
|
function native() {
|
|
1364
|
-
flock ??= dlopen(
|
|
1391
|
+
flock ??= dlopen(process19.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
|
|
1365
1392
|
return flock;
|
|
1366
1393
|
}
|
|
1367
1394
|
function tryLock(path) {
|
|
@@ -1405,7 +1432,7 @@ function defaultSlots() {
|
|
|
1405
1432
|
return Math.max(1, Math.floor(availableParallelism() / 2));
|
|
1406
1433
|
}
|
|
1407
1434
|
async function stateDir() {
|
|
1408
|
-
const dir =
|
|
1435
|
+
const dir = process20.env.SLOT_DIR ?? await privateLogDirectory("slot");
|
|
1409
1436
|
for (const sub of ["slots", "locks", "waiters"])
|
|
1410
1437
|
mkdirSync2(join8(dir, sub), { recursive: true, mode: 448 });
|
|
1411
1438
|
return dir;
|
|
@@ -1447,7 +1474,7 @@ function waitingLine(dir, wanted) {
|
|
|
1447
1474
|
}
|
|
1448
1475
|
async function holderOf(command) {
|
|
1449
1476
|
const session = await currentSession(await liveSessions());
|
|
1450
|
-
return { pid:
|
|
1477
|
+
return { pid: process20.pid, command: command.join(" "), cwd: process20.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
|
|
1451
1478
|
}
|
|
1452
1479
|
var waiterCount = 0;
|
|
1453
1480
|
async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
@@ -1473,7 +1500,7 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
|
1473
1500
|
held.release();
|
|
1474
1501
|
const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
|
|
1475
1502
|
if (waiter === undefined) {
|
|
1476
|
-
const path = join8(dir, "waiters", `${
|
|
1503
|
+
const path = join8(dir, "waiters", `${process20.pid}-${waiterCount++}`);
|
|
1477
1504
|
const held = tryLock(path);
|
|
1478
1505
|
if (held !== undefined) {
|
|
1479
1506
|
writeHeld(held, JSON.stringify({ ...holder, resource }));
|
|
@@ -1514,7 +1541,7 @@ ${RUN_USAGE}`);
|
|
|
1514
1541
|
const count = wholeNumber(values.slots, "slots", defaultSlots());
|
|
1515
1542
|
const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
|
|
1516
1543
|
const deadline = Date.now() + timeoutMs;
|
|
1517
|
-
const holding = new Set((
|
|
1544
|
+
const holding = new Set((process20.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
|
|
1518
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 }]];
|
|
1519
1546
|
const signals = holdSignals(() => {
|
|
1520
1547
|
return;
|
|
@@ -1529,7 +1556,7 @@ ${RUN_USAGE}`);
|
|
|
1529
1556
|
const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
|
|
1530
1557
|
let child;
|
|
1531
1558
|
try {
|
|
1532
|
-
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...
|
|
1559
|
+
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process20.env, [HOLDING]: [...tokens].join(",") } });
|
|
1533
1560
|
} catch (error) {
|
|
1534
1561
|
fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
|
|
1535
1562
|
}
|
|
@@ -1572,11 +1599,11 @@ async function listSlots(args) {
|
|
|
1572
1599
|
printJson({ slots: count, busy, entries });
|
|
1573
1600
|
return 0;
|
|
1574
1601
|
}
|
|
1575
|
-
console.log(paint(
|
|
1602
|
+
console.log(paint(process20.stdout).bold(`slots: ${busy} of ${count} busy`));
|
|
1576
1603
|
if (entries.length > 0)
|
|
1577
|
-
console.log(table(entries.map((entry) => [badge(entry.state,
|
|
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)])));
|
|
1578
1605
|
return 0;
|
|
1579
1606
|
}
|
|
1580
1607
|
|
|
1581
1608
|
// src/slot-cli.ts
|
|
1582
|
-
|
|
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.
|
|
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.
|
|
41
|
+
"@kaynooo/cli-kit": "0.40.0"
|
|
42
42
|
}
|
|
43
43
|
}
|