chore: import upstream snapshot with attribution
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:43:05 +08:00
commit 426e9eeabd
41828 changed files with 9656266 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
dist
node_modules
.env
.elizadb
.turbo
target/
__pycache__
*.pyc
.venv
*.egg-info
.DS_Store
package-lock.json
tsconfig.tsbuildinfo
+204
View File
@@ -0,0 +1,204 @@
# @elizaos/plugin-cli
CLI framework infrastructure for elizaOS agents: command registration, a TTY-aware progress reporter, and duration/byte formatting helpers.
## Purpose / role
This plugin provides the scaffolding for building a Commander-based CLI on top of an Eliza agent runtime. It ships a module-level command registry that other plugins or host apps populate at startup, plus `buildProgram` / `runCli` entry points that assemble the final CLI. It is **opt-in** — load it explicitly via the agent's plugin list. It registers no actions, providers, services, evaluators, or routes; its value is its exported API.
## Plugin surface
The `cliPlugin` export (default) registers:
| Field | Value |
|-------|-------|
| `name` | `"cli"` |
| `actions` | `[]` |
| `providers` | `[]` |
| `services` | `[]` |
| `routes` | `[]` |
| `config` | `CLI_NAME`, `CLI_VERSION` (see below) |
| `init` | Logs count of registered commands; no persistent side effects |
| `dispose` | Returns immediately |
All real functionality is in the exported API (registry + utils), not in the plugin object's hooks.
## Exported API
### `src/index.ts` — entry point
- `cliPlugin` — the `Plugin` object; default export.
- `buildProgram(options?)` — constructs a `Command` with all registered commands attached; returns the Commander root.
- `runCli(argv?, options?)` — calls `buildProgram`, then `program.parseAsync`. Pass `argv` to override `process.argv`.
- Re-exports `Command` from `commander` for convenience.
### `src/registry.ts` — command registry
Module-level `Map<string, CliCommand>` — shared across all imports in the same process.
| Export | Purpose |
|--------|---------|
| `registerCliCommand(cmd)` | Add a `CliCommand`; warns and replaces on duplicate name |
| `unregisterCliCommand(name)` | Remove by name; returns `boolean` |
| `getCliCommand(name)` | Look up by name |
| `listCliCommands()` | All commands sorted by `priority` (lower = earlier, default 100) |
| `registerAllCommands(ctx)` | Called by `buildProgram`; iterates sorted list, calls each `register(ctx)` |
| `clearCliCommands()` | Empties the registry — test helper only |
| `defineCliCommand(name, description, register, options?)` | Factory for `CliCommand`; accepts optional `aliases` and `priority` |
| `addSubcommand(parent, name, description)` | Thin wrapper: `parent.command(name).description(description)` |
### `src/utils.ts` — utilities
| Export | Purpose |
|--------|---------|
| `DEFAULT_CLI_NAME` | `"elizaos"` |
| `DEFAULT_CLI_VERSION` | `"1.0.0"` |
| `resolveCliName(argv?)` | Derives CLI name from `process.argv[1]` (strips path + extension) |
| `createDefaultDeps()` | Returns `CliDeps` (`console.log`, `console.error`, `process.exit`) |
| `createProgressReporter(deps, options?)` | TTY-aware spinner; falls back to plain log when not a TTY |
| `withProgress(deps, message, fn)` | Runs an async function with spinner; succeeds/fails reporter automatically |
| `parseDurationMs(input)` | Parses `"1s"`, `"5m"`, `"2h"`, `"7d"`, bare ms numbers → `ParsedDuration` |
| `parseTimeoutMs(input?, defaultMs)` | `parseDurationMs` with a fallback default |
| `formatDuration(ms)` | `ms` → human string (`"1.5s"`, `"3.2m"`, `"1.0h"`) |
| `formatBytes(bytes)` | Bytes → `"1.4 MB"` etc. |
| `formatCliCommand(command, options?)` | Formats `elizaos [--profile P] [--env E] <command>` |
| `isInteractive()` | `stdin.isTTY && stdout.isTTY` |
### `src/types.ts` — shared types
`CliContext`, `CliCommand`, `CliRegistrationFn`, `CliPluginConfig`, `CliLogger`, `ProgressReporter`, `ProgressOptions`, `CliDeps`, `ParsedDuration`, `CommonCommandOptions`.
## Layout
```
plugins/plugin-cli/
src/
index.ts Plugin object, buildProgram, runCli, re-exports
registry.ts Module-level command registry (Map-backed)
utils.ts Progress reporter, duration/byte helpers, CLI name resolution
types.ts All shared interfaces and type aliases
__tests__/
core-test-mock.ts vitest setupFile (vi.mock of @elizaos/core logger)
package.json
tsconfig.json
biome.json
vitest.config.ts
```
## Commands
```bash
bun run --cwd plugins/plugin-cli build # tsc compile → dist/
bun run --cwd plugins/plugin-cli build:watch # tsc --watch
bun run --cwd plugins/plugin-cli dev # alias for build:watch
bun run --cwd plugins/plugin-cli test # vitest run
bun run --cwd plugins/plugin-cli lint # biome check --write --unsafe
bun run --cwd plugins/plugin-cli lint:check # biome check (read-only)
bun run --cwd plugins/plugin-cli format # biome format --write
bun run --cwd plugins/plugin-cli format:check # biome format (read-only)
bun run --cwd plugins/plugin-cli typecheck # tsgo --noEmit
```
## Config / env vars
Declared in `agentConfig.pluginParameters` but **not read from `process.env`** by any source file. Pass values directly to `buildProgram` / `runCli` as call-site options:
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `CLI_NAME` | No | `"elizaos"` | CLI binary name shown in help output |
| `CLI_VERSION` | No | `"1.0.0"` | Version string shown by `--version` |
Pass via `buildProgram({ name: "myapp", version: "2.0.0" })` or `runCli(argv, { name, version })`. The `init` function does not read the config parameter (`_config` is intentionally unused).
## How to extend
### Add a new CLI command
1. Call `defineCliCommand` + `registerCliCommand` before `buildProgram` runs (typically at module load time or in your plugin's `init`):
```typescript
import { defineCliCommand, registerCliCommand } from "@elizaos/plugin-cli";
registerCliCommand(
defineCliCommand(
"my-cmd",
"Does something useful",
(ctx) => {
ctx.program
.command("my-cmd")
.description("Does something useful")
.option("--flag", "a flag")
.action((opts) => {
const runtime = ctx.getRuntime?.();
// ...
});
},
{ priority: 50 }, // lower = registered earlier
),
);
```
2. The command appears in `elizaos --help` automatically once `buildProgram` is called.
### Use the progress reporter in a command
```typescript
import { createDefaultDeps, withProgress } from "@elizaos/plugin-cli";
const deps = createDefaultDeps();
await withProgress(deps, "Doing work", async () => {
await someLongOperation();
});
```
## Conventions / gotchas
- The command registry is **module-level state** (a `Map`). In a single Node/Bun process all imports share the same registry; in tests always call `clearCliCommands()` in `beforeEach` / `afterEach` to avoid cross-test pollution.
- `buildProgram` iterates `listCliCommands()` at call time. Register all commands before calling `buildProgram`.
- `registerCliCommand` silently replaces on duplicate name (with a `logger.warn`). Use distinct names to avoid accidental overrides.
- The plugin object itself has no persistent resources: `dispose` returns immediately and `init` only logs.
- `createProgressReporter` writes directly to `process.stdout` using ANSI escapes when `isTTY`; it degrades to plain `deps.log` in non-TTY environments (CI, piped output).
- `parseDurationMs` returns `{ valid: false, ms: 0 }` on bad input — always check `valid` before using `ms`.
- Build output goes to `dist/` (`.gitignored`). The package ships only `dist/` — no `src/` in the published tarball.
<!-- BEGIN: evidence-and-e2e-mandate (managed; canonical standard = repo-root AGENTS.md) -->
## ⛔ NON-NEGOTIABLE — evidence, trajectories & real end-to-end tests
> The binding, repo-wide standard is **[AGENTS.md](../../AGENTS.md)**. Read it.
> Nothing in this package is *done* until it is *proven* done — a reviewer must confirm it
> works **without reading the code**, from the artifacts you attach. This applies to **every**
> feature, fix, refactor, and chore here. "Tests pass" is not proof; "CI is green" is not proof.
- **Record AND read model trajectories.** Capture the *actual* inputs and outputs of the model
from a **live** LLM — not the deterministic proxy, not a mock: the prompt, the
providers/context, the raw model output, every tool/action call, and the result. Then **open
the trajectory and review it by hand.** A captured-but-unread trajectory is not evidence
(`packages/scenario-runner/bin/eliza-scenarios run <scenario> --report <out>`).
- **Real, full-featured E2E — no larp.** Every feature ships detailed end-to-end tests that
drive the *real* path end to end. Not the happy "front door" only: cover error paths,
edge/empty/invalid input, concurrency, roles/permissions, and adversarial input. A test that
asserts against a mock/stub/fixture standing in for the thing under test **does not count**.
If the real model/device/chain/connector/account is hard to reach, **make it reachable — that
is the work**, not an excuse to mock. If the existing tests here are shallow or mocked, fixing
them is part of your change.
- **Screenshots + logs at every phase**, plus a **complete walkthrough video/run-through** of
the entire feature or view, start to finish (`bun run test:e2e:record`).
- **Manually review every artifact the change touches** — never just the green check: client
logs (console + network), server logs (`[ClassName] …`), the model trajectories in and out,
before/after full-page screenshots, **and the domain artifacts listed below for this package.**
- **No residuals. No shortcuts.** The goal is not "done" — it is *everything* done. Clear every
blocker by the **hard path**: build the real architecture, stand up the real
model/device/service, actually test it. Never leave a TODO, a stub, a stepping-stone, or a
"follow-up." When unsure, research thoroughly, weigh the options, and ship the best,
highest-effort, production-ready version. Keep going until every possibility is exhausted.
Artifacts → attached inline in the PR (MP4 video, JPG screenshots, logs in `<details>`); attach each evidence type **or**
explicitly mark it N/A with a reason — never leave it blank. If `develop` moved and changed
behavior, **re-capture** evidence; stale proof is worse than none.
**Capture & manually review for this package — CLI / tooling:**
- The real command/flow invocation transcript (args in, stdout/stderr, exit code) and the artifacts it generated (files, scaffolds, manifests, screenshots/recordings).
- Failure paths: bad args, missing deps, partial state, permission/network errors.
- A recording/log of the actual run end to end — not a unit test of one helper.
- Any model interaction captured as a live trajectory and reviewed.
<!-- END: evidence-and-e2e-mandate -->
+204
View File
@@ -0,0 +1,204 @@
# @elizaos/plugin-cli
CLI framework infrastructure for elizaOS agents: command registration, a TTY-aware progress reporter, and duration/byte formatting helpers.
## Purpose / role
This plugin provides the scaffolding for building a Commander-based CLI on top of an Eliza agent runtime. It ships a module-level command registry that other plugins or host apps populate at startup, plus `buildProgram` / `runCli` entry points that assemble the final CLI. It is **opt-in** — load it explicitly via the agent's plugin list. It registers no actions, providers, services, evaluators, or routes; its value is its exported API.
## Plugin surface
The `cliPlugin` export (default) registers:
| Field | Value |
|-------|-------|
| `name` | `"cli"` |
| `actions` | `[]` |
| `providers` | `[]` |
| `services` | `[]` |
| `routes` | `[]` |
| `config` | `CLI_NAME`, `CLI_VERSION` (see below) |
| `init` | Logs count of registered commands; no persistent side effects |
| `dispose` | Returns immediately |
All real functionality is in the exported API (registry + utils), not in the plugin object's hooks.
## Exported API
### `src/index.ts` — entry point
- `cliPlugin` — the `Plugin` object; default export.
- `buildProgram(options?)` — constructs a `Command` with all registered commands attached; returns the Commander root.
- `runCli(argv?, options?)` — calls `buildProgram`, then `program.parseAsync`. Pass `argv` to override `process.argv`.
- Re-exports `Command` from `commander` for convenience.
### `src/registry.ts` — command registry
Module-level `Map<string, CliCommand>` — shared across all imports in the same process.
| Export | Purpose |
|--------|---------|
| `registerCliCommand(cmd)` | Add a `CliCommand`; warns and replaces on duplicate name |
| `unregisterCliCommand(name)` | Remove by name; returns `boolean` |
| `getCliCommand(name)` | Look up by name |
| `listCliCommands()` | All commands sorted by `priority` (lower = earlier, default 100) |
| `registerAllCommands(ctx)` | Called by `buildProgram`; iterates sorted list, calls each `register(ctx)` |
| `clearCliCommands()` | Empties the registry — test helper only |
| `defineCliCommand(name, description, register, options?)` | Factory for `CliCommand`; accepts optional `aliases` and `priority` |
| `addSubcommand(parent, name, description)` | Thin wrapper: `parent.command(name).description(description)` |
### `src/utils.ts` — utilities
| Export | Purpose |
|--------|---------|
| `DEFAULT_CLI_NAME` | `"elizaos"` |
| `DEFAULT_CLI_VERSION` | `"1.0.0"` |
| `resolveCliName(argv?)` | Derives CLI name from `process.argv[1]` (strips path + extension) |
| `createDefaultDeps()` | Returns `CliDeps` (`console.log`, `console.error`, `process.exit`) |
| `createProgressReporter(deps, options?)` | TTY-aware spinner; falls back to plain log when not a TTY |
| `withProgress(deps, message, fn)` | Runs an async function with spinner; succeeds/fails reporter automatically |
| `parseDurationMs(input)` | Parses `"1s"`, `"5m"`, `"2h"`, `"7d"`, bare ms numbers → `ParsedDuration` |
| `parseTimeoutMs(input?, defaultMs)` | `parseDurationMs` with a fallback default |
| `formatDuration(ms)` | `ms` → human string (`"1.5s"`, `"3.2m"`, `"1.0h"`) |
| `formatBytes(bytes)` | Bytes → `"1.4 MB"` etc. |
| `formatCliCommand(command, options?)` | Formats `elizaos [--profile P] [--env E] <command>` |
| `isInteractive()` | `stdin.isTTY && stdout.isTTY` |
### `src/types.ts` — shared types
`CliContext`, `CliCommand`, `CliRegistrationFn`, `CliPluginConfig`, `CliLogger`, `ProgressReporter`, `ProgressOptions`, `CliDeps`, `ParsedDuration`, `CommonCommandOptions`.
## Layout
```
plugins/plugin-cli/
src/
index.ts Plugin object, buildProgram, runCli, re-exports
registry.ts Module-level command registry (Map-backed)
utils.ts Progress reporter, duration/byte helpers, CLI name resolution
types.ts All shared interfaces and type aliases
__tests__/
core-test-mock.ts vitest setupFile (vi.mock of @elizaos/core logger)
package.json
tsconfig.json
biome.json
vitest.config.ts
```
## Commands
```bash
bun run --cwd plugins/plugin-cli build # tsc compile → dist/
bun run --cwd plugins/plugin-cli build:watch # tsc --watch
bun run --cwd plugins/plugin-cli dev # alias for build:watch
bun run --cwd plugins/plugin-cli test # vitest run
bun run --cwd plugins/plugin-cli lint # biome check --write --unsafe
bun run --cwd plugins/plugin-cli lint:check # biome check (read-only)
bun run --cwd plugins/plugin-cli format # biome format --write
bun run --cwd plugins/plugin-cli format:check # biome format (read-only)
bun run --cwd plugins/plugin-cli typecheck # tsgo --noEmit
```
## Config / env vars
Declared in `agentConfig.pluginParameters` but **not read from `process.env`** by any source file. Pass values directly to `buildProgram` / `runCli` as call-site options:
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `CLI_NAME` | No | `"elizaos"` | CLI binary name shown in help output |
| `CLI_VERSION` | No | `"1.0.0"` | Version string shown by `--version` |
Pass via `buildProgram({ name: "myapp", version: "2.0.0" })` or `runCli(argv, { name, version })`. The `init` function does not read the config parameter (`_config` is intentionally unused).
## How to extend
### Add a new CLI command
1. Call `defineCliCommand` + `registerCliCommand` before `buildProgram` runs (typically at module load time or in your plugin's `init`):
```typescript
import { defineCliCommand, registerCliCommand } from "@elizaos/plugin-cli";
registerCliCommand(
defineCliCommand(
"my-cmd",
"Does something useful",
(ctx) => {
ctx.program
.command("my-cmd")
.description("Does something useful")
.option("--flag", "a flag")
.action((opts) => {
const runtime = ctx.getRuntime?.();
// ...
});
},
{ priority: 50 }, // lower = registered earlier
),
);
```
2. The command appears in `elizaos --help` automatically once `buildProgram` is called.
### Use the progress reporter in a command
```typescript
import { createDefaultDeps, withProgress } from "@elizaos/plugin-cli";
const deps = createDefaultDeps();
await withProgress(deps, "Doing work", async () => {
await someLongOperation();
});
```
## Conventions / gotchas
- The command registry is **module-level state** (a `Map`). In a single Node/Bun process all imports share the same registry; in tests always call `clearCliCommands()` in `beforeEach` / `afterEach` to avoid cross-test pollution.
- `buildProgram` iterates `listCliCommands()` at call time. Register all commands before calling `buildProgram`.
- `registerCliCommand` silently replaces on duplicate name (with a `logger.warn`). Use distinct names to avoid accidental overrides.
- The plugin object itself has no persistent resources: `dispose` returns immediately and `init` only logs.
- `createProgressReporter` writes directly to `process.stdout` using ANSI escapes when `isTTY`; it degrades to plain `deps.log` in non-TTY environments (CI, piped output).
- `parseDurationMs` returns `{ valid: false, ms: 0 }` on bad input — always check `valid` before using `ms`.
- Build output goes to `dist/` (`.gitignored`). The package ships only `dist/` — no `src/` in the published tarball.
<!-- BEGIN: evidence-and-e2e-mandate (managed; canonical standard = repo-root AGENTS.md) -->
## ⛔ NON-NEGOTIABLE — evidence, trajectories & real end-to-end tests
> The binding, repo-wide standard is **[AGENTS.md](../../AGENTS.md)**. Read it.
> Nothing in this package is *done* until it is *proven* done — a reviewer must confirm it
> works **without reading the code**, from the artifacts you attach. This applies to **every**
> feature, fix, refactor, and chore here. "Tests pass" is not proof; "CI is green" is not proof.
- **Record AND read model trajectories.** Capture the *actual* inputs and outputs of the model
from a **live** LLM — not the deterministic proxy, not a mock: the prompt, the
providers/context, the raw model output, every tool/action call, and the result. Then **open
the trajectory and review it by hand.** A captured-but-unread trajectory is not evidence
(`packages/scenario-runner/bin/eliza-scenarios run <scenario> --report <out>`).
- **Real, full-featured E2E — no larp.** Every feature ships detailed end-to-end tests that
drive the *real* path end to end. Not the happy "front door" only: cover error paths,
edge/empty/invalid input, concurrency, roles/permissions, and adversarial input. A test that
asserts against a mock/stub/fixture standing in for the thing under test **does not count**.
If the real model/device/chain/connector/account is hard to reach, **make it reachable — that
is the work**, not an excuse to mock. If the existing tests here are shallow or mocked, fixing
them is part of your change.
- **Screenshots + logs at every phase**, plus a **complete walkthrough video/run-through** of
the entire feature or view, start to finish (`bun run test:e2e:record`).
- **Manually review every artifact the change touches** — never just the green check: client
logs (console + network), server logs (`[ClassName] …`), the model trajectories in and out,
before/after full-page screenshots, **and the domain artifacts listed below for this package.**
- **No residuals. No shortcuts.** The goal is not "done" — it is *everything* done. Clear every
blocker by the **hard path**: build the real architecture, stand up the real
model/device/service, actually test it. Never leave a TODO, a stub, a stepping-stone, or a
"follow-up." When unsure, research thoroughly, weigh the options, and ship the best,
highest-effort, production-ready version. Keep going until every possibility is exhausted.
Artifacts → attached inline in the PR (MP4 video, JPG screenshots, logs in `<details>`); attach each evidence type **or**
explicitly mark it N/A with a reason — never leave it blank. If `develop` moved and changed
behavior, **re-capture** evidence; stale proof is worse than none.
**Capture & manually review for this package — CLI / tooling:**
- The real command/flow invocation transcript (args in, stdout/stderr, exit code) and the artifacts it generated (files, scaffolds, manifests, screenshots/recordings).
- Failure paths: bad args, missing deps, partial state, permission/network errors.
- A recording/log of the actual run end to end — not a unit test of one helper.
- Any model interaction captured as a live trajectory and reviewed.
<!-- END: evidence-and-e2e-mandate -->
+112
View File
@@ -0,0 +1,112 @@
# @elizaos/plugin-cli
CLI framework plugin for elizaOS agents. Provides a Commander-based command registry, TTY-aware progress reporting, and common helpers (duration parsing, byte formatting) for building agent-driven CLI tools.
## What it does
- Maintains a module-level registry of `CliCommand` objects that other plugins or host code populate.
- Assembles a Commander `Command` tree from the registry via `buildProgram` / `runCli`.
- Offers a TTY-aware spinner (`createProgressReporter`, `withProgress`) that degrades to plain log lines in non-interactive environments.
- Ships parsing and formatting helpers for durations (`parseDurationMs`, `formatDuration`) and byte sizes (`formatBytes`).
The plugin object (`cliPlugin`) registers no actions, providers, services, or routes. Its value is the exported API that other code calls.
## Capabilities
| Export | Description |
|--------|-------------|
| `buildProgram(options?)` | Builds a Commander program from all registered commands |
| `runCli(argv?, options?)` | Builds and runs the program against `argv` (defaults to `process.argv`) |
| `registerCliCommand(cmd)` | Register a `CliCommand` in the shared registry |
| `defineCliCommand(...)` | Factory to construct a `CliCommand` |
| `unregisterCliCommand(name)` | Remove a command from the registry |
| `listCliCommands()` | Returns all registered commands sorted by `priority` |
| `addSubcommand(parent, name, desc)` | Attach a subcommand to an existing Commander command |
| `createProgressReporter(deps, options?)` | TTY-aware spinner / progress reporter |
| `withProgress(deps, message, fn)` | Run an async function wrapped with start/success/fail reporting |
| `parseDurationMs(input)` | Parse `"1s"`, `"5m"`, `"2h"`, `"7d"`, bare ms strings |
| `parseTimeoutMs(input?, defaultMs)` | `parseDurationMs` with a default fallback |
| `formatDuration(ms)` | Milliseconds → human-readable string |
| `formatBytes(bytes)` | Bytes → human-readable string |
| `isInteractive()` | Returns `true` when both stdin and stdout are TTYs |
## Installation
```bash
bun add @elizaos/plugin-cli
```
Add to your agent's plugin list:
```typescript
import { cliPlugin } from "@elizaos/plugin-cli";
export const character = {
plugins: [cliPlugin],
// ...
};
```
## Registering commands
```typescript
import { defineCliCommand, registerCliCommand, runCli } from "@elizaos/plugin-cli";
registerCliCommand(
defineCliCommand(
"greet",
"Print a greeting",
(ctx) => {
ctx.program
.command("greet")
.description("Print a greeting")
.argument("<name>", "Name to greet")
.action((name) => {
console.log(`Hello, ${name}!`);
});
},
),
);
await runCli(process.argv, { name: "myapp", version: "1.0.0" });
```
## Configuration
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `CLI_NAME` | No | `"elizaos"` | CLI binary name in help output |
| `CLI_VERSION` | No | `"1.0.0"` | Version string shown by `--version` |
Pass directly to `buildProgram` / `runCli` as options (`{ name, version }`). These values are declared in `agentConfig.pluginParameters` but are not read from `process.env` — the `init` function does not use its config parameter.
## Using the progress reporter
```typescript
import { createDefaultDeps, withProgress } from "@elizaos/plugin-cli";
const deps = createDefaultDeps();
await withProgress(deps, "Fetching data", async () => {
await fetchSomething();
});
// Prints spinner while running, then "✓ Fetching data" or "✗ <error message>"
```
## Duration parsing
```typescript
import { parseDurationMs } from "@elizaos/plugin-cli";
parseDurationMs("5m"); // { ms: 300000, valid: true, original: "5m" }
parseDurationMs("30s"); // { ms: 30000, valid: true, original: "30s" }
parseDurationMs("bad"); // { ms: 0, valid: false, original: "bad" }
```
Supported units: `ms`, `s`/`sec`/`second(s)`, `m`/`min`/`minute(s)`, `h`/`hr`/`hour(s)`, `d`/`day(s)`. Plain integers are treated as milliseconds.
## Notes
- The command registry is module-level state shared across all imports in the same process. In tests, call `clearCliCommands()` in `beforeEach` / `afterEach`.
- All commands must be registered before `buildProgram` / `runCli` is called.
- The progress spinner writes ANSI escape sequences directly to `process.stdout` when running in a TTY; it degrades gracefully in CI and piped output.
@@ -0,0 +1,17 @@
/**
* Vitest setup file that stubs the @elizaos/core logger so registry and plugin
* suites can assert on log calls without pulling in the full core module.
*/
import { vi } from "vitest";
vi.mock("@elizaos/core", () => ({
logger: {
debug: vi.fn(),
error: vi.fn(),
info: vi.fn(),
log: vi.fn(),
success: vi.fn(),
warn: vi.fn(),
},
}));
+18
View File
@@ -0,0 +1,18 @@
{
"root": false,
"$schema": "https://biomejs.dev/schemas/2.5.1/schema.json",
"files": {
"includes": ["src/**", "*.ts", "vitest.config.ts"]
},
"linter": {
"enabled": true,
"rules": {
"suspicious": {
"noExplicitAny": "off"
}
}
},
"formatter": {
"enabled": true
}
}
+84
View File
@@ -0,0 +1,84 @@
{
"name": "@elizaos/plugin-cli",
"version": "2.0.3-beta.7",
"description": "CLI framework plugin for ElizaOS agents - provides command registration, execution, and utilities",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"eliza-source": {
"types": "./src/index.ts",
"import": "./src/index.ts",
"default": "./src/index.ts"
},
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./*.css": "./dist/*.css",
"./*": {
"types": "./dist/*.d.ts",
"eliza-source": {
"types": "./src/*.ts",
"import": "./src/*.ts",
"default": "./src/*.ts"
},
"import": "./dist/*.js",
"default": "./dist/*.js"
}
},
"files": [
"registry-entry.json",
"dist"
],
"scripts": {
"build": "tsc",
"build:watch": "tsc --watch",
"dev": "tsc --watch",
"test": "vitest run",
"lint": "bunx @biomejs/biome check --write --unsafe .",
"lint:check": "bunx @biomejs/biome check .",
"format": "bunx @biomejs/biome format --write .",
"format:check": "bunx @biomejs/biome format .",
"typecheck": "tsgo --noEmit"
},
"dependencies": {
"@elizaos/core": "workspace:*",
"commander": "^15.0.0"
},
"devDependencies": {
"@biomejs/biome": "2.5.3",
"strip-literal": "^3.1.0",
"typescript": "^6.0.3",
"vitest": "^4.0.18"
},
"keywords": [
"elizaos",
"plugin",
"cli",
"command-line",
"terminal"
],
"license": "MIT",
"publishConfig": {
"access": "public"
},
"agentConfig": {
"pluginType": "elizaos:plugin:1.0.0",
"pluginParameters": {
"CLI_NAME": {
"type": "string",
"description": "CLI command name",
"required": false,
"sensitive": false
},
"CLI_VERSION": {
"type": "string",
"description": "CLI version string",
"required": false,
"sensitive": false
}
}
}
}
+40
View File
@@ -0,0 +1,40 @@
{
"id": "cli",
"name": "Cli",
"description": "CLI framework plugin for ElizaOS agents - provides command registration, execution, and utilities",
"npmName": "@elizaos/plugin-cli",
"version": "2.0.0-beta.0",
"source": "bundled",
"tags": ["cli", "developer-tools", "terminal"],
"config": {
"CLI_NAME": {
"type": "string",
"required": false,
"sensitive": false,
"label": "Name",
"help": "CLI command name",
"advanced": false
},
"CLI_VERSION": {
"type": "string",
"required": false,
"sensitive": false,
"label": "Version",
"help": "CLI version string",
"advanced": false
}
},
"render": {
"visible": true,
"pinTo": [],
"style": "card",
"icon": "Hash",
"group": "devtools",
"groupOrder": 5,
"actions": ["enable", "configure"]
},
"resources": {},
"dependsOn": [],
"kind": "plugin",
"subtype": "devtools"
}
+87
View File
@@ -0,0 +1,87 @@
/**
* Exercises the plugin's public program surface — buildProgram, runCli, and
* command registration through the Commander root. Deterministic: commands and
* runtime are stubbed with vitest, no live model or process spawning.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
buildProgram,
clearCliCommands,
defineCliCommand,
registerCliCommand,
runCli,
} from "./index.js";
describe("plugin-cli program surface", () => {
beforeEach(() => {
clearCliCommands();
});
it("builds a Commander program and registers command callbacks with context", () => {
const getRuntime = vi.fn(() => ({ agentId: "agent-1" }) as never);
const register = vi.fn((ctx) => {
ctx.program.command("hello").description("Say hello");
expect(ctx.cliName).toBe("agent");
expect(ctx.version).toBe("2.3.4");
expect(ctx.getRuntime?.()).toEqual({ agentId: "agent-1" });
});
registerCliCommand(defineCliCommand("hello", "Say hello", register));
const program = buildProgram({
name: "agent",
version: "2.3.4",
getRuntime,
});
expect(program.name()).toBe("agent");
expect(program.version()).toBe("2.3.4");
expect(program.commands.map((command) => command.name())).toContain(
"hello",
);
expect(register).toHaveBeenCalledTimes(1);
});
it("runCli executes registered command actions", async () => {
const action = vi.fn();
registerCliCommand(
defineCliCommand("ping", "Ping", (ctx) => {
ctx.program.command("ping").action(action);
}),
);
await runCli(["node", "elizaos", "ping"]);
expect(action).toHaveBeenCalledTimes(1);
});
it("runCli propagates command action failures", async () => {
registerCliCommand(
defineCliCommand("explode", "Explode", (ctx) => {
ctx.program.command("explode").action(() => {
throw new Error("boom");
});
}),
);
await expect(runCli(["node", "elizaos", "explode"])).rejects.toThrow(
"boom",
);
});
it("runCli returns for help and version instead of exiting the host process", async () => {
const write = vi
.spyOn(process.stdout, "write")
.mockImplementation(() => true);
await expect(
runCli(["node", "elizaos", "--help"]),
).resolves.toBeUndefined();
await expect(
runCli(["node", "elizaos", "--version"], { version: "9.9.9" }),
).resolves.toBeUndefined();
expect(write).toHaveBeenCalled();
write.mockRestore();
});
});
+187
View File
@@ -0,0 +1,187 @@
/**
* @elizaos/plugin-cli
*
* CLI framework plugin for ElizaOS agents
*
* Provides:
* - CLI command registration and management
* - Progress reporting utilities
* - Duration/timeout parsing
* - Common CLI dependencies
*/
import type { IAgentRuntime, Plugin } from "@elizaos/core";
import { logger } from "@elizaos/core";
import { Command } from "commander";
// Registry
export {
addSubcommand,
clearCliCommands,
defineCliCommand,
getCliCommand,
listCliCommands,
registerAllCommands,
registerCliCommand,
unregisterCliCommand,
} from "./registry.js";
// Types
export * from "./types.js";
// Utils
export {
createDefaultDeps,
createProgressReporter,
DEFAULT_CLI_NAME,
DEFAULT_CLI_VERSION,
formatBytes,
formatCliCommand,
formatDuration,
isInteractive,
parseDurationMs,
parseTimeoutMs,
resolveCliName,
withProgress,
} from "./utils.js";
import { listCliCommands, registerAllCommands } from "./registry.js";
import type { CliContext } from "./types.js";
import {
DEFAULT_CLI_NAME,
DEFAULT_CLI_VERSION,
resolveCliName,
} from "./utils.js";
/**
* Build the Commander program with all registered commands
*/
export function buildProgram(options?: {
name?: string;
version?: string;
getRuntime?: () => IAgentRuntime | null;
}): Command {
const cliName = options?.name ?? resolveCliName();
const version = options?.version ?? DEFAULT_CLI_VERSION;
const program = new Command()
.name(cliName)
.version(version)
.description(`${cliName} - ElizaOS agent CLI`);
program.exitOverride();
const ctx: CliContext = {
program,
getRuntime: options?.getRuntime,
cliName,
version,
};
// Register all commands
registerAllCommands(ctx);
return program;
}
/**
* Run the CLI with the given arguments
*/
export async function runCli(
argv?: string[],
options?: {
name?: string;
version?: string;
getRuntime?: () => IAgentRuntime | null;
},
): Promise<void> {
const program = buildProgram(options);
try {
await program.parseAsync(argv ?? process.argv);
} catch (error) {
const commanderError = error as { code?: string; message?: string };
if (
commanderError.code === "commander.helpDisplayed" ||
commanderError.code === "commander.version"
) {
return;
}
if (error instanceof Error) {
// Commander throws an error for --help and --version
if (error.message.includes("outputHelp")) {
return;
}
}
throw error;
}
}
/**
* CLI Plugin for ElizaOS
*
* Provides CLI command infrastructure for the agent runtime.
*
* Configuration:
* - CLI_NAME: CLI command name (default: "elizaos")
* - CLI_VERSION: CLI version string
*
* @example
* ```typescript
* import { cliPlugin, buildProgram, registerCliCommand, defineCliCommand } from '@elizaos/plugin-cli';
*
* // Register a custom command
* registerCliCommand(defineCliCommand(
* 'mycommand',
* 'My custom command',
* (ctx) => {
* ctx.program.command('mycommand')
* .description('My custom command')
* .action(() => console.log('Hello!'));
* }
* ));
*
* // Build and run
* const program = buildProgram();
* await program.parseAsync(process.argv);
* ```
*/
export const cliPlugin: Plugin = {
name: "cli",
description: "CLI framework plugin for command registration and execution",
providers: [],
actions: [],
services: [],
routes: [],
config: {
CLI_NAME: DEFAULT_CLI_NAME,
CLI_VERSION: DEFAULT_CLI_VERSION,
},
async init(
_config: Record<string, string>,
_runtime: IAgentRuntime,
): Promise<void> {
try {
const commands = listCliCommands();
logger.info(
{ commandCount: commands.length },
"[CLIPlugin] Plugin initialized",
);
} catch (error) {
logger.error(
"[CLIPlugin] Error initializing:",
error instanceof Error ? error.message : String(error),
);
throw error;
}
},
// No services or persistent resources — nothing to dispose.
dispose: async (_runtime) => {},
};
export default cliPlugin;
// Re-export Command for convenience
export { Command } from "commander";
+88
View File
@@ -0,0 +1,88 @@
/**
* Covers the module-level command registry: register/unregister/lookup,
* priority-sorted listing, duplicate-name replacement, and bulk registration
* against a real Commander instance. Deterministic; the core logger is mocked.
*/
import { logger } from "@elizaos/core";
import { Command } from "commander";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
addSubcommand,
clearCliCommands,
defineCliCommand,
getCliCommand,
listCliCommands,
registerAllCommands,
registerCliCommand,
unregisterCliCommand,
} from "./registry.js";
describe("CLI command registry", () => {
beforeEach(() => {
clearCliCommands();
vi.clearAllMocks();
});
it("replaces commands by name and warns about the replacement", () => {
const first = defineCliCommand("run", "first", vi.fn());
const second = defineCliCommand("run", "second", vi.fn());
registerCliCommand(first);
registerCliCommand(second);
expect(getCliCommand("run")).toBe(second);
expect(logger.warn).toHaveBeenCalledWith(
'[CLI] Command "run" already registered, replacing',
);
});
it("lists commands in ascending priority order with default priority last", () => {
registerCliCommand(defineCliCommand("default", "default", vi.fn()));
registerCliCommand(
defineCliCommand("first", "first", vi.fn(), { priority: 1 }),
);
registerCliCommand(
defineCliCommand("middle", "middle", vi.fn(), { priority: 50 }),
);
expect(listCliCommands().map((command) => command.name)).toEqual([
"first",
"middle",
"default",
]);
});
it("continues registering later commands when one command throws", () => {
const firstRegister = vi.fn(() => {
throw new Error("broken registration");
});
const secondRegister = vi.fn();
const program = new Command();
const ctx = { program, cliName: "elizaos", version: "1.0.0" };
registerCliCommand(defineCliCommand("broken", "broken", firstRegister));
registerCliCommand(defineCliCommand("healthy", "healthy", secondRegister));
registerAllCommands(ctx);
expect(firstRegister).toHaveBeenCalledWith(ctx);
expect(secondRegister).toHaveBeenCalledWith(ctx);
expect(logger.error).toHaveBeenCalledWith(
'[CLI] Failed to register command "broken":',
"broken registration",
);
});
it("unregisters commands and creates described subcommands", () => {
registerCliCommand(defineCliCommand("doctor", "doctor", vi.fn()));
expect(unregisterCliCommand("doctor")).toBe(true);
expect(getCliCommand("doctor")).toBeUndefined();
expect(unregisterCliCommand("doctor")).toBe(false);
const parent = new Command();
const child = addSubcommand(parent, "status", "Show status");
expect(child.name()).toBe("status");
expect(child.description()).toBe("Show status");
});
});
+106
View File
@@ -0,0 +1,106 @@
/**
* CLI command registry
*
* Provides command registration and management for the CLI plugin.
*/
import { logger } from "@elizaos/core";
import type { Command } from "commander";
import type { CliCommand, CliContext, CliRegistrationFn } from "./types.js";
/**
* Internal registry of CLI commands
*/
const commands = new Map<string, CliCommand>();
/**
* Register a CLI command
*/
export function registerCliCommand(command: CliCommand): void {
if (commands.has(command.name)) {
logger.warn(
`[CLI] Command "${command.name}" already registered, replacing`,
);
}
commands.set(command.name, command);
}
/**
* Unregister a CLI command
*/
export function unregisterCliCommand(name: string): boolean {
return commands.delete(name);
}
/**
* Get a CLI command by name
*/
export function getCliCommand(name: string): CliCommand | undefined {
return commands.get(name);
}
/**
* List all registered CLI commands
*/
export function listCliCommands(): CliCommand[] {
return Array.from(commands.values()).sort(
(a, b) => (a.priority ?? 100) - (b.priority ?? 100),
);
}
/**
* Register all commands with the program
*/
export function registerAllCommands(ctx: CliContext): void {
const sorted = listCliCommands();
for (const command of sorted) {
try {
command.register(ctx);
logger.debug(`[CLI] Registered command: ${command.name}`);
} catch (error) {
logger.error(
`[CLI] Failed to register command "${command.name}":`,
error instanceof Error ? error.message : String(error),
);
}
}
}
/**
* Clear all registered commands (for testing)
*/
export function clearCliCommands(): void {
commands.clear();
}
/**
* Helper to create a CLI command definition
*/
export function defineCliCommand(
name: string,
description: string,
register: CliRegistrationFn,
options?: {
aliases?: string[];
priority?: number;
},
): CliCommand {
return {
name,
description,
register,
aliases: options?.aliases,
priority: options?.priority,
};
}
/**
* Helper to create a subcommand on an existing command
*/
export function addSubcommand(
parent: Command,
name: string,
description: string,
): Command {
return parent.command(name).description(description);
}
+137
View File
@@ -0,0 +1,137 @@
/**
* CLI plugin types
*
* Core types for CLI command registration and execution.
*/
import type { IAgentRuntime } from "@elizaos/core";
import type { Command } from "commander";
/**
* Logger interface for CLI context
*/
export interface CliLogger {
info: (msg: string) => void;
warn: (msg: string) => void;
error: (msg: string) => void;
debug?: (msg: string) => void;
}
/**
* CLI context provided to command handlers
*/
export interface CliContext {
/** Commander program instance */
program: Command;
/** Optional runtime getter for plugins that need it */
getRuntime?: () => IAgentRuntime | null;
/** CLI name (e.g., "elizaos", "otto") */
cliName: string;
/** CLI version */
version: string;
/** Optional configuration object */
config?: Record<string, unknown>;
/** Optional workspace directory */
workspaceDir?: string;
/** Optional logger for CLI output */
logger?: CliLogger;
}
/**
* CLI command registration function signature
*/
export type CliRegistrationFn = (ctx: CliContext) => void;
/**
* CLI command definition
*/
export interface CliCommand {
/** Command name (e.g., "run", "config") */
name: string;
/** Command description */
description: string;
/** Command aliases */
aliases?: string[];
/** Registration function */
register: CliRegistrationFn;
/** Priority for registration order (lower = earlier) */
priority?: number;
}
/**
* CLI plugin configuration
*/
export interface CliPluginConfig {
/** CLI name */
name?: string;
/** CLI version */
version?: string;
/** Commands to register */
commands?: CliCommand[];
}
/**
* Progress reporter interface
*/
export interface ProgressReporter {
/** Start progress reporting */
start(message: string): void;
/** Update progress message */
update(message: string): void;
/** Complete with success */
success(message: string): void;
/** Complete with failure */
fail(message: string): void;
/** Stop progress reporting */
stop(): void;
}
/**
* Progress options
*/
export interface ProgressOptions {
/** Initial message */
message?: string;
/** Whether to show spinner */
spinner?: boolean;
}
/**
* CLI dependencies for command execution
*/
export interface CliDeps {
/** Log function */
log: (message: string) => void;
/** Error function */
error: (message: string) => void;
/** Exit function */
exit: (code: number) => void;
}
/**
* Duration parsing result
*/
export interface ParsedDuration {
/** Duration in milliseconds */
ms: number;
/** Original string */
original: string;
/** Whether parsing was successful */
valid: boolean;
}
/**
* Command options commonly used across CLI commands
*/
export interface CommonCommandOptions {
/** JSON output format */
json?: boolean;
/** Verbose output */
verbose?: boolean;
/** Quiet mode (minimal output) */
quiet?: boolean;
/** Force action without confirmation */
force?: boolean;
/** Dry run (show what would happen) */
dryRun?: boolean;
}
+111
View File
@@ -0,0 +1,111 @@
/**
* Tests the CLI utility helpers — duration/timeout parsing, byte and duration
* formatting, command formatting, CLI-name resolution, and the progress
* wrapper. Deterministic, with fast-check property tests over the parsers.
*/
import fc from "fast-check";
import { describe, expect, it, vi } from "vitest";
import {
formatBytes,
formatCliCommand,
formatDuration,
parseDurationMs,
parseTimeoutMs,
resolveCliName,
withProgress,
} from "./utils.js";
describe("plugin-cli utilities", () => {
it("parses duration strings and falls back for invalid timeout values", () => {
expect(parseDurationMs("250")).toEqual({
ms: 250,
original: "250",
valid: true,
});
expect(parseDurationMs("1.5m")).toEqual({
ms: 90_000,
original: "1.5m",
valid: true,
});
expect(parseDurationMs("bad")).toEqual({
ms: 0,
original: "bad",
valid: false,
});
expect(parseTimeoutMs(undefined, 5000)).toBe(5000);
expect(parseTimeoutMs("bad", 5000)).toBe(5000);
expect(parseTimeoutMs("2s", 5000)).toBe(2000);
});
it("rejects hostile duration values that overflow safe millisecond integers", () => {
for (const input of [
"999999999999999999999999999999999999999999999999999999d",
"1e309d",
"Infinity",
"NaN",
"-1s",
]) {
expect(parseDurationMs(input)).toEqual({
ms: 0,
original: input,
valid: false,
});
expect(parseTimeoutMs(input, 1234)).toBe(1234);
}
});
it("fuzzes duration parsing so valid results are finite safe integers", () => {
fc.assert(
fc.property(fc.string({ maxLength: 200 }), (input) => {
const parsed = parseDurationMs(input);
expect(parsed.original).toBe(input);
if (parsed.valid) {
expect(Number.isSafeInteger(parsed.ms)).toBe(true);
expect(parsed.ms).toBeGreaterThanOrEqual(0);
} else {
expect(parsed.ms).toBe(0);
}
}),
{ numRuns: 500 },
);
});
it("formats command, byte, duration, and argv-derived CLI names", () => {
expect(
formatCliCommand("run task", {
cliName: "agent",
profile: "dev",
env: "local",
}),
).toBe("agent --profile dev --env local run task");
expect(formatBytes(1024 * 1024)).toBe("1.0 MB");
expect(formatDuration(90_000)).toBe("1.5m");
expect(resolveCliName(["node", "/usr/local/bin/elizaos.mjs"])).toBe(
"elizaos",
);
expect(resolveCliName(["node", "C:\\tools\\elizaos.cmd"])).toBe("elizaos");
});
it("reports success and failure around async work", async () => {
const deps = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
await expect(withProgress(deps, "Working", async () => 42)).resolves.toBe(
42,
);
expect(deps.log).toHaveBeenCalledWith("Working");
expect(deps.log).toHaveBeenCalledWith("✓ Working");
await expect(
withProgress(deps, "Failing", async () => {
throw new Error("bad");
}),
).rejects.toThrow("bad");
expect(deps.error).toHaveBeenCalledWith("✗ bad");
});
});
+285
View File
@@ -0,0 +1,285 @@
/**
* CLI utilities
*
* Common utilities for CLI operations.
*/
import type {
CliDeps,
ParsedDuration,
ProgressOptions,
ProgressReporter,
} from "./types.js";
/**
* Default CLI name
*/
export const DEFAULT_CLI_NAME = "elizaos";
/**
* Default CLI version
*/
export const DEFAULT_CLI_VERSION = "2.0.3-beta.0";
/**
* Create default CLI dependencies
*/
export function createDefaultDeps(): CliDeps {
return {
log: (message: string) => console.log(message),
error: (message: string) => console.error(message),
exit: (code: number) => process.exit(code),
};
}
/**
* Create a progress reporter
*/
export function createProgressReporter(
deps: CliDeps,
options?: ProgressOptions,
): ProgressReporter {
let running = false;
let intervalId: ReturnType<typeof setInterval> | null = null;
const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
let frameIndex = 0;
let currentMessage = options?.message ?? "";
const clearLine = () => {
if (process.stdout.isTTY) {
process.stdout.write("\r\x1b[K");
}
};
const writeSpinner = () => {
if (process.stdout.isTTY && options?.spinner !== false) {
clearLine();
process.stdout.write(`${spinnerFrames[frameIndex]} ${currentMessage}`);
frameIndex = (frameIndex + 1) % spinnerFrames.length;
}
};
return {
start(message: string) {
currentMessage = message;
running = true;
if (options?.spinner !== false && process.stdout.isTTY) {
writeSpinner();
intervalId = setInterval(writeSpinner, 80);
} else {
deps.log(message);
}
},
update(message: string) {
currentMessage = message;
if (!running && !process.stdout.isTTY) {
deps.log(message);
}
},
success(message: string) {
this.stop();
if (process.stdout.isTTY) {
clearLine();
}
deps.log(`${message}`);
},
fail(message: string) {
this.stop();
if (process.stdout.isTTY) {
clearLine();
}
deps.error(`${message}`);
},
stop() {
running = false;
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
if (process.stdout.isTTY) {
clearLine();
}
},
};
}
/**
* Execute with progress reporting
*/
export async function withProgress<T>(
deps: CliDeps,
message: string,
fn: () => Promise<T>,
): Promise<T> {
const progress = createProgressReporter(deps, { message, spinner: true });
progress.start(message);
try {
const result = await fn();
progress.success(message);
return result;
} catch (error) {
progress.fail(error instanceof Error ? error.message : String(error));
throw error;
}
}
/**
* Parse a duration string to milliseconds
*
* Supports formats like:
* - "1s", "30s" (seconds)
* - "1m", "5m" (minutes)
* - "1h", "2h" (hours)
* - "1d", "7d" (days)
* - "1000" (milliseconds)
*/
export function parseDurationMs(input: string): ParsedDuration {
const trimmed = input.trim().toLowerCase();
// Check for number only (milliseconds). Negative or non-safe-integer values
// are invalid durations — return the {valid:false, ms:0} sentinel rather than
// a negative ms (matches the unit branch below and the documented contract).
const numOnly = parseInt(trimmed, 10);
if (!Number.isNaN(numOnly) && String(numOnly) === trimmed) {
if (numOnly < 0 || !Number.isSafeInteger(numOnly)) {
return { ms: 0, original: input, valid: false };
}
return { ms: numOnly, original: input, valid: true };
}
// Parse with unit
const match = trimmed.match(
/^(\d+(?:\.\d+)?)\s*(s|sec|second|seconds|m|min|minute|minutes|h|hr|hour|hours|d|day|days|ms|millisecond|milliseconds)?$/,
);
if (!match) {
return { ms: 0, original: input, valid: false };
}
const value = parseFloat(match[1]);
const unit = match[2] ?? "ms";
let multiplier: number;
switch (unit) {
case "ms":
case "millisecond":
case "milliseconds":
multiplier = 1;
break;
case "s":
case "sec":
case "second":
case "seconds":
multiplier = 1000;
break;
case "m":
case "min":
case "minute":
case "minutes":
multiplier = 60 * 1000;
break;
case "h":
case "hr":
case "hour":
case "hours":
multiplier = 60 * 60 * 1000;
break;
case "d":
case "day":
case "days":
multiplier = 24 * 60 * 60 * 1000;
break;
default:
return { ms: 0, original: input, valid: false };
}
const ms = Math.round(value * multiplier);
if (!Number.isSafeInteger(ms) || ms < 0) {
return { ms: 0, original: input, valid: false };
}
return { ms, original: input, valid: true };
}
/**
* Parse a timeout string with defaults
*/
export function parseTimeoutMs(
input: string | undefined,
defaultMs: number,
): number {
if (!input) return defaultMs;
const parsed = parseDurationMs(input);
return parsed.valid ? parsed.ms : defaultMs;
}
/**
* Format a CLI command with profile/env context
*/
export function formatCliCommand(
command: string,
options?: {
cliName?: string;
profile?: string;
env?: string;
},
): string {
const parts = [options?.cliName ?? DEFAULT_CLI_NAME];
if (options?.profile) {
parts.push(`--profile ${options.profile}`);
}
if (options?.env) {
parts.push(`--env ${options.env}`);
}
parts.push(command);
return parts.join(" ");
}
/**
* Resolve CLI name from argv
*/
export function resolveCliName(argv?: string[]): string {
const args = argv ?? process.argv;
if (args.length < 2) return DEFAULT_CLI_NAME;
const scriptPath = args[1];
const scriptName = scriptPath.split(/[\\/]/).pop() ?? DEFAULT_CLI_NAME;
// Remove common extensions
return scriptName.replace(/\.(js|ts|mjs|cjs|cmd|exe)$/, "");
}
/**
* Check if running interactively
*/
export function isInteractive(): boolean {
return process.stdin.isTTY === true && process.stdout.isTTY === true;
}
/**
* Format bytes to human readable string
*/
export function formatBytes(bytes: number): string {
const units = ["B", "KB", "MB", "GB", "TB"];
let unitIndex = 0;
let value = bytes;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex++;
}
return `${value.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`;
}
/**
* Format duration to human readable string
*/
export function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
if (ms < 3600000) return `${(ms / 60000).toFixed(1)}m`;
return `${(ms / 3600000).toFixed(1)}h`;
}
+35
View File
@@ -0,0 +1,35 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"types": [
"node"
],
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"declarationMap": true,
"composite": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"src/**/__tests__/**",
"src/**/*.test.ts",
"src/**/*.test.tsx",
"**/__tests__/**",
"**/*.test.ts",
"**/*.test.tsx",
"**/*.e2e.test.ts"
]
}
+35
View File
@@ -0,0 +1,35 @@
/**
* Vitest configuration for the CLI plugin: node environment, serial execution
* (single worker, no file parallelism) so the module-level command registry
* stays isolated between suites, with the core logger mock loaded as a setup file.
*/
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
include: [
"__tests__/**/*.test.ts",
"__tests__/**/*.test.tsx",
"src/**/*.test.ts",
"src/**/*.test.tsx",
"test/**/*.test.ts",
"test/**/*.test.tsx",
],
exclude: [
"dist/**",
"**/node_modules/**",
"**/*.live.test.ts",
"**/*.e2e.test.ts",
],
testTimeout: 60000,
hookTimeout: 60000,
fileParallelism: false,
maxWorkers: 1,
setupFiles: ["./__tests__/core-test-mock.ts"],
sequence: {
concurrent: false,
},
},
});