Workflows, commands and the CLI
A workflow is a chain of flow steps over one state. A workflow with a command in its spec is a command, and a CLI is a program whose commands are such workflows.
This page turns the program of A first program into a command-line program:
notes summarize --file notes.txt --model <model-id>It keeps TextFile, ReadLinesTool and SummaryHarness. Three flow steps, a workflow that is also the command, a CLI and notes.ts replace SummaryStep, SummaryWorkflow and main.ts.
A flow step
Section titled “A flow step”ModelStep.ts
import { Inject } from "@asenajs/ioc";import { ExitCode, FlowStep, FlowStepBase, type HarnessLogger, type LlmAdapter } from "@kerpetensh/harness-kit";import { AiSdkAdapter } from "@kerpetensh/harness-kit/ai-sdk";import type { Env, SummarizeInput } from "./summarize-types";
@FlowStep({ name: "model", description: "Builds the model adapter from the model id and the API key." })export class ModelStep extends FlowStepBase { @Inject("notes:env") private readonly env!: Env;
public execute(state: SummarizeInput) { const apiKey = this.env.OPENROUTER_API_KEY;
if (apiKey === undefined) return this.end(this.command.fail(ExitCode.USAGE, "OPENROUTER_API_KEY is not set"));
const llm: LlmAdapter = AiSdkAdapter.fromSettings({ provider: "openrouter", model: state.model, apiKey, zdr: false }); const quiet = () => {}; const log: HarnessLogger = { debug: quiet, info: quiet, warn: (message) => this.command.report(message) };
return { llm, log }; }}summarize-types.ts
export interface SummarizeInput { readonly path: string; readonly model: string;}
export type Env = Readonly<Record<string, string | undefined>>;The rules of a flow step:
descriptionis one plain sentence that says what the step does.executetakes the state so far. The first step of a workflow takes the workflow’s input type.executereturns the fields it adds, as a plain object:return { llm, log };. It returns{}when it adds nothing.- Write no return type on
execute. The next step reads the fields from the inferred type. - A step may not add a field that is already in the state.
- To end the workflow early,
return this.end(result). The later steps andfinishdo not run. The result must have the workflow’s result type. this.runis the run the step executes in.this.commandis the command a CLI is running. Both throw when read outside.
The next step names its place in the chain with After<typeof ModelStep>. That is the state after ModelStep ran: what that step took plus what it added. A step that needs the step before it only as a type imports it with import type.
SummarizeStep.ts
import { Inject } from "@asenajs/ioc";import { type After, FlowStep, FlowStepBase } from "@kerpetensh/harness-kit";import type { ModelStep } from "./ModelStep";import { SummaryHarness } from "./SummaryHarness";
@FlowStep({ name: "summarize", description: "Has the model read the file and summarize it." })export class SummarizeStep extends FlowStepBase { @Inject(SummaryHarness) private readonly harness!: SummaryHarness;
public async execute(state: After<typeof ModelStep>) { const deadline = Date.now() + 60_000;
const run = await this.harness.run(state.path, { llm: state.llm, limits: { maxToolCalls: 10, stepDeadline: deadline, finalizeDeadline: deadline + 30_000 }, now: Date.now, log: state.log, });
if (run.value === undefined) throw new Error(`the model gave no summary: ${run.error ?? run.partialReason}`);
return { summary: run.value.summary }; }}PrintStep.ts
import { Inject } from "@asenajs/ioc";import { type After, FlowStep, FlowStepBase, type KitInstances, KitNames } from "@kerpetensh/harness-kit";import type { SummarizeStep } from "./SummarizeStep";
@FlowStep({ name: "print", description: "Prints the summary." })export class PrintStep extends FlowStepBase { @Inject(KitNames.IO) private readonly io!: KitInstances[KitNames.IO];
public execute(state: After<typeof SummarizeStep>) { this.io.out(state.summary);
return {}; }}A workflow
Section titled “A workflow”SummarizeCommand.ts
import { type After, type CommandArgs, ExitCode, UsageError, Workflow, WorkflowBase } from "@kerpetensh/harness-kit";import { ModelStep } from "./ModelStep";import { PrintStep } from "./PrintStep";import type { SummarizeInput } from "./summarize-types";import { SummarizeStep } from "./SummarizeStep";
@Workflow({ name: "summarize", description: "Summarize a text file in one sentence.", steps: [ModelStep, SummarizeStep, PrintStep], command: { name: "summarize", usage: "--file <path> --model <model-id>", options: { file: { type: "string" }, model: { type: "string" } }, },})export class SummarizeCommand extends WorkflowBase<SummarizeInput, After<typeof PrintStep>, number> { public override commandInput(args: CommandArgs): SummarizeInput { const path = args.string("file"); const model = args.string("model");
if (path === undefined) throw new UsageError("--file is required"); if (model === undefined) throw new UsageError("--model is required");
return { path, model }; }
protected finish(): number { return ExitCode.OK; }
protected override rescue(error: unknown): number { return this.command.fail(ExitCode.FAILED, error instanceof Error ? error.message : String(error)); }}The three type arguments of WorkflowBase are the input, the final state and the result. The final state is After<typeof LastStep>. finish(state) builds the result from the final state.
The chain is checked by the compiler
Section titled “The chain is checked by the compiler”@Workflow checks the chain when the program is compiled:
- each step finds the fields it takes,
- no step adds a field that is already there,
- the steps reach the final state,
- an early end carries the workflow’s result.
A broken chain is a type error on the @Workflow line. Its message names a marker type with the step and the problem.
| Marker type | What it means |
|---|---|
FlowStepNeedsMore<typeof SummarizeStep, "llm" | "log"> |
SummarizeStep needs llm and log, and no step before it adds them. The compiler names this one when ModelStep is not in the list above. |
StepsNeedTupleType |
The step list has the type of an array, which names neither the steps nor their order. Write the list in the decorator, or declare it elsewhere with as const. |
FlowStepAddsTwice, NoStepAdds, FlowStepEndsWithOtherResult |
The other marker types. |
The state is a plain record
Section titled “The state is a plain record”- The state keeps the own fields of the input and of what each step returns, and no getter or method of a class.
- So the input and what a step returns are plain objects, written with
{}. runthrows on an input that is an instance of a class or an array, without askingrescue.- A step that returns one ends the workflow with an error.
A workflow as a step
Section titled “A workflow as a step”A workflow may be listed in the steps of another. It runs to its own result, and the fields of that result join the outer state, so its result is a plain object too. Its inner state stays hidden.
What happens when a workflow runs
Section titled “What happens when a workflow runs”workflow.run(input) does this, in order:
- It opens a run, or joins the open one. A run it opens gets the grant of the group that
group(input)names. - The grant is checked against the harnesses the workflow reaches. A grant that misses a required permission ends the workflow with a
PermissionGroupError. admitruns.- The input joins the values of the run.
- The run builds the run components marked with
@OnFlowStartthat the workflow reaches, and runs their hooks. - For each step: the run makes ready what the step takes with
@Use, thenexecuteruns and its fields join the state. finishbuilds the result.
An error at any of these points goes to rescue. Runs and permissions tells what the grant and the hooks are.
A workflow may override these:
| Method | Purpose |
|---|---|
group(input) |
The permission group of a run this workflow opens. It names none by default, which gives every permission. |
grant(input) |
The grant of a run this workflow opens. Override it only for a grant that comes from no group. |
admit(input, grant, gaps) |
Runs after the grant passed the check. Report the optional gaps, or throw to refuse a grant. |
rescue(error, state) |
Turns an error that ends the workflow into its result. state is the state when the error came. It throws the error by default. |
commandInput(args) |
Turns the parsed command line into the input. Only for a command. |
A command
Section titled “A command”| Workflow | What it is |
|---|---|
With a command in its spec |
A command. Its result type is number: the exit code. |
| Without one | Internal. It runs as a step of another workflow or when code calls its run. |
The fields of command:
| Field | What it is |
|---|---|
name |
The word that runs the command. |
usage |
The text after that word in the usage line. |
options |
The flags, each { type: "string" } or { type: "boolean" }. They are parsed with parseArgs of node:util, in strict mode. |
oneOf |
Optional. A group of boolean flags of which a line gives at most one: { flags, fallback, label }. |
actions |
Optional. Words of which the line must start with one, like login, logout, status. |
A command takes no positional arguments other than the action word. The workflow’s description is the command’s description in the usage.
Reading the command line
Section titled “Reading the command line”commandInput(args) reads the parsed line:
| Call | What it gives |
|---|---|
args.string(name) |
The value of a string option, or undefined when the line does not give it. |
args.boolean(name) |
Whether the line gives a boolean option. |
args.choice() |
The one flag of the oneOf group the line gives, or its fallback. Two flags throw a UsageError. |
args.action |
The action word, when the spec has actions. |
A line the command cannot take throws a UsageError. The CLI prints its message and the usage and exits with 2.
One flag of a group
Section titled “One flag of a group”A oneOf group looks like this in a spec:
command: { name: "echo", usage: "--text <text>", options: { text: { type: "string" } }, oneOf: { flags: ["loud", "quiet"], fallback: "quiet", label: "volume" },},The flags need no entry in options. A flag with the name of an option throws when the class is defined.
For a CLI named demo, the usage shows the flags in the line of the command and a note below the list:
demo echo --text <text> [--loud | --quiet]
echo volume: at most one of --loud, --quiet; --quiet when none is givenThe CLI
Section titled “The CLI”NotesCli.ts
import { CLI, CliBase } from "@kerpetensh/harness-kit";import { SummarizeCommand } from "./SummarizeCommand";
@CLI({ name: "notes", version: "0.1.0", commands: [SummarizeCommand] })export class NotesCli extends CliBase {}cli.run(argv) takes the arguments after the program name and gives the exit code. It runs a command line in four steps:
- It parses the arguments by the command spec.
- The workflow turns them into its input with
commandInput. - It runs the workflow.
- It returns the workflow’s result.
--help, -h and help print the usage. --version and -v print the version. cli.usage is the usage text:
notes 0.1.0
usage: notes summarize --file <path> --model <model-id> Summarize a text file in one sentence. notes --version | --helpThe program builds the application, starts it and runs the CLI:
notes.ts
import { ExitCode, HarnessApplication } from "@kerpetensh/harness-kit";import { ModelStep } from "./ModelStep";import { NotesCli } from "./NotesCli";import { PrintStep } from "./PrintStep";import { ReadLinesTool } from "./ReadLinesTool";import { SummarizeCommand } from "./SummarizeCommand";import { SummarizeStep } from "./SummarizeStep";import { SummaryHarness } from "./SummaryHarness";import { TextFile } from "./TextFile";
async function main(argv: readonly string[]): Promise<number> { const app = await HarnessApplication.create({ components: [NotesCli, SummarizeCommand, ModelStep, SummarizeStep, PrintStep, SummaryHarness, ReadLinesTool, TextFile], instances: { "notes:env": process.env }, });
try { await app.start(); } catch (error) { console.error(error instanceof Error ? error.message : String(error));
return ExitCode.FAILED; }
try { const cli = await app.resolve(NotesCli);
return await cli.run(argv); } finally { await app.stop(); }}
process.exit(await main(process.argv.slice(2)));When the container starts, the CLI takes its commands in the order of commands. It stops the start when one of them:
- is not registered,
- has no
command, - has the command name of another, or
- is listed by another CLI.
The command a step runs in
Section titled “The command a step runs in”A workflow and its flow steps read the command a CLI is running with this.command.
| Member | What it does |
|---|---|
this.command.program |
The name of the CLI. |
this.command.name |
The name of the command. |
this.command.report(message) |
Writes <program> <command>: <message> on the error output of the io. |
this.command.fail(code, message) |
Does the same and gives the code back. |
report and fail add the program and the command name, so the message does not hold them:
notes summarize: OPENROUTER_API_KEY is not setRead outside a command, this.command throws. So a flow step that reads it works only in a workflow a CLI runs.
Exit codes
Section titled “Exit codes”ExitCode.OK is 0, ExitCode.FAILED is 1 and ExitCode.USAGE is 2.
| Who | Case | Code |
|---|---|---|
CliBase |
--help, -h, help, --version, -v |
0 |
CliBase |
No arguments. It prints the usage on the standard output. | 2 |
CliBase |
An unknown command, a line that cannot be parsed, or an error thrown by commandInput. It prints the error and the usage on the error output. |
2 |
| The command | What finish returns, what a step gives to this.end, or what rescue returns. |
the command decides |
The kit never returns ExitCode.FAILED itself. It is there for the commands and for the program around the CLI, as in notes.ts above for a container that does not start.
How an error ends a command
Section titled “How an error ends a command”The kit does not turn a thrown error into an exit code:
cli.runcatches only the errors of the parse and ofcommandInput.- An error that no
rescueturns into a result leavescli.runas a thrown error.
So a failure the user can cause becomes an exit code in one of two ways.
In a flow step, report and end with the code:
if (apiKey === undefined) return this.end(this.command.fail(ExitCode.USAGE, "OPENROUTER_API_KEY is not set"));In the workflow, override rescue for the errors that steps throw, also the steps of a workflow listed as a step:
protected override rescue(error: unknown): number { return this.command.fail(ExitCode.FAILED, error instanceof Error ? error.message : String(error));}- An error class of the program can carry the kind of failure from a step to
rescue, so that a wrong input becomes 2 and everything else 1. - Let
rescuethrow what it does not know, as the default does. - A run component whose build failed ends the workflow with that error, also when a flow step caught it.
rescuegets it like any other error, and a workflow around this one still ends with it.