PUBLIC MODULE · lib/cli.js

CLI

lib/cli.js — shared process-facing command helpers.

Exposes the CLI bindings used by executables and the TUI. execute creates and closes its environment; other helpers use the environment supplied by their caller.

async execute(command) function

Execute one normalized administrative command. Argument parsing and flag names remain the executable's concern; this function creates and closes its own environment.

Returns — {Promise< {type: "login", name: string, endpoint: object, auth?: object, scope: string, verified?: *} | {type: "logout", name: string, dynamic: boolean} | {type: "initialize", file: string} | {type: "listModels", endpoints: Array<{name: string, models: string[]}>} >} the command-specific result

class CLI class

Static namespace exposing every named CLI helper and execute.

parseFlags(argv, { flags, bools = [], durations = ["timeout"], numbers = ["max-turns", "max-tool-calls"] }) function

Parse argv into a flat options object.

Grammar: --name value for every name in flags; --name alone for every name in bools; --help/-h short-circuits to {help: true}. Names in durations parse as durations (a ms numeral or a unit string: "500ms", "20s", "20m", "1h"); names in numbers must be positive numbers. Anything else throws an Error whose message names the offender. Relationships between flags and value-specific transforms are executable policy and belong to the caller.

argv string[]
process.argv.slice(2)
spec Object
spec.flags string[]
value-taking flag names
[spec.bools] string[]
boolean flag names
[spec.durations] string[]
flags parsed as durations
[spec.numbers] string[]
flags parsed as positive numbers

Returns Object} the parsed options (`{help: true — ` for --help)

Defined in lib/cli/flags.js

EXIT = Object.freeze({…}) constant

Exit codes shared by the command-line tools.

Defined in lib/cli/exit.js

exitCodeFor(terminal) function

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

Returns number

Defined in lib/cli/exit.js

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 {agent?: object, session?: {id: string, file?: string}|null}

Defined in lib/cli/exit.js

async readStdin() function

Read all of stdin, resolving only at EOF.

Returns Promise<string> — the complete buffered input

Defined in lib/cli/stdin.js

async readContextFromStdin() function

Read stdin to EOF and parse it into a context array.

Returns Promise<Array<object>>

Defined in lib/cli/stdin.js

async resolveModelCombo(value, env, { url } = {…}) function

Resolve <endpoint>/<model>, a model id, an endpoint, or a bare model.

Defined in lib/cli/model.js

listModelCandidates(env, { access = env.settings?.modelAccess ?? "all" } = {…}) function

Published endpoint/model completion candidates (cache-only).

Defined in lib/cli/model.js

listEndpointModels(env, { access = env.settings?.modelAccess ?? "all" } = {…}) function

Published endpoints with published cached model ids for the menu; loginRequired flags endpoints whose credentials failed (see Agent).

Defined in lib/cli/model.js

async listModels(env, { access = env.settings?.modelAccess ?? "all" } = {…}) function

Query each published endpoint and return its currently available public model ids. A provider failure falls back to that endpoint's cached/static catalogue, as Env.endpointModels promises.

Defined in lib/cli/model.js

readLastCombo(env) function

the last-used combo, or null when none is stored

Returns {endpoint?: string, model: string}|null — the last-used combo, or null when none is stored

Defined in lib/cli/model.js

writeLastCombo(env, { endpoint, model } = {…}) function

Persist a selected endpoint/model combo (in the user settings folder).

Defined in lib/cli/model.js

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

No implicit endpoint/model exists: with neither --model nor a valid last-model.json, interactive callers start model-less.

Defined in lib/cli/select.js

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

Arm SIGINT/SIGTERM cancellation for a CLI binding.

options Object
options.onCancel (signal: string) => void
invoked once, with "SIGINT" or "SIGTERM", on the first caught signal
[options.process] NodeJS.Process
injectable for tests

Returns () => void — disarm — remove the listeners (idempotent)

Defined in lib/cli/signals.js

async loginEndpoint(env, { name, provider, url, token, auth, scope = "package", } = {…}) function

Configure one endpoint, invoke its protocol login (or accept a pre-seeded auth, e.g. browser-OAuth tokens), verify the connection, and refresh models.

Defined in lib/cli/login.js

logoutEndpoint(env, name) function

Remove an endpoint (the /logout and --logout contract): its entry drops out of settings.json, its auth file is deleted, and the live Env forgets it (see Env.removeEndpoint). Environment-detected (dynamic) endpoints were never persisted — the removal is in-memory only, and the endpoint re-detects on the next startup while the environment still provides it.

env object
name string
endpoint name

Returns {name: string, dynamic: boolean}

Defined in lib/cli/login.js

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

Cooked terminal wizard used by --login. Lists every KNOWN endpoint the loaded protocols can already talk to (Env.knownEndpoints — e.g. OpenAI, GitHub Copilot, LM Studio, Ollama) next to a manual (enter-URL) option: adding a NEW endpoint is half the reason the wizard exists, so it is never limited to the known list.

Defined in lib/cli/login.js

defaultUrl(provider) function

Known setup defaults only; runtime endpoint discovery remains class-owned.

Defined in lib/cli/login.js

renderSettingsTemplate(env) function

Render the template text: one commented-out line per known key, sorted, its default (or null when there isn't one) as the placeholder value and its description as a trailing comment.

env object

Returns string — the file's full text (trailing newline)

Defined in lib/cli/init.js

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

Write a fresh namespaced settings template into the project folder (env.cwd). Refuses to overwrite an existing file unless force.

env object

Returns string — the written file's path

Defined in lib/cli/init.js

resolveToolArgs(raw, entry) function

Resolve a raw JSON-args string into a tool's actual args object. A JSON OBJECT passes through as-is; a bare JSON value (array, string, number, ...) is a SHORTHAND for the tool's FIRST schema property — so "["core"]" against a tool whose first property is names becomes {names: ["core"]}.

raw string|undefined
undefined/"" means no arguments ({})

Returns object

Defined in lib/cli/tool-run.js

resolveCliToolArgs(argv, entry) function

Resolve the tool CLI's shell-friendly non-JSON arguments. A colon in the first argument selects object form (path: file.md or path:file.md); otherwise every argument is a string array shorthand. JSON remains the exact, explicit form and is tried first for backwards compatibility.

argv string[]

Returns object

Defined in lib/cli/tool-run.js

unwrapToolResult(value) function

Split a tool's return value into its {result, system?, display?} envelope (see the Tool contract's RETURNS section) — a plain return value is result with no side channels.

value *

Returns {result: *, system: string[], display: string[]}

Defined in lib/cli/tool-run.js

formatToolResult(result) function

A result value as printable text: a string as-is, else pretty JSON — ALWAYS a string (JSON.stringify(undefined) is the JS value undefined, not text, so that case is coerced explicitly).

Defined in lib/cli/tool-run.js

async runOAuthFlow(descriptor, options = {…}) function

Run one OAuth sign-in. Resolves the token response.

descriptor object
the endpoint preset's `oauth` block
[options] Object
[options.onAuthUrl] (url: string) => void
the URL the user must visit (shown to them; the browser open is already attempted)
[options.onLog] (line: string) => void
[options.signal] AbortSignal
[options.open] (url: string) => boolean
browser opener (tests)

Returns Promise<object> — the provider's token response

Defined in lib/cli/oauth.js

completeOAuthPaste(input) function

Feed a pasted redirect URL / code#state to the in-flight flow.

input string

Returns boolean — whether a flow was waiting for it

Defined in lib/cli/oauth.js

async refreshOAuthTokens(descriptor, refresh, { signal } = {…}) function

Refresh stored OAuth credentials without repeating browser/device authorization. A refresh response may omit refresh_token; retain the old one in tokensToAuth()'s caller.

Defined in lib/cli/oauth.js

tokensToAuth(tokens, previous = {…}) function

Map a token response to the stored auth payload. token mirrors the access token so bearer-auth wire code needs no OAuth awareness.

tokens object
the provider's token response

Returns {type: string, access: string, token: string, refresh?: string, expires?: number}

Defined in lib/cli/oauth.js

parseAuthorizationInput(input) function

Parse pasted authorization input: a full redirect URL (...?code=…&state=…), code#state, or a bare code.

input string

Returns {code?: string, state?: string}

Defined in lib/cli/oauth.js

oauthPasteOnly(descriptor) function

Is this flow paste-only (grant shape A with a NON-loopback redirect URI — the provider hosts the callback page and shows the code)? A wizard uses it to word its prompt: nothing arrives by itself. {object} descriptor - the preset's oauth block {boolean}

Defined in lib/cli/oauth.js

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

Adopt an explicitly resumed session's origin folder as the cwd.

options Object
[options.resume] string
the --resume flag value
[options.anonymous] boolean
an anonymous session resumes nothing

Returns string|null — the origin folder chdir'd into, or null

Defined in lib/cli/resume.js

usageSummary(usage) function

One-line human-readable usage summary (e.g. for a host's diagnostics).

Defined in lib/context/usage.js