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
+112
View File
@@ -0,0 +1,112 @@
/**
* Loads and zod-validates the shell configuration from environment variables
* into a ShellConfig, applying defaults and merging DEFAULT_FORBIDDEN_COMMANDS.
* Throws when SHELL_ALLOWED_DIRECTORY is missing or does not exist on disk.
*/
import fs from "node:fs";
import path from "node:path";
import { logger } from "@elizaos/core";
import { z } from "zod";
import type { ShellConfig } from "../types";
const configSchema = z.object({
enabled: z.boolean(),
allowedDirectory: z.string(),
timeout: z.number().positive().default(30000),
forbiddenCommands: z.array(z.string()),
maxOutputChars: z.number().positive().default(200000),
pendingMaxOutputChars: z.number().positive().default(200000),
defaultBackgroundMs: z.number().positive().default(10000),
allowBackground: z.boolean().default(true),
});
export const DEFAULT_FORBIDDEN_COMMANDS: readonly string[] = [
"rm -rf /",
"rmdir",
"chmod 777",
"chown",
"chgrp",
"shutdown",
"reboot",
"halt",
"poweroff",
"kill -9",
"killall",
"pkill",
"sudo rm -rf",
"su",
"passwd",
"useradd",
"userdel",
"groupadd",
"groupdel",
"format",
"fdisk",
"mkfs",
"dd if=/dev/zero",
"shred",
":(){:|:&};:",
] as const;
export function loadShellConfig(): ShellConfig {
const allowedDirectory = process.env.SHELL_ALLOWED_DIRECTORY || process.cwd();
const timeout = parseInt(process.env.SHELL_TIMEOUT || "30000", 10);
const maxOutputChars = parseInt(process.env.SHELL_MAX_OUTPUT_CHARS || "200000", 10);
const pendingMaxOutputChars = parseInt(
process.env.SHELL_PENDING_MAX_OUTPUT_CHARS || "200000",
10
);
const defaultBackgroundMs = parseInt(process.env.SHELL_BACKGROUND_MS || "10000", 10);
const allowBackground = process.env.SHELL_ALLOW_BACKGROUND !== "false";
const customForbidden = process.env.SHELL_FORBIDDEN_COMMANDS
? process.env.SHELL_FORBIDDEN_COMMANDS.split(",").map((cmd) => cmd.trim())
: [];
const forbiddenCommands = [...new Set([...DEFAULT_FORBIDDEN_COMMANDS, ...customForbidden])];
const config: ShellConfig = {
enabled: true,
allowedDirectory,
timeout,
forbiddenCommands,
maxOutputChars,
pendingMaxOutputChars,
defaultBackgroundMs,
allowBackground,
};
const parseResult = configSchema.safeParse(config);
if (!parseResult.success) {
const errorMessage = parseResult.error.issues[0]?.message || parseResult.error.toString();
throw new Error(`Shell plugin configuration error: ${errorMessage}`);
}
try {
const stats = fs.statSync(allowedDirectory);
if (!stats.isDirectory()) {
throw new Error(`SHELL_ALLOWED_DIRECTORY is not a directory: ${allowedDirectory}`);
}
config.allowedDirectory = path.resolve(allowedDirectory);
logger.info(
`Shell plugin enabled with allowed directory: ${config.allowedDirectory}, ` +
`background: ${allowBackground}, timeout: ${timeout}ms`
);
} catch (error) {
// error-policy:J1 config boundary; translate the expected ENOENT into a
// clear "does not exist" message (preserving the original via `cause`) and
// rethrow every other stat failure unchanged so it is not masked.
if (
error instanceof Error &&
"code" in error &&
(error as NodeJS.ErrnoException).code === "ENOENT"
) {
throw new Error(`SHELL_ALLOWED_DIRECTORY does not exist: ${allowedDirectory}`, {
cause: error,
});
}
throw error;
}
return config;
}
+54
View File
@@ -0,0 +1,54 @@
/** Barrel re-export of the shell plugin's utility surface. */
export { DEFAULT_FORBIDDEN_COMMANDS, loadShellConfig } from "./config";
export {
extractBaseCommand,
isForbiddenCommand,
isSafeCommand,
validatePath,
} from "./pathUtils";
// Process queue and command execution utilities
export {
attachChildProcessBridge,
type ChildProcessBridgeOptions,
CommandLane,
type CommandLane as CommandLaneType,
type CommandOptions,
clearCommandLane,
enqueueCommand,
enqueueCommandInLane,
getQueueSize,
getTotalQueueSize,
runCommandWithTimeout,
runExec,
type SpawnResult,
setCommandLaneConcurrency,
} from "./processQueue";
export {
BRACKETED_PASTE_END,
BRACKETED_PASTE_START,
buildCursorPositionResponse,
encodeKeySequence,
encodePaste,
type KeyEncodingRequest,
type KeyEncodingResult,
stripDsrRequests,
} from "./ptyKeys";
// Shell argument parsing
export { splitShellArgs } from "./shellArgv";
export {
chunkString,
clampNumber,
coerceEnv,
deriveSessionName,
formatDuration,
getShellConfig,
killProcessTree,
killSession,
pad,
readEnvInt,
resolveWorkdir,
sanitizeBinaryOutput,
sliceLogLines,
sliceUtf16Safe,
truncateMiddle,
} from "./shellUtils";
+81
View File
@@ -0,0 +1,81 @@
/**
* Path and command-safety guards: validatePath() confines a resolved path to the
* allowed directory, while isForbiddenCommand/isSafeCommand/extractBaseCommand
* gate which commands the shell will run (the command-injection boundary).
*/
import path from "node:path";
import { logger } from "@elizaos/core";
export function validatePath(
commandPath: string,
allowedDir: string,
currentDir: string
): string | null {
const resolvedPath = path.resolve(currentDir, commandPath);
const normalizedPath = path.normalize(resolvedPath);
const normalizedAllowed = path.normalize(allowedDir);
const relative = path.relative(normalizedAllowed, normalizedPath);
if (relative.startsWith("..") || path.isAbsolute(relative)) {
logger.warn(
`Path validation failed: ${normalizedPath} is outside allowed directory ${normalizedAllowed}`
);
return null;
}
return normalizedPath;
}
export function isSafeCommand(command: string): boolean {
const pathTraversalPatterns = [/\.\.\//g, /\.\.\\/g, /\/\.\./g, /\\\.\./g];
const dangerousPatterns = [/\$\(/g, /`[^']*`/g, /\|\s*sudo/g, /;\s*sudo/g, /&\s*&/g, /\|\s*\|/g];
for (const pattern of pathTraversalPatterns) {
if (pattern.test(command)) {
logger.warn(`Path traversal detected in command: ${command}`);
return false;
}
}
for (const pattern of dangerousPatterns) {
if (pattern.test(command)) {
logger.warn(`Dangerous pattern detected in command: ${command}`);
return false;
}
}
const pipeCount = (command.match(/\|/g) || []).length;
if (pipeCount > 1) {
logger.warn(`Multiple pipes detected in command: ${command}`);
return false;
}
return true;
}
export function extractBaseCommand(fullCommand: string): string {
const parts = fullCommand.trim().split(/\s+/);
return parts[0] || "";
}
export function isForbiddenCommand(command: string, forbiddenCommands: string[]): boolean {
const normalizedCommand = command.trim().toLowerCase();
return forbiddenCommands.some((forbidden) => {
const forbiddenLower = forbidden.toLowerCase();
if (normalizedCommand.startsWith(forbiddenLower)) {
return true;
}
if (!forbidden.includes(" ")) {
const baseCommand = extractBaseCommand(command);
if (baseCommand.toLowerCase() === forbiddenLower) {
return true;
}
}
return false;
});
}
+460
View File
@@ -0,0 +1,460 @@
/**
* Process execution utilities with command queuing.
*
* Provides cross-platform child process execution with:
* - Windows command resolution (.cmd extension handling)
* - Timeout support
* - Lane-based command queuing for serialization
* - Signal forwarding between parent and child processes
*
* @module utils/processQueue
*/
import { type ChildProcess, execFile, spawn } from "node:child_process";
import path from "node:path";
import process from "node:process";
import { promisify } from "node:util";
import { sanitizeSpawnEnv } from "@elizaos/core";
import { resolveRuntimeExecutionMode } from "@elizaos/shared";
// ============================================================================
// Command Lanes
// ============================================================================
/**
* Command execution lanes for organizing concurrent command execution.
* Lanes allow serialization within a lane while permitting parallelism across lanes.
*/
export const CommandLane = {
Main: "main",
Cron: "cron",
Subagent: "subagent",
Nested: "nested",
} as const;
export type CommandLane = (typeof CommandLane)[keyof typeof CommandLane];
// ============================================================================
// Process Execution
// ============================================================================
const execFileAsync = promisify(execFile);
/**
* Resolves a command for Windows compatibility.
* On Windows, non-.exe commands (like npm) require their .cmd extension.
*/
function resolveCommand(command: string): string {
if (process.platform !== "win32") {
return command;
}
const basename = path.basename(command).toLowerCase();
const ext = path.extname(basename);
if (ext) {
return command;
}
const cmdCommands = ["npm", "yarn", "npx"];
if (cmdCommands.includes(basename)) {
return `${command}.cmd`;
}
return command;
}
function resolveCommandStdio(params: {
hasInput: boolean;
preferInherit: boolean;
}): ["pipe" | "inherit" | "ignore", "pipe", "pipe"] {
const stdin = params.hasInput ? "pipe" : params.preferInherit ? "inherit" : "pipe";
return [stdin, "pipe", "pipe"];
}
/**
* Simple promise-wrapped execFile with timeout support.
*
* @param command - The command to execute
* @param args - Command arguments
* @param opts - Timeout in ms or options object
* @returns Promise resolving to stdout and stderr
*/
export async function runExec(
command: string,
args: string[],
opts: number | { timeoutMs?: number; maxBuffer?: number } = 10_000
): Promise<{ stdout: string; stderr: string }> {
const options =
typeof opts === "number"
? { timeout: opts, encoding: "utf8" as const }
: {
timeout: opts.timeoutMs,
maxBuffer: opts.maxBuffer,
encoding: "utf8" as const,
};
const { stdout, stderr } = await execFileAsync(resolveCommand(command), args, options);
return { stdout, stderr };
}
/**
* Result from a spawned command execution.
*/
export type SpawnResult = {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
killed: boolean;
};
/**
* Options for running a command with timeout.
*/
export type CommandOptions = {
timeoutMs: number;
cwd?: string;
input?: string;
env?: NodeJS.ProcessEnv;
windowsVerbatimArguments?: boolean;
};
/**
* Run a command with timeout, input, and environment control.
*
* @param argv - Command and arguments as array
* @param optionsOrTimeout - Options object or timeout in ms
* @returns Promise resolving to spawn result
*/
export async function runCommandWithTimeout(
argv: string[],
optionsOrTimeout: number | CommandOptions
): Promise<SpawnResult> {
const mode = resolveRuntimeExecutionMode();
if (mode === "cloud") {
throw new Error("Local shell execution disabled in cloud mode.");
}
if (mode === "local-safe") {
throw new Error(
"[shell] runCommandWithTimeout cannot route through SandboxManager from this code path; use the runtime-aware shell action."
);
}
const options: CommandOptions =
typeof optionsOrTimeout === "number" ? { timeoutMs: optionsOrTimeout } : optionsOrTimeout;
const { timeoutMs, cwd, input, env } = options;
const { windowsVerbatimArguments } = options;
const hasInput = input !== undefined;
const shouldSuppressNpmFund = (() => {
const cmd = path.basename(argv[0] ?? "");
if (cmd === "npm" || cmd === "npm.cmd" || cmd === "npm.exe") {
return true;
}
if (cmd === "node" || cmd === "node.exe") {
const script = argv[1] ?? "";
return script.includes("npm-cli.js");
}
return false;
})();
const merged = env ? { ...process.env, ...env } : { ...process.env };
const resolvedEnv = sanitizeSpawnEnv(merged) as Record<string, string | undefined>;
if (shouldSuppressNpmFund) {
if (resolvedEnv.NPM_CONFIG_FUND == null) {
resolvedEnv.NPM_CONFIG_FUND = "false";
}
if (resolvedEnv.npm_config_fund == null) {
resolvedEnv.npm_config_fund = "false";
}
}
const stdio = resolveCommandStdio({ hasInput, preferInherit: true });
const child = spawn(resolveCommand(argv[0]), argv.slice(1), {
stdio,
cwd,
env: resolvedEnv,
windowsVerbatimArguments,
});
return await new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
let settled = false;
const timer = setTimeout(() => {
if (typeof child.kill === "function") {
child.kill("SIGKILL");
}
}, timeoutMs);
if (hasInput && child.stdin) {
child.stdin.write(input);
child.stdin.end();
}
child.stdout?.on("data", (d) => {
stdout += d.toString();
});
child.stderr?.on("data", (d) => {
stderr += d.toString();
});
child.on("error", (err) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
reject(err);
});
child.on("close", (code, signal) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
resolve({ stdout, stderr, code, signal, killed: child.killed });
});
});
}
// ============================================================================
// Command Queue
// ============================================================================
type QueueEntry = {
task: () => Promise<unknown>;
resolve: (value: unknown) => void;
reject: (reason?: unknown) => void;
enqueuedAt: number;
warnAfterMs: number;
onWait?: (waitMs: number, queuedAhead: number) => void;
};
type LaneState = {
lane: string;
queue: QueueEntry[];
active: number;
maxConcurrent: number;
draining: boolean;
};
const lanes = new Map<string, LaneState>();
function getLaneState(lane: string): LaneState {
const existing = lanes.get(lane);
if (existing) {
return existing;
}
const created: LaneState = {
lane,
queue: [],
active: 0,
maxConcurrent: 1,
draining: false,
};
lanes.set(lane, created);
return created;
}
function drainLane(lane: string) {
const state = getLaneState(lane);
if (state.draining) {
return;
}
state.draining = true;
const pump = () => {
while (state.active < state.maxConcurrent && state.queue.length > 0) {
const entry = state.queue.shift() as QueueEntry;
const waitedMs = Date.now() - entry.enqueuedAt;
if (waitedMs >= entry.warnAfterMs) {
entry.onWait?.(waitedMs, state.queue.length);
}
state.active += 1;
void (async () => {
try {
const result = await entry.task();
state.active -= 1;
pump();
entry.resolve(result);
} catch (err) {
// error-policy:J1 queue-worker boundary; the task failure is
// propagated to the awaiting caller via entry.reject (never
// swallowed), and the active count is decremented so the pump drains.
state.active -= 1;
pump();
entry.reject(err);
}
})();
}
state.draining = false;
};
pump();
}
/**
* Set the maximum concurrency for a command lane.
*
* @param lane - The lane name
* @param maxConcurrent - Maximum concurrent tasks
*/
export function setCommandLaneConcurrency(lane: string, maxConcurrent: number) {
const cleaned = lane.trim() || CommandLane.Main;
const state = getLaneState(cleaned);
state.maxConcurrent = Math.max(1, Math.floor(maxConcurrent));
drainLane(cleaned);
}
/**
* Enqueue a task to execute in a specific lane.
*
* @param lane - The lane name
* @param task - Async task function
* @param opts - Options including warning threshold and callbacks
* @returns Promise resolving when task completes
*/
export function enqueueCommandInLane<T>(
lane: string,
task: () => Promise<T>,
opts?: {
warnAfterMs?: number;
onWait?: (waitMs: number, queuedAhead: number) => void;
}
): Promise<T> {
const cleaned = lane.trim() || CommandLane.Main;
const warnAfterMs = opts?.warnAfterMs ?? 2_000;
const state = getLaneState(cleaned);
return new Promise<T>((resolve, reject) => {
state.queue.push({
task: () => task(),
resolve: (value) => resolve(value as T),
reject,
enqueuedAt: Date.now(),
warnAfterMs,
onWait: opts?.onWait,
});
drainLane(cleaned);
});
}
/**
* Enqueue a task to execute in the main lane.
*
* @param task - Async task function
* @param opts - Options including warning threshold and callbacks
* @returns Promise resolving when task completes
*/
export function enqueueCommand<T>(
task: () => Promise<T>,
opts?: {
warnAfterMs?: number;
onWait?: (waitMs: number, queuedAhead: number) => void;
}
): Promise<T> {
return enqueueCommandInLane(CommandLane.Main, task, opts);
}
/**
* Get the current queue size for a lane (queued + active).
*
* @param lane - The lane name (defaults to main)
* @returns Queue size
*/
export function getQueueSize(lane: string = CommandLane.Main): number {
const resolved = lane.trim() || CommandLane.Main;
const state = lanes.get(resolved);
if (!state) {
return 0;
}
return state.queue.length + state.active;
}
/**
* Get total queue size across all lanes.
*
* @returns Total queue size
*/
export function getTotalQueueSize(): number {
let total = 0;
for (const s of lanes.values()) {
total += s.queue.length + s.active;
}
return total;
}
/**
* Clear all pending tasks in a lane.
*
* @param lane - The lane name (defaults to main)
* @returns Number of tasks cleared
*/
export function clearCommandLane(lane: string = CommandLane.Main): number {
const cleaned = lane.trim() || CommandLane.Main;
const state = lanes.get(cleaned);
if (!state) {
return 0;
}
const removed = state.queue.length;
state.queue.length = 0;
return removed;
}
// ============================================================================
// Child Process Bridge
// ============================================================================
/**
* Options for attaching a child process signal bridge.
*/
export type ChildProcessBridgeOptions = {
signals?: NodeJS.Signals[];
onSignal?: (signal: NodeJS.Signals) => void;
};
const defaultSignals: NodeJS.Signals[] =
process.platform === "win32"
? ["SIGTERM", "SIGINT", "SIGBREAK"]
: ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
/**
* Attach signal forwarding from parent to child process.
* Signals sent to the parent will be forwarded to the child.
* Automatically detaches when child exits.
*
* @param child - The child process
* @param options - Bridge options
* @returns Object with detach function
*/
export function attachChildProcessBridge(
child: ChildProcess,
{ signals = defaultSignals, onSignal }: ChildProcessBridgeOptions = {}
): { detach: () => void } {
const listeners = new Map<NodeJS.Signals, () => void>();
for (const signal of signals) {
const listener = (): void => {
onSignal?.(signal);
try {
child.kill(signal);
} catch {
// error-policy:J6 best-effort signal forwarding; the child may have
// already exited, so a failed kill is a no-op.
}
};
try {
process.on(signal, listener);
listeners.set(signal, listener);
} catch {
// error-policy:J6 the signal is unsupported on this platform (e.g. SIGHUP
// on Windows); skipping its listener is the designed degrade.
}
}
const detach = (): void => {
for (const [signal, listener] of listeners) {
process.off(signal, listener);
}
listeners.clear();
};
child.once("exit", detach);
child.once("error", detach);
return { detach };
}
+323
View File
@@ -0,0 +1,323 @@
/**
* Encodes keyboard input into the escape sequences a PTY expects — bracketed
* paste, control keys, and named key sequences — and strips terminal DSR
* (device-status-report) requests from output. Used when driving interactive
* PTY sessions.
*/
const ESC = "\x1b";
const CR = "\r";
const TAB = "\t";
const BACKSPACE = "\x7f";
export const BRACKETED_PASTE_START = `${ESC}[200~`;
export const BRACKETED_PASTE_END = `${ESC}[201~`;
type Modifiers = {
ctrl: boolean;
alt: boolean;
shift: boolean;
};
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const namedKeyMap = new Map<string, string>([
["enter", CR],
["return", CR],
["tab", TAB],
["escape", ESC],
["esc", ESC],
["space", " "],
["bspace", BACKSPACE],
["backspace", BACKSPACE],
["up", `${ESC}[A`],
["down", `${ESC}[B`],
["right", `${ESC}[C`],
["left", `${ESC}[D`],
["home", `${ESC}[1~`],
["end", `${ESC}[4~`],
["pageup", `${ESC}[5~`],
["pgup", `${ESC}[5~`],
["ppage", `${ESC}[5~`],
["pagedown", `${ESC}[6~`],
["pgdn", `${ESC}[6~`],
["npage", `${ESC}[6~`],
["insert", `${ESC}[2~`],
["ic", `${ESC}[2~`],
["delete", `${ESC}[3~`],
["del", `${ESC}[3~`],
["dc", `${ESC}[3~`],
["btab", `${ESC}[Z`],
["f1", `${ESC}OP`],
["f2", `${ESC}OQ`],
["f3", `${ESC}OR`],
["f4", `${ESC}OS`],
["f5", `${ESC}[15~`],
["f6", `${ESC}[17~`],
["f7", `${ESC}[18~`],
["f8", `${ESC}[19~`],
["f9", `${ESC}[20~`],
["f10", `${ESC}[21~`],
["f11", `${ESC}[23~`],
["f12", `${ESC}[24~`],
["kp/", `${ESC}Oo`],
["kp*", `${ESC}Oj`],
["kp-", `${ESC}Om`],
["kp+", `${ESC}Ok`],
["kp7", `${ESC}Ow`],
["kp8", `${ESC}Ox`],
["kp9", `${ESC}Oy`],
["kp4", `${ESC}Ot`],
["kp5", `${ESC}Ou`],
["kp6", `${ESC}Ov`],
["kp1", `${ESC}Oq`],
["kp2", `${ESC}Or`],
["kp3", `${ESC}Os`],
["kp0", `${ESC}Op`],
["kp.", `${ESC}On`],
["kpenter", `${ESC}OM`],
]);
const modifiableNamedKeys = new Set([
"up",
"down",
"left",
"right",
"home",
"end",
"pageup",
"pgup",
"ppage",
"pagedown",
"pgdn",
"npage",
"insert",
"ic",
"delete",
"del",
"dc",
]);
export type KeyEncodingRequest = {
keys?: string[];
hex?: string[];
literal?: string;
};
export type KeyEncodingResult = {
data: string;
warnings: string[];
};
export function encodeKeySequence(request: KeyEncodingRequest): KeyEncodingResult {
const warnings: string[] = [];
let data = "";
if (request.literal) {
data += request.literal;
}
if (request.hex?.length) {
for (const raw of request.hex) {
const byte = parseHexByte(raw);
if (byte === null) {
warnings.push(`Invalid hex byte: ${raw}`);
continue;
}
data += String.fromCharCode(byte);
}
}
if (request.keys?.length) {
for (const token of request.keys) {
data += encodeKeyToken(token, warnings);
}
}
return { data, warnings };
}
export function encodePaste(text: string, bracketed = true): string {
if (!bracketed) {
return text;
}
return `${BRACKETED_PASTE_START}${text}${BRACKETED_PASTE_END}`;
}
function encodeKeyToken(raw: string, warnings: string[]): string {
const token = raw.trim();
if (!token) {
return "";
}
if (token.length === 2 && token.startsWith("^")) {
const ctrl = toCtrlChar(token[1]);
if (ctrl) {
return ctrl;
}
}
const parsed = parseModifiers(token);
const base = parsed.base;
const baseLower = base.toLowerCase();
if (baseLower === "tab" && parsed.mods.shift) {
return `${ESC}[Z`;
}
const baseSeq = namedKeyMap.get(baseLower);
if (baseSeq) {
let seq = baseSeq;
if (modifiableNamedKeys.has(baseLower) && hasAnyModifier(parsed.mods)) {
const mod = xtermModifier(parsed.mods);
if (mod > 1) {
const modified = applyXtermModifier(seq, mod);
if (modified) {
seq = modified;
return seq;
}
}
}
if (parsed.mods.alt) {
return `${ESC}${seq}`;
}
return seq;
}
if (base.length === 1) {
return applyCharModifiers(base, parsed.mods);
}
if (parsed.hasModifiers) {
warnings.push(`Unknown key "${base}" for modifiers; sending literal.`);
}
return base;
}
function parseModifiers(token: string): {
mods: Modifiers;
base: string;
hasModifiers: boolean;
} {
const mods: Modifiers = { ctrl: false, alt: false, shift: false };
let rest = token;
let sawModifiers = false;
while (rest.length > 2 && rest[1] === "-") {
const mod = rest[0].toLowerCase();
if (mod === "c") {
mods.ctrl = true;
} else if (mod === "m") {
mods.alt = true;
} else if (mod === "s") {
mods.shift = true;
} else {
break;
}
sawModifiers = true;
rest = rest.slice(2);
}
return { mods, base: rest, hasModifiers: sawModifiers };
}
function applyCharModifiers(char: string, mods: Modifiers): string {
let value = char;
if (mods.shift && value.length === 1 && /[a-z]/.test(value)) {
value = value.toUpperCase();
}
if (mods.ctrl) {
const ctrl = toCtrlChar(value);
if (ctrl) {
value = ctrl;
}
}
if (mods.alt) {
value = `${ESC}${value}`;
}
return value;
}
function toCtrlChar(char: string): string | null {
if (char.length !== 1) {
return null;
}
if (char === "?") {
return "\x7f";
}
const code = char.toUpperCase().charCodeAt(0);
if (code >= 64 && code <= 95) {
return String.fromCharCode(code & 0x1f);
}
return null;
}
function xtermModifier(mods: Modifiers): number {
let mod = 1;
if (mods.shift) {
mod += 1;
}
if (mods.alt) {
mod += 2;
}
if (mods.ctrl) {
mod += 4;
}
return mod;
}
function applyXtermModifier(sequence: string, modifier: number): string | null {
const escPattern = escapeRegExp(ESC);
const csiNumber = new RegExp(`^${escPattern}\\[(\\d+)([~A-Z])$`);
const csiArrow = new RegExp(`^${escPattern}\\[(A|B|C|D|H|F)$`);
const numberMatch = sequence.match(csiNumber);
if (numberMatch) {
return `${ESC}[${numberMatch[1]};${modifier}${numberMatch[2]}`;
}
const arrowMatch = sequence.match(csiArrow);
if (arrowMatch) {
return `${ESC}[1;${modifier}${arrowMatch[1]}`;
}
return null;
}
function hasAnyModifier(mods: Modifiers): boolean {
return mods.ctrl || mods.alt || mods.shift;
}
function parseHexByte(raw: string): number | null {
const trimmed = raw.trim().toLowerCase();
const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
if (!/^[0-9a-f]{1,2}$/.test(normalized)) {
return null;
}
const value = Number.parseInt(normalized, 16);
if (Number.isNaN(value) || value < 0 || value > 0xff) {
return null;
}
return value;
}
// DSR (Device Status Report) handling
const DSR_PATTERN = new RegExp(`${ESC}\\[\\??6n`, "g");
export function stripDsrRequests(input: string): {
cleaned: string;
requests: number;
} {
let requests = 0;
const cleaned = input.replace(DSR_PATTERN, () => {
requests += 1;
return "";
});
return { cleaned, requests };
}
export function buildCursorPositionResponse(row = 1, col = 1): string {
return `\x1b[${row};${col}R`;
}
+98
View File
@@ -0,0 +1,98 @@
/**
* Shell argument parsing utilities.
*
* Provides functions to split shell command strings into argument arrays,
* handling quotes and escape sequences.
*
* @module utils/shellArgv
*/
/**
* Split a shell command string into an array of arguments.
*
* Handles:
* - Single quotes (literal strings)
* - Double quotes (literal strings)
* - Backslash escapes (outside quotes)
* - Whitespace as argument separator
*
* @param raw - The raw command string
* @returns Array of arguments, or null if string has unclosed quotes/escapes
*
* @example
* ```ts
* splitShellArgs('git commit -m "fix bug"')
* // => ['git', 'commit', '-m', 'fix bug']
*
* splitShellArgs("echo 'hello world'")
* // => ['echo', 'hello world']
*
* splitShellArgs('path\\ with\\ spaces')
* // => ['path with spaces']
*
* splitShellArgs('"unclosed')
* // => null (unclosed quote)
* ```
*/
export function splitShellArgs(raw: string): string[] | null {
const tokens: string[] = [];
let buf = "";
let inSingle = false;
let inDouble = false;
let escaped = false;
const pushToken = () => {
if (buf.length > 0) {
tokens.push(buf);
buf = "";
}
};
for (let i = 0; i < raw.length; i += 1) {
const ch = raw[i];
if (escaped) {
buf += ch;
escaped = false;
continue;
}
if (!inSingle && !inDouble && ch === "\\") {
escaped = true;
continue;
}
if (inSingle) {
if (ch === "'") {
inSingle = false;
} else {
buf += ch;
}
continue;
}
if (inDouble) {
if (ch === '"') {
inDouble = false;
} else {
buf += ch;
}
continue;
}
if (ch === "'") {
inSingle = true;
continue;
}
if (ch === '"') {
inDouble = true;
continue;
}
if (/\s/.test(ch)) {
pushToken();
continue;
}
buf += ch;
}
if (escaped || inSingle || inDouble) {
return null;
}
pushToken();
return tokens;
}
+484
View File
@@ -0,0 +1,484 @@
/**
* Platform-specific shell helpers shared across the plugin: resolving the shell
* config, spawning with a PTY-to-cross-spawn fallback, killing sessions,
* sanitizing binary output, and slicing captured log lines.
*/
import type {
ChildProcess,
ChildProcessWithoutNullStreams,
SpawnOptions,
} from "node:child_process";
import { spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";
import { resolveExecutable, resolveTerminalShell } from "./terminalCapabilities";
const CHUNK_LIMIT = 8 * 1024;
/**
* Resolve PowerShell path on Windows
*/
function resolvePowerShellPath(): string {
const systemRoot = process.env.SystemRoot || process.env.WINDIR;
if (systemRoot) {
const candidate = path.join(
systemRoot,
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe"
);
if (existsSync(candidate)) {
return candidate;
}
}
return "powershell.exe";
}
/**
* Get shell configuration for the current platform
*/
export function getShellConfig(): { shell: string; args: string[] } {
if (process.platform === "win32") {
// Use PowerShell instead of cmd.exe on Windows.
// Many Windows system utilities write directly to the console via WriteConsole API,
// bypassing stdout pipes. PowerShell properly captures and redirects their output.
return {
shell: resolvePowerShellPath(),
args: ["-NoProfile", "-NonInteractive", "-Command"],
};
}
const envShell = process.env.SHELL?.trim();
const shellName = envShell ? path.basename(envShell) : "";
// Fish rejects common bashisms used by tools, so prefer bash when detected.
if (shellName === "fish") {
const bash = resolveExecutable("bash");
if (bash) {
return { shell: bash, args: ["-c"] };
}
const sh = resolveExecutable("sh");
if (sh) {
return { shell: sh, args: ["-c"] };
}
}
const resolved = resolveTerminalShell();
return { shell: resolved.shell, args: resolved.args };
}
/**
* Sanitize binary output by removing control characters
*/
export function sanitizeBinaryOutput(text: string): string {
const scrubbed = text.replace(/[\p{Format}\p{Surrogate}]/gu, "");
if (!scrubbed) {
return scrubbed;
}
const chunks: string[] = [];
for (const char of scrubbed) {
const code = char.codePointAt(0);
if (code == null) {
continue;
}
if (code === 0x09 || code === 0x0a || code === 0x0d) {
chunks.push(char);
continue;
}
if (code < 0x20) {
continue;
}
chunks.push(char);
}
return chunks.join("");
}
/**
* Kill a process tree (cross-platform)
*/
export function killProcessTree(pid: number): void {
if (process.platform === "win32") {
try {
spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
stdio: "ignore",
detached: true,
});
} catch {
// error-policy:J6 best-effort teardown; a failed taskkill spawn leaves
// the tree for the OS to reap and must not throw out of cleanup.
}
return;
}
try {
process.kill(-pid, "SIGKILL");
} catch {
// error-policy:J6 process-group kill failed (no group / already gone) →
// fall back to a single-pid kill during teardown.
try {
process.kill(pid, "SIGKILL");
} catch {
// error-policy:J6 best-effort teardown; the process is already dead.
}
}
}
/**
* Kill a session's process
*/
export function killSession(session: {
pid?: number;
child?: ChildProcessWithoutNullStreams;
}): void {
const pid = session.pid ?? session.child?.pid;
if (pid) {
killProcessTree(pid);
}
}
/**
* Coerce environment object to Record<string, string>
*/
export function coerceEnv(
env?: NodeJS.ProcessEnv | Record<string, string>
): Record<string, string> {
const record: Record<string, string> = {};
if (!env) {
return record;
}
for (const [key, value] of Object.entries(env)) {
if (typeof value === "string") {
record[key] = value;
}
}
return record;
}
/**
* Resolve working directory with fallback
*/
export function resolveWorkdir(workdir: string, warnings: string[]): string {
const current = safeCwd();
const fallback = current ?? homedir();
try {
const stats = statSync(workdir);
if (stats.isDirectory()) {
return workdir;
}
} catch {
// error-policy:J4 designed degrade; an unavailable workdir falls back to the
// process cwd/home and the substitution is surfaced to the caller via the
// `warnings` array below (never silently swapped).
}
warnings.push(`Warning: workdir "${workdir}" is unavailable; using "${fallback}".`);
return fallback;
}
function safeCwd(): string | null {
try {
const cwd = process.cwd();
return existsSync(cwd) ? cwd : null;
} catch {
// error-policy:J3 cwd probe; process.cwd() throws when the working
// directory was deleted out from under the process — null is the miss.
return null;
}
}
/**
* Clamp a number to a range with a default value
*/
export function clampNumber(
value: number | undefined,
defaultValue: number,
min: number,
max: number
): number {
if (value === undefined || Number.isNaN(value)) {
return defaultValue;
}
return Math.min(Math.max(value, min), max);
}
/**
* Read an environment variable as an integer
*/
export function readEnvInt(key: string): number | undefined {
const raw = process.env[key];
if (!raw) {
return undefined;
}
const parsed = Number.parseInt(raw, 10);
return Number.isFinite(parsed) ? parsed : undefined;
}
/**
* Chunk a string into smaller pieces
*/
export function chunkString(input: string, limit = CHUNK_LIMIT): string[] {
const chunks: string[] = [];
for (let i = 0; i < input.length; i += limit) {
chunks.push(input.slice(i, i + limit));
}
return chunks;
}
/**
* Safely slice a string respecting UTF-16 surrogate pairs
*/
export function sliceUtf16Safe(str: string, start: number, end?: number): string {
const effectiveEnd = end ?? str.length;
if (start < 0) {
const adjustedStart = Math.max(0, str.length + start);
return str.slice(adjustedStart, effectiveEnd);
}
return str.slice(start, effectiveEnd);
}
/**
* Truncate string in the middle with ellipsis
*/
export function truncateMiddle(str: string, max: number): string {
if (str.length <= max) {
return str;
}
const half = Math.floor((max - 3) / 2);
return `${sliceUtf16Safe(str, 0, half)}...${sliceUtf16Safe(str, -half)}`;
}
/**
* Slice log lines with optional offset and limit
*/
export function sliceLogLines(
text: string,
offset?: number,
limit?: number
): { slice: string; totalLines: number; totalChars: number } {
if (!text) {
return { slice: "", totalLines: 0, totalChars: 0 };
}
const normalized = text.replace(/\r\n/g, "\n");
const lines = normalized.split("\n");
if (lines.length > 0 && lines[lines.length - 1] === "") {
lines.pop();
}
const totalLines = lines.length;
const totalChars = text.length;
let start =
typeof offset === "number" && Number.isFinite(offset) ? Math.max(0, Math.floor(offset)) : 0;
if (limit !== undefined && offset === undefined) {
const tailCount = Math.max(0, Math.floor(limit));
start = Math.max(totalLines - tailCount, 0);
}
const end =
typeof limit === "number" && Number.isFinite(limit)
? start + Math.max(0, Math.floor(limit))
: undefined;
return { slice: lines.slice(start, end).join("\n"), totalLines, totalChars };
}
/**
* Derive a session name from a command
*/
export function deriveSessionName(command: string): string | undefined {
const tokens = tokenizeCommand(command);
if (tokens.length === 0) {
return undefined;
}
const verb = tokens[0];
let target = tokens.slice(1).find((t) => !t.startsWith("-"));
if (!target) {
target = tokens[1];
}
if (!target) {
return verb;
}
const cleaned = truncateMiddle(stripQuotes(target), 48);
return `${stripQuotes(verb)} ${cleaned}`;
}
function tokenizeCommand(command: string): string[] {
const matches = command.match(/(?:[^\s"']+|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+/g) ?? [];
return matches.map((token) => stripQuotes(token)).filter(Boolean);
}
function stripQuotes(value: string): string {
const trimmed = value.trim();
if (
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
) {
return trimmed.slice(1, -1);
}
return trimmed;
}
/**
* Format duration in human-readable format
*/
export function formatDuration(ms: number): string {
if (ms < 1000) {
return `${ms}ms`;
}
const seconds = Math.floor(ms / 1000);
if (seconds < 60) {
return `${seconds}s`;
}
const minutes = Math.floor(seconds / 60);
const rem = seconds % 60;
return `${minutes}m${rem.toString().padStart(2, "0")}s`;
}
/**
* Pad a string to a minimum width
*/
export function pad(str: string, width: number): string {
if (str.length >= width) {
return str;
}
return str + " ".repeat(width - str.length);
}
// ===== Spawn Utilities =====
export type SpawnFallback = {
label: string;
options: SpawnOptions;
};
export type SpawnWithFallbackResult = {
child: ChildProcess;
usedFallback: boolean;
fallbackLabel?: string;
};
type SpawnWithFallbackParams = {
argv: string[];
options: SpawnOptions;
fallbacks?: SpawnFallback[];
spawnImpl?: typeof spawn;
retryCodes?: string[];
onFallback?: (err: unknown, fallback: SpawnFallback) => void;
};
const DEFAULT_RETRY_CODES = ["EBADF"];
/**
* Format a spawn error for display
*/
export function formatSpawnError(err: unknown): string {
if (!(err instanceof Error)) {
return String(err);
}
const details = err as NodeJS.ErrnoException;
const parts: string[] = [];
const message = err.message.trim();
if (message) {
parts.push(message);
}
if (details.code && !message.includes(details.code)) {
parts.push(details.code);
}
if (details.syscall) {
parts.push(`syscall=${details.syscall}`);
}
if (typeof details.errno === "number") {
parts.push(`errno=${details.errno}`);
}
return parts.join(" ");
}
function shouldRetry(err: unknown, codes: string[]): boolean {
const code =
err && typeof err === "object" && "code" in err ? String((err as { code?: unknown }).code) : "";
return code.length > 0 && codes.includes(code);
}
async function spawnAndWaitForSpawn(
spawnImpl: typeof spawn,
argv: string[],
options: SpawnOptions
): Promise<ChildProcess> {
const child = spawnImpl(argv[0], argv.slice(1), options);
return await new Promise((resolve, reject) => {
let settled = false;
const cleanup = () => {
child.removeListener("error", onError);
child.removeListener("spawn", onSpawn);
};
const finishResolve = () => {
if (settled) {
return;
}
settled = true;
cleanup();
resolve(child);
};
const onError = (err: unknown) => {
if (settled) {
return;
}
settled = true;
cleanup();
reject(err);
};
const onSpawn = () => {
finishResolve();
};
child.once("error", onError);
child.once("spawn", onSpawn);
// Ensure mocked spawns that never emit "spawn" don't stall.
process.nextTick(() => {
if (typeof child.pid === "number") {
finishResolve();
}
});
});
}
/**
* Spawn a process with fallback options on certain error codes
*/
export async function spawnWithFallback(
params: SpawnWithFallbackParams
): Promise<SpawnWithFallbackResult> {
const spawnImpl = params.spawnImpl ?? spawn;
const retryCodes = params.retryCodes ?? DEFAULT_RETRY_CODES;
const baseOptions = { ...params.options };
const fallbacks = params.fallbacks ?? [];
const attempts: Array<{ label?: string; options: SpawnOptions }> = [
{ options: baseOptions },
...fallbacks.map((fallback) => ({
label: fallback.label,
options: { ...baseOptions, ...fallback.options },
})),
];
let lastError: unknown;
for (let index = 0; index < attempts.length; index += 1) {
const attempt = attempts[index];
try {
const child = await spawnAndWaitForSpawn(spawnImpl, params.argv, attempt.options);
return {
child,
usedFallback: index > 0,
fallbackLabel: attempt.label,
};
} catch (err) {
// error-policy:J4 designed spawn-fallback retry; a retryable spawn error
// advances to the next fallback shell, but a non-retryable error (or the
// exhausted fallback list) rethrows immediately — the failure is surfaced,
// not masked by silently trying alternatives forever.
lastError = err;
const nextFallback = fallbacks[index];
if (!nextFallback || !shouldRetry(err, retryCodes)) {
throw err;
}
params.onFallback?.(err, nextFallback);
}
}
throw lastError;
}
@@ -0,0 +1,269 @@
/**
* Terminal-capability detection: enumerates known terminal tool names, detects
* whether a usable terminal/shell exists in the environment, resolves the shell
* and executables to run, and reports the missing tool for a given command.
*/
import fs from "node:fs";
import path from "node:path";
export const TERMINAL_TOOL_NAMES = [
"sh",
"git",
"rg",
"bun",
"acpx",
"codex",
"claude",
"opencode",
] as const;
export type TerminalToolName = (typeof TERMINAL_TOOL_NAMES)[number];
export interface ToolCapability {
name: TerminalToolName;
path?: string;
available: boolean;
}
export interface ShellResolution {
shell: string;
args: string[];
available: boolean;
source: "env:CODING_TOOLS_SHELL" | "env:SHELL" | "candidate" | "fallback";
warning?: string;
}
export type TerminalUnsupportedReason =
| "store_build"
| "vanilla_mobile"
| "not_local_yolo"
| "missing_shell";
export interface TerminalSupport {
supported: boolean;
reason?: TerminalUnsupportedReason;
message?: string;
}
const ANDROID_PATH_ENTRIES = ["/system/bin", "/system/xbin", "/vendor/bin"];
export function isAndroidRuntime(): boolean {
return (
process.env.ELIZA_PLATFORM?.trim().toLowerCase() === "android" ||
Boolean(process.env.ANDROID_ROOT || process.env.ANDROID_DATA)
);
}
function isIosRuntime(): boolean {
return process.env.ELIZA_PLATFORM?.trim().toLowerCase() === "ios";
}
function isTruthyEnv(value: string | undefined): boolean {
if (!value) return false;
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
function isStoreBuild(): boolean {
const variant = process.env.ELIZA_BUILD_VARIANT ?? "";
return variant.trim().toLowerCase() === "store";
}
function runtimeMode(): string {
return (
process.env.ELIZA_RUNTIME_MODE ??
process.env.RUNTIME_MODE ??
process.env.LOCAL_RUNTIME_MODE ??
""
)
.trim()
.toLowerCase();
}
export function isAospTerminalRuntime(): boolean {
return isAndroidRuntime() && isTruthyEnv(process.env.ELIZA_AOSP_BUILD);
}
function executableExists(candidate: string): boolean {
try {
fs.accessSync(candidate, fs.constants.X_OK);
return true;
} catch {
// error-policy:J3 existence/permission probe; access failure means the
// candidate is absent or not executable — false is the expected miss.
return false;
}
}
function pathEntries(): string[] {
const entries = (process.env.PATH ?? "")
.split(path.delimiter)
.map((entry) => entry.trim())
.filter(Boolean);
if (isAndroidRuntime()) {
for (const entry of ANDROID_PATH_ENTRIES) {
if (!entries.includes(entry)) entries.push(entry);
}
}
return entries;
}
export function resolveExecutable(nameOrPath: string): string | undefined {
const trimmed = nameOrPath.trim();
if (!trimmed) return undefined;
if (trimmed.includes("/") || path.isAbsolute(trimmed)) {
return executableExists(trimmed) ? trimmed : undefined;
}
for (const entry of pathEntries()) {
const candidate = path.join(entry, trimmed);
if (executableExists(candidate)) return candidate;
}
return undefined;
}
function firstExecutable(candidates: readonly string[]): string | undefined {
for (const candidate of candidates) {
const resolved = resolveExecutable(candidate);
if (resolved) return resolved;
}
return undefined;
}
export function resolveTerminalShell(): ShellResolution {
const explicitEntries = [
["CODING_TOOLS_SHELL", process.env.CODING_TOOLS_SHELL] as const,
["SHELL", process.env.SHELL] as const,
];
for (const [key, raw] of explicitEntries) {
const value = raw?.trim();
if (!value) continue;
const resolved = resolveExecutable(value);
if (resolved) {
return {
shell: resolved,
args: ["-c"],
available: true,
source: key === "CODING_TOOLS_SHELL" ? "env:CODING_TOOLS_SHELL" : "env:SHELL",
};
}
}
const candidates = isAndroidRuntime()
? ["/system/bin/sh", "sh"]
: ["/bin/bash", "bash", "/bin/sh", "sh"];
const shell = firstExecutable(candidates);
if (shell) {
return {
shell,
args: ["-c"],
available: true,
source: "candidate",
};
}
return {
shell: isAndroidRuntime() ? "/system/bin/sh" : "sh",
args: ["-c"],
available: false,
source: "fallback",
warning: isAndroidRuntime()
? "No executable POSIX shell was detected. Android direct/AOSP local-yolo builds must expose /system/bin/sh or set CODING_TOOLS_SHELL to an executable shell."
: "No executable POSIX shell was detected. Set SHELL or CODING_TOOLS_SHELL to an executable shell.",
};
}
export function detectTerminalCapabilities(): ToolCapability[] {
return TERMINAL_TOOL_NAMES.map((name) => {
if (name === "sh") {
const shell = resolveTerminalShell();
return {
name,
path: shell.available ? shell.shell : undefined,
available: shell.available,
};
}
const resolved = resolveExecutable(name);
return {
name,
path: resolved,
available: Boolean(resolved),
};
});
}
export function formatTerminalCapabilities(capabilities = detectTerminalCapabilities()): string {
return capabilities
.map((capability) =>
capability.available
? `${capability.name}=ok(${capability.path})`
: `${capability.name}=missing`
)
.join(" ");
}
export function missingToolMessage(tool: TerminalToolName): string {
if (tool === "sh") {
return resolveTerminalShell().warning ?? "No executable shell was detected.";
}
const suffix = isAndroidRuntime()
? " On Android direct/AOSP builds, ensure the binary is staged into the agent image and PATH includes /system/bin or the tool's install directory."
: " Install it or add it to PATH.";
return `${tool} CLI is not available in PATH.${suffix}`;
}
export function missingTerminalToolForCommand(command: string): TerminalToolName | undefined {
const tokens = command.trim().split(/\s+/).filter(Boolean);
let index = 0;
while (tokens[index] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index])) {
index += 1;
}
const first = tokens[index]?.replace(/^["']|["']$/g, "");
if (!first) return undefined;
const name = path.basename(first) as TerminalToolName;
if (!(TERMINAL_TOOL_NAMES as readonly string[]).includes(name) || name === "sh") {
return undefined;
}
return resolveExecutable(first) ? undefined : name;
}
export function detectTerminalSupport(): TerminalSupport {
if (isStoreBuild()) {
return {
supported: false,
reason: "store_build",
message:
"Local terminal execution is unavailable in store builds because the OS sandbox blocks spawning local shells and developer CLIs.",
};
}
if (isIosRuntime()) {
return {
supported: false,
reason: "vanilla_mobile",
message:
"Local terminal execution is unavailable on iOS because the runtime does not expose shell, coding, or orchestrator subprocess capabilities.",
};
}
if (isAndroidRuntime()) {
if (runtimeMode() !== "local-yolo") {
return {
supported: false,
reason: "not_local_yolo",
message:
"Android direct/AOSP terminal execution requires ELIZA_RUNTIME_MODE=local-yolo so commands run in the local agent environment.",
};
}
const shell = resolveTerminalShell();
if (!shell.available) {
return {
supported: false,
reason: "missing_shell",
message:
shell.warning ??
"Android direct/AOSP terminal execution requires an executable shell. Set CODING_TOOLS_SHELL or SHELL to a staged shell binary.",
};
}
}
return { supported: true };
}