Skip to content
Myr

cli.ts

This file

Path

packages/protocol/src/cli.ts

705 lines · 22.5 KiB · TypeScript

Last changed by

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

History of this file

Take it

1// Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-command.ts`2// l.14–247, and ours to change since: it projects the contracts' Rpcs, named3// and given positionals by the `Cli` annotation, not Rat Stack's capabilities.4// Rat Stack's licence travels with the code it copied:5//6// MIT License7//8// Copyright (c) 2026 Joel Hooks9//10// Permission is hereby granted, free of charge, to any person obtaining a copy11// of this software and associated documentation files (the "Software"), to deal12// in the Software without restriction, including without limitation the rights13// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell14// copies of the Software, and to permit persons to whom the Software is15// furnished to do so, subject to the following conditions:16//17// The above copyright notice and this permission notice shall be included in all18// copies or substantial portions of the Software.19//20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR21// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,22// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE23// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER24// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,25// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE26// SOFTWARE.2728import {29  Array,30  Config,31  Context,32  Effect,33  Option,34  Predicate,35  Runtime,36  Schema,37  SchemaAST,38} from "effect";39import { Argument, Command, Flag } from "effect/cli";40import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";4142import {43  Cli,44  Description,45  NeedsApproval,46  ReadOnly,47  Surfaces,48} from "./annotations.ts";49import { ExitCode, exitCodeFor } from "./exit-code.ts";50import type { Unauthenticated } from "./principal.ts";51import { Refusal } from "./refusal.ts";5253/** How a call can fail before its handler runs: in transit, or unauthenticated. */54type CallError = RpcClientError.RpcClientError | Unauthenticated;5556/** A schema that needs no services to decode or encode, as every wire schema is. */57type Plain = Schema.Top & {58  readonly DecodingServices: never;59  readonly EncodingServices: never;60};6162/**63 * An Rpc a command can project: its payload is a struct of plain fields, or64 * a record that takes none (`listProjects`).65 */66export type CommandRpc = Rpc.AnyWithProps & {67  readonly errorSchema: Plain;68  readonly payloadSchema: Plain;69  readonly successSchema: Plain;70};7172/** A result as prose: Markdown, and plain text where a person reads it. */73export interface View {74  readonly markdown: string;75  readonly text?: string;76}7778/**79 * How a projected command prints. apps/cli's `Output` implements it, and80 * decides the form: text for a person, Markdown for an agent, one `--json`81 * envelope for a script.82 */83export interface CommandOutput {84  /** The command's result; `data` is its encoded success. */85  readonly success: (input: {86    readonly command: string;87    readonly json: boolean;88    readonly data: unknown;89    readonly view: View;90  }) => Effect.Effect<void>;91  /** The refusals the command met instead: printed there, and only there. */92  readonly refused: (input: {93    readonly command: string;94    readonly json: boolean;95    readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;96  }) => Effect.Effect<void>;97  /** What `--dry-run` would send; `payload` is encoded. */98  readonly plan: (input: {99    readonly command: string;100    readonly json: boolean;101    readonly payload: unknown;102  }) => Effect.Effect<void>;103}104105/**106 * Values for payload fields a person may leave out, such as the project the107 * repo they stand in belongs to.108 */109export interface Defaults<R> {110  /** The fields it may fill, each with where its value comes from, for `--help`. */111  readonly fields: Readonly<Record<string, string>>;112  /**113   * Their values, as typed on the command line. Read only when a required114   * field it may fill was left out; a field it has no value for stays out.115   */116  readonly values: Effect.Effect<Readonly<Record<string, string>>, never, R>;117}118119export interface ToCommandOptions<Success, OutputR, DefaultsR> {120  /** Where the command prints its result, its refusals and its plan. */121  readonly output: Effect.Effect<CommandOutput, never, OutputR>;122  readonly defaults?: Defaults<DefaultsR> | undefined;123  /** The result as prose; none, or none given, prints the encoded JSON. */124  readonly render?: ((success: Success) => Option.Option<View>) | undefined;125  /**126   * The refusals a success carries in place of a result, such as a refused127   * answer's receipt: they print as a refusal does, once, and the command128   * fails with `Reported`.129   */130  readonly refusalsIn?: ((success: Success) => readonly Refusal[]) | undefined;131}132133/**134 * Each contract's result as prose, by tag. A view reads any contract's135 * success and renders the one it knows; a contract with no view prints its136 * encoded JSON.137 */138export type Views<Rpcs extends Rpc.Any> = Readonly<139  Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>140>;141142/**143 * A command that changes something a person must approve ran without144 * `--yes`. A usage error: nothing was called.145 */146export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(147  "ApprovalNeeded",148  { command: Schema.String }149) {150  override get message() {151    return `${this.command} needs a person's approval: run it again with --yes, or with --dry-run to see what it would send`;152  }153}154155/**156 * A required payload field was given neither on the command line nor by the157 * defaults. A usage error: nothing was called, and nobody was asked for it.158 */159export class MissingValue extends Schema.TaggedError<MissingValue>()(160  "MissingValue",161  { command: Schema.String, flag: Schema.String }162) {163  override get message() {164    return `${this.command} needs ${this.flag}: give it, since nothing here does`;165  }166}167168/**169 * Everything a command printed has been printed: the program exits with170 * `exitCode` (1 unless refusals set it) and prints nothing more, and the171 * runtime reports nothing of its own.172 */173export class Reported extends Schema.TaggedError<Reported>()("Reported", {174  exitCode: Schema.optionalKey(Schema.Int),175}) {176  override readonly [Runtime.errorExitCode] = this.exitCode ?? ExitCode.failed;177  override readonly [Runtime.errorReported] = false;178179  /** Refusals printed: the program exits with the code they share (`exitCodeFor`). */180  static readonly of = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>181    new Reported({ exitCode: exitCodeFor(refusals) });182}183184/**185 * Hands `refusals` to `output` once, then ends the command as `Reported`186 * with their exit code: how every command meets a refusal.187 */188export const endRefused = (189  output: Pick<CommandOutput, "refused">,190  input: Parameters<CommandOutput["refused"]>[0]191): Effect.Effect<never, Reported> =>192  Effect.andThen(193    output.refused(input),194    Effect.fail(Reported.of(input.refusals))195  );196197interface FieldSpec {198  readonly description: string | undefined;199  readonly kind:200    | "string"201    | "number"202    | "boolean"203    | "switch"204    | "literals"205    | "json";206  readonly literals: readonly string[];207  readonly optional: boolean;208}209210const literalOf = (ast: SchemaAST.AST): string | undefined =>211  SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)212    ? ast.literal213    : undefined;214215const primitiveKinds: Partial<216  Record<SchemaAST.AST["_tag"], FieldSpec["kind"]>217> = {218  Boolean: "boolean",219  Number: "number",220  String: "string",221};222223const primitiveKind = (ast: SchemaAST.AST): FieldSpec["kind"] =>224  primitiveKinds[ast._tag] ?? "json";225226const describe = (field: Plain): FieldSpec => {227  let ast: SchemaAST.AST = field.ast;228  let optional = ast.context?.isOptional === true;229230  const description = SchemaAST.resolveDescription(ast);231232  if (SchemaAST.isUnion(ast)) {233    const members = ast.types.filter(234      (member) => !SchemaAST.isUndefined(member)235    );236237    if (members.length < ast.types.length) {238      optional = true;239    }240241    const [only] = members;242243    if (members.length === 1 && only !== undefined) {244      ast = only;245    } else {246      const literals = members.map(literalOf);247248      if (literals.every((literal) => literal !== undefined)) {249        return { description, kind: "literals", literals, optional };250      }251252      return { description, kind: "json", literals: [], optional };253    }254  }255256  // A field that is `true` or absent is a switch: named, it is on.257  if (SchemaAST.isLiteral(ast) && ast.literal === true) {258    return { description, kind: "switch", literals: [], optional };259  }260261  const literal = literalOf(ast);262263  if (literal !== undefined) {264    return { description, kind: "literals", literals: [literal], optional };265  }266267  const kind = primitiveKind(ast);268269  return { description, kind, literals: [], optional };270};271272/**273 * A payload's fields, by name: a struct's, or none for a payload that takes274 * nothing (an empty record, which an MCP tool's input needs).275 */276const fieldsOf = (payload: Plain): readonly (readonly [string, Plain])[] =>277  SchemaAST.isObjects(payload.ast)278    ? payload.ast.propertySignatures.flatMap(({ name, type }) =>279        Predicate.isString(name)280          ? [[name, Schema.make<Schema.Codec<unknown>>(type)] as const]281          : []282      )283    : [];284285/** Whether a person must give the field: a switch is off unless named. */286const isRequired = (spec: FieldSpec) =>287  !spec.optional && spec.kind !== "boolean" && spec.kind !== "switch";288289const jsonFlag = (name: string, field: Plain) =>290  Flag.String(name).pipe(291    Flag.withSchema(Schema.fromJsonString(field)),292    Flag.withMetavar("JSON")293  );294295const flagBuilders = {296  boolean: (name) => Flag.Boolean(name).pipe(Flag.withDefault(false)),297  json: (name, field) => jsonFlag(name, field),298  literals: (name, _field, spec) => Flag.Literals(name, spec.literals),299  number: (name) => Flag.Finite(name),300  // The field's own schema checks the text, so a malformed value is refused301  // by the parser, naming its flag, before anything is called.302  string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),303  // On when named; left out of the payload otherwise.304  switch: (name) =>305    Flag.Boolean(name).pipe(306      Flag.withDefault(false),307      Flag.map((on) => (on ? true : undefined))308    ),309} satisfies Record<310  FieldSpec["kind"],311  (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>312>;313314/** A field's help text, and where its default comes from when it has one. */315const helpOf = (spec: FieldSpec, fallback: string | undefined) => {316  if (fallback === undefined) {317    return spec.description;318  }319320  return spec.description === undefined321    ? `Defaults to ${fallback}`322    : `${spec.description}; defaults to ${fallback}`;323};324325/**326 * A field as a flag. It is optional when the payload says so, or when the327 * defaults may fill it; the handler then says if it is still missing.328 */329const flagFor = (330  name: string,331  field: Plain,332  fallback: string | undefined333): Flag.Flag<unknown> => {334  const spec = describe(field);335  const base = flagBuilders[spec.kind](name, field, spec);336  const help = helpOf(spec, fallback);337338  const described =339    help === undefined ? base : base.pipe(Flag.withDescription(help));340341  return (spec.optional || fallback !== undefined) &&342    spec.kind !== "boolean" &&343    spec.kind !== "switch"344    ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))345    : described;346};347348const schemaArgument = (name: string, field: Plain, metavar: string) =>349  Argument.String(name).pipe(350    Argument.withSchema(Schema.fromJsonString(field)),351    Argument.withMetavar(metavar)352  );353354const argumentBuilders = {355  boolean: (name, field) => schemaArgument(name, field, "BOOLEAN"),356  json: (name, field) => schemaArgument(name, field, "JSON"),357  literals: (name, _field, spec) => Argument.Literals(name, spec.literals),358  number: (name) => Argument.Finite(name),359  string: (name) => Argument.String(name),360  switch: (name, field) => schemaArgument(name, field, "true"),361} satisfies Record<362  FieldSpec["kind"],363  (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>364>;365366/**367 * An argument that was a flag until now, left out: none yet. The parser368 * takes it so, since the flag it was may still give its value, and the369 * handler says if neither did (`MissingValue`). Unlike `Argument.optional`,370 * a fallback leaves help showing the argument as required.371 */372const leftOutForNow = (373  argument: Argument.Argument<unknown>374): Argument.Argument<unknown> =>375  argument.pipe(376    Argument.map(Option.some),377    Argument.withFallbackConfig(Config.succeed(Option.none())),378    Argument.map(Option.getOrUndefined)379  );380381const argumentFor = (382  name: string,383  field: Plain,384  fallback: string | undefined,385  wasFlag: boolean386): Argument.Argument<unknown> => {387  const spec = describe(field);388  const base = argumentBuilders[spec.kind](name, field, spec);389  const help = helpOf(spec, fallback);390391  const described =392    help === undefined ? base : base.pipe(Argument.withDescription(help));393394  if (spec.optional || fallback !== undefined) {395    return described.pipe(396      Argument.optional,397      Argument.map(Option.getOrUndefined)398    );399  }400401  return wasFlag ? leftOutForNow(described) : described;402};403404/**405 * The flag a positional field was until now (`Cli`'s `formerFlags`): it406 * still parses, checked by the field's schema, but help leaves it out and407 * using it prints nothing more.408 */409const formerFlagFor = (name: string, field: Plain): Flag.Flag<unknown> => {410  const spec = describe(field);411412  return flagBuilders[spec.kind](name, field, spec).pipe(413    Flag.withHidden,414    Flag.optional,415    Flag.map(Option.getOrUndefined)416  );417};418419/**420 * The flags a projected command takes beside its payload's: `--json`421 * always, `--yes` when a person approves it, and `--dry-run` unless it only422 * reads.423 */424const controls = (approval: boolean, readOnly: boolean) =>425  Object.fromEntries([426    [427      "json",428      Flag.Boolean("json").pipe(429        Flag.withDefault(false),430        Flag.withDescription(431          "Print one versioned JSON envelope on stdout, and nothing else there"432        )433      ),434    ],435    ...(approval436      ? [437          [438            "yes",439            Flag.Boolean("yes").pipe(440              Flag.withDefault(false),441              Flag.withDescription(442                "Approve it: it runs only with --yes, since a person approves it first"443              )444            ),445          ] as const,446        ]447      : []),448    ...(readOnly449      ? []450      : [451          [452            "dryRun",453            Flag.Boolean("dry-run").pipe(454              Flag.withDefault(false),455              Flag.withDescription(456                "Print the payload it would send, and send nothing"457              )458            ),459          ] as const,460        ]),461  ]);462463const isRefusal = Schema.is(Refusal);464465/** The contract's command, as a person types it: `asks`, `ask open`. */466export const commandName = (rpc: Rpc.AnyWithProps): string =>467  Context.get(rpc.annotations, Cli).name ?? rpc._tag;468469/** The words that reach the contract's command: `["ask", "open"]`. */470export const commandPath = (471  rpc: Rpc.AnyWithProps472): readonly [string, ...string[]] => {473  const [first = rpc._tag, ...rest] = commandName(rpc).split(" ");474475  return [first, ...rest];476};477478/** JSON text as Markdown, and as itself for a person. */479const asJson = (text: string): View => ({480  markdown: ["```json", text, "```"].join("\n"),481  text,482});483484/**485 * Projects one contract onto a CLI command. Its payload's fields become486 * flags (or the positional arguments its `Cli` annotation names), and it is487 * named by the last word of that annotation's name. Every command takes488 * `--json`; one that needs approval takes `--yes` and runs only with it;489 * one that changes something takes `--dry-run`, which prints the encoded490 * payload and calls nothing. A refusal, or the refusals a success carries491 * (`refusalsIn`), go to `output.refused` once, and the command fails with492 * `Reported` and their exit code (`endRefused`).493 */494export const toCommand = <495  R extends CommandRpc,496  ClientR,497  OutputR,498  DefaultsR = never,499>(500  rpc: R,501  client: Effect.Effect<RpcClient.RpcClient<R, CallError>, never, ClientR>,502  options: ToCommandOptions<Rpc.Success<R>, OutputR, DefaultsR>503) => {504  const cli = Context.get(rpc.annotations, Cli);505  const command = commandName(rpc);506  const positional = new Set(cli.positional);507508  const wasFlag = new Set(509    cli.formerFlags?.filter((name) => positional.has(name))510  );511512  const approval = Context.get(rpc.annotations, NeedsApproval);513  const readOnly = Context.get(rpc.annotations, ReadOnly);514  const filled = options.defaults?.fields ?? {};515  const fields = fieldsOf(rpc.payloadSchema);516517  const required = fields.flatMap(([name, field]) =>518    isRequired(describe(field)) ? [name] : []519  );520521  const payload: Record<522    string,523    Flag.Flag<unknown> | Argument.Argument<unknown>524  > = {};525526  const former: Record<string, Flag.Flag<unknown>> = {};527528  for (const [name, field] of fields) {529    const fallback = required.includes(name) ? filled[name] : undefined;530531    payload[name] = positional.has(name)532      ? argumentFor(name, field, fallback, wasFlag.has(name))533      : flagFor(name, field, fallback);534535    if (wasFlag.has(name)) {536      former[name] = formerFlagFor(name, field);537    }538  }539540  const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);541  const encodePayload = Schema.encodeUnknownEffect(rpc.payloadSchema);542  const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);543544  /** The fields given, by name, then the defaults for required ones left out. */545  const complete = (given: readonly (readonly [string, unknown])[]) =>546    Effect.gen(function* () {547      const provided = Object.fromEntries(548        given.filter(([, value]) => value !== undefined)549      );550551      const wanting = required.filter(552        (name) => !Object.hasOwn(provided, name) && Object.hasOwn(filled, name)553      );554555      const values: Readonly<Record<string, string>> =556        wanting.length === 0 || options.defaults === undefined557          ? {}558          : yield* options.defaults.values;559560      const merged = {561        ...provided,562        ...Object.fromEntries(563          wanting.flatMap((name) =>564            values[name] === undefined ? [] : [[name, values[name]] as const]565          )566        ),567      };568569      const missing = required.find((name) => !Object.hasOwn(merged, name));570571      if (missing !== undefined) {572        return yield* new MissingValue({573          command,574          flag: positional.has(missing) ? `<${missing}>` : `--${missing}`,575        });576      }577578      return yield* decodePayload(merged);579    });580581  return Command.make(582    commandPath(rpc).at(-1) ?? rpc._tag,583    { control: controls(approval, readOnly), former, payload },584    ({ control, former: formerly, payload: given }) =>585      Effect.gen(function* () {586        const json = control.json === true;587        const dryRun = control.dryRun === true;588589        if (approval && control.yes !== true && !dryRun) {590          return yield* new ApprovalNeeded({ command });591        }592593        // An argument left out takes the value its former flag gave.594        const decoded = yield* complete(595          Object.entries(given).map(596            ([name, value]) => [name, value ?? formerly[name]] as const597          )598        );599600        const output = yield* options.output;601602        if (dryRun) {603          const encoded = yield* Effect.orDie(encodePayload(decoded));604605          return yield* output.plan({ command, json, payload: encoded });606        }607608        const calls = yield* client;609610        // SAFETY: an RpcClient for a group without prefixes has one method per tag, and `decoded` was just decoded with that Rpc's payload schema.611        // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the client's mapped type cannot be indexed by a generic tag; see SAFETY.612        const byTag = calls as Readonly<613          Record<614            string,615            (616              payload: typeof decoded617            ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | CallError>618          >619        >;620621        const call =622          byTag[rpc._tag] ??623          (() => Effect.die(`The client has no method for ${rpc._tag}`));624625        const success = yield* call(decoded).pipe(626          Effect.catchIf(isRefusal, (refusal) =>627            endRefused(output, { command, json, refusals: [refusal] })628          )629        );630631        const carried = options.refusalsIn?.(success) ?? [];632633        if (Array.isReadonlyArrayNonEmpty(carried)) {634          return yield* endRefused(output, {635            command,636            json,637            refusals: carried,638          });639        }640641        const data = yield* Effect.orDie(encodeSuccess(success));642643        const view = Option.getOrElse(644          options.render === undefined645            ? Option.none()646            : options.render(success),647          () => asJson(JSON.stringify(data, null, 2))648        );649650        return yield* output.success({ command, data, json, view });651      }).pipe(Effect.withSpan(`protocol.${rpc._tag}`))652  ).pipe(653    Command.withDescription(654      [655        Context.get(rpc.annotations, Description),656        ...(readOnly ? ["It only reads."] : []),657        ...(approval ? ["It runs only with --yes: a person approves it."] : []),658      ].join(" ")659    )660  );661};662663export interface ToCommandsOptions<Rpcs extends Rpc.Any, OutputR, DefaultsR> {664  readonly output: Effect.Effect<CommandOutput, never, OutputR>;665  readonly defaults?: Defaults<DefaultsR> | undefined;666  readonly views?: Views<Rpcs> | undefined;667  /** The refusals any contract's success carries in place of a result. */668  readonly refusalsIn?:669    | ((success: Rpc.Success<Rpcs>) => readonly Refusal[])670    | undefined;671  /** Tags a hand-written command wraps instead, such as `setEnv`'s `env set`. */672  readonly exclude: readonly string[];673}674675/**676 * Every contract in `group` whose `Surfaces` include `cli`, but those677 * `exclude` names, as a command at the path its `Cli` annotation names.678 */679export const toCommands = <680  Rpcs extends CommandRpc,681  ClientR,682  OutputR,683  DefaultsR = never,684>(685  group: RpcGroup.RpcGroup<Rpcs>,686  client: Effect.Effect<RpcClient.RpcClient<Rpcs, CallError>, never, ClientR>,687  options: ToCommandsOptions<Rpcs, OutputR, DefaultsR>688) =>689  [...group.requests.values()].flatMap((rpc) =>690    Context.get(rpc.annotations, Surfaces).includes("cli") &&691    !options.exclude.includes(rpc._tag)692      ? [693          {694            command: toCommand(rpc, client, {695              defaults: options.defaults,696              output: options.output,697              refusalsIn: options.refusalsIn,698              render: options.views?.[rpc._tag],699            }),700            path: commandPath(rpc),701            rpc,702          },703        ]704      : []705  );