@kaynooo/cli-workspace 0.3.0 → 0.5.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/dist/sweep-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/sweep-cli.ts
5
- import process15 from "process";
5
+ import process17 from "process";
6
6
 
7
7
  // ../kit/src/advisory.ts
8
8
  var SEVERITIES = ["low", "moderate", "high", "critical"];
@@ -13,14 +13,35 @@ function isIgnored(advisory, ignore) {
13
13
  return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
14
14
  }
15
15
  // ../kit/src/args.ts
16
- import process8 from "process";
16
+ import process9 from "process";
17
17
  import { parseArgs } from "util";
18
18
 
19
19
  // ../kit/src/format.ts
20
- import process6 from "process";
20
+ import process7 from "process";
21
+
22
+ // ../kit/src/mode.ts
23
+ import process2 from "process";
24
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
25
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
26
+ function isSet(value) {
27
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
28
+ }
29
+ function outputMode(stream = process2.stdout, env = process2.env) {
30
+ const chosen = env.KIT_MODE;
31
+ if (chosen !== undefined && MODES.has(chosen))
32
+ return chosen;
33
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
34
+ return "agent";
35
+ if (stream.isTTY === true)
36
+ return "terminal";
37
+ return isSet(env.CI) ? "ci" : "pipe";
38
+ }
39
+ function isInteractive(streams = process2) {
40
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
41
+ }
21
42
 
22
43
  // ../kit/src/style.ts
23
- import process5 from "process";
44
+ import process6 from "process";
24
45
 
25
46
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
26
47
  function x(s) {
@@ -287,13 +308,13 @@ var t = le();
287
308
  import { existsSync as existsSync3, readFileSync, statSync } from "fs";
288
309
  import { homedir as homedir2 } from "os";
289
310
  import { join as join3, resolve as resolve2 } from "path";
290
- import process4 from "process";
311
+ import process5 from "process";
291
312
 
292
313
  // ../kit/src/config.ts
293
314
  import { existsSync } from "fs";
294
315
  import { dirname, join, resolve } from "path";
295
- import process2 from "process";
296
- function findUp(names, from = process2.cwd(), stop = () => false) {
316
+ import process3 from "process";
317
+ function findUp(names, from = process3.cwd(), stop = () => false) {
297
318
  const wanted = typeof names === "string" ? [names] : names;
298
319
  for (let dir = resolve(from);; dir = dirname(dir)) {
299
320
  const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
@@ -308,9 +329,9 @@ function findUp(names, from = process2.cwd(), stop = () => false) {
308
329
  import { existsSync as existsSync2 } from "fs";
309
330
  import { homedir } from "os";
310
331
  import { join as join2 } from "path";
311
- import process3 from "process";
332
+ import process4 from "process";
312
333
  function configBase(where = {}) {
313
- const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
334
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
314
335
  return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
315
336
  }
316
337
  function userConfigPath(bin, where = {}) {
@@ -350,10 +371,30 @@ function isColorSpec(spec) {
350
371
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
351
372
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
352
373
  }
353
- function tinted(colors, spec) {
374
+ var CUBE = [0, 95, 135, 175, 215, 255];
375
+ function cubeLevel(channel) {
376
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
377
+ }
378
+ function nearest256(hex) {
379
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
380
+ const levels = rgb.map(cubeLevel);
381
+ const cube = levels.map((level) => CUBE[level]);
382
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
383
+ const greyValue = 8 + grey * 10;
384
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
385
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
386
+ }
387
+ function hasTrueColor(env) {
388
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
389
+ }
390
+ function tinted(colors, spec, env = process5.env) {
354
391
  if (typeof spec === "number")
355
392
  return colors.ansi256(spec);
356
- return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
393
+ return spec.trim().split(SPACES).reduce((chain, token) => {
394
+ if (HEX.test(token))
395
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
396
+ return chain[token] ?? chain;
397
+ }, colors);
357
398
  }
358
399
  function isRecord(value) {
359
400
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -437,7 +478,7 @@ function warnOnce(message) {
437
478
  function isPath(chosen) {
438
479
  return chosen.includes("/") || chosen.endsWith(".json");
439
480
  }
440
- function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
481
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
441
482
  const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
442
483
  const sources = [];
443
484
  const chosen = env.KIT_THEME ?? "";
@@ -467,7 +508,7 @@ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(
467
508
  var current;
468
509
  var currentKey = "";
469
510
  function activeTheme() {
470
- const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
511
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
471
512
  if (current === undefined || key !== currentKey) {
472
513
  current = loadTheme();
473
514
  currentKey = key;
@@ -477,38 +518,38 @@ function activeTheme() {
477
518
 
478
519
  // ../kit/src/style.ts
479
520
  var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
480
- function takesControlCodes(stream, env = process5.env) {
481
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
521
+ function takesControlCodes(stream, env = process6.env) {
522
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
482
523
  }
483
- function paint(stream, env = process5.env) {
524
+ function paint(stream, env = process6.env) {
484
525
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
485
526
  }
486
- function marked(mark, text, stream, detail, env = process5.env) {
527
+ function marked(mark, text, stream, detail, env = process6.env) {
487
528
  const colors = paint(stream, env);
488
529
  let head = MARK_WORDS[mark];
489
530
  if (takesControlCodes(stream, env)) {
490
531
  const { theme } = activeTheme();
491
- head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
532
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
492
533
  }
493
534
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
494
535
  }
495
536
  function ok(text, detail) {
496
- console.log(marked("ok", text, process5.stdout, detail));
537
+ console.log(marked("ok", text, process6.stdout, detail));
497
538
  }
498
539
  function note(text, detail) {
499
- console.log(marked("note", text, process5.stdout, detail));
540
+ console.log(marked("note", text, process6.stdout, detail));
500
541
  }
501
542
  function problem(text, detail) {
502
- console.error(marked("problem", text, process5.stderr, detail));
543
+ console.error(marked("problem", text, process6.stderr, detail));
503
544
  }
504
- function role(name, stream, env = process5.env) {
545
+ function role(name, stream, env = process6.env) {
505
546
  const colors = paint(stream, env);
506
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
547
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
507
548
  }
508
549
  var STATUS_WORDS = {
509
550
  passed: ["passed", "success", "succeeded", "ok"],
510
551
  failed: ["failed", "failure", "error", "errored"],
511
- running: ["running", "in_progress", "started"],
552
+ running: ["running", "in_progress", "started", "holding"],
512
553
  queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
513
554
  skipped: ["skipped", "cancelled", "canceled", "manual"]
514
555
  };
@@ -562,8 +603,11 @@ var ESCAPE = String.fromCharCode(27);
562
603
  function textWidth(text) {
563
604
  return Bun.stringWidth(text);
564
605
  }
565
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
606
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
566
607
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
608
+ if (outputMode(stream, env) === "agent")
609
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
610
+ `);
567
611
  const widths = [];
568
612
  for (const row of cells) {
569
613
  for (const [index, cell] of row.entries())
@@ -598,32 +642,35 @@ function narrow(rows, widths, limit) {
598
642
  }
599
643
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
600
644
  }
645
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
646
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
647
+ }
601
648
  function printJson(value) {
602
- console.log(JSON.stringify(value, undefined, 2));
649
+ console.log(jsonText(value));
603
650
  }
604
651
 
605
652
  // ../kit/src/help.ts
606
- import process7 from "process";
653
+ import process8 from "process";
607
654
  var OPTIONAL = /\[[^\]]+\]/g;
608
655
  var USAGE_PREFIX = /^usage:\s*/i;
609
656
  var FULL_STOP = /\.$/;
610
- function usageLine(usage, colors = paint(process7.stdout)) {
657
+ function usageLine(usage, colors = paint(process8.stdout)) {
611
658
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
612
659
  }
613
- function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
660
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
614
661
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
615
662
  `);
616
663
  }
617
- function exitRows(exits, colors = paint(process7.stdout)) {
664
+ function exitRows(exits, colors = paint(process8.stdout)) {
618
665
  if (exits.length === 0)
619
666
  return [];
620
667
  const width = Math.max(...exits.map(([code]) => String(code).length));
621
668
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
622
669
  }
623
- function replacesRows(replaces, colors = paint(process7.stdout)) {
624
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
670
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
671
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
625
672
  }
626
- function wantsHelpJson(env = process7.env) {
673
+ function wantsHelpJson(env = process8.env) {
627
674
  return env.KIT_HELP === "json";
628
675
  }
629
676
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -642,12 +689,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
642
689
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
643
690
  };
644
691
  }
645
- function exampleRows(examples, colors = paint(process7.stdout)) {
646
- if (examples.length === 0)
692
+ function exampleRows(examples, colors = paint(process8.stdout)) {
693
+ if (examples.length === 0 || outputMode() === "agent")
647
694
  return [];
648
695
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
649
696
  }
650
- function optionRows(options, colors = paint(process7.stdout)) {
697
+ function optionRows(options, colors = paint(process8.stdout)) {
651
698
  const rows = Object.entries(options).map(([name, option]) => {
652
699
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
653
700
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -740,7 +787,7 @@ var OUTPUT_OPTIONS = {
740
787
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
741
788
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
742
789
  };
743
- function applyOutput(color, plain, env = process8.env) {
790
+ function applyOutput(color, plain, env = process9.env) {
744
791
  const when = plain === true ? "never" : color ?? "auto";
745
792
  if (when === "auto")
746
793
  return;
@@ -911,7 +958,7 @@ function nearestOption(message, options, allowNegative) {
911
958
  }
912
959
  // ../kit/src/process.ts
913
960
  import { constants } from "os";
914
- import process9 from "process";
961
+ import process10 from "process";
915
962
  var KILL_GRACE_MS = 2000;
916
963
  function exitCodeOf(code, signal) {
917
964
  if (code !== null)
@@ -931,7 +978,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
931
978
  return;
932
979
  try {
933
980
  if (grouped)
934
- process9.kill(-proc.pid, killing);
981
+ process10.kill(-proc.pid, killing);
935
982
  else
936
983
  proc.kill(killing);
937
984
  } catch {}
@@ -1006,10 +1053,10 @@ var RESET_STYLE = `${ESC}[0m`;
1006
1053
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1007
1054
 
1008
1055
  // ../kit/src/tool.ts
1009
- import process10 from "process";
1056
+ import process11 from "process";
1010
1057
  function cwdGone() {
1011
1058
  try {
1012
- process10.cwd();
1059
+ process11.cwd();
1013
1060
  return false;
1014
1061
  } catch {
1015
1062
  return true;
@@ -1031,7 +1078,7 @@ function spawnFailure(command, error) {
1031
1078
  async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1032
1079
  let ran;
1033
1080
  try {
1034
- ran = await runCommand(argv, { env: process10.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1081
+ ran = await runCommand(argv, { env: process11.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1035
1082
  } catch (error) {
1036
1083
  throw spawnFailure(label, error);
1037
1084
  }
@@ -1048,13 +1095,13 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1048
1095
  // ../kit/src/cli.ts
1049
1096
  import { readFileSync as readFileSync2, realpathSync } from "fs";
1050
1097
  import { dirname as dirname3, join as join5 } from "path";
1051
- import process12 from "process";
1098
+ import process13 from "process";
1052
1099
 
1053
1100
  // ../kit/src/usage.ts
1054
1101
  import { appendFileSync, mkdirSync } from "fs";
1055
1102
  import { homedir as homedir3 } from "os";
1056
1103
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1057
- import process11 from "process";
1104
+ import process12 from "process";
1058
1105
 
1059
1106
  // ../kit/src/logs.ts
1060
1107
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1068,14 +1115,14 @@ var usageError;
1068
1115
  function noteUsageError(message) {
1069
1116
  usageError = message;
1070
1117
  }
1071
- function stateHome(env = process11.env) {
1118
+ function stateHome(env = process12.env) {
1072
1119
  const dir = env.XDG_STATE_HOME;
1073
1120
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1074
1121
  }
1075
- function usagePath(env = process11.env) {
1122
+ function usagePath(env = process12.env) {
1076
1123
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1077
1124
  }
1078
- function usageRecorded(env = process11.env) {
1125
+ function usageRecorded(env = process12.env) {
1079
1126
  const off = env.KAYNOOO_CLI_NO_USAGE;
1080
1127
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1081
1128
  }
@@ -1089,7 +1136,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1089
1136
  usageError = undefined;
1090
1137
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1091
1138
  }
1092
- function recordUsage(entry, env = process11.env) {
1139
+ function recordUsage(entry, env = process12.env) {
1093
1140
  if (!usageRecorded(env))
1094
1141
  return;
1095
1142
  try {
@@ -1180,8 +1227,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1180
1227
  `);
1181
1228
  }
1182
1229
  function printError(prefix, message, hint, cause) {
1183
- const colors = paint(process12.stderr);
1184
- const styled = takesControlCodes(process12.stderr);
1230
+ const colors = paint(process13.stderr);
1231
+ const styled = takesControlCodes(process13.stderr);
1185
1232
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1186
1233
  const under = (label, text, tint) => text === undefined ? "" : `
1187
1234
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1224,11 +1271,11 @@ async function dispatch(level, typed, { version, redact }) {
1224
1271
  }
1225
1272
  }
1226
1273
  if (name === undefined && level.path.length > 1) {
1227
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1274
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1228
1275
  return 2;
1229
1276
  }
1230
1277
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1231
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1278
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1232
1279
  return 0;
1233
1280
  }
1234
1281
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1355,7 +1402,7 @@ function packageVersion(entry = Bun.main) {
1355
1402
  return "0.0.0";
1356
1403
  }
1357
1404
  }
1358
- async function runCli(cli, argv = process12.argv.slice(2)) {
1405
+ async function runCli(cli, argv = process13.argv.slice(2)) {
1359
1406
  const version = cli.version ?? packageVersion();
1360
1407
  if (argv[0] === COMPLETE)
1361
1408
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1382,7 +1429,7 @@ function commandPath(scope, argv) {
1382
1429
  }
1383
1430
  return path.length === 0 ? undefined : path.join(" ");
1384
1431
  }
1385
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1432
+ async function runMain({ name, version, run, redact, usage }, argv = process13.argv.slice(2)) {
1386
1433
  if (argv[0] === COMPLETE)
1387
1434
  return printCandidates(leafCandidates(run, argv.slice(1)));
1388
1435
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1402,6 +1449,19 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
1402
1449
  }
1403
1450
  return code;
1404
1451
  }
1452
+ // ../kit/src/pool.ts
1453
+ async function pool(items, limit, task) {
1454
+ const results = Array.from({ length: items.length });
1455
+ let next = 0;
1456
+ async function worker() {
1457
+ while (next < items.length) {
1458
+ const index = next++;
1459
+ results[index] = await task(items[index]);
1460
+ }
1461
+ }
1462
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1463
+ return results;
1464
+ }
1405
1465
  // ../kit/src/secrets.ts
1406
1466
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1407
1467
  // ../kit/src/sessions.ts
@@ -1418,18 +1478,55 @@ function parseSize(text, bareUnit = 1) {
1418
1478
  const suffix = match[2].toLowerCase();
1419
1479
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1420
1480
  }
1481
+ // ../kit/src/workspace-root.ts
1482
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
1483
+ import { homedir as homedir4 } from "os";
1484
+ import { dirname as dirname4, join as join6, resolve as resolve3 } from "path";
1485
+ import process14 from "process";
1486
+ function expandHome(path, home) {
1487
+ if (path === "~")
1488
+ return home;
1489
+ return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1490
+ }
1491
+ function configured(env, home) {
1492
+ const path = userConfigPath("config", { home, xdg: env.XDG_CONFIG_HOME });
1493
+ if (!existsSync4(path))
1494
+ return;
1495
+ try {
1496
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
1497
+ const folder = typeof parsed === "object" && parsed !== null ? parsed.workspace : undefined;
1498
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
1499
+ } catch {
1500
+ return;
1501
+ }
1502
+ }
1503
+ function workspaceRoot({ given, env = process14.env, home = homedir4() } = {}) {
1504
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1505
+ return resolve3(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1506
+ }
1421
1507
  // src/sweep.ts
1422
- import { existsSync as existsSync6, statSync as statSync2 } from "fs";
1423
- import { homedir as homedir5 } from "os";
1424
- import { join as join9, relative, resolve as resolve3 } from "path";
1508
+ import { existsSync as existsSync7, statSync as statSync2 } from "fs";
1509
+ import { homedir as homedir6 } from "os";
1510
+ import { relative } from "path";
1425
1511
 
1426
1512
  // ../kit/src/prompt.ts
1427
- import process14 from "process";
1513
+ import process16 from "process";
1428
1514
  var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1429
1515
  var CONTROL2 = /^[\x00-\x1F\x7F]/;
1430
- var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1431
- function readKeys(input) {
1432
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL2.test(sequence) ? [] : [{ text: sequence }]));
1516
+ var PASTE_START = "\x1B[200~";
1517
+ var PASTE_END = "\x1B[201~";
1518
+ var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\x1B[5~": "pageup", "\x1B[6~": "pagedown", "\x1B[H": "home", "\x1B[1~": "home", "\x1BOH": "home", "\x1B[F": "end", "\x1B[4~": "end", "\x1BOF": "end", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1519
+ function readKeys(input, paste = { active: false }) {
1520
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1521
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1522
+ paste.active = sequence === PASTE_START;
1523
+ return [];
1524
+ }
1525
+ if (paste.active && (sequence === "\r" || sequence === `
1526
+ `))
1527
+ return [];
1528
+ return KEYS[sequence] ?? (CONTROL2.test(sequence) ? [] : [{ text: sequence }]);
1529
+ });
1433
1530
  }
1434
1531
  async function confirm(question, { default: fallback, ...settings } = {}) {
1435
1532
  let answered = fallback;
@@ -1453,27 +1550,34 @@ function asking(colors, question, typed, keys) {
1453
1550
  function answer(colors, question, state, picked) {
1454
1551
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1455
1552
  }
1456
- async function ask(question, { hint, terminal = process14 }, render, press) {
1553
+ async function ask(question, { hint, terminal = process16 }, render, press) {
1457
1554
  const { stdin, stderr } = terminal;
1458
- if (stdin.isTTY !== true || stderr.isTTY !== true)
1555
+ if (!isInteractive(terminal))
1459
1556
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
1460
1557
  const colors = paint(stderr);
1461
- let drawn = 0;
1558
+ let drawn = [];
1559
+ let current = "asking";
1462
1560
  let outcome;
1561
+ const columns = () => stderr.columns || 80;
1463
1562
  const draw = (state) => {
1464
- const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1465
- stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1563
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1564
+ const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
1565
+ stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
1466
1566
  `)}`);
1467
- drawn = frame.length;
1567
+ drawn = frame;
1568
+ current = state;
1468
1569
  };
1570
+ const redraw = () => draw(current);
1571
+ const paste = { active: false };
1469
1572
  try {
1573
+ stderr.on?.("resize", redraw);
1470
1574
  stdin.setRawMode(true);
1471
1575
  stdin.resume();
1472
- stderr.write("\x1B[?25l");
1576
+ stderr.write("\x1B[?25l\x1B[?2004h");
1473
1577
  draw("asking");
1474
1578
  return await new Promise((resolve) => {
1475
1579
  function onData(data) {
1476
- for (const key of readKeys(data.toString())) {
1580
+ for (const key of readKeys(data.toString(), paste)) {
1477
1581
  const pressed = press(key);
1478
1582
  if (pressed !== undefined) {
1479
1583
  settle(pressed);
@@ -1495,40 +1599,32 @@ async function ask(question, { hint, terminal = process14 }, render, press) {
1495
1599
  stdin.on("end", onEnd);
1496
1600
  });
1497
1601
  } finally {
1602
+ stderr.off?.("resize", redraw);
1498
1603
  draw(outcome ?? "cancel");
1499
1604
  stderr.write(`
1500
- \x1B[?25h`);
1605
+ \x1B[?25h\x1B[?2004l`);
1501
1606
  stdin.setRawMode(false);
1502
1607
  stdin.pause();
1503
1608
  }
1504
1609
  }
1505
1610
 
1506
1611
  // src/apply.ts
1507
- import { existsSync as existsSync5 } from "fs";
1612
+ import { existsSync as existsSync6 } from "fs";
1508
1613
  import { lstat as lstat3, rm } from "fs/promises";
1509
- import { basename as basename2, join as join8 } from "path";
1614
+ import { basename as basename2, join as join9 } from "path";
1510
1615
 
1511
1616
  // src/sweep-scan.ts
1512
- import { existsSync as existsSync4 } from "fs";
1617
+ import { existsSync as existsSync5 } from "fs";
1513
1618
  import { lstat as lstat2, readdir as readdir2, realpath } from "fs/promises";
1514
- import { homedir as homedir4 } from "os";
1515
- import { basename, dirname as dirname4, join as join7 } from "path";
1619
+ import { homedir as homedir5 } from "os";
1620
+ import { basename, dirname as dirname5, join as join8 } from "path";
1516
1621
 
1517
1622
  // src/size.ts
1518
1623
  import { lstat, readdir } from "fs/promises";
1519
- import { join as join6 } from "path";
1520
- async function pooled(items, limit, work) {
1521
- const results = Array.from({ length: items.length });
1522
- let next = 0;
1523
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
1524
- while (next < items.length) {
1525
- const index = next++;
1526
- results[index] = await work(items[index]);
1527
- }
1528
- }));
1529
- return results;
1530
- }
1624
+ import { join as join7 } from "path";
1531
1625
  var FS_LIMIT = 32;
1626
+ var FIND_MS = 60000;
1627
+ var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
1532
1628
  var waiting = [];
1533
1629
  var running = 0;
1534
1630
  async function gated(call) {
@@ -1542,7 +1638,7 @@ async function gated(call) {
1542
1638
  waiting.shift()?.();
1543
1639
  }
1544
1640
  }
1545
- async function sizeOf(folder) {
1641
+ async function walkSize(folder) {
1546
1642
  const seen = new Set;
1547
1643
  let total = 0;
1548
1644
  const visit = async (dir) => {
@@ -1553,7 +1649,7 @@ async function sizeOf(folder) {
1553
1649
  return;
1554
1650
  }
1555
1651
  await Promise.all(entries.map(async (entry) => {
1556
- const path = join6(dir, entry.name);
1652
+ const path = join7(dir, entry.name);
1557
1653
  if (entry.isDirectory())
1558
1654
  return visit(path);
1559
1655
  try {
@@ -1571,14 +1667,38 @@ async function sizeOf(folder) {
1571
1667
  await visit(folder);
1572
1668
  return total;
1573
1669
  }
1670
+ async function findSize(folder) {
1671
+ try {
1672
+ const ran = await runCommand(["find", "-P", folder, "(", "-type", "f", "-o", "-type", "l", ")", "-printf", "%n %D:%i %s\\n"], { timeoutMs: FIND_MS });
1673
+ const lines = [...ran.text.matchAll(FIND_LINE)];
1674
+ if (ran.timedOut || ran.code !== 0 && lines.length === 0)
1675
+ return;
1676
+ const seen = new Set;
1677
+ let total = 0;
1678
+ for (const [, links, id, bytes] of lines) {
1679
+ if (Number(links) > 1) {
1680
+ if (seen.has(id))
1681
+ continue;
1682
+ seen.add(id);
1683
+ }
1684
+ total += Number(bytes);
1685
+ }
1686
+ return total;
1687
+ } catch {
1688
+ return;
1689
+ }
1690
+ }
1691
+ async function sizeOf(folder) {
1692
+ return await findSize(folder) ?? await walkSize(folder);
1693
+ }
1574
1694
 
1575
1695
  // src/sweep-scan.ts
1576
1696
  var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target"]);
1577
1697
  var MAX_DEPTH = 3;
1578
1698
  var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit"]);
1579
1699
  var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
1580
- function isCachePath(path, home = homedir4()) {
1581
- return GLOBAL_CACHES.some((cache) => join7(home, cache) === path) || basename(path) === ".cache" && basename(dirname4(path)) === "node_modules";
1700
+ function isCachePath(path, home = homedir5()) {
1701
+ return GLOBAL_CACHES.some((cache) => join8(home, cache) === path) || basename(path) === ".cache" && basename(dirname5(path)) === "node_modules";
1582
1702
  }
1583
1703
  async function listing(dir) {
1584
1704
  try {
@@ -1589,7 +1709,7 @@ async function listing(dir) {
1589
1709
  }
1590
1710
  async function addGlobalCaches(found, home) {
1591
1711
  for (const cache of GLOBAL_CACHES) {
1592
- const path = join7(home, cache);
1712
+ const path = join8(home, cache);
1593
1713
  try {
1594
1714
  const stat = await lstat2(path);
1595
1715
  if (stat.isSymbolicLink())
@@ -1599,12 +1719,12 @@ async function addGlobalCaches(found, home) {
1599
1719
  } catch {}
1600
1720
  }
1601
1721
  }
1602
- async function findCandidates(root, home = homedir4(), withGlobal = true) {
1722
+ async function findCandidates(root, home = homedir5(), withGlobal = true) {
1603
1723
  const found = { candidates: [], skipped: [] };
1604
1724
  const visit = async (dir, depth) => {
1605
1725
  const entries = await listing(dir);
1606
1726
  for (const entry of entries) {
1607
- const path = join7(dir, entry.name);
1727
+ const path = join8(dir, entry.name);
1608
1728
  if (entry.name === ".git")
1609
1729
  continue;
1610
1730
  if (entry.name === ".worktrees" || entry.name === "worktrees" && basename(dir) === ".claude") {
@@ -1614,13 +1734,13 @@ async function findCandidates(root, home = homedir4(), withGlobal = true) {
1614
1734
  }
1615
1735
  for (const worktree of await listing(path)) {
1616
1736
  if (worktree.isDirectory())
1617
- found.candidates.push({ path: join7(path, worktree.name), kind: "worktree" });
1737
+ found.candidates.push({ path: join8(path, worktree.name), kind: "worktree" });
1618
1738
  else if (worktree.isSymbolicLink())
1619
- found.skipped.push({ path: join7(path, worktree.name), reason: "symlink" });
1739
+ found.skipped.push({ path: join8(path, worktree.name), reason: "symlink" });
1620
1740
  }
1621
1741
  continue;
1622
1742
  }
1623
- if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync4(join7(dir, "Cargo.toml")))) {
1743
+ if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync5(join8(dir, "Cargo.toml")))) {
1624
1744
  if (entry.isSymbolicLink()) {
1625
1745
  found.skipped.push({ path, reason: "symlink" });
1626
1746
  } else if (entry.isDirectory()) {
@@ -1628,9 +1748,9 @@ async function findCandidates(root, home = homedir4(), withGlobal = true) {
1628
1748
  if (entry.name === "node_modules") {
1629
1749
  const cache = (await listing(path)).find((inner) => inner.name === ".cache");
1630
1750
  if (cache?.isSymbolicLink())
1631
- found.skipped.push({ path: join7(path, ".cache"), reason: "symlink" });
1751
+ found.skipped.push({ path: join8(path, ".cache"), reason: "symlink" });
1632
1752
  else if (cache?.isDirectory())
1633
- found.candidates.push({ path: join7(path, ".cache"), kind: "cache", inside: path });
1753
+ found.candidates.push({ path: join8(path, ".cache"), kind: "cache", inside: path });
1634
1754
  }
1635
1755
  }
1636
1756
  continue;
@@ -1701,12 +1821,12 @@ var worktreesOf = memo(async (repo) => {
1701
1821
  return branches;
1702
1822
  });
1703
1823
  async function judgeFolder(path, kind, inside) {
1704
- const parent = dirname4(path);
1824
+ const parent = dirname5(path);
1705
1825
  const name = basename(path);
1706
1826
  const located = await toplevelOf(parent);
1707
1827
  if (located === "failed")
1708
1828
  return { skip: "git failed" };
1709
- if (existsSync4(join7(path, ".git")))
1829
+ if (existsSync5(join8(path, ".git")))
1710
1830
  return { skip: "holds a git repository" };
1711
1831
  if (located === "none")
1712
1832
  return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
@@ -1718,7 +1838,7 @@ async function judgeFolder(path, kind, inside) {
1718
1838
  return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
1719
1839
  }
1720
1840
  async function judgeWorktree(path) {
1721
- const located = await toplevelOf(dirname4(path));
1841
+ const located = await toplevelOf(dirname5(path));
1722
1842
  if (located === "failed")
1723
1843
  return { skip: "git failed" };
1724
1844
  if (located === "none")
@@ -1757,7 +1877,7 @@ async function judge(candidate) {
1757
1877
  async function inspect({ candidates, skipped }) {
1758
1878
  const entries = [];
1759
1879
  const rejected = [...skipped];
1760
- await pooled(candidates, 8, async (candidate) => {
1880
+ await pool(candidates, 8, async (candidate) => {
1761
1881
  const verdict = await judge(candidate);
1762
1882
  if ("skip" in verdict)
1763
1883
  rejected.push({ path: candidate.path, reason: verdict.skip });
@@ -1774,7 +1894,7 @@ async function removeFolder(entry) {
1774
1894
  const stat = await lstat3(entry.path);
1775
1895
  if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename2(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
1776
1896
  return { path: entry.path, removed: false, error: "no longer a plain folder" };
1777
- if (existsSync5(join8(entry.path, ".git")))
1897
+ if (existsSync6(join9(entry.path, ".git")))
1778
1898
  return { path: entry.path, removed: false, error: "holds a git repository" };
1779
1899
  await rm(entry.path, { recursive: true, force: true });
1780
1900
  return { path: entry.path, removed: true };
@@ -1807,7 +1927,7 @@ async function applyAll(entries, done) {
1807
1927
  // src/sweep.ts
1808
1928
  var LARGE = 100 * 1024 ** 2;
1809
1929
  var BIG = 1024 ** 3;
1810
- var USAGE = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, target beside a Cargo.toml), the caches (.nuxt, .next, .turbo, .svelte-kit and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (~/Workspace by default, ${MAX_DEPTH} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
1930
+ var USAGE = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, target beside a Cargo.toml), the caches (.nuxt, .next, .turbo, .svelte-kit and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
1811
1931
 
1812
1932
  Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.
1813
1933
 
@@ -1836,8 +1956,8 @@ async function sweep(args) {
1836
1956
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
1837
1957
  if (positionals.length > 1)
1838
1958
  badUsage("give one root");
1839
- const root = resolve3(positionals[0] ?? join9(homedir5(), "Workspace"));
1840
- if (!existsSync6(root) || !statSync2(root).isDirectory())
1959
+ const root = workspaceRoot({ given: positionals[0] });
1960
+ if (!existsSync7(root) || !statSync2(root).isDirectory())
1841
1961
  fail(`${root} is not a folder`);
1842
1962
  if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
1843
1963
  badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
@@ -1846,7 +1966,7 @@ async function sweep(args) {
1846
1966
  if (minBytes === undefined)
1847
1967
  badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
1848
1968
  const now = Date.now();
1849
- const found = await findCandidates(root, homedir5(), positionals.length === 0 || values.only === "caches");
1969
+ const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
1850
1970
  const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
1851
1971
  const { entries: all, skipped } = await inspect({ candidates: wanted, skipped: found.skipped });
1852
1972
  const entries = all.filter((entry) => entry.bytes >= minBytes && (olderMs === undefined || entry.committedAt !== undefined && now - entry.committedAt >= olderMs)).sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
@@ -1911,4 +2031,4 @@ ${$e(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
1911
2031
  }
1912
2032
 
1913
2033
  // src/sweep-cli.ts
1914
- process15.exitCode = await runMain({ name: "sweep", run: sweep });
2034
+ process17.exitCode = await runMain({ name: "sweep", run: sweep });