@kaynooo/cli-kit 0.10.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 +6 -1
- package/package.json +1 -1
- package/src/args.ts +5 -2
- package/src/ci.ts +132 -0
- package/src/config.ts +11 -5
- package/src/git.ts +55 -0
- package/src/index.ts +6 -0
- package/src/logs.ts +72 -0
- package/src/process.ts +113 -12
- package/src/secrets.ts +10 -0
- package/src/sessions.ts +107 -0
- package/src/shell.ts +467 -35
- package/src/tool.ts +71 -0
package/README.md
CHANGED
|
@@ -33,6 +33,9 @@ On a terminal, help has bold `Usage:`, `Commands:` and `Options:` headers, comma
|
|
|
33
33
|
## API
|
|
34
34
|
|
|
35
35
|
- `runCli({ name, version, about, commands, aliases })` dispatches `<cli> <command> [args]`: `--help` lists the commands, `--version` prints the version, a typo names the command it likely meant, and an `Exit` thrown by a command prints `error: <cli> <command>: <message>`, its hint under it, and exits with its code. Any other error exits 1, named by its class unless a plain `Error` (`error: tool sync: MigrationError: ...`), its cause's message on a `cause:` line under it when the cause is an `Error`; `redact(text)` rewrites both before they print, for errors that may quote what a log must not keep.
|
|
36
|
+
- `runTool(label, argv, { timeoutMs, cwd, onStart })` runs a command through `runCommand` with the current environment and returns `{ code, stdout, stderr }`; it throws, naming `label`, when the command cannot start (noting a removed working directory) or outlives `timeoutMs`. `isPermanentFailure(error)` is true for what a retry cannot mend: a missing binary, or an answer of 401, 403 or 404. `cwdGone()` tells that the working directory was deleted.
|
|
37
|
+
- `git(args, timeoutMs?)`, `gitOk`, `resolveCommit`, `fetchBranch`, `defaultBranch` and `leaveWorktree` are the git helpers the forge CLIs share, over `runTool`.
|
|
38
|
+
- `waitForCi({ tool, short, giveUpMs, noneMs, stalledMs, covering, finished, key, announce, links, settle, stall, lines })` is the wait loop of `ft ci` and `gl ci`: it polls `covering` until what it returns is `finished`, retries a poll that failed for a network reason, fails at once on a refusal (`Exit`) or a permanent failure, and gives up on a timeout, on nothing covering the commit for `noneMs`, or on a `stall` that is certain or lasts `stalledMs`.
|
|
36
39
|
- `parse(args, usage, options)` wraps `node:util` `parseArgs` with a generated `--help` (`usage` given with or without its `usage:`), which prints the help and ends the command with exit 0 (it throws `HelpShown`, which `runCli` and `runMain` take), so the command needs no check after it. A string option takes a next argument starting with a dash as its value (`--from "- item"`, `-n -3`) unless that argument names one of the command's options, which parseArgs alone refuses as ambiguous. `{ positionals: ['<key>', '[file]'] }` names the positionals the command takes: `<key>` or `KEY` required, `[file]` optional, a last one ending in `...` taking any more; one missing (`missing <key>`) or one too many (`unexpected argument x`) is a usage error, and `positionals` comes back typed as `[string, string?]`. `fail(message, code = 2, hint?)` ends a command, the hint printed under the error; `badUsage(message)` ends it with a `UsageError`, which `parse`, `wholeNumber` and `duration` throw too and which gets the hint `run <cli> <command> --help for its options`; `wholeNumber` reads a numeric option.
|
|
37
40
|
- `table`, `truncate`, `formatSeconds`, `formatAge` and `upTo` format output.
|
|
38
41
|
- `runMain({ name, version, run })` runs a CLI that is a single command: `--version` or `-v` alone prints the version, and an `Exit` or any error prints `error: <name>: <message>` and becomes the exit code. `await` it into `process.exitCode`.
|
|
@@ -41,8 +44,9 @@ On a terminal, help has bold `Usage:`, `Commands:` and `Options:` headers, comma
|
|
|
41
44
|
- `<bin> __complete <words>... <word>` is answered by `runCli` and `runMain` for shell completion: the subcommands with their summaries, a leaf command's options (read by running it until its `parse` call throws them, so every command parses its arguments first), or `__files__` where a path fits.
|
|
42
45
|
- `parse(args, usage, options, { rest: true })` stops at the first `--` and returns what follows untouched as `rest` (`out -n 200 -- <cmd>`), `undefined` without a `--`; `{ allowNegative: true }` takes `--no-<flag>` as `false` for a boolean flag.
|
|
43
46
|
- `readInput(path, { noStdin })` reads a file, or stdin when the path is `-`; a missing file or a stdin left on the terminal ends the command with a message.
|
|
44
|
-
- `runCommand(argv, { cwd, env, stdin })` runs a command and returns `{ code, text, output, chunks }`, the output of both streams (in arrival order, tagged by stream in `chunks`); it throws when the command cannot start. `exitCodeOf(code, signal)` is the exit code a shell reports.
|
|
47
|
+
- `runCommand(argv, { cwd, env, stdin, timeoutMs, signal, maxBytes, onChunk, onStart })` runs a command and returns `{ code, text, output, chunks, timedOut, truncated }`, the output of both streams (in arrival order, tagged by stream in `chunks`); it throws when the command cannot start. With `timeoutMs`, `signal`, `onChunk` or `onStart` the child leads its own process group, ended whole (SIGTERM, SIGKILL after 2 s) when the timeout passes, the signal aborts or `onChunk` throws, the pipes still read to the end: `timedOut` is then true, for the caller to exit 2. `maxBytes` caps what `chunks`, `output` and `text` keep (`truncated`), `onChunk` sees every chunk, and `onStart` hands over `{ kill }` for the whole group, to pass to `holdSignals().forward`. `exitCodeOf(code, signal)` is the exit code a shell reports.
|
|
45
48
|
- `holdSignals(cleanup?)` takes SIGINT, SIGTERM and SIGHUP over until `release()`: a signal goes to the child given to `forward(child)`, so the CLI exits with the child's code; without one, `cleanup(signal)` runs and the signal is raised again, ending the process as it would have; without either, it is only kept in `signal`, for the caller to wind down (`base` holds them while its worktree exists).
|
|
49
|
+
- `privateLogDirectory(name)` returns a folder for log files only this user reads (`$XDG_RUNTIME_DIR` or `~/.cache/agent-tools`, mode 0700, verified with `lstat` when it exists, else a fresh temp folder), `createLog(path)` opens a 0600 file that must not exist (returning its descriptor), and `sweepLogs(dir, maxAgeMs?)` removes what is older than a day, subfolders included.
|
|
46
50
|
- `openUrl(target, env?)` opens a URL, or a file path made absolute, with the command `BROWSER` names or the platform's opener (`xdg-open`, `open`, `start`), without waiting; it returns `false` when that command cannot start.
|
|
47
51
|
- Every command's `parse`, and `runCli` before the command name (`ft --plain runs`), takes `--color auto|always|never` and `--plain` (`--color never`), unless the command has its own option of that name. `always` sets `FORCE_COLOR=1` and `never` sets `NO_COLOR=1`, each dropping the other, so the kit's colours, marks and redrawn lines follow, and so do the processes the command starts; `always` colours a pipe but never redraws in one. `applyOutput(color, plain, env?)` is what they run.
|
|
48
52
|
- `--help` lists the commands under `Commands:`, then a heading per `group` a command names (`{ summary, group: 'Admin', run }`), then the level's `Options:` and the `Examples:` the CLI or a group's `examples` give (`['ft ci', ['ft ci HEAD~1', 'the commit before']]`, a note shown dimmed after `#`); a command's own examples go to `parse(args, usage, options, { examples })`, shown under its options.
|
|
@@ -53,6 +57,7 @@ On a terminal, help has bold `Usage:`, `Commands:` and `Options:` headers, comma
|
|
|
53
57
|
- `stripAnsi(text)` removes colour and cursor codes, and `distance(a, b)` is the edit distance between two names.
|
|
54
58
|
- `table(rows, { cellWidth, header })` also flattens each cell's line breaks and cuts it to `cellWidth`, and with `header` prints the first row bold on a terminal; and `formatDuration(ms)` formats milliseconds like `formatSeconds` but with one decimal under a minute (`0.3s`).
|
|
55
59
|
- `ok(text, detail?)`, `note`, `warn` and `problem` print a status line marked with a green ✓, a dimmed ·, a yellow ! or a red ✗ (`ok` and `note` on stdout, the others on stderr), the detail dimmed after the text; plain, the marks read `ok:`, `note:`, `warning:` and `error:`. `marked(mark, text, stream, detail?)` returns such a line, `paint(stream)` the colours for a stream and `takesControlCodes(stream)` whether it draws in place.
|
|
60
|
+
- `isSecretName(name)` is true for the name of a variable, column or JSON key that holds a secret (`API_TOKEN`, `DB_PASS`, `SMTP_PWD`, `clientSecret`, `session_id`, `ssn`), by whole words so `compass` and `author` stay plain; `ev`, `redact` and `db` share it.
|
|
56
61
|
- `capture(fn)` from `@kaynooo/cli-kit/test` runs a command in-process and returns `{ result, out, err }`, what it printed through `console` and `process.stdout`/`stderr`, so a test needs no spy.
|
|
57
62
|
- `findUp(names, from?)` is the nearest of `names` in the current folder (or `from`) or one above it; `loadConfig(names, { from?, path? })` imports the nearest config (`.ts`, `.js` or `.json`), or the file `path` names, and returns `{ path, dir, config }` with its default export for the caller to check, `undefined` when there is none. A named file missing, one failing to import or one without a default export ends the command with exit 1.
|
|
58
63
|
- `@kaynooo/cli-kit/prompt` asks on the terminal, on stderr:
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-kit",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.12.0",
|
|
5
5
|
"description": "What every @kaynooo CLI shares: argument parsing with --help, a command dispatcher with typo hints and shell completion, and output formatting.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
package/src/args.ts
CHANGED
|
@@ -276,14 +276,17 @@ function nearestOption(message: string, options: Options, allowNegative: boolean
|
|
|
276
276
|
return meant === undefined ? undefined : `did you mean ${known.find(flag => flag.replace(DASHES, '') === meant)}?`
|
|
277
277
|
}
|
|
278
278
|
|
|
279
|
+
const WHOLE = /^\d+$/
|
|
280
|
+
|
|
281
|
+
// A name written `<run id>` is a positional and is printed as is, any other is an option printed `--name`.
|
|
279
282
|
export function wholeNumber(value: string | undefined, name: string, fallback: number, min = 1): number {
|
|
280
283
|
if (value === undefined)
|
|
281
284
|
return fallback
|
|
282
285
|
|
|
283
286
|
const number = Number(value)
|
|
284
287
|
|
|
285
|
-
if (!Number.
|
|
286
|
-
badUsage(`--${name} takes a whole number from ${min}, not ${value}`)
|
|
288
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
289
|
+
badUsage(`${name.startsWith('<') ? name : `--${name}`} takes a whole number from ${min}, not ${value}`)
|
|
287
290
|
|
|
288
291
|
return number
|
|
289
292
|
}
|
package/src/ci.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { Exit, fail } from './args'
|
|
2
|
+
import { formatDuration } from './format'
|
|
3
|
+
import { liveRegion } from './progress'
|
|
4
|
+
import { cwdGone, isPermanentFailure } from './tool'
|
|
5
|
+
|
|
6
|
+
export interface CiStall {
|
|
7
|
+
// The message the wait fails with.
|
|
8
|
+
message: string
|
|
9
|
+
// Fails at once instead of after `stalledMs`.
|
|
10
|
+
certain?: boolean
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface CiWait<T> {
|
|
14
|
+
// The command's name, as its warnings print it (`ft ci`).
|
|
15
|
+
tool: string
|
|
16
|
+
// The abbreviated sha the wait is for.
|
|
17
|
+
short: string
|
|
18
|
+
giveUpMs: number
|
|
19
|
+
// How long the wait goes on with nothing covering the commit.
|
|
20
|
+
noneMs: number
|
|
21
|
+
// How long queued work may sit while nothing moves.
|
|
22
|
+
stalledMs: number
|
|
23
|
+
pollMs?: number
|
|
24
|
+
// The message the wait fails with once nothing covered the commit for `noneMs`.
|
|
25
|
+
noneMessage: string
|
|
26
|
+
// What covers the commit now, or undefined; a refusal such as a commit not on the branch is thrown as an Exit.
|
|
27
|
+
covering: () => Promise<T | undefined>
|
|
28
|
+
finished: (found: T) => boolean
|
|
29
|
+
// Identifies what is followed, so `announce` runs again when it changes.
|
|
30
|
+
key: (found: T) => string
|
|
31
|
+
announce: (found: T) => void
|
|
32
|
+
// The links to what is followed, for the messages of a wait that ends unfinished.
|
|
33
|
+
links: (found: T) => string
|
|
34
|
+
// What a covering that failed leaves of the followed value once it can be read as over, or undefined to go on polling.
|
|
35
|
+
settle: (found: T) => Promise<T | undefined>
|
|
36
|
+
// Why the unfinished work is not moving, or undefined while it moves.
|
|
37
|
+
stall?: (found: T) => Promise<CiStall | undefined>
|
|
38
|
+
// The lines of a live region under the wait, on a terminal.
|
|
39
|
+
lines?: (spinner: string, found: T | undefined, startedAt: number) => string[]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const POLL = 15_000
|
|
43
|
+
|
|
44
|
+
// Waits until what covers a commit has finished, polling `covering`: a poll failing for a network reason is retried, one failing for good (a missing binary, a 401, 403 or 404) or a refusal ends the wait.
|
|
45
|
+
export async function waitForCi<T>(wait: CiWait<T>): Promise<T> {
|
|
46
|
+
const { tool, short, giveUpMs, noneMs, stalledMs, pollMs = POLL } = wait
|
|
47
|
+
const started = Date.now()
|
|
48
|
+
let seen = started
|
|
49
|
+
let moving = started
|
|
50
|
+
let followed = ''
|
|
51
|
+
let found: T | undefined
|
|
52
|
+
const region = wait.lines === undefined ? undefined : liveRegion(spinner => wait.lines?.(spinner, found, started) ?? [])
|
|
53
|
+
const suffix = () => found === undefined ? '' : `: ${wait.links(found)}`
|
|
54
|
+
|
|
55
|
+
// A failure to read the stall is retried on the next poll, and leaves the stall unknown.
|
|
56
|
+
async function stallOf(current: T): Promise<CiStall | undefined | 'unknown'> {
|
|
57
|
+
try {
|
|
58
|
+
return await wait.stall?.(current)
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (error instanceof Exit || isPermanentFailure(error))
|
|
62
|
+
throw error
|
|
63
|
+
|
|
64
|
+
console.warn(`${tool}: ${error instanceof Error ? error.message : String(error)}, polling again`)
|
|
65
|
+
|
|
66
|
+
return 'unknown'
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
for (;;) {
|
|
72
|
+
if (Date.now() - started > giveUpMs)
|
|
73
|
+
fail(`CI has not finished on ${short} in ${formatDuration(giveUpMs)}${suffix()}`)
|
|
74
|
+
|
|
75
|
+
// The forge or origin missing one poll leaves the wait to the next, unless what is followed is over by then.
|
|
76
|
+
try {
|
|
77
|
+
found = await wait.covering()
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error instanceof Exit)
|
|
81
|
+
throw error
|
|
82
|
+
|
|
83
|
+
if (cwdGone())
|
|
84
|
+
fail(`the working directory was removed while waiting for CI on ${short}${suffix()}`)
|
|
85
|
+
|
|
86
|
+
if (isPermanentFailure(error))
|
|
87
|
+
fail(error instanceof Error ? error.message : String(error))
|
|
88
|
+
|
|
89
|
+
console.warn(`${tool}: ${error instanceof Error ? error.message : String(error)}, polling again`)
|
|
90
|
+
|
|
91
|
+
const latest = found === undefined ? undefined : await wait.settle(found)
|
|
92
|
+
|
|
93
|
+
if (latest !== undefined)
|
|
94
|
+
return latest
|
|
95
|
+
|
|
96
|
+
await Bun.sleep(pollMs)
|
|
97
|
+
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (found !== undefined) {
|
|
102
|
+
seen = Date.now()
|
|
103
|
+
|
|
104
|
+
const key = wait.key(found)
|
|
105
|
+
|
|
106
|
+
if (key !== followed) {
|
|
107
|
+
followed = key
|
|
108
|
+
moving = Date.now()
|
|
109
|
+
wait.announce(found)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (wait.finished(found))
|
|
113
|
+
return found
|
|
114
|
+
|
|
115
|
+
const stall = await stallOf(found)
|
|
116
|
+
|
|
117
|
+
if (stall === undefined)
|
|
118
|
+
moving = Date.now()
|
|
119
|
+
else if (stall !== 'unknown' && (stall.certain === true || Date.now() - moving > stalledMs))
|
|
120
|
+
fail(stall.message)
|
|
121
|
+
}
|
|
122
|
+
else if (Date.now() - seen > noneMs) {
|
|
123
|
+
fail(wait.noneMessage)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
await Bun.sleep(pollMs)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
region?.stop()
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
2
3
|
import { dirname, join, resolve } from 'node:path'
|
|
3
4
|
import process from 'node:process'
|
|
4
5
|
import { fail } from './args'
|
|
5
6
|
|
|
6
|
-
// The nearest of `names` in `from` or a folder above it, the first name winning within one folder.
|
|
7
|
-
export function findUp(names: string | string[], from = process.cwd()): string | undefined {
|
|
7
|
+
// The nearest of `names` in `from` or a folder above it, the first name winning within one folder; the walk ends after a folder `stop` accepts.
|
|
8
|
+
export function findUp(names: string | string[], from = process.cwd(), stop: (dir: string) => boolean = () => false): string | undefined {
|
|
8
9
|
const wanted = typeof names === 'string' ? [names] : names
|
|
9
10
|
|
|
10
11
|
for (let dir = resolve(from); ; dir = dirname(dir)) {
|
|
@@ -13,11 +14,16 @@ export function findUp(names: string | string[], from = process.cwd()): string |
|
|
|
13
14
|
if (found !== undefined)
|
|
14
15
|
return found
|
|
15
16
|
|
|
16
|
-
if (dirname(dir) === dir)
|
|
17
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
17
18
|
return undefined
|
|
18
19
|
}
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
// A config is looked for up to the repository root or the home folder, never in a folder above them where a stranger's file could sit.
|
|
23
|
+
function endsWalk(dir: string): boolean {
|
|
24
|
+
return dir === resolve(homedir()) || existsSync(join(dir, '.git'))
|
|
25
|
+
}
|
|
26
|
+
|
|
21
27
|
export interface ConfigSettings {
|
|
22
28
|
// Where the search starts, the current folder by default.
|
|
23
29
|
from?: string
|
|
@@ -33,9 +39,9 @@ export interface LoadedConfig {
|
|
|
33
39
|
config: unknown
|
|
34
40
|
}
|
|
35
41
|
|
|
36
|
-
// Imports the nearest config named `names` (`.ts`, `.js` or `.json`), or the one `path` names; undefined when none is found. A named file missing, one failing to import or one without a default export ends the command.
|
|
42
|
+
// Imports the nearest config named `names` (`.ts`, `.js` or `.json`) up to the git root or the home folder, or the one `path` names; undefined when none is found. A named file missing, one failing to import or one without a default export ends the command.
|
|
37
43
|
export async function loadConfig(names: string | string[], { from = process.cwd(), path }: ConfigSettings = {}): Promise<LoadedConfig | undefined> {
|
|
38
|
-
const file = path === undefined ? findUp(names, from) : resolve(from, path)
|
|
44
|
+
const file = path === undefined ? findUp(names, from, endsWalk) : resolve(from, path)
|
|
39
45
|
|
|
40
46
|
if (file === undefined)
|
|
41
47
|
return undefined
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { basename, dirname } from 'node:path'
|
|
2
|
+
import process from 'node:process'
|
|
3
|
+
import { fail } from './args'
|
|
4
|
+
import { cwdGone, runTool } from './tool'
|
|
5
|
+
|
|
6
|
+
const ORIGIN_PREFIX = /^origin\//
|
|
7
|
+
|
|
8
|
+
// How long a git call that reaches the network waits for origin.
|
|
9
|
+
export const GIT_NETWORK_MS = 60_000
|
|
10
|
+
|
|
11
|
+
// Runs git and returns its trimmed output; throws with git's own message on a failure, or when git cannot start or outlives `timeoutMs`.
|
|
12
|
+
export async function git(args: string[], timeoutMs?: number): Promise<string> {
|
|
13
|
+
const result = await runTool(`git ${args.join(' ')}`, ['git', ...args], { timeoutMs })
|
|
14
|
+
|
|
15
|
+
if (result.code !== 0)
|
|
16
|
+
throw new Error(`git ${args.join(' ')}: ${result.stderr.trim() || `exit ${result.code}`}${cwdGone() ? ' (the working directory was removed)' : ''}`)
|
|
17
|
+
|
|
18
|
+
return result.stdout.trim()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function gitOk(args: string[]): Promise<boolean> {
|
|
22
|
+
return (await runTool(`git ${args.join(' ')}`, ['git', ...args])).code === 0
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function resolveCommit(ref: string): Promise<string> {
|
|
26
|
+
const sha = (await runTool('git rev-parse', ['git', 'rev-parse', '--verify', '-q', '--end-of-options', `${ref}^{commit}`])).stdout.trim()
|
|
27
|
+
|
|
28
|
+
if (sha === '')
|
|
29
|
+
fail(`no commit ${ref}`)
|
|
30
|
+
|
|
31
|
+
return sha
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Fetches one branch of origin; a name that is no branch, such as `--upload-pack=<command>`, is refused before git reads it, and the refspec is spelled out so it can never be an option.
|
|
35
|
+
export async function fetchBranch(branch: string): Promise<void> {
|
|
36
|
+
if (branch.startsWith('-') || !await gitOk(['check-ref-format', '--branch', branch]))
|
|
37
|
+
fail(`${branch} is not a branch name`)
|
|
38
|
+
|
|
39
|
+
await git(['fetch', '-q', 'origin', `refs/heads/${branch}`], GIT_NETWORK_MS)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The branch origin's HEAD names, which is the repository's default branch once cloned or `git remote set-head origin -a` ran.
|
|
43
|
+
export async function defaultBranch(): Promise<string> {
|
|
44
|
+
const head = (await runTool('git symbolic-ref', ['git', 'symbolic-ref', '--short', '-q', 'refs/remotes/origin/HEAD'])).stdout.trim()
|
|
45
|
+
|
|
46
|
+
return head === '' ? 'main' : head.replace(ORIGIN_PREFIX, '')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// A linked worktree can be deleted while a wait runs in it, so the wait moves to the main checkout, which outlives it.
|
|
50
|
+
export async function leaveWorktree(): Promise<void> {
|
|
51
|
+
const common = await git(['rev-parse', '--path-format=absolute', '--git-common-dir'])
|
|
52
|
+
|
|
53
|
+
if (basename(common) === '.git')
|
|
54
|
+
process.chdir(dirname(common))
|
|
55
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
export * from './args'
|
|
2
2
|
export * from './chart'
|
|
3
|
+
export * from './ci'
|
|
3
4
|
export * from './cli'
|
|
4
5
|
export * from './config'
|
|
5
6
|
export * from './format'
|
|
7
|
+
export * from './git'
|
|
6
8
|
export * from './limit'
|
|
9
|
+
export * from './logs'
|
|
7
10
|
export * from './process'
|
|
11
|
+
export * from './secrets'
|
|
12
|
+
export * from './sessions'
|
|
8
13
|
export * from './style'
|
|
9
14
|
export * from './text'
|
|
15
|
+
export * from './tool'
|
package/src/logs.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { lstatSync, openSync } from 'node:fs'
|
|
2
|
+
import { mkdir, mkdtemp, readdir, rm, stat } from 'node:fs/promises'
|
|
3
|
+
import { homedir, tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import process from 'node:process'
|
|
6
|
+
|
|
7
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
8
|
+
|
|
9
|
+
// Whether the folder is a real directory (not a link) that only this user can use.
|
|
10
|
+
function isPrivateDirectory(path: string): boolean {
|
|
11
|
+
try {
|
|
12
|
+
const info = lstatSync(path, { throwIfNoEntry: false })
|
|
13
|
+
|
|
14
|
+
return info !== undefined && info.isDirectory() && info.uid === (process.getuid?.() ?? info.uid) && (info.mode & 0o077) === 0
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// A folder for log files that only this user can read: `<name>` under $XDG_RUNTIME_DIR, else ~/.cache/agent-tools. When one already exists it must be a private directory of this user, otherwise a fresh private folder in the temp directory is used instead of trusting it.
|
|
22
|
+
export async function privateLogDirectory(name: string, env: Record<string, string | undefined> = process.env): Promise<string> {
|
|
23
|
+
const runtime = env.XDG_RUNTIME_DIR
|
|
24
|
+
const base = runtime === undefined || runtime === '' ? join(homedir(), '.cache', 'agent-tools') : join(runtime, 'agent-tools')
|
|
25
|
+
const path = join(base, name)
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
await mkdir(path, { recursive: true, mode: 0o700 })
|
|
29
|
+
|
|
30
|
+
if (isPrivateDirectory(path))
|
|
31
|
+
return path
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// Falls through to the temp folder below.
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return mkdtemp(join(tmpdir(), `${name.replaceAll('/', '-')}-`))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Removes what is older than `maxAgeMs` in the folder, and the empty subfolders it leaves, best effort since another run may be doing the same.
|
|
41
|
+
export async function sweepLogs(dir: string, maxAgeMs = DAY_MS, now = Date.now()): Promise<void> {
|
|
42
|
+
let names: string[]
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
names = await readdir(dir)
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
for (const name of names) {
|
|
52
|
+
const path = join(dir, name)
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
const info = await stat(path)
|
|
56
|
+
|
|
57
|
+
if (info.isDirectory())
|
|
58
|
+
await sweepLogs(path, maxAgeMs, now)
|
|
59
|
+
|
|
60
|
+
if (now - info.mtimeMs > maxAgeMs)
|
|
61
|
+
await rm(path, { force: true, recursive: info.isDirectory() })
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Creates a log file nobody else can read and that must not exist yet, so a planted link is never followed; returns its descriptor, for writeSync.
|
|
70
|
+
export function createLog(path: string): number {
|
|
71
|
+
return openSync(path, 'wx', 0o600)
|
|
72
|
+
}
|
package/src/process.ts
CHANGED
|
@@ -14,12 +14,26 @@ export interface Ran {
|
|
|
14
14
|
// The bytes of every chunk joined.
|
|
15
15
|
output: Buffer
|
|
16
16
|
text: string
|
|
17
|
+
// The command was ended because `timeoutMs` passed, its code then being the signal's.
|
|
18
|
+
timedOut: boolean
|
|
19
|
+
// More than `maxBytes` came, and the rest was left out of chunks, output and text.
|
|
20
|
+
truncated: boolean
|
|
17
21
|
}
|
|
18
22
|
|
|
19
23
|
export interface RunSettings {
|
|
20
24
|
cwd?: string
|
|
21
25
|
env?: Record<string, string | undefined>
|
|
22
26
|
stdin?: 'inherit' | 'ignore'
|
|
27
|
+
// Ends the command and its children after this long.
|
|
28
|
+
timeoutMs?: number
|
|
29
|
+
// Ends the command and its children when aborted.
|
|
30
|
+
signal?: AbortSignal
|
|
31
|
+
// Bytes kept in the result; the pipes are still read to the end.
|
|
32
|
+
maxBytes?: number
|
|
33
|
+
// Called with each chunk as it arrives; throwing ends the command and rethrows once the pipes are drained.
|
|
34
|
+
onChunk?: (chunk: Chunk) => void
|
|
35
|
+
// Called once the command runs, with a handle that sends a signal to its whole process group, for `holdSignals().forward`.
|
|
36
|
+
onStart?: (child: { kill: (signal: NodeJS.Signals) => void }) => void
|
|
23
37
|
}
|
|
24
38
|
|
|
25
39
|
export interface HeldSignals {
|
|
@@ -31,16 +45,12 @@ export interface HeldSignals {
|
|
|
31
45
|
release: () => void
|
|
32
46
|
}
|
|
33
47
|
|
|
48
|
+
const KILL_GRACE_MS = 2000
|
|
34
49
|
const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
|
|
35
50
|
// A scheme of two letters or more, so a Windows drive is read as a path.
|
|
36
51
|
const SCHEME = /^[a-z][\w+.-]+:/i
|
|
37
52
|
const OPENERS: Partial<Record<NodeJS.Platform, string[]>> = { darwin: ['open'], win32: ['cmd', '/c', 'start', ''] }
|
|
38
53
|
|
|
39
|
-
async function collect(stream: ReadableStream<Uint8Array>, name: Chunk['stream'], chunks: Chunk[]): Promise<void> {
|
|
40
|
-
for await (const data of stream)
|
|
41
|
-
chunks.push({ stream: name, data })
|
|
42
|
-
}
|
|
43
|
-
|
|
44
54
|
// The exit code a shell would report: the code, or 128 plus the signal.
|
|
45
55
|
export function exitCodeOf(code: number | null, signal: NodeJS.Signals | number | null): number {
|
|
46
56
|
if (code !== null)
|
|
@@ -106,15 +116,106 @@ export function openUrl(target: string, env: Record<string, string | undefined>
|
|
|
106
116
|
}
|
|
107
117
|
}
|
|
108
118
|
|
|
109
|
-
// Runs a command with stdout and stderr captured; throws when it cannot be started.
|
|
110
|
-
export async function runCommand(argv: string[], { cwd, env, stdin = 'ignore' }: RunSettings = {}): Promise<Ran> {
|
|
119
|
+
// Runs a command with stdout and stderr captured; throws when it cannot be started. With `timeoutMs`, `signal`, `onStart` or `onChunk` the child leads its own process group, and the whole group is ended (SIGTERM, then SIGKILL after a short grace) on the timeout, an abort or a throwing `onChunk`; the pipes are drained to their end either way.
|
|
120
|
+
export async function runCommand(argv: string[], { cwd, env, stdin = 'ignore', timeoutMs, signal, maxBytes = Infinity, onChunk, onStart }: RunSettings = {}): Promise<Ran> {
|
|
111
121
|
const chunks: Chunk[] = []
|
|
112
|
-
const
|
|
122
|
+
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined
|
|
123
|
+
const proc = Bun.spawn(argv, { ...(cwd === undefined ? {} : { cwd }), ...(env === undefined ? {} : { env }), stdin, stdout: 'pipe', stderr: 'pipe', ...(grouped ? { detached: true } : {}) })
|
|
124
|
+
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined as unknown, done: false }
|
|
125
|
+
const timers: ReturnType<typeof setTimeout>[] = []
|
|
126
|
+
|
|
127
|
+
const killGroup = (killing: NodeJS.Signals) => {
|
|
128
|
+
if (state.done)
|
|
129
|
+
return
|
|
130
|
+
|
|
131
|
+
try {
|
|
132
|
+
if (grouped)
|
|
133
|
+
process.kill(-proc.pid, killing)
|
|
134
|
+
else
|
|
135
|
+
proc.kill(killing)
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// The group is already gone.
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const stop = () => {
|
|
143
|
+
killGroup('SIGTERM')
|
|
144
|
+
timers.push(setTimeout(killGroup, KILL_GRACE_MS, 'SIGKILL'))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const onAbort = () => stop()
|
|
148
|
+
|
|
149
|
+
if (timeoutMs !== undefined) {
|
|
150
|
+
timers.push(setTimeout(() => {
|
|
151
|
+
state.timedOut = true
|
|
152
|
+
stop()
|
|
153
|
+
}, timeoutMs))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (signal?.aborted === true)
|
|
157
|
+
onAbort()
|
|
158
|
+
else
|
|
159
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
160
|
+
|
|
161
|
+
onStart?.({ kill: killing => killGroup(killing) })
|
|
162
|
+
|
|
163
|
+
const drain = async (stream: ReadableStream<Uint8Array>, name: Chunk['stream']) => {
|
|
164
|
+
for await (const data of stream) {
|
|
165
|
+
if (state.failure !== undefined)
|
|
166
|
+
continue
|
|
113
167
|
|
|
114
|
-
|
|
115
|
-
|
|
168
|
+
try {
|
|
169
|
+
onChunk?.({ stream: name, data })
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
state.failure = error
|
|
173
|
+
stop()
|
|
116
174
|
|
|
117
|
-
|
|
175
|
+
continue
|
|
176
|
+
}
|
|
118
177
|
|
|
119
|
-
|
|
178
|
+
if (state.kept + data.length > maxBytes) {
|
|
179
|
+
state.truncated = true
|
|
180
|
+
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
state.kept += data.length
|
|
185
|
+
chunks.push({ stream: name, data })
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
try {
|
|
190
|
+
await Promise.all([drain(proc.stdout, 'stdout'), drain(proc.stderr, 'stderr')])
|
|
191
|
+
await proc.exited
|
|
192
|
+
}
|
|
193
|
+
finally {
|
|
194
|
+
state.done = true
|
|
195
|
+
|
|
196
|
+
for (const timer of timers)
|
|
197
|
+
clearTimeout(timer)
|
|
198
|
+
|
|
199
|
+
signal?.removeEventListener('abort', onAbort)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (state.failure !== undefined)
|
|
203
|
+
throw state.failure
|
|
204
|
+
|
|
205
|
+
const joined = () => Buffer.concat(chunks.map(({ data }) => data))
|
|
206
|
+
let output: Buffer | undefined
|
|
207
|
+
let text: string | undefined
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
211
|
+
chunks,
|
|
212
|
+
timedOut: state.timedOut,
|
|
213
|
+
truncated: state.truncated,
|
|
214
|
+
get output() {
|
|
215
|
+
return output ??= joined()
|
|
216
|
+
},
|
|
217
|
+
get text() {
|
|
218
|
+
return text ??= (output ??= joined()).toString()
|
|
219
|
+
},
|
|
220
|
+
}
|
|
120
221
|
}
|
package/src/secrets.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Parts of a name that make it secret wherever they sit in it (`DB_PASSWORD`, `PGPASSWORD`, `clientSecret`).
|
|
2
|
+
const SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i
|
|
3
|
+
// Whole words of a name that make it secret (`DB_PASS`, `SMTP_PWD`, `encryptionKey`, `session_id`), so `compass`, `author` or `keyword` stay plain.
|
|
4
|
+
const SECRET_WORDS = new Set(['key', 'pass', 'pwd', 'auth', 'salt', 'cookie', 'session', 'jwt', 'ssn', 'iban', 'card', 'cvv', 'otp'])
|
|
5
|
+
const WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/
|
|
6
|
+
|
|
7
|
+
// True for the name of a variable, a column or a JSON key that holds a secret, by one definition shared by ev, redact and db.
|
|
8
|
+
export function isSecretName(name: string): boolean {
|
|
9
|
+
return SECRET_PART.test(name) || name.split(WORD_BREAKS).some(word => SECRET_WORDS.has(word.toLowerCase()))
|
|
10
|
+
}
|
package/src/sessions.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { homedir } from 'node:os'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { Glob } from 'bun'
|
|
5
|
+
|
|
6
|
+
// A running Claude Code session, as it registers itself in <config dir>/sessions/<pid>.json.
|
|
7
|
+
export interface Session { name: string, pid: number, status: string, cwd: string }
|
|
8
|
+
|
|
9
|
+
interface Entry { name?: string, pid?: number, procStart?: string, status?: string, cwd?: string }
|
|
10
|
+
|
|
11
|
+
const SESSION_FILES = new Glob('*.json')
|
|
12
|
+
const ACCOUNT_DIRS = new Glob('*/sessions')
|
|
13
|
+
|
|
14
|
+
async function sessionDirs(): Promise<string[]> {
|
|
15
|
+
const home = homedir()
|
|
16
|
+
const dirs = new Set([join(home, '.claude', 'sessions')])
|
|
17
|
+
|
|
18
|
+
if (process.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
19
|
+
dirs.add(join(process.env.CLAUDE_CONFIG_DIR, 'sessions'))
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join(home, '.claude-accounts'), onlyFiles: false, absolute: true }))
|
|
23
|
+
dirs.add(dir)
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
// No ~/.claude-accounts: the default config dir is the only one.
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return [...dirs]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The fields of /proc/<pid>/stat after the command name, which may itself hold spaces and parentheses.
|
|
33
|
+
async function procStat(pid: number): Promise<string[] | undefined> {
|
|
34
|
+
try {
|
|
35
|
+
const stat = await Bun.file(`/proc/${pid}/stat`).text()
|
|
36
|
+
|
|
37
|
+
return stat.slice(stat.lastIndexOf(')') + 2).split(' ')
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Alive and the same process the session registered, not a later one given its pid; starttime is field 22, the 20th after the name.
|
|
45
|
+
async function isAlive(pid: number, procStart: string | undefined): Promise<boolean> {
|
|
46
|
+
const stat = await procStat(pid)
|
|
47
|
+
|
|
48
|
+
if (stat === undefined)
|
|
49
|
+
return false
|
|
50
|
+
|
|
51
|
+
return procStart === undefined || stat[19] === procStart
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function liveSessions(): Promise<Session[]> {
|
|
55
|
+
const sessions = new Map<number, Session>()
|
|
56
|
+
|
|
57
|
+
for (const dir of await sessionDirs()) {
|
|
58
|
+
let files: string[]
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
files = await Array.fromAsync(SESSION_FILES.scan({ cwd: dir, absolute: true }))
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
for (const file of files) {
|
|
68
|
+
let entry: Entry
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
entry = await Bun.file(file).json() as Entry
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (entry.name === undefined || entry.pid === undefined || sessions.has(entry.pid) || !await isAlive(entry.pid, entry.procStart))
|
|
78
|
+
continue
|
|
79
|
+
|
|
80
|
+
sessions.set(entry.pid, { name: entry.name, pid: entry.pid, status: entry.status ?? 'unknown', cwd: entry.cwd ?? '' })
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return [...sessions.values()]
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// The session this process runs under, found by walking up its parent pids.
|
|
88
|
+
export async function currentSession(sessions: Session[]): Promise<Session | undefined> {
|
|
89
|
+
const byPid = new Map(sessions.map(session => [session.pid, session]))
|
|
90
|
+
let pid = process.ppid
|
|
91
|
+
|
|
92
|
+
for (let depth = 0; depth < 32 && pid > 1; depth++) {
|
|
93
|
+
const session = byPid.get(pid)
|
|
94
|
+
|
|
95
|
+
if (session !== undefined)
|
|
96
|
+
return session
|
|
97
|
+
|
|
98
|
+
const parent = Number((await procStat(pid))?.[1])
|
|
99
|
+
|
|
100
|
+
if (!Number.isInteger(parent))
|
|
101
|
+
return undefined
|
|
102
|
+
|
|
103
|
+
pid = parent
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return undefined
|
|
107
|
+
}
|