npm package: @indusagi/bg-process
Description: Background process manager extension for indusagi. Run long-running commands (dev servers, builds, tests) without blocking your AI agent workflow.
Author: Varun Israni
Latest version: 1.0.0

# @indusagi/bg-process - Background Process Extension

Manage background processes directly from your indusagi coding agent. Start long-running commands (dev servers, build processes, tests) without blocking your workflow.

## Overview

The `@indusagi/bg-process` extension provides a complete background process management system for indusagi. Run commands in the background, monitor their output, get alerts on completion, and manage them all from your AI agent.

### What It Does

- 🚀 **Start processes in background** - Run `npm run dev`, builds, tests, etc. without blocking
- 📊 **Monitor processes** - List all running processes with status and info
- 📝 **Stream output** - Get stdout/stderr in real-time or on demand
- 🎯 **Smart alerts** - Get notified when processes succeed, fail, or crash
- 🧹 **Auto-cleanup** - Automatic cleanup when session ends
- 📂 **File-based logging** - All output stored in temp files, not memory
- 🎮 **Interactive CLI** - Full keyboard-driven UI for process management

## Installation

### Method 1: With indusagi-coding-agent (Recommended)

The extension is already integrated! Load it with the `-e` flag:

```bash
indusagi -e /path/to/indusagi-bg-tool/src/index.ts
```

Or from your indusagi-coding-agent directory:

```bash
node dist/cli.js -e ../indusagi-bg-tool/src/index.ts
```

### Method 2: As NPM Package

```bash
npm install @indusagi/bg-process
```

Then load it in your extension configuration.

### Method 3: Development (Clone)

```bash
git clone <repo>
cd indusagi-bg-tool
npm install
```

Use `-e ./src/index.ts` to load it.

## Usage

### Via Tool (Agent Access)

The agent can use the `process` tool directly:

```
Start a background dev server named "backend" running "npm run dev"
```

**Tool Actions:**

#### **start** - Run a command in background

```
process action=start name="my-build" command="npm run build"
process action=start name="dev-server" command="npm run dev" alertOnSuccess=true
process action=start name="tests" command="npm test" alertOnFailure=true alertOnSuccess=true
```

Parameters:
- `command` (required) - The command to run
- `name` (required) - Friendly name for the process (e.g., "backend-dev", "test-runner")
- `alertOnSuccess` (optional, default: false) - Get agent turn when completes successfully
- `alertOnFailure` (optional, default: true) - Get agent turn when fails/crashes
- `alertOnKill` (optional, default: false) - Get agent turn when killed by signal

#### **list** - Show all managed processes

```
process action=list
```

Shows all processes with:
- ID (proc_1, proc_2, etc.)
- Name (your friendly name)
- Status (running, exited, killed, etc.)
- PID
- Command
- Runtime duration

#### **output** - Get recent stdout/stderr

```
process action=output id="backend"
process action=output id="proc_1"
```

Returns the last N lines of output from the process.

#### **logs** - Get log file paths

```
process action=logs id="my-build"
```

Returns paths to stdout and stderr log files. Use with `read` tool to inspect full logs.

#### **kill** - Terminate a process

```
process action=kill id="backend"
process action=kill id="proc_1"
```

Gracefully kills the process (sends SIGTERM, then SIGKILL if needed).

#### **clear** - Remove finished processes

```
process action=clear
```

Removes all exited/killed processes from the list.

### Via Commands (Interactive UI)

Load the extension and use interactive commands:

#### `/process:list` - Main process panel

Opens interactive process management UI:

```
indusagi -e ./src/index.ts
/process:list
```

**Keyboard shortcuts:**
- `j/k` - Move selection up/down
- `J/K` - Scroll logs up/down
- `enter` - Stream logs for selected process
- `x` - Kill selected process
- `c` - Clear finished processes
- `q` - Quit and return to chat

#### `/process:stream [id|name]` - Stream logs

```
/process:stream backend
/process:stream proc_1
```

Continuously streams stdout/stderr from a running process.

#### `/process:logs [id|name]` - Show log file paths

```
/process:logs my-build
```

Shows file paths for stdout and stderr logs.

#### `/process:kill [id|name]` - Kill a process

```
/process:kill backend
```

Terminates the specified process.

#### `/process:clear` - Clear finished processes

```
/process:clear
```

Removes all exited/killed processes.

## Features

### Process Management
- ✅ Start multiple background processes simultaneously
- ✅ Assign friendly names to processes (auto-generated or custom)
- ✅ Track process status (running, exited, killed, crashed)
- ✅ View process information (PID, command, runtime)
- ✅ Kill processes gracefully (SIGTERM → SIGKILL)
- ✅ Clear finished processes from list

### Output Handling
- ✅ Real-time log streaming
- ✅ Recent output access (last N lines)
- ✅ File-based storage (temp files, not memory)
- ✅ Separate stdout/stderr logs
- ✅ ANSI color code support
- ✅ Automatic log file cleanup

### Notifications & Alerts
- ✅ Alert on successful completion
- ✅ Alert on failure/crash
- ✅ Alert on external kill signal
- ✅ Configurable alert behavior per process
- ✅ User always sees updates in UI

### Interactive UI
- ✅ Full keyboard-driven interface
- ✅ Real-time process status updates
- ✅ Live log streaming panel
- ✅ Process selection and actions
- ✅ Syntax-highlighted output
- ✅ Responsive layout

## Examples

### Development Workflow

```
1. Start dev server:
   process action=start name="dev-server" command="npm run dev" alertOnFailure=true

2. Run tests in parallel:
   process action=start name="tests" command="npm test" alertOnSuccess=true

3. Build in background:
   process action=start name="build" command="npm run build" alertOnSuccess=true

4. Check status:
   process action=list

5. View build output when needed:
   process action=output id="build"

6. Stream test results:
   /process:stream tests

7. Kill dev server when done:
   process action=kill id="dev-server"
```

### CI/CD Automation

```
process action=start name="lint" command="npm run lint" alertOnFailure=true
process action=start name="type-check" command="npm run type-check" alertOnFailure=true
process action=start name="test" command="npm test" alertOnSuccess=true alertOnFailure=true
process action=list
```

## Process Lifecycle

1. **Start** - Process created and starts running
2. **Running** - Process is active and executing
3. **Exited** - Process completed with exit code 0
4. **Failed** - Process exited with non-zero code
5. **Killed** - Process terminated by signal
6. **Crashed** - Process crashed unexpectedly

## Configuration

### Shell Configuration

Set default shell in `.indusagi/config.json`:

```json
{
  "processes": {
    "execution": {
      "shellPath": "/bin/bash"
    }
  }
}
```

Or use the interactive config:

```
indusagi config
```

## Architecture

### Components

- **ProcessManager** - Core process lifecycle management
- **Tool Handler** - Agent tool registration and execution
- **Commands** - Interactive CLI commands
- **Components** - UI components for interactive mode
- **Hooks** - Session lifecycle hooks
- **Settings** - Configuration management

### Logging

All process output is stored in:

```
$TMPDIR/pi-processes-{timestamp}/
├── proc_1_stdout.log
├── proc_1_stderr.log
├── proc_2_stdout.log
├── proc_2_stderr.log
└── ...
```

Logs are automatically cleaned up when the session ends.

## Performance

- **Minimal memory usage** - Output stored in files, not memory
- **Efficient process monitoring** - Polling every 5 seconds
- **Non-blocking** - Processes run independently
- **Scalable** - Support for many concurrent processes

## Limitations

- **macOS/Linux only** - Not supported on Windows
- **No process environment variables** - Uses parent environment
- **No resource limits** - All processes share system resources
- **Local processes only** - Cannot run on remote machines

## Platform Support

- ✅ macOS 10.15+
- ✅ Linux (glibc 2.17+)
- ❌ Windows (not supported)

## API Reference

### ProcessManager

```typescript
interface ProcessManager {
  // Start a process
  start(options: StartOptions): ProcessInfo;

  // List all processes
  list(): ProcessInfo[];

  // Get process info
  get(id: string): ProcessInfo | undefined;

  // Get process output
  getOutput(id: string): ProcessOutput;

  // Kill a process
  kill(id: string): KillResult;

  // Clear finished processes
  clear(): void;

  // Listen to events
  onEvent(listener: (event: ManagerEvent) => void): () => void;
}
```

### Types

```typescript
interface ProcessInfo {
  id: string;
  name: string;
  pid: number | null;
  command: string;
  cwd: string;
  status: ProcessStatus;
  startTime: number;
  endTime: number | null;
  exitCode: number | null;
  success: boolean;
}

type ProcessStatus = 
  | "running" 
  | "exited" 
  | "killed" 
  | "crashed";

interface StartOptions {
  name: string;
  command: string;
  alertOnSuccess?: boolean;
  alertOnFailure?: boolean;
  alertOnKill?: boolean;
}
```

## Testing

Test scripts are included in `src/test/`:

```bash
./src/test/test-output.sh          # Continuous output (80 chars/sec)
./src/test/test-exit-success.sh 5  # Exits with code 0 after 5s
./src/test/test-exit-failure.sh 5  # Exits with code 1 after 5s
./src/test/test-exit-crash.sh 5    # Exits with code 137 after 5s
```

Test with agent:

```bash
indusagi -e ./src/index.ts

# Then in agent:
process action=start name="test-success" command="./src/test/test-exit-success.sh 5" alertOnSuccess=true
process action=start name="test-failure" command="./src/test/test-exit-failure.sh 5" alertOnFailure=true
process action=list
process action=output id="test-success"
```

## Future Improvements

- [ ] **Windows support** - Implement Windows process management
- [ ] **Process restart** - Auto-restart on failure
- [ ] **Resource limits** - CPU/memory constraints per process
- [ ] **Process groups** - Manage related processes as groups
- [ ] **Web UI** - Browser-based process dashboard
- [ ] **Process history** - Archive completed processes
- [ ] **Log rotation** - Handle large log files
- [ ] **Remote execution** - SSH/container support

## Contributing

Issues and PRs welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a PR

## License

MIT

## Support

For issues, questions, or suggestions:

- 📝 Open an issue on GitHub
- 💬 Discuss on Discord
- 📧 Email: support@indusagi.dev

---

**Happy process managing!** 🚀