PUBLIC MODULE · lib/app/cli.js

App.CLI

lib/app/cli.js — CLI-owned process-facing command helpers.

Exposes process-facing command helpers used by executables.

class CLI class

Static namespace exposing every named CLI operation.

Defined in lib/app/cli.js

EXIT = Object.freeze({…}) constant

Exit codes shared by the command-line tools.

Defined in lib/app/cli/exit.js

async adoptResumeOrigin({ resume, anonymous = false, dir } = {…}) function

Move the process to the recorded origin folder for an explicit session resume. Skips cwd changes for anonymous, absent, "true", and "latest" resume values. Resolves the session origin (using dir or the configured sessions folder), verifies that folder exists, then changes process.cwd() before environment setup.

[options={}] Object
Resume selection and session lookup options.
[options.resume] string
The `--resume` value; values other than `"true"` and `"latest"` are treated as explicit session IDs.
[options.anonymous=false] boolean
Whether this is an anonymous session.
[options.dir] string
Session directory passed to origin lookup; defaults to the configured sessions folder when omitted or nullish.

Returns Promise<string|null> — The origin folder after changing cwd, or `null` when no explicit origin should be adopted.

Throws — {Error} If the session has no recorded origin or its origin folder no longer exists. `process.chdir()` errors also propagate.

Defined in lib/app/cli/resume.js

armCancelSignals({ onCancel, process: proc = process }) function

Arm SIGINT/SIGTERM cancellation for a CLI binding.

options Object
configuration object
options.onCancel (signal: string) => void
invoked once, with "SIGINT" or "SIGTERM", on the first caught signal
[options.process=process] NodeJS.Process
process-like signal emitter; defaults to the global Node.js `process` and can be injected for tests

Returns () => void — disarm function; removes both listeners, and is safe to call repeatedly

Throws — {TypeError} if `onCancel` is not a function

Throws — {*} if registering either signal listener throws; the error propagates, and a SIGINT listener already registered is not rolled back if SIGTERM registration fails

Effects — Registers SIGINT and SIGTERM listeners on the selected process. The first signal invokes `onCancel` once; any exception from it propagates from the signal handler and does not allow a later retry. Calling the returned function removes both listeners; if removal throws, the error propagates and the disarm function remains marked as used.

Defined in lib/app/cli/signals.js

async close({ env, agent } = {…}) function

Close a command-line library runtime. This is the sole public housekeeping boundary: agents are cancelled, sessions are flushed/closed, and tool-owned background resources are released. Repeated calls are safe.

Returns Promise<{agent?: object, session: {id: string, file?: string}|null}> — The explicit agent and its context's id/file when present, otherwise a null session. Resolves after owned teardown; rejects after all releases when cleanup fails.

Defined in lib/app/cli/exit.js

exitCodeFor(terminal) function

Map a terminal done/error event (or an error-shaped {kind}) to the process exit code.

Returns number — The mapped process exit code; this function is synchronous and has no side effects.

Defined in lib/app/cli/exit.js

finishSignalsArm({ process: proc = process, signals = ["SIGINT", "SIGTERM", "SIGHUP"], } = {…}) function

Arm process termination signals to run Agent's synchronous finish hooks, then re-raise the received signal so the process retains signal exit semantics. Repeated arming returns the existing disarm function without changing options. This is an opt-in CLI binding; it is not suitable for asynchronous cancellation.

[options] Object
Signal-arming options.
[options.process=process] NodeJS.Process
Process on which to install handlers and call `kill`.
[options.signals=["SIGINT", "SIGTERM", "SIGHUP"] string[]
] Signals to handle.

Returns () => void — Idempotent function that removes these signal handlers and permits rearming.

Effects — Registers a process exit listener (once per process) and handlers for the selected signals. On a signal, runs Agent.finishRun(), removes the signal handlers, then calls process.kill(process.pid, signal). Finish callbacks may run again on exit and must be synchronous and idempotent.

Defined in lib/app/cli/finish-signals.js

parseFlags(argv, { flags, bools = [], durations = ["timeout"], numbers = [] }) function

Parse command-line arguments into a flat options object. Value-taking flags use --name value; boolean flags use --name. --help and -h return {help: true} immediately. Repeated flags overwrite earlier values. Configured duration values are converted with durationParse; configured numeric values are converted with Number and must be finite and positive. Flag relationships and value-specific transformations remain caller policy.

argv string[]
Arguments to parse, typically `process.argv.slice(2)`.
spec Object
Flag-name configuration.
spec.flags string[]
Names of value-taking flags (required).
[spec.bools=[] string[]
] - Names of valueless boolean flags.
[spec.durations=["timeout"] string[]
] - Value-taking flag names converted by `durationParse` when present.
[spec.numbers=[] string[]
] - Value-taking flag names converted to finite, positive numbers when present.

Returns Object — Parsed options; values are strings except converted duration/number values, boolean flags (`true`), or `{help: true}`.

Throws — {Error} For positional arguments, unknown flags, missing values, invalid duration values, or configured numbers that are not finite and positive. Duration errors are prefixed with the flag name.

Defined in lib/app/cli/flags.js

async readContextFromStdin() function

Read standard input through EOF and parse its UTF-8 contents as messages.

Returns Promise<Array<object>> — The parsed context/message array.

Throws — {Error} Rejects if reading stdin fails or message parsing throws.

Defined in lib/app/cli/stdin.js

async readStdin() function

Read and buffer all bytes from standard input until the stream reaches EOF, then decode the concatenated bytes as UTF-8.

Returns Promise<string> — The complete stdin contents as a UTF-8 string.

Throws — {Error} Rejects if reading the stdin stream fails.

Defined in lib/app/cli/stdin.js

async runLoginWizard(env, { input = process.stdin, output = process.stderr, } = {…}) function

Run the cooked-terminal wizard used by --login. Lists known endpoints from Env.loginPresets alongside a manual URL option, then prompts for endpoint details and credentials or browser OAuth where available. Closes its readline interface on completion or failure.

env object
Environment providing presets and endpoint login.
[options={}] object
I/O options; defaults to `{}`.
[options.input=process.stdin] import("node:stream").Readable
Prompt input stream.
[options.output=process.stderr] import("node:stream").Writable
Wizard and OAuth output stream.

Returns Promise<*> — Resolves with the result of the selected endpoint login.

Throws — {Error} If no protocols are loaded, a choice is invalid, the URL is missing, or OAuth/login fails; propagates errors from the login operation.

Defined in lib/app/cli/login.js

async runMcpLogin(env, name, { input = process.stdin, output = process.stderr } = {…}) function

Start explicit MCP browser sign-in. Loopback callback wins without waiting for Enter; in a terminal, a full pasted redirect URL is a fallback.

env object
Environment with mcpLogin/mcpPaste methods.
name string
Configured MCP server name.

Returns Promise<{name: string}> — Signed-in server identity.

Defined in lib/app/cli/mcp-login.js

async selectEndpointModel(env, args, { lastUsed = false, log = () => {} } = {…}) function

Select a qualified model from CLI input or the last-used published model.

env object
Environment providing model resolution and login.
args object
CLI arguments: model selector and optional invocation-only URL.
[options={}] object
Selection options.
[options.lastUsed=false] boolean
Consider the newest available last-used model when no explicit model is supplied.
[options.log=()=>{}] Function
Log the selected last-used qualified model.

Returns Promise<string|undefined> — Qualified `<endpoint>/<model>`, or undefined if unresolved.

Throws — {Error} Invalid input or catalog failures; explicit URL login failures leave the model unresolved.

Effects — May register an invocation-only endpoint; never persists the URL here.

Defined in lib/app/cli/select.js

usageSummary(usage) function

Format one terminal usage envelope for CLI diagnostics without mutating it.

Returns string — One-line token summary with finite provider cost when supplied.

Defined in lib/app/cli/usage.js

writeSettingsTemplate(env, { force = false } = {…}) function

Write a namespaced settings template to the project settings path under env.folder. Refuses to replace an existing file unless options.force is true.

Returns string — Path of the written settings file.

Throws — {Error} If the file already exists and force is false, or if rendering or writing the template fails. An existing file is not overwritten on the refusal path.

Defined in lib/app/cli/init.js