/** * ProcBoss (pboss) — JavaScript & TypeScript Process Manager * A production-grade, runtime-agnostic process manager — Bun, Node.js and Deno. * * Features: * - Fork & cluster execution modes * - Auto-restart & crash recovery * - Health checks & monitoring * - Log management & rotation * - Deployment support * * https://procboss.com * https://github.com/procboss/pboss * License: GPL-3.0-only */ export type ProcessStatus = | "online" | "stopping" | "stopped" | "errored" | "launching" | "waiting-restart" | "one-launch-status"; export type ExecMode = "fork" | "cluster"; /** * Namespace member-exit policy (issue #31): what a namespaced process * should do when ANOTHER member of its namespace exits for good * (terminal stop / gave-up errored — not a pboss-initiated stop, not a * crash that auto-restart is already handling). * * - `ignore` (default): do nothing — the default standalone-like behavior. * - `exit`: stop this process too, so the namespace either runs complete * or not at all. * * Only applies to processes WITH a namespace; standalone processes are * never affected by another process's exit. */ export type NsMemberExitPolicy = "ignore" | "exit"; export const NS_MEMBER_EXIT_POLICIES: readonly NsMemberExitPolicy[] = ["ignore", "exit"]; // ── Issue #33: first-class process dependencies ───────────────────────── /** * What happens when a dependency is unavailable. * * - `required` (default): the dependent process cannot start until the * dependency is satisfied. * - `optional`: the dependency is preferred but never blocks startup. * * The model is intentionally policy-based (not a hard-coded "block always") * so future policies (stop/restart propagation, restart-on-recovery) can be * added without changing the configuration format. */ export type DependencyPolicy = "required" | "optional"; export const DEPENDENCY_POLICIES: readonly DependencyPolicy[] = ["required", "optional"]; /** A dependency as declared in configuration: a bare name, or an object. */ export interface DependencyObject { name: string; policy?: DependencyPolicy; } export type DependencySpec = string | DependencyObject; /** The internal, persisted form — always fully specified. */ export interface NormalizedDependency { name: string; policy: DependencyPolicy; } /** Where a dependency was resolved. `unresolved` = nowhere. */ export type DependencyProviderKind = "pboss" | "systemd" | "unresolved"; /** systemd unit states we distinguish (issue #33 "System service state"). */ export type SystemServiceState = | "active" | "inactive" | "failed" | "activating" | "not-found" | "unknown"; /** One resolved dependency — what `pboss deps` and the API report. */ export interface DependencyResolution { /** Dependency name exactly as declared in `dependsOn`. */ name: string; policy: DependencyPolicy; provider: DependencyProviderKind; /** ProcBoss process name (cluster base) or systemd unit name. */ target?: string; /** "running"/"stopped"/"partial" (pboss) or a SystemServiceState. */ status?: string; satisfied: boolean; /** Machine-readable cause when not satisfied. */ reason?: string; } /** A process that depends on another (reverse view). */ export interface DependentRef { name: string; status?: string; policy: DependencyPolicy; } /** The full dependency report for one process (`pboss deps `). */ export interface DepsReport { process: string; namespace?: string; dependencies: DependencyResolution[]; dependents: DependentRef[]; /** Populated when the process sits on a circular dependency chain. */ circular?: string[] | null; } /** * Machine-readable failure details — attached to dependency errors so * automation and AI agents can diagnose blocked startups without parsing * human terminal output (issue #33 "AI/automation considerations"). */ export interface DependencyFailureDetails { /** The process being started. */ process: string; /** The dependency that failed. */ dependency: string; provider: DependencyProviderKind; /** systemd unit name, when provider is systemd. */ service?: string; /** Last-known state of the dependency. */ state?: string; reason: string; } export interface ProcessDescription { id: number; name: string; script: string; args: string[]; cwd: string; env: Record; instances: number; execMode: ExecMode; autorestart: boolean; maxRestarts: number; minUptime: number; maxMemoryRestart?: number; watch: boolean; watchPaths?: string[]; ignoreWatch?: string[]; cronRestart?: string; interpreter?: string; interpreterArgs?: string[]; /** * Issue #40: the ABSOLUTE ecosystem config path this process was started * from — set by ProcessManager.startEcosystem, persisted in the dump, and * read at every spawn so a whole-ecosystem runtime override * (`pboss start --runtime=deno ecosystem.config.ts`) keeps applying to * every process inside it across restarts and reboots. Absent for CLI * script starts (their override is keyed by the process name instead). */ ecosystemPath?: string; mergeLogs: boolean; /** Also forward child stdout/stderr to pboss's own stdout/stderr. */ raw: boolean; logDateFormat?: string; errorFile?: string; outFile?: string; pidFile?: string; killTimeout: number; restartDelay: number; listenTimeout?: number; shutdownWithMessage?: boolean; treekill?: boolean; port?: number; // Cluster specific clusterMode?: boolean; reusePort?: boolean; /** * True when the app runs as a node:cluster group (owner rule, 2026-09-29): * instances > 1 AND the app's runtime is Node → ONE supervised container * (a node primary wrapper) forks the N workers through node:cluster — * the only clustering a Node script can use, and the only one that shares * the listening port across workers. Unstated runtimes inherit the main * runtime running pboss, so "is the app Node?" follows that resolution. */ nodeCluster?: boolean; // Health check healthCheckUrl?: string; healthCheckInterval?: number; healthCheckTimeout?: number; healthCheckMaxFails?: number; // Log rotation logMaxSize?: number; logRetain?: number; logCompress?: boolean; // Graceful gracefulListenTimeout?: number; waitReady?: boolean; // Deploy deployConfig?: DeployConfig; // Source map sourceMapSupport?: boolean; // Node args compatibility nodeArgs?: string[]; // ── Runtime-unique features ───────────────────────────────────────────── // Options in this section belong to ONE runtime. They are honored when the // app runs under that runtime and silently ignored under every other — // one ecosystem file stays portable across machines whose interpreter // chains differ. Translation happens at the single command-build choke // point (ClusterManager.buildWorkerCommand → src/deno-permissions.ts). /** * Deno-only (runtime-unique): the app's permission list — * `permissions: ["allow-read", "allow-net=api.example.com", "deny-write"]`. * Translated to real deno flags at spawn time; entries already stated in * `interpreterArgs` (or `nodeArgs`) are never duplicated. The UNSTATED * default carries NO permission flags (deno's own deny-by-default — the * first restricted operation fails fast with the pointed `--allow-*` * hint); a stated list is exactly what it says. Ignored under bun/node. * See src/deno-permissions.ts for the full contract. */ permissions?: string[]; // Namespace namespace?: string; /** Issue #31: reaction to a namespace sibling's terminal exit. */ onNsMemberExit?: NsMemberExitPolicy; /** Issue #33: normalized dependencies (persisted with the config). */ dependsOn?: NormalizedDependency[]; // Resource threshold alerts (per-process overrides — see threshold-monitor.ts) /** CPU spike trigger (percent). Defaults to 95. */ alertCpuSpikePercent?: number; /** Sustained CPU trigger (percent). Defaults to 70. */ alertCpuSustainedPercent?: number; /** Memory-spike growth trigger (percent per 60s window). Defaults to 40. */ alertMemSpikeGrowthPercent?: number; /** Memory-high trigger, percent of maxMemoryRestart. Defaults to 85. */ alertMemHighPercent?: number; /** Memory-high ceiling in MB for processes without maxMemoryRestart * (opt-in — off by default without a limit). */ alertMemHighMB?: number; /** Opt this process out of ALL resource threshold alerts. */ alertDisabled?: boolean; // Version tracking version?: string; versioningConfig?: VersioningConfig; } export interface VersioningConfig { currentVersion?: string; previousVersions?: string[]; maxVersions?: number; } export interface ProcessEnvMeta extends ProcessDescription { status: ProcessStatus; pm_uptime: number; restart_time: number; unstable_restarts: number; created_at: number; pm_id: number; version?: string; axm_monitor?: Record; axm_actions?: any[]; /** Facts from the last exit (null until the process has exited once). */ last_exit_code?: number | null; last_exit_signal?: string | null; } export interface ProcessState { id: number; name: string; namespace?: string; status: ProcessStatus; pid?: number; pm_id: number; monit: { memory: number; cpu: number; handles?: number; eventLoopLatency?: number; }; pboss_env: ProcessEnvMeta; bm2_env?: ProcessEnvMeta; } export interface StartOptions { name?: string; script: string; args?: string[]; cwd?: string; env?: Record; instances?: number; execMode?: ExecMode; autorestart?: boolean; maxRestarts?: number; minUptime?: number; maxMemoryRestart?: string | number; watch?: boolean | string[]; ignoreWatch?: string[]; interpreter?: string; interpreterArgs?: string[]; mergeLogs?: boolean; /** Also forward child stdout/stderr to pboss's own stdout/stderr. */ raw?: boolean; logDateFormat?: string; errorFile?: string; outFile?: string; killTimeout?: number; restartDelay?: number; cron?: string; port?: number; healthCheckUrl?: string; healthCheckInterval?: number; healthCheckTimeout?: number; healthCheckMaxFails?: number; logMaxSize?: string | number; logRetain?: number; logCompress?: boolean; waitReady?: boolean; listenTimeout?: number; namespace?: string; /** Issue #31: `"ignore"` (default) or `"exit"` — see NsMemberExitPolicy. */ onNsMemberExit?: NsMemberExitPolicy; /** Issue #33: names or `{ name, policy }` objects the process requires. */ dependsOn?: DependencySpec[]; /** Per-process resource-threshold overrides (threshold-monitor). */ alertCpuSpikePercent?: number; alertCpuSustainedPercent?: number; alertMemSpikeGrowthPercent?: number; alertMemHighPercent?: number; alertMemHighMB?: number; alertDisabled?: boolean; nodeArgs?: string[]; sourceMapSupport?: boolean; /** * Run in foreground without a daemon. Documented in the config reference * (Process options); honored per-app and at the ecosystem top level — * anywhere it is `true`, `pboss start` stays in the foreground and hosts * the supervisor in-process (same as `--no-daemon`). Issue #28. */ noDaemon?: boolean; /** * Deno-only (runtime-unique): permission list for the app — see the * ProcessDescription field of the same name and src/deno-permissions.ts. * `--permissions allow-read,allow-net=api.com` on the CLI, or an array in * an ecosystem file. Ignored when the app runs under bun/node. */ permissions?: string[]; /** * Issue #40: the LAUNCHER runtime override for this start — the value the * bin wrapper handed down through PBOSS_LAUNCHER_RUNTIME after consuming * `pboss start --runtime=`. The CLI sets it; the daemon pins it in * ~/.pboss/runtime-overrides (process base name / ecosystem config path) * and every future spawn of that process/ecosystem reuses it. NEVER * written to ~/.pboss/.runtime — an override, not a default change. * Distinct from the app-level `interpreter` (which stays the most * explicit, per-app choice and wins over this pin). */ runtime?: "node" | "bun" | "deno"; /** * Issue #40: the ABSOLUTE path of the ecosystem file this app came from * (set on each app by ProcessManager.startEcosystem; carried into the * persisted ProcessDescription as `ecosystemPath`). Not part of the * user-facing config-file schema. */ ecosystemPath?: string; } export interface EcosystemConfig { apps: StartOptions[]; noDaemon?: boolean; deploy?: Record; /** Standalone scheduled commands — see `pboss cron run` / CronJobConfig. */ crons?: CronJobConfig[]; /** * Issue #40: the ABSOLUTE source path, set by loadEcosystemConfig — the * identity under which a whole-ecosystem runtime override is pinned * (`pboss start --runtime=deno ` → runtime-overrides[absPath]). * Not part of the user-facing schema; the loader stamps it. */ configPath?: string; /** * Issue #40: the LAUNCHER runtime override the CLI attached for this * start (from the wrapper's PBOSS_LAUNCHER_RUNTIME channel). Applies to * EVERY app in the file; the daemon pins it under configPath and each * app's description carries the path so spawns keep resolving it. */ runtime?: "node" | "bun" | "deno"; } /** Lifecycle state of a standalone cron job. */ export type CronJobState = "scheduled" | "completed" | "disabled"; /** * A standalone scheduled command — runs a shell command on a schedule, * independent of any managed process. * * Defined in ecosystem files (`crons: [...]`) or created with * `pboss cron run `. */ export interface CronJobConfig { /** Job name (defaults to a slug derived from the command). */ name?: string; /** Friendly schedule ("everyday@9:11", "every-30-seconds") or a raw 5/6-field cron expression. */ schedule: string; /** Shell command to run when the schedule fires. */ command: string; /** Working directory for the command. */ cwd?: string; /** Set false to keep the job defined but paused. */ enabled?: boolean; } /** Runtime record of a standalone cron job (persisted in ~/.pboss/cron.json). */ export interface CronJob extends CronJobConfig { id: number; name: string; schedule: string; command: string; cwd: string; /** Cron expression — 5 fields, or 6 when seconds matter (recurring jobs). */ cron?: string; /** One-shot execution time, epoch ms (one-shot jobs). */ at?: number; oneShot: boolean; /** Human-readable expansion of the schedule, e.g. "every day at 09:11". */ description: string; enabled: boolean; state: CronJobState; createdAt: number; /** Next scheduled run, epoch ms (null when paused or completed). */ nextRun: number | null; /** Last execution start, epoch ms. */ lastRun: number | null; /** Exit code of the last execution (null while running / never run). */ lastExitCode: number | null; /** Error message when the last execution could not be spawned. */ lastError?: string | null; runCount: number; } export interface DeployConfig { user: string; host: string | string[]; ref: string; repo: string; path: string; preDeploy?: string; postDeploy?: string; preSetup?: string; postSetup?: string; ssh_options?: string; env?: Record; } export interface DaemonMessage { type: string; data?: any; id?: string; mode?: "stream" | "http" } export interface DaemonResponse { type: string; data?: any; success: boolean; error?: string; id?: string; /** Populated by the "ecosystem" command: standalone cron jobs applied. */ cronsAdded?: number; cronsUpdated?: number; /** Issue #33: structured dependency-failure details (machine-readable). */ dependencyFailure?: DependencyFailureDetails; } export interface MetricSnapshot { timestamp: number; processes: Array<{ id: number; name: string; pid?: number; cpu: number; memory: number; eventLoopLatency?: number; handles?: number; status: ProcessStatus; restarts: number; uptime: number; }>; system: { totalMemory: number; freeMemory: number; cpuCount: number; loadAvg: number[]; platform: string; }; } export interface LogRotateOptions { maxSize: number; retain: number; compress: boolean; dateFormat?: string; } export interface HealthCheckConfig { url: string; interval: number; timeout: number; maxFails: number; } export interface DashboardState { processes: ProcessState[]; metrics: MetricSnapshot; logs: Record; } export type LogEntry = { ts: string; level?: "err" | "out", msg: string; }; export interface LogItem { name: string; id: number; ts: string; msg: string; level?: "err" | "out"; }