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
+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`;
}