Starting programs
A capability that starts another program extends ProcessCapability. Every program it starts has a time limit, so none is left running behind the program that started it.
This capability runs git:
Git.ts
import { Capability, ProcessCapability, type ProcessSettings, ProcessTimeoutError, RunValue,} from "@kerpetensh/harness-kit";
@Capability({ name: "git", description: "Runs git in the repository of the run.", scope: "run" })export class Git extends ProcessCapability { private static readonly LOG_TIMEOUT_MS = 10_000;
@RunValue("repo") private readonly repo!: string;
public async head(): Promise<string> { const result = await this.collect(["rev-parse", "HEAD"]);
if (result.exitCode !== 0) throw new Error(`git rev-parse failed: ${result.stderr.trim()}`);
return result.stdout.toString().trim(); }
public async subjects(max: number): Promise<string[]> { try { const result = await this.collect(["log", `--max-count=${max}`, "--format=%s"], Git.LOG_TIMEOUT_MS);
return result.stdout.toString().split("\n").filter((line) => line !== ""); } catch (error) { if (error instanceof ProcessTimeoutError) return [];
throw error; } }
public async firstSubjects(max: number): Promise<string[]> { const decoder = new TextDecoder(); let text = "";
const outcome = await this.stream( ["log", "--format=%s"], (chunk) => { text += decoder.decode(chunk, { stream: true });
return text.split("\n").length <= max; }, Git.LOG_TIMEOUT_MS, );
if (outcome.kind === "not_started") throw new Error(`git did not start: ${outcome.error}`); if (outcome.kind === "timed_out") throw new Error(`git did not finish within ${outcome.timeoutMs} ms`); if (outcome.kind === "exited" && outcome.exitCode !== 0) throw new Error(`git log failed: ${outcome.stderr.trim()}`);
return text.split("\n").filter((line) => line !== "").slice(0, max); }
protected processSettings(): ProcessSettings { return { command: "git", fixedArgs: ["--no-pager"], cwd: this.repo, env: "inherit" }; }}A subclass implements processSettings and starts the program with two protected methods: collect for the whole output, stream for the output chunk by chunk. Both are for the capability’s own methods. Other classes call head() or subjects(), and never collect.
The settings
Section titled “The settings”processSettings() gives what every start of the program shares.
| Field | What it is |
|---|---|
command |
The program. |
fixedArgs |
The arguments that come first in every call. |
cwd |
The working directory. |
env |
"inherit" for the environment of the process, or a record of the variables the program gets and no others. |
- The settings are read each time the program is started. So a capability with
scope: "run"can take them from the values of its run, asGittakes the repository. - The program is started without a shell. Its arguments are
fixedArgsand then the arguments of the call, each passed as it is. - It gets no standard input unless the call gives one; see Standard input.
collect
Section titled “collect”collect(args, timeoutMs?, input?) runs the program to its end and gives a ProcessResult:
| Field | What it is |
|---|---|
exitCode |
The exit code of the program. |
stdout |
The whole output, as a Buffer. |
stderr |
The error output, as a string. |
- An exit code other than 0 is a result and no error: the capability decides what it means.
- A program that does not finish within the time limit is killed, and
collectthrows aProcessTimeoutError. WithouttimeoutMsthe limit isProcessCapability.MAX_RUN_MS. collectkeeps the whole output in memory. For a program that may write a lot, usestreamand stop it.
stream
Section titled “stream”stream(args, take, timeoutMs, input?) runs the program and gives take its output chunk by chunk.
takereturnsfalseto stop the program.timeoutMsis required here.- When
takethrows, the program is killed andstreamthrows that error.
stream does not throw for a program that fails. It gives a ProcessOutcome that says how it went:
kind |
What happened | Other fields |
|---|---|---|
exited |
The program ended by itself. | exitCode, stderr |
stopped |
take returned false, and the program was killed. |
none |
timed_out |
The program did not finish within the time limit and was killed. | timeoutMs |
not_started |
The program could not be started. | error, and code when the system named one: ENOENT for a program that is not found |
Standard input
Section titled “Standard input”collect and stream take an optional input, a Uint8Array. The kit writes it to the standard input of the program and then closes it.
const body = new TextEncoder().encode(text);const result = await this.collect(["api", "--input", "-", path], 120_000, body);- Without
inputthe program gets no standard input. - A program that ends without reading its input is no error.
- So a text of any length reaches a program without being one of its arguments. An argument has a length limit, and other users of the machine can see it in the list of processes.
collecttakes theinputaftertimeoutMs. Passundefinedthere to keep the default limit,ProcessCapability.MAX_RUN_MS.
The input came with version 0.2.0 of the kit.
The time limit
Section titled “The time limit”ProcessCapability.MAX_RUN_MS is 300000: five minutes. It is the longest a program started by collect or stream may take.
collectgives the programMAX_RUN_MSunless its caller gives a shortertimeoutMs.streamtakestimeoutMsfrom its caller.- Both refuse a limit that is not a finite number over 0, or that is over
MAX_RUN_MS. They throw aRangeErrorand start nothing. - The maximum cannot be raised. A program that needs longer than five minutes cannot be run through
ProcessCapabilityin this version.
What the time covers
Section titled “What the time covers”The time runs until the program has exited and its output and error output are read to their end. It does not end when the program closes its output.
When the time is up:
- The program is killed with
SIGKILL. - The reads that are still open are dropped.
- The method returns once the program is gone.
That also holds for a program that closes its output and goes on running, and for one that has exited while a program it started keeps the output open.
What the kill reaches
Section titled “What the kill reaches”The kill reaches the started program only. A program that one started in turn is not killed: the method stops waiting for it and returns, and that program goes on until it ends by itself.
ProcessTimeoutError
Section titled “ProcessTimeoutError”collect throws it when the time limit killed the program.
| Field | What it is |
|---|---|
command |
The command of the settings. |
timeoutMs |
The limit that was reached. |
message |
<command> did not finish within <timeoutMs> ms and was killed |
The message names the command and the limit, never the arguments, which may hold data from outside.
Time limits of a harness and of a program
Section titled “Time limits of a harness and of a program”The step deadline of a harness run ends the wait for a tool call, but it does not stop what the tool started; see Limits. A program a tool started through a capability goes on until its own time limit.
So give a program a limit that fits the work, and do not count on the harness to end it.
Names a subclass must not use
Section titled “Names a subclass must not use”ProcessCapability has three private methods of its own: finish, text and spawn. A subclass must not declare a field or a method with one of these names.
At run time a method text() of the subclass replaces the kit’s text, and collect and stream then call the wrong method. For example, a subclass with a method text() that calls collect ends with Maximum call stack size exceeded: collect calls text, which calls collect again.
Run tsc --noEmit on the program: it reports the clash as error TS2415. Components tells why and lists the names of the other base classes.
Only capabilities start programs
Section titled “Only capabilities start programs”The kit starts programs in one place, ProcessCapability. Keep it that way in a program: a tool or a flow step that needs another program takes a capability for it. The capability is then listed, can be given a permission, and can be replaced in a test.