electron-cli-integration
Integrate external CLI tools (Claude, Node, npx) in Electron apps with proper PATH handling
What this skill does
# Electron CLI Integration Skill
When Electron apps launch from Finder/Explorer, the PATH is minimal. This skill covers detecting and using CLI tools reliably.
## The PATH Problem
When launched from terminal:
```
PATH=/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin:~/.nvm/versions/node/v20/bin:...
```
When launched from Finder (macOS):
```
PATH=/usr/bin:/bin:/usr/sbin:/sbin
```
## CLI Detector Pattern
```typescript
// electron/cli-detector.ts
import { exec } from 'child_process';
import { promisify } from 'util';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
const execAsync = promisify(exec);
export interface CliStatus {
found: boolean;
path?: string;
version?: string;
error?: string;
}
// Common installation paths for various tools
function getCommonPaths(toolName: string): string[] {
const home = os.homedir();
return [
// Homebrew (macOS)
`/usr/local/bin/${toolName}`,
`/opt/homebrew/bin/${toolName}`,
// User-local installations
path.join(home, '.local', 'bin', toolName),
// Tool-specific locations
path.join(home, '.claude', 'bin', toolName),
// Node.js via nvm
path.join(home, '.nvm', 'versions', 'node', 'current', 'bin', toolName),
// System paths
`/usr/bin/${toolName}`,
// Windows-specific (if on Windows)
path.join(home, 'AppData', 'Roaming', 'npm', `${toolName}.cmd`),
`C:\\Program Files\\nodejs\\${toolName}.cmd`,
];
}
function isExecutable(filePath: string): boolean {
try {
fs.accessSync(filePath, fs.constants.X_OK);
return true;
} catch {
return false;
}
}
function findInCommonPaths(toolName: string): string | null {
for (const toolPath of getCommonPaths(toolName)) {
if (fs.existsSync(toolPath) && isExecutable(toolPath)) {
return toolPath;
}
}
return null;
}
export async function detectCli(toolName: string): Promise<CliStatus> {
// First, check common installation paths
let toolPath = findInCommonPaths(toolName);
// If not found, try 'which' command (works if terminal has full PATH)
if (!toolPath) {
try {
const which = await import('which');
toolPath = await which.default(toolName);
} catch {
// Not found in PATH either
}
}
if (!toolPath) {
return {
found: false,
error: `${toolName} not found. Check common installation paths or ensure it's in your PATH.`,
};
}
// Get version
try {
const { stdout } = await execAsync(`"${toolPath}" --version`, {
timeout: 5000,
});
const version = stdout.trim();
return {
found: true,
path: toolPath,
version,
};
} catch {
// Found but couldn't get version
return {
found: true,
path: toolPath,
error: `Found ${toolName} but could not determine version`,
};
}
}
// Specific detectors for common tools
export async function detectClaudeCli(): Promise<CliStatus> {
return detectCli('claude');
}
export async function detectNode(): Promise<CliStatus> {
return detectCli('node');
}
export async function detectNpx(): Promise<CliStatus> {
return detectCli('npx');
}
```
## Using CLI Tools at Runtime
### Spawning with Safe Paths
```typescript
// src/server/services/cli-runner.ts
import { spawn } from 'child_process';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
interface SpawnOptions {
args: string[];
cwd?: string;
env?: NodeJS.ProcessEnv;
onStdout?: (data: string) => void;
onStderr?: (data: string) => void;
}
// Get safe working directory (not root!)
function getSafeWorkingDir(): string {
if (process.env.ELECTRON_DB_PATH) {
return path.dirname(process.env.ELECTRON_DB_PATH);
}
return os.tmpdir();
}
// Find executable in common paths
function findExecutable(name: string): string {
const home = os.homedir();
const paths = [
`/usr/local/bin/${name}`,
`/opt/homebrew/bin/${name}`,
path.join(home, '.local', 'bin', name),
path.join(home, '.nvm/versions/node/current/bin', name),
`/usr/bin/${name}`,
];
for (const p of paths) {
try {
fs.accessSync(p, fs.constants.X_OK);
return p;
} catch {}
}
// Fallback - hope it's in PATH
return name;
}
export async function runCli(
toolName: string,
options: SpawnOptions
): Promise<{ exitCode: number; stdout: string; stderr: string }> {
return new Promise((resolve) => {
const toolPath = process.env[`${toolName.toUpperCase()}_PATH`] || findExecutable(toolName);
const cwd = options.cwd || getSafeWorkingDir();
let stdout = '';
let stderr = '';
// Use bash to ensure proper environment
const fullCommand = `"${toolPath}" ${options.args.map((a) => `"${a}"`).join(' ')}`;
const proc = spawn('/bin/bash', ['-c', fullCommand], {
cwd,
env: { ...process.env, ...options.env },
stdio: ['pipe', 'pipe', 'pipe'],
});
proc.stdout.on('data', (data) => {
const text = data.toString();
stdout += text;
options.onStdout?.(text);
});
proc.stderr.on('data', (data) => {
const text = data.toString();
stderr += text;
options.onStderr?.(text);
});
proc.on('close', (code) => {
resolve({
exitCode: code ?? 1,
stdout,
stderr,
});
});
proc.on('error', (err) => {
resolve({
exitCode: 1,
stdout,
stderr: err.message,
});
});
});
}
```
### Claude CLI Integration
```typescript
// src/server/services/claude-cli.ts
import { spawn } from 'child_process';
import * as path from 'path';
import * as os from 'os';
function getClaudePath(): string {
// Check environment variable first (set by main process)
if (process.env.CLAUDE_PATH) {
return process.env.CLAUDE_PATH;
}
// Search common paths
const home = os.homedir();
const paths = [
'/usr/local/bin/claude',
'/opt/homebrew/bin/claude',
path.join(home, '.local', 'bin', 'claude'),
path.join(home, '.claude', 'bin', 'claude'),
];
for (const p of paths) {
try {
require('fs').accessSync(p, require('fs').constants.X_OK);
return p;
} catch {}
}
return 'claude'; // Fallback
}
function getSafeWorkingDir(): string {
if (process.env.ELECTRON_DB_PATH) {
return path.dirname(process.env.ELECTRON_DB_PATH);
}
return os.tmpdir();
}
export async function runClaudeCommand(
prompt: string
): Promise<{ success: boolean; output: string; error?: string }> {
return new Promise((resolve) => {
const claudePath = getClaudePath();
const proc = spawn('/bin/bash', ['-c', `"${claudePath}" --print --output-format text`], {
cwd: getSafeWorkingDir(),
env: { ...process.env },
stdio: ['pipe', 'pipe', 'pipe'],
});
let output = '';
let error = '';
// Write prompt to stdin
proc.stdin.write(prompt);
proc.stdin.end();
proc.stdout.on('data', (data) => {
output += data.toString();
});
proc.stderr.on('data', (data) => {
error += data.toString();
});
proc.on('close', (code) => {
if (code === 0 && output.trim()) {
resolve({ success: true, output: output.trim() });
} else {
resolve({
success: false,
output,
error: error || 'Command failed',
});
}
});
proc.on('error', (err) => {
resolve({
success: false,
output: '',
error: err.message,
});
});
});
}
```
### Running npx Without .bin Directory
In packaged apps, `node_modules/.bin` doesn't exist. Call CLI scripts directly:
```typescript
// src/server/services/remotion-runner.ts
import { spawn } from 'child_process';
import * as path from 'path';
import * as os from 'os';
function findNodePath(): string {
const home = os.homedir();
const paths = [
'/usr/local/bin/node',
'/opt/homebrew/bin/node',
path.join(home, '.nvm/versions/node/current/bin/node'),
];
const Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.