diff --git a/src/server/automation/broadcast-service.ts b/src/server/automation/broadcast-service.ts new file mode 100644 index 0000000..4909164 --- /dev/null +++ b/src/server/automation/broadcast-service.ts @@ -0,0 +1,354 @@ +import crypto from 'node:crypto'; +import type { ServerWsFrame } from '../../shared/ws-protocol.js'; +import type { WsHub } from '../api/ws-hub.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { AuditService } from '../security/audit.js'; +import type { VaultService } from '../security/vault.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { BufferedStreamEmitter } from './stream-buffer.js'; +import { + buildWorkflowEnv, + interpolateShellCommandSafe, + resolveTargetServers, + validateAndResolveInputs, +} from './template.js'; + +export interface BroadcastTargetResult { + serverId: string; + serverName: string; + status: 'pending' | 'running' | 'ok' | 'error' | 'cancelled'; + exitCode: number | null; + stdout: string; + stderr: string; + durationMs: number; +} + +export interface BroadcastJobSummary { + jobId: string; + snippetId?: string; + command: string; + sudo: boolean; + createdAt: number; + finishedAt: number | null; + cancelled: boolean; + done: boolean; + targets: BroadcastTargetResult[]; +} + +interface ActiveBroadcastJob extends BroadcastJobSummary { + emitter: BufferedStreamEmitter; + abortController: AbortController; +} + +const MAX_RETAINED_BROADCASTS = 25; +const MAX_OUTPUT_PER_SERVER = 256 * 1024; + +async function runPool( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + const limit = Math.max(1, Math.min(concurrency, items.length || 1)); + let idx = 0; + const runners = Array.from({ length: limit }, async () => { + while (idx < items.length) { + const current = items[idx++]!; + await worker(current); + } + }); + await Promise.all(runners); +} + +export class BroadcastService { + private readonly jobs = new Map(); + + constructor( + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly sshPool: SSHPool, + private readonly wsHub: WsHub, + private readonly auditService: AuditService, + ) {} + + getStreamReplayFrames(jobId: string): ServerWsFrame[] { + return this.jobs.get(jobId)?.emitter.getReplayFrames() ?? []; + } + + getBroadcastResult(jobId: string): BroadcastJobSummary | undefined { + const job = this.jobs.get(jobId); + if (!job) return undefined; + return { + jobId: job.jobId, + snippetId: job.snippetId, + command: job.command, + sudo: job.sudo, + createdAt: job.createdAt, + finishedAt: job.finishedAt, + cancelled: job.cancelled, + done: job.done, + targets: job.targets.map((t) => ({ ...t })), + }; + } + + cancelBroadcast(jobId: string): boolean { + const job = this.jobs.get(jobId); + if (!job || job.done) return false; + job.cancelled = true; + job.abortController.abort(); + return true; + } + + cancelAll(): void { + for (const job of this.jobs.values()) { + if (!job.done) { + job.cancelled = true; + job.abortController.abort(); + } + } + } + + startBroadcast(opts: { + snippetId?: string; + command?: string; + inputs?: Record; + sudo?: boolean; + concurrency?: number; + timeoutSec?: number; + target: { serverId?: string; serverIds?: string[]; tags?: string[]; all?: boolean }; + actorIp: string; + sessionIdHash: string | null; + }): BroadcastJobSummary { + if (!this.vaultService.isRuntimeReady) { + throw new Error('Vault is sealed; unseal Vault before running Fleet Broadcast'); + } + + let rawCommand = opts.command?.trim() ?? ''; + let sudo = Boolean(opts.sudo); + let resolvedInputs: Record = {}; + + if (opts.snippetId) { + const snip = this.configManager + .getSnippets() + .snippets.find((s) => s.id === opts.snippetId); + if (!snip) { + throw new Error(`Unknown command snippet "${opts.snippetId}"`); + } + resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {}); + rawCommand = snip.command; + sudo = opts.sudo ?? snip.sudo; + } else { + if (!rawCommand) { + throw new Error('Command or snippetId is required for Fleet Broadcast'); + } + if (opts.inputs) { + for (const [k, v] of Object.entries(opts.inputs)) { + if (v !== undefined && v !== null) resolvedInputs[k] = String(v); + } + } + } + + const baseCtx = { inputs: resolvedInputs }; + const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx); + const allServers = this.configManager.listServers(); + + let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx); + if (opts.target.serverIds && opts.target.serverIds.length > 0) { + const byId = new Set(matchedServers.map((s) => s.id)); + const wanted = new Set(opts.target.serverIds); + for (const s of allServers) { + if (s.enabled && wanted.has(s.id) && !byId.has(s.id)) { + byId.add(s.id); + matchedServers.push(s); + } + } + } + + if (matchedServers.length === 0) { + throw new Error('No enabled target servers matched broadcast filter'); + } + + const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`; + const emitter = new BufferedStreamEmitter(this.wsHub, jobId); + const abortController = new AbortController(); + + const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({ + serverId: s.id, + serverName: s.name, + status: 'pending', + exitCode: null, + stdout: '', + stderr: '', + durationMs: 0, + })); + + const job: ActiveBroadcastJob = { + jobId, + snippetId: opts.snippetId, + command: renderedCommand, + sudo, + createdAt: Date.now(), + finishedAt: null, + cancelled: false, + done: false, + targets, + emitter, + abortController, + }; + this.jobs.set(jobId, job); + + this.auditService.log({ + action: 'broadcast.start', + actorIp: opts.actorIp, + sessionIdHash: opts.sessionIdHash, + target: opts.snippetId ?? 'adhoc', + status: 'ok', + details: { + jobId, + serverIds: matchedServers.map((s) => s.id), + }, + }); + + emitter.pushMeta({ + event: 'start', + jobId, + command: renderedCommand, + targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })), + }); + + const timeoutMs = (opts.timeoutSec ?? 120) * 1000; + const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32)); + + void runPool(matchedServers, concurrency, async (srv) => { + const targetEntry = job.targets.find((t) => t.serverId === srv.id)!; + if (abortController.signal.aborted) { + targetEntry.status = 'cancelled'; + emitter.pushMeta({ + event: 'server-exit', + serverId: srv.id, + exitCode: null, + durationMs: 0, + status: 'cancelled', + }); + return; + } + + const started = Date.now(); + targetEntry.status = 'running'; + emitter.pushMeta({ event: 'server-start', serverId: srv.id }); + + const env = buildWorkflowEnv({ + inputs: resolvedInputs, + serverId: srv.id, + }); + + try { + const handle = await this.sshPool.execStream(srv.id, renderedCommand, { + env, + sudo, + }); + + const outChunks: Buffer[] = []; + const errChunks: Buffer[] = []; + let outBytes = 0; + let errBytes = 0; + + handle.channel.on('data', (chunk: Buffer) => { + const text = chunk.toString('utf8'); + if (outBytes < MAX_OUTPUT_PER_SERVER) { + const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes); + outChunks.push(slice); + outBytes += slice.length; + } + emitter.push('stdout', `[${srv.id}] ${text}`); + emitter.pushMeta({ + event: 'server-output', + serverId: srv.id, + channel: 'stdout', + data: text, + }); + }); + + handle.channel.stderr?.on('data', (chunk: Buffer) => { + const text = chunk.toString('utf8'); + if (errBytes < MAX_OUTPUT_PER_SERVER) { + const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes); + errChunks.push(slice); + errBytes += slice.length; + } + emitter.push('stderr', `[${srv.id}] ${text}`); + emitter.pushMeta({ + event: 'server-output', + serverId: srv.id, + channel: 'stderr', + data: text, + }); + }); + + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + handle.abort(); + }, timeoutMs); + timer.unref(); + + const onAbort = () => handle.abort(); + abortController.signal.addEventListener('abort', onAbort, { once: true }); + + try { + const { exitCode } = await handle.done; + targetEntry.stdout = Buffer.concat(outChunks).toString('utf8'); + targetEntry.stderr = Buffer.concat(errChunks).toString('utf8'); + targetEntry.durationMs = Date.now() - started; + targetEntry.exitCode = exitCode; + + if (job.cancelled || abortController.signal.aborted) { + targetEntry.status = 'cancelled'; + } else if (timedOut) { + targetEntry.status = 'error'; + targetEntry.stderr += `\nTimed out after ${timeoutMs}ms`; + } else { + targetEntry.status = exitCode === 0 ? 'ok' : 'error'; + } + } finally { + clearTimeout(timer); + abortController.signal.removeEventListener('abort', onAbort); + } + } catch (err) { + targetEntry.durationMs = Date.now() - started; + targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error'; + const msg = err instanceof Error ? err.message : String(err); + targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg; + emitter.push('stderr', `[${srv.id}] ${msg}\n`); + } + + emitter.pushMeta({ + event: 'server-exit', + serverId: srv.id, + exitCode: targetEntry.exitCode, + durationMs: targetEntry.durationMs, + status: targetEntry.status, + }); + }).finally(() => { + job.done = true; + job.finishedAt = Date.now(); + const okCount = job.targets.filter((t) => t.status === 'ok').length; + emitter.pushMeta({ + event: 'done', + cancelled: job.cancelled, + okCount, + total: job.targets.length, + }); + this.pruneJobs(); + }); + + return this.getBroadcastResult(jobId)!; + } + + private pruneJobs(): void { + const done = [...this.jobs.values()].filter((j) => j.done); + while (done.length > MAX_RETAINED_BROADCASTS) { + const oldest = done.shift()!; + this.jobs.delete(oldest.jobId); + } + } +} diff --git a/src/server/automation/stream-buffer.ts b/src/server/automation/stream-buffer.ts new file mode 100644 index 0000000..bc26e55 --- /dev/null +++ b/src/server/automation/stream-buffer.ts @@ -0,0 +1,44 @@ +import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; +import type { WsHub } from '../api/ws-hub.js'; + +const DEFAULT_MAX_REPLAY_BYTES = 128 * 1024; + +export class BufferedStreamEmitter { + private readonly frames: ServerWsFrame[] = []; + private bufferBytes = 0; + + constructor( + private readonly wsHub: WsHub, + public readonly jobId: string, + private readonly maxReplayBytes = DEFAULT_MAX_REPLAY_BYTES, + ) {} + + push(stream: 'stdout' | 'stderr' | 'meta', data: string): void { + const frame: ServerWsFrame = { + type: 'stream:chunk', + jobId: this.jobId, + stream, + data, + }; + const bytes = Buffer.byteLength(data, 'utf8'); + this.frames.push(frame); + this.bufferBytes += bytes; + + while (this.bufferBytes > this.maxReplayBytes && this.frames.length > 0) { + const dropped = this.frames.shift()!; + if (dropped.type === 'stream:chunk') { + this.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8'); + } + } + + this.wsHub.broadcastChannel(WS_CHANNELS.stream(this.jobId), frame); + } + + pushMeta(payload: Record): void { + this.push('meta', JSON.stringify(payload)); + } + + getReplayFrames(): ServerWsFrame[] { + return [...this.frames]; + } +} diff --git a/src/server/automation/template.ts b/src/server/automation/template.ts new file mode 100644 index 0000000..a890e2f --- /dev/null +++ b/src/server/automation/template.ts @@ -0,0 +1,192 @@ +import type { InputDef } from '../../shared/schemas/common.js'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import { posixSingleQuote } from '../ssh/sudo.js'; + +export interface StepOutputSummary { + stdout: string; + exitCode: number | null; +} + +export interface TemplateContext { + workflowId?: string; + runId?: string; + serverId?: string; + inputs: Record; + stepOutputs?: Map; + captures?: Map; + eventMeta?: Record; +} + +export function toEnvIdent(raw: string): string { + return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase(); +} + +export function validateAndResolveInputs( + defs: InputDef[], + supplied: Record = {}, +): Record { + const out: Record = {}; + + for (const def of defs) { + const raw = supplied[def.name]; + const hasSupplied = raw !== undefined && raw !== null && raw !== ''; + const candidate = hasSupplied ? raw : def.default; + + if (candidate === undefined || candidate === null || candidate === '') { + if (def.required) { + throw new Error(`Missing required input "${def.label ?? def.name}"`); + } + continue; + } + + if (def.type === 'number') { + const n = Number(candidate); + if (!Number.isFinite(n)) { + throw new Error(`Input "${def.name}" must be a valid number`); + } + out[def.name] = String(n); + continue; + } + + if (def.type === 'boolean') { + if (typeof candidate === 'boolean') { + out[def.name] = candidate ? 'true' : 'false'; + } else { + const lower = String(candidate).trim().toLowerCase(); + if (lower === 'true' || lower === '1' || lower === 'yes') out[def.name] = 'true'; + else if (lower === 'false' || lower === '0' || lower === 'no') out[def.name] = 'false'; + else throw new Error(`Input "${def.name}" must be true or false`); + } + continue; + } + + const strVal = String(candidate); + if (def.type === 'select' && def.options && def.options.length > 0) { + if (!def.options.includes(strVal)) { + throw new Error( + `Input "${def.name}" must be one of: ${def.options.join(', ')}`, + ); + } + } + out[def.name] = strVal; + } + + for (const [k, v] of Object.entries(supplied)) { + if (!(k in out) && v !== undefined && v !== null) { + out[k] = String(v); + } + } + + return out; +} + +export function buildWorkflowEnv(ctx: TemplateContext): Record { + const env: Record = {}; + if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId; + if (ctx.runId) env.GCOORD_RUN_ID = ctx.runId; + if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId; + + for (const [k, v] of Object.entries(ctx.inputs)) { + env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v; + } + + if (ctx.stepOutputs) { + for (const [stepId, res] of ctx.stepOutputs.entries()) { + const keyBase = `GCOORD_STEP_${toEnvIdent(stepId)}`; + env[`${keyBase}_STDOUT`] = res.stdout.slice(0, 32 * 1024); + env[`${keyBase}_EXIT`] = res.exitCode === null ? '' : String(res.exitCode); + } + } + + if (ctx.captures) { + for (const [alias, val] of ctx.captures.entries()) { + env[`GCOORD_CAPTURE_${toEnvIdent(alias)}`] = val.slice(0, 32 * 1024); + } + } + + if (ctx.eventMeta) { + for (const [k, v] of Object.entries(ctx.eventMeta)) { + env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v; + } + } + + return env; +} + +function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string { + const expr = rawExpr.trim(); + if (expr.startsWith('inputs.')) { + const key = expr.slice('inputs.'.length); + return ctx.inputs[key] ?? ''; + } + if (expr.startsWith('steps.')) { + const rest = expr.slice('steps.'.length); + const dot = rest.lastIndexOf('.'); + if (dot > 0) { + const stepId = rest.slice(0, dot); + const field = rest.slice(dot + 1); + const out = ctx.stepOutputs?.get(stepId); + if (!out) return ''; + if (field === 'stdout') return out.stdout.trim(); + if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode); + } + } + if (expr.startsWith('captures.')) { + const key = expr.slice('captures.'.length); + return (ctx.captures?.get(key) ?? '').trim(); + } + if (expr.startsWith('event.')) { + const key = expr.slice('event.'.length); + return ctx.eventMeta?.[key] ?? ''; + } + return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim(); +} + +export function interpolateValuePlain(template: string, ctx: TemplateContext): string { + return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => + resolveTemplateToken(expr, ctx), + ); +} + +export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string { + return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => + posixSingleQuote(resolveTemplateToken(expr, ctx)), + ); +} + +export function resolveTargetServers( + target: { serverId?: string; tags?: string[]; all?: boolean }, + servers: ServerConfig[], + ctx: TemplateContext, +): ServerConfig[] { + const enabled = servers.filter((s) => s.enabled); + + if (target.all) { + return enabled; + } + + const out: ServerConfig[] = []; + const seen = new Set(); + + if (target.serverId) { + const resolvedId = interpolateValuePlain(target.serverId, ctx).trim(); + const match = enabled.find((s) => s.id === resolvedId); + if (match) { + seen.add(match.id); + out.push(match); + } + } + + if (target.tags && target.tags.length > 0) { + const wanted = new Set(target.tags); + for (const s of enabled) { + if (seen.has(s.id)) continue; + if (s.tags.some((t) => wanted.has(t))) { + seen.add(s.id); + out.push(s); + } + } + } + + return out; +} diff --git a/src/server/automation/workflow-engine.ts b/src/server/automation/workflow-engine.ts new file mode 100644 index 0000000..8d3a181 --- /dev/null +++ b/src/server/automation/workflow-engine.ts @@ -0,0 +1,1438 @@ +import crypto from 'node:crypto'; +import type Database from 'better-sqlite3'; +import { Cron } from 'croner'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { + StepDependencySchema, + WorkflowConfig, + WorkflowStep, +} from '../../shared/schemas/workflow.schema.js'; +import type { z } from 'zod'; +import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; +import type { WsHub } from '../api/ws-hub.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { AuditService } from '../security/audit.js'; +import type { VaultService } from '../security/vault.js'; +import type { SftpService } from '../ssh/sftp-service.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { posixSingleQuote } from '../ssh/sudo.js'; +import type { CustomSystemsEngine } from '../systems/systems-engine.js'; +import { BufferedStreamEmitter } from './stream-buffer.js'; +import { + buildWorkflowEnv, + interpolateShellCommandSafe, + interpolateValuePlain, + resolveTargetServers, + validateAndResolveInputs, + type StepOutputSummary, + type TemplateContext, +} from './template.js'; +import type { TransferEngine } from './transfer-engine.js'; + +type StepDependency = z.infer; + +export type WorkflowRunStatus = + | 'queued' + | 'running' + | 'succeeded' + | 'failed' + | 'cancelled' + | 'skipped'; + +export interface WorkflowRunRecord { + runId: string; + workflowId: string; + triggerSource: string; + status: WorkflowRunStatus; + startedAt: number; + finishedAt: number | null; + cancelledBy: string | null; + inputsJson?: string | null; +} + +export interface WorkflowStepLogRecord { + id: number; + runId: string; + stepId: string; + serverId: string; + exitCode: number | null; + durationMs: number; + stdout: string; + stderr: string; + createdAt: number; +} + +export interface DryRunStepPlan { + stepId: string; + type: WorkflowStep['type']; + wave: number; + dependsOn: Array<{ stepId: string; on: 'success' | 'failure' | 'always' }>; + targets: Array<{ serverId: string; serverName: string }>; + renderedCommand?: string; + renderedPath?: string; + systemId?: string; + actionId?: string; + discoveredItems?: Record; + transferPreview?: { + mode: 'hub-relayed' | 'direct'; + sourceServerId: string; + sourcePath: string; + destinationServerId: string; + destinationPath: string; + }; + envKeys: string[]; +} + +export interface SystemTriggerEvent { + event: + | 'server.offline' + | 'server.online' + | 'probe.failed' + | 'system.unhealthy' + | 'alert.fired'; + serverId?: string; + systemId?: string; + item?: string; + probeId?: string; + ruleId?: string; + message?: string; +} + +interface ActiveRunControl { + runId: string; + workflowId: string; + status: WorkflowRunStatus; + abortController: AbortController; + emitter: BufferedStreamEmitter; + done: boolean; + cancelledBy?: string; +} + +interface QueuedRunRequest { + runId: string; + workflow: WorkflowConfig; + triggerSource: string; + inputs: Record; + eventMeta?: Record; + actorIp: string; + sessionIdHash: string | null; + startedAt: number; + onFailureDepth: number; +} + +export type FailureNotifierFn = ( + channelId: string, + message: string, + workflowId: string, +) => Promise; + +const MAX_OUTPUT_CHARS = 256 * 1024; +const MAX_RETAINED_STREAM_RUNS = 30; + +function normalizeDep(dep: StepDependency): { + stepId: string; + on: 'success' | 'failure' | 'always'; +} { + if (typeof dep === 'string') return { stepId: dep, on: 'success' }; + return { stepId: dep.stepId, on: dep.on }; +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + const limit = Math.max(1, Math.min(concurrency, items.length || 1)); + let idx = 0; + const workers = Array.from({ length: limit }, async () => { + while (idx < items.length) { + const item = items[idx++]!; + await worker(item); + } + }); + await Promise.all(workers); +} + +export class WorkflowEngine { + private readonly cronJobs = new Map(); + private readonly activeByWorkflow = new Map(); + private readonly queueByWorkflow = new Map(); + private readonly runsById = new Map(); + private failureNotifier: FailureNotifierFn | null = null; + private closed = false; + + constructor( + private readonly db: Database.Database, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly sshPool: SSHPool, + private readonly sftpService: SftpService, + private readonly customSystemsEngine: CustomSystemsEngine, + private readonly transferEngine: TransferEngine, + private readonly wsHub: WsHub, + private readonly auditService: AuditService, + ) {} + + setFailureNotifier(fn: FailureNotifierFn): void { + this.failureNotifier = fn; + } + + getStreamReplayFrames(jobId: string): ServerWsFrame[] { + if (!jobId.startsWith('wf:')) return []; + const runId = jobId.slice(3); + return this.runsById.get(runId)?.emitter.getReplayFrames() ?? []; + } + + start(): void { + this.closed = false; + this.syncCronJobs(); + } + + syncCronJobs(): void { + this.stopCronJobs(); + if (this.closed || !this.vaultService.isRuntimeReady) return; + + for (const wf of this.configManager.listWorkflows()) { + if (!wf.enabled || wf.trigger.type !== 'cron') continue; + const wfId = wf.id; + const cron = new Cron( + wf.trigger.expression, + { + timezone: wf.trigger.timezone, + protect: true, + unref: true, + }, + () => { + if (this.closed || !this.vaultService.isRuntimeReady) return; + void this.triggerWorkflow(wfId, { + triggerSource: 'cron', + }).catch(() => undefined); + }, + ); + this.cronJobs.set(wfId, cron); + } + } + + stopCronJobs(): void { + for (const job of this.cronJobs.values()) { + job.stop(); + } + this.cronJobs.clear(); + } + + handlePanicLock(): void { + this.stopCronJobs(); + for (const [wfId, q] of this.queueByWorkflow.entries()) { + for (const req of q) { + this.markRunFinished(req.runId, wfId, 'cancelled', 'cron', Date.now(), 'panic_lock'); + } + } + this.queueByWorkflow.clear(); + for (const run of this.activeByWorkflow.values()) { + this.cancelRun(run.runId, 'panic_lock'); + } + } + + close(): void { + this.closed = true; + this.handlePanicLock(); + } + + getNextCronRun(workflowId: string): number | null { + const job = this.cronJobs.get(workflowId); + if (!job) return null; + const next = job.nextRun(); + return next ? next.getTime() : null; + } + + listWorkflowsWithSummary(): Array<{ + workflow: WorkflowConfig; + nextRunAt: number | null; + activeRunId: string | null; + queuedCount: number; + latestRun: WorkflowRunRecord | null; + latestStepLogs: WorkflowStepLogRecord[]; + }> { + const workflows = this.configManager.listWorkflows(); + return workflows.map((workflow) => { + const latestRun = + (this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + WHERE workflow_id = ? + ORDER BY started_at DESC + LIMIT 1`, + ) + .get(workflow.id) as WorkflowRunRecord | undefined) ?? null; + + const latestStepLogs = latestRun + ? (this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC`, + ) + .all(latestRun.runId) as WorkflowStepLogRecord[]) + : []; + + const active = this.activeByWorkflow.get(workflow.id); + const queued = this.queueByWorkflow.get(workflow.id)?.length ?? 0; + + return { + workflow, + nextRunAt: this.getNextCronRun(workflow.id), + activeRunId: active && !active.done ? active.runId : null, + queuedCount: queued, + latestRun, + latestStepLogs, + }; + }); + } + + listRuns(workflowId?: string, limit = 50): WorkflowRunRecord[] { + const capped = Math.max(1, Math.min(limit, 200)); + if (workflowId) { + return this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + WHERE workflow_id = ? + ORDER BY started_at DESC + LIMIT ?`, + ) + .all(workflowId, capped) as WorkflowRunRecord[]; + } + return this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + ORDER BY started_at DESC + LIMIT ?`, + ) + .all(capped) as WorkflowRunRecord[]; + } + + getRunDetail(runId: string): { + run: WorkflowRunRecord; + stepLogs: WorkflowStepLogRecord[]; + workflow: WorkflowConfig | null; + } | null { + const run = this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + WHERE run_id = ?`, + ) + .get(runId) as WorkflowRunRecord | undefined; + if (!run) return null; + + const stepLogs = this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC`, + ) + .all(runId) as WorkflowStepLogRecord[]; + + return { + run, + stepLogs, + workflow: this.configManager.getWorkflow(run.workflowId) ?? null, + }; + } + + async handleSystemEvent(ev: SystemTriggerEvent): Promise { + if (this.closed || !this.vaultService.isRuntimeReady) return []; + + const triggeredRunIds: string[] = []; + const srv = ev.serverId ? this.configManager.getServer(ev.serverId) : undefined; + const workflows = this.configManager.listWorkflows(); + + for (const wf of workflows) { + if (!wf.enabled || wf.trigger.type !== 'event') continue; + if (wf.trigger.event !== ev.event) continue; + + const filter = wf.trigger.filter; + if (filter) { + if (filter.serverId && filter.serverId !== ev.serverId) continue; + if (filter.systemId && filter.systemId !== ev.systemId) continue; + if (filter.tags && filter.tags.length > 0) { + if (!srv || !srv.tags.some((t) => filter.tags!.includes(t))) continue; + } + } + + const autoInputs: Record = {}; + if (ev.serverId && wf.inputs.some((i) => i.name === 'serverId')) { + autoInputs.serverId = ev.serverId; + } + + const eventMeta: Record = { type: ev.event }; + if (ev.serverId) eventMeta.serverId = ev.serverId; + if (ev.systemId) eventMeta.systemId = ev.systemId; + if (ev.item) eventMeta.item = ev.item; + if (ev.probeId) eventMeta.probeId = ev.probeId; + if (ev.ruleId) eventMeta.ruleId = ev.ruleId; + if (ev.message) eventMeta.message = ev.message; + + try { + const res = await this.triggerWorkflow(wf.id, { + triggerSource: `event:${ev.event}`, + inputs: autoInputs, + eventMeta, + }); + triggeredRunIds.push(res.runId); + } catch { + // Isolate event-triggered workflow failures + } + } + + return triggeredRunIds; + } + + async triggerWorkflow( + workflowId: string, + opts: { + triggerSource: string; + inputs?: Record; + eventMeta?: Record; + actorIp?: string; + sessionIdHash?: string | null; + onFailureDepth?: number; + }, + ): Promise<{ runId: string; status: WorkflowRunStatus; skippedReason?: string }> { + if (this.closed) { + throw new Error('WorkflowEngine is closed'); + } + if (!this.vaultService.isRuntimeReady) { + throw new Error('Vault is sealed; unseal Vault before running workflows'); + } + + const wf = this.configManager.getWorkflow(workflowId); + if (!wf) { + throw new Error(`Unknown workflow "${workflowId}"`); + } + + const inputs = validateAndResolveInputs(wf.inputs, opts.inputs ?? {}); + const runId = `run-${crypto.randomBytes(6).toString('hex')}`; + const now = Date.now(); + const depth = opts.onFailureDepth ?? 0; + const actorIp = opts.actorIp ?? 'scheduler'; + const sessionIdHash = opts.sessionIdHash ?? null; + + const existingActive = this.activeByWorkflow.get(wf.id); + if (existingActive && !existingActive.done) { + if (wf.overlapPolicy === 'skip') { + this.db + .prepare( + `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) + VALUES (?, ?, ?, 'skipped', ?, ?, 'overlap:skip', ?)`, + ) + .run(runId, wf.id, opts.triggerSource, now, now, JSON.stringify(inputs)); + + this.broadcastRunFrame({ + runId, + workflowId: wf.id, + status: 'skipped', + triggerSource: opts.triggerSource, + startedAt: now, + finishedAt: now, + }); + return { runId, status: 'skipped', skippedReason: 'overlap' }; + } + + if (wf.overlapPolicy === 'queue') { + this.db + .prepare( + `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) + VALUES (?, ?, ?, 'queued', ?, NULL, NULL, ?)`, + ) + .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + + const q = this.queueByWorkflow.get(wf.id) ?? []; + q.push({ + runId, + workflow: wf, + triggerSource: opts.triggerSource, + inputs, + eventMeta: opts.eventMeta, + actorIp, + sessionIdHash, + startedAt: now, + onFailureDepth: depth, + }); + this.queueByWorkflow.set(wf.id, q); + + this.broadcastRunFrame({ + runId, + workflowId: wf.id, + status: 'queued', + triggerSource: opts.triggerSource, + startedAt: now, + }); + return { runId, status: 'queued' }; + } + + if (wf.overlapPolicy === 'cancel-previous') { + const queued = this.queueByWorkflow.get(wf.id); + if (queued) { + for (const item of queued) { + this.markRunFinished( + item.runId, + wf.id, + 'cancelled', + item.triggerSource, + item.startedAt, + 'overlap:cancel-previous', + ); + } + this.queueByWorkflow.delete(wf.id); + } + this.cancelRun(existingActive.runId, 'overlap:cancel-previous'); + } + } + + this.db + .prepare( + `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) + VALUES (?, ?, ?, 'running', ?, NULL, NULL, ?)`, + ) + .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + + this.startExecution({ + runId, + workflow: wf, + triggerSource: opts.triggerSource, + inputs, + eventMeta: opts.eventMeta, + actorIp, + sessionIdHash, + startedAt: now, + onFailureDepth: depth, + }); + + return { runId, status: 'running' }; + } + + cancelRun(runId: string, actor = 'admin'): boolean { + for (const [wfId, queue] of this.queueByWorkflow.entries()) { + const idx = queue.findIndex((q) => q.runId === runId); + if (idx >= 0) { + const [removed] = queue.splice(idx, 1); + if (queue.length === 0) this.queueByWorkflow.delete(wfId); + if (removed) { + this.markRunFinished( + removed.runId, + removed.workflow.id, + 'cancelled', + removed.triggerSource, + removed.startedAt, + actor, + ); + } + return true; + } + } + + const active = this.runsById.get(runId); + if (!active || active.done) return false; + + active.cancelledBy = actor; + active.status = 'cancelled'; + active.abortController.abort(); + active.emitter.pushMeta({ event: 'cancelled', actor }); + return true; + } + + async previewDryRun( + workflowInput: string | WorkflowConfig, + suppliedInputs: Record = {}, + ): Promise<{ workflowId: string; workflowName: string; inputs: Record; steps: DryRunStepPlan[] }> { + const wf = + typeof workflowInput === 'string' + ? this.configManager.getWorkflow(workflowInput) + : workflowInput; + if (!wf) { + throw new Error(`Unknown workflow "${String(workflowInput)}"`); + } + + const inputs = validateAndResolveInputs(wf.inputs, suppliedInputs); + const allServers = this.configManager.listServers(); + const baseCtx: TemplateContext = { workflowId: wf.id, inputs }; + const envKeys = Object.keys(buildWorkflowEnv(baseCtx)); + + // Compute topological waves matching WorkflowConfigSchema DAG + const waveMap = new Map(); + const stepById = new Map(wf.steps.map((s) => [s.id, s])); + const computeWave = (stepId: string): number => { + if (waveMap.has(stepId)) return waveMap.get(stepId)!; + const step = stepById.get(stepId)!; + if (step.dependsOn.length === 0) { + waveMap.set(stepId, 0); + return 0; + } + let maxDep = 0; + for (const d of step.dependsOn) { + const depId = normalizeDep(d).stepId; + maxDep = Math.max(maxDep, computeWave(depId) + 1); + } + waveMap.set(stepId, maxDep); + return maxDep; + }; + for (const s of wf.steps) computeWave(s.id); + + const ordered = [...wf.steps].sort( + (a, b) => (waveMap.get(a.id) ?? 0) - (waveMap.get(b.id) ?? 0), + ); + + const steps: DryRunStepPlan[] = []; + for (const step of ordered) { + const deps = step.dependsOn.map(normalizeDep); + const wave = waveMap.get(step.id) ?? 0; + + if (step.type === 'transfer') { + const srcId = interpolateValuePlain(step.source.serverId, baseCtx); + const dstId = interpolateValuePlain(step.destination.serverId, baseCtx); + const srcSrv = allServers.find((s) => s.id === srcId && s.enabled); + const dstSrv = allServers.find((s) => s.id === dstId && s.enabled); + const targets: Array<{ serverId: string; serverName: string }> = []; + if (srcSrv) targets.push({ serverId: srcSrv.id, serverName: srcSrv.name }); + if (dstSrv && dstSrv.id !== srcSrv?.id) { + targets.push({ serverId: dstSrv.id, serverName: dstSrv.name }); + } + steps.push({ + stepId: step.id, + type: step.type, + wave, + dependsOn: deps, + targets, + transferPreview: { + mode: step.mode, + sourceServerId: srcId, + sourcePath: interpolateValuePlain(step.source.path, baseCtx), + destinationServerId: dstId, + destinationPath: interpolateValuePlain(step.destination.path, baseCtx), + }, + envKeys, + }); + continue; + } + + const matched = resolveTargetServers(step.target, allServers, baseCtx); + const plan: DryRunStepPlan = { + stepId: step.id, + type: step.type, + wave, + dependsOn: deps, + targets: matched.map((s) => ({ serverId: s.id, serverName: s.name })), + envKeys, + }; + + if (step.type === 'exec') { + plan.renderedCommand = interpolateShellCommandSafe(step.command, baseCtx); + } else if (step.type === 'read-file') { + plan.renderedPath = interpolateValuePlain(step.path, baseCtx); + } else if (step.type === 'system-action') { + plan.systemId = step.systemId; + plan.actionId = step.action; + const discoveredItems: Record = {}; + if (this.vaultService.isRuntimeReady && step.item === '*') { + for (const srv of matched) { + if (!srv.systems.some((a) => a.systemId === step.systemId)) continue; + try { + const snap = await this.customSystemsEngine.getServerSystem(srv.id, step.systemId); + discoveredItems[srv.id] = snap.items.map((i) => i.name); + } catch { + discoveredItems[srv.id] = []; + } + } + } + plan.discoveredItems = discoveredItems; + } + + steps.push(plan); + } + + return { + workflowId: wf.id, + workflowName: wf.name, + inputs, + steps, + }; + } + + private startExecution(req: QueuedRunRequest): void { + const emitter = new BufferedStreamEmitter(this.wsHub, `wf:${req.runId}`); + const abortController = new AbortController(); + const control: ActiveRunControl = { + runId: req.runId, + workflowId: req.workflow.id, + status: 'running', + abortController, + emitter, + done: false, + }; + + this.activeByWorkflow.set(req.workflow.id, control); + this.runsById.set(req.runId, control); + + this.auditService.log({ + action: 'workflow.start', + actorIp: req.actorIp, + sessionIdHash: req.sessionIdHash, + target: `${req.workflow.id}:${req.runId}`, + status: 'ok', + details: { triggerSource: req.triggerSource }, + }); + + this.broadcastRunFrame({ + runId: req.runId, + workflowId: req.workflow.id, + status: 'running', + triggerSource: req.triggerSource, + startedAt: req.startedAt, + }); + + emitter.pushMeta({ + event: 'start', + runId: req.runId, + workflowId: req.workflow.id, + triggerSource: req.triggerSource, + }); + + void this.executeDag(req, control) + .then((finalStatus) => { + control.done = true; + control.status = finalStatus; + this.markRunFinished( + req.runId, + req.workflow.id, + finalStatus, + req.triggerSource, + req.startedAt, + control.cancelledBy ?? null, + ); + emitter.pushMeta({ event: 'done', runId: req.runId, status: finalStatus }); + }) + .catch((err) => { + control.done = true; + const msg = err instanceof Error ? err.message : String(err); + emitter.push('stderr', `${msg}\n`); + control.status = abortController.signal.aborted ? 'cancelled' : 'failed'; + this.markRunFinished( + req.runId, + req.workflow.id, + control.status, + req.triggerSource, + req.startedAt, + control.cancelledBy ?? null, + ); + emitter.pushMeta({ event: 'done', runId: req.runId, status: control.status }); + }) + .finally(() => { + if (this.activeByWorkflow.get(req.workflow.id)?.runId === req.runId) { + this.activeByWorkflow.delete(req.workflow.id); + } + this.pruneRetainedStreams(); + this.pumpQueue(req.workflow.id); + }); + } + + private pumpQueue(workflowId: string): void { + if (this.closed || !this.vaultService.isRuntimeReady) return; + if (this.activeByWorkflow.has(workflowId)) return; + + const queue = this.queueByWorkflow.get(workflowId); + if (!queue || queue.length === 0) return; + const next = queue.shift()!; + if (queue.length === 0) this.queueByWorkflow.delete(workflowId); + + this.db + .prepare(`UPDATE workflow_runs SET status = 'running' WHERE run_id = ?`) + .run(next.runId); + this.startExecution(next); + } + + private async executeDag( + req: QueuedRunRequest, + control: ActiveRunControl, + ): Promise { + const wf = req.workflow; + const allServers = this.configManager.listServers(); + const stepOutputs = new Map(); + const captures = new Map(); + const terminalState = new Map(); + const runningPromises = new Map>(); + + let abortUnrelated = false; + let hasFatalFailure = false; + + while (terminalState.size < wf.steps.length) { + if (control.abortController.signal.aborted) { + if (runningPromises.size > 0) { + await Promise.allSettled(runningPromises.values()); + } + return 'cancelled'; + } + + let madeProgress = false; + + for (const step of wf.steps) { + if (terminalState.has(step.id) || runningPromises.has(step.id)) continue; + + const deps = step.dependsOn.map(normalizeDep); + if (!deps.every((d) => terminalState.has(d.stepId))) continue; + + let eligible = true; + if (deps.length === 0) { + if (abortUnrelated) eligible = false; + } else { + for (const d of deps) { + const depSt = terminalState.get(d.stepId)!; + if (d.on === 'success') { + if (depSt !== 'succeeded' || abortUnrelated) { + eligible = false; + break; + } + } else if (d.on === 'failure') { + if (depSt !== 'failed') { + eligible = false; + break; + } + } + } + + if (eligible) { + const allAlways = deps.every((d) => d.on === 'always'); + const anyNonSkipped = deps.some((d) => terminalState.get(d.stepId) !== 'skipped'); + if (allAlways && !anyNonSkipped) { + eligible = false; + } + if (abortUnrelated && deps.every((d) => d.on === 'success')) { + eligible = false; + } + } + } + + if (!eligible) { + terminalState.set(step.id, 'skipped'); + madeProgress = true; + continue; + } + + madeProgress = true; + const p = (async () => { + const ok = await this.runSingleStep( + wf, + step, + allServers, + req, + control, + stepOutputs, + captures, + ); + terminalState.set(step.id, ok ? 'succeeded' : 'failed'); + if (!ok && !control.abortController.signal.aborted) { + await this.handleStepFailure(wf, step, req, control); + const continueOnErr = + step.onFailure === 'continue' || + (typeof step.onFailure === 'object' && step.onFailure.action === 'continue'); + const forceAbort = + step.onFailure === 'abort' || + (typeof step.onFailure === 'object' && step.onFailure.action === 'abort'); + if (!continueOnErr) { + hasFatalFailure = true; + } + if (forceAbort || (wf.stopOnError && !continueOnErr)) { + abortUnrelated = true; + } + } + })() + .catch(() => { + terminalState.set(step.id, 'failed'); + hasFatalFailure = true; + if (wf.stopOnError && step.onFailure !== 'continue') { + abortUnrelated = true; + } + }) + .finally(() => { + runningPromises.delete(step.id); + }); + + runningPromises.set(step.id, p); + } + + if (runningPromises.size > 0) { + await Promise.race(runningPromises.values()); + } else if (!madeProgress) { + break; + } + } + + if (runningPromises.size > 0) { + await Promise.allSettled(runningPromises.values()); + } + + if (control.abortController.signal.aborted) { + return 'cancelled'; + } + return hasFatalFailure ? 'failed' : 'succeeded'; + } + + private async handleStepFailure( + wf: WorkflowConfig, + step: WorkflowStep, + req: QueuedRunRequest, + control: ActiveRunControl, + ): Promise { + const onFail = step.onFailure; + if (!onFail || onFail === 'abort' || onFail === 'continue') return; + + if (typeof onFail === 'string') { + const targetWf = this.configManager.getWorkflow(onFail); + if (targetWf) { + if (req.onFailureDepth < 1) { + await this.triggerWorkflow(targetWf.id, { + triggerSource: `onFailure:${wf.id}:${step.id}`, + onFailureDepth: req.onFailureDepth + 1, + }).catch(() => undefined); + } + } else if (this.failureNotifier) { + await this.failureNotifier( + onFail, + `Workflow "${wf.name}" (${wf.id}) failed at step "${step.id}" (run ${req.runId})`, + wf.id, + ).catch(() => undefined); + } + return; + } + + if (onFail.action === 'notify' && onFail.channelId && this.failureNotifier) { + await this.failureNotifier( + onFail.channelId, + `Workflow "${wf.name}" (${wf.id}) failed at step "${step.id}" (run ${req.runId})`, + wf.id, + ).catch(() => undefined); + } else if ( + onFail.action === 'run-workflow' && + onFail.workflowId && + req.onFailureDepth < 1 + ) { + await this.triggerWorkflow(onFail.workflowId, { + triggerSource: `onFailure:${wf.id}:${step.id}`, + onFailureDepth: req.onFailureDepth + 1, + }).catch(() => undefined); + } else { + void control; + } + } + + private async runSingleStep( + wf: WorkflowConfig, + step: WorkflowStep, + allServers: ServerConfig[], + req: QueuedRunRequest, + control: ActiveRunControl, + stepOutputs: Map, + captures: Map, + ): Promise { + const timeoutMs = (step.timeoutSec ?? 300) * 1000; + const stepAbort = new AbortController(); + const onParentAbort = () => stepAbort.abort(); + if (control.abortController.signal.aborted) { + return false; + } + control.abortController.signal.addEventListener('abort', onParentAbort, { once: true }); + + let timedOut = false; + const stepTimer = setTimeout(() => { + timedOut = true; + stepAbort.abort(); + }, timeoutMs); + stepTimer.unref(); + + const makeCtx = (serverId?: string): TemplateContext => ({ + workflowId: wf.id, + runId: req.runId, + serverId, + inputs: req.inputs, + stepOutputs, + captures, + eventMeta: req.eventMeta, + }); + + control.emitter.pushMeta({ event: 'step-start', stepId: step.id, type: step.type }); + + try { + if (step.type === 'transfer') { + const ctx = makeCtx(); + const srcServerId = interpolateValuePlain(step.source.serverId, ctx); + const srcPath = interpolateValuePlain(step.source.path, ctx); + const dstServerId = interpolateValuePlain(step.destination.serverId, ctx); + const dstPath = interpolateValuePlain(step.destination.path, ctx); + + const started = Date.now(); + try { + const xfer = await this.transferEngine.transfer({ + mode: step.mode, + source: { serverId: srcServerId, path: srcPath }, + destination: { serverId: dstServerId, path: dstPath }, + sudo: step.sudo, + timeoutMs, + signal: stepAbort.signal, + onProgress: (msg) => { + control.emitter.push('stdout', `[${step.id}] ${msg}\n`); + }, + }); + const summaryJson = JSON.stringify(xfer); + this.recordStepLog( + req.runId, + step.id, + `${srcServerId}->${dstServerId}`, + 0, + xfer.durationMs, + summaryJson, + '', + ); + stepOutputs.set(step.id, { stdout: xfer.destinationPath, exitCode: 0 }); + if (step.captureAs) captures.set(step.captureAs, xfer.destinationPath); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); + return true; + } catch (err) { + const msg = timedOut + ? `Step "${step.id}" timed out after ${timeoutMs}ms` + : err instanceof Error + ? err.message + : String(err); + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + `${srcServerId}->${dstServerId}`, + 1, + Date.now() - started, + '', + msg, + ); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return false; + } + } + + const targets = resolveTargetServers(step.target, allServers, makeCtx()); + if (targets.length === 0) { + const msg = `No enabled target servers matched step "${step.id}"`; + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return false; + } + + if (step.type === 'exec') { + let allOk = true; + const stdouts: string[] = []; + let lastExit: number | null = 0; + + await runWithConcurrency(targets, step.concurrency ?? wf.concurrency, async (srv) => { + const started = Date.now(); + const ctx = makeCtx(srv.id); + const env = buildWorkflowEnv(ctx); + const cmd = interpolateShellCommandSafe(step.command, ctx); + try { + const res = await this.execStreamAbortable(srv.id, cmd, { + env, + sudo: step.sudo, + signal: stepAbort.signal, + onStdout: (txt) => control.emitter.push('stdout', `[${step.id}@${srv.id}] ${txt}`), + onStderr: (txt) => control.emitter.push('stderr', `[${step.id}@${srv.id}] ${txt}`), + }); + this.recordStepLog( + req.runId, + step.id, + srv.id, + res.exitCode, + res.durationMs, + res.stdout, + res.stderr, + ); + stdouts.push(res.stdout); + lastExit = res.exitCode; + if (res.exitCode !== 0) allOk = false; + } catch (err) { + allOk = false; + lastExit = 1; + const msg = timedOut + ? `Timed out after ${timeoutMs}ms` + : err instanceof Error + ? err.message + : String(err); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + } + }); + + const joined = stdouts.join('\n'); + stepOutputs.set(step.id, { stdout: joined, exitCode: lastExit }); + if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); + return allOk; + } + + if (step.type === 'read-file') { + let allOk = true; + const contents: string[] = []; + + await runWithConcurrency(targets, wf.concurrency, async (srv) => { + const started = Date.now(); + const ctx = makeCtx(srv.id); + const remotePath = interpolateValuePlain(step.path, ctx); + const tailRaw = + typeof step.tailLines === 'number' + ? step.tailLines + : typeof step.tailLines === 'string' + ? Number(interpolateValuePlain(step.tailLines, ctx)) + : undefined; + + try { + let text = ''; + try { + const fileRes = await this.sftpService.readTextFile(srv.id, remotePath, { + sudo: step.sudo, + }); + text = fileRes.content; + if (tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { + const lines = text.replace(/\n$/, '').split(/\r?\n/); + text = `${lines.slice(-Math.floor(tailRaw)).join('\n')}\n`; + } + } catch (readErr) { + const code = (readErr as { code?: string }).code; + if (code === 'FILE_TOO_LARGE' && tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { + const execRes = await this.execStreamAbortable( + srv.id, + `tail -n ${Math.floor(tailRaw)} -- ${posixSingleQuote(remotePath)}`, + { sudo: step.sudo, signal: stepAbort.signal }, + ); + if (execRes.exitCode !== 0) { + throw new Error(execRes.stderr.trim() || `tail failed for ${remotePath}`); + } + text = execRes.stdout; + } else { + throw readErr; + } + } + + control.emitter.push('stdout', `[${step.id}@${srv.id}] ${text}`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 0, + Date.now() - started, + text, + '', + ); + contents.push(text); + } catch (err) { + allOk = false; + const msg = err instanceof Error ? err.message : String(err); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + } + }); + + const joined = contents.join('\n'); + stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); + if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); + return allOk; + } + + // system-action step + const attachedTargets = targets.filter((s) => + s.systems.some((a) => a.systemId === step.systemId), + ); + if (attachedTargets.length === 0) { + const msg = `No matched server has system "${step.systemId}" attached`; + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return false; + } + + const system = this.configManager.getSystem(step.systemId); + const actionDef = system?.actions.find((a) => a.id === step.action); + let allOk = true; + const sysOutputs: string[] = []; + + await runWithConcurrency(attachedTargets, step.concurrency ?? wf.concurrency, async (srv) => { + const started = Date.now(); + const ctx = makeCtx(srv.id); + const itemSpec = interpolateValuePlain(step.item, ctx); + const subItemVal = step.subItem ? interpolateValuePlain(step.subItem, ctx) : undefined; + + try { + if (actionDef?.scope === 'system') { + const res = await this.customSystemsEngine.executeActionBlocking({ + serverId: srv.id, + systemId: step.systemId, + actionId: step.action, + timeoutMs, + signal: stepAbort.signal, + onChunk: (st, txt) => control.emitter.push(st, `[${step.id}@${srv.id}] ${txt}`), + }); + this.recordStepLog( + req.runId, + step.id, + srv.id, + res.exitCode, + res.durationMs, + res.stdout, + res.stderr, + ); + sysOutputs.push(res.stdout); + if (res.exitCode !== 0) allOk = false; + return; + } + + let itemNames: string[]; + if (itemSpec === '*') { + const snap = await this.customSystemsEngine.getServerSystem(srv.id, step.systemId, { + forceRefresh: true, + }); + itemNames = snap.items.map((i) => i.name); + } else { + itemNames = [itemSpec]; + } + + if (itemNames.length === 0) { + this.recordStepLog( + req.runId, + step.id, + srv.id, + 0, + Date.now() - started, + `No discovered items for ${step.systemId}`, + '', + ); + return; + } + + for (const itemName of itemNames) { + const res = await this.customSystemsEngine.executeActionBlocking({ + serverId: srv.id, + systemId: step.systemId, + actionId: step.action, + itemName, + subItemName: subItemVal, + timeoutMs, + signal: stepAbort.signal, + onChunk: (st, txt) => + control.emitter.push(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), + }); + this.recordStepLog( + req.runId, + step.id, + `${srv.id}:${itemName}`, + res.exitCode, + res.durationMs, + res.stdout, + res.stderr, + ); + sysOutputs.push(res.stdout); + if (res.exitCode !== 0) allOk = false; + } + } catch (err) { + allOk = false; + const msg = err instanceof Error ? err.message : String(err); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + } + }); + + const joined = sysOutputs.join('\n'); + stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); + if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); + return allOk; + } finally { + clearTimeout(stepTimer); + control.abortController.signal.removeEventListener('abort', onParentAbort); + } + } + + private async execStreamAbortable( + serverId: string, + command: string, + opts: { + env?: Record; + sudo?: boolean; + signal: AbortSignal; + onStdout?: (text: string) => void; + onStderr?: (text: string) => void; + }, + ): Promise<{ exitCode: number | null; stdout: string; stderr: string; durationMs: number }> { + if (opts.signal.aborted) { + throw new Error('Workflow step aborted'); + } + + const started = Date.now(); + const handle = await this.sshPool.execStream(serverId, command, { + env: opts.env, + sudo: opts.sudo, + }); + + const outChunks: Buffer[] = []; + const errChunks: Buffer[] = []; + let outLen = 0; + let errLen = 0; + + return new Promise((resolve, reject) => { + let settled = false; + const cleanup = () => { + opts.signal.removeEventListener('abort', onAbort); + }; + const onAbort = () => { + handle.abort(); + if (!settled) { + settled = true; + cleanup(); + reject(new Error('Workflow step aborted')); + } + }; + + if (opts.signal.aborted) { + onAbort(); + return; + } + opts.signal.addEventListener('abort', onAbort, { once: true }); + + handle.channel.on('data', (chunk: Buffer) => { + if (outLen < MAX_OUTPUT_CHARS) { + outChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - outLen)); + outLen += chunk.length; + } + opts.onStdout?.(chunk.toString('utf8')); + }); + handle.channel.stderr?.on('data', (chunk: Buffer) => { + if (errLen < MAX_OUTPUT_CHARS) { + errChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - errLen)); + errLen += chunk.length; + } + opts.onStderr?.(chunk.toString('utf8')); + }); + + handle.done + .then(({ exitCode }) => { + if (!settled) { + settled = true; + cleanup(); + resolve({ + exitCode, + stdout: Buffer.concat(outChunks).toString('utf8'), + stderr: Buffer.concat(errChunks).toString('utf8'), + durationMs: Date.now() - started, + }); + } + }) + .catch((err) => { + if (!settled) { + settled = true; + cleanup(); + reject(err); + } + }); + }); + } + + private recordStepLog( + runId: string, + stepId: string, + serverId: string, + exitCode: number | null, + durationMs: number, + stdout: string, + stderr: string, + ): void { + this.db + .prepare( + `INSERT INTO workflow_step_logs (run_id, step_id, server_id, exit_code, duration_ms, stdout, stderr, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + runId, + stepId, + serverId, + exitCode, + Math.max(0, Math.round(durationMs)), + stdout.slice(0, MAX_OUTPUT_CHARS), + stderr.slice(0, MAX_OUTPUT_CHARS), + Date.now(), + ); + } + + private markRunFinished( + runId: string, + workflowId: string, + status: WorkflowRunStatus, + triggerSource: string, + startedAt: number, + cancelledBy: string | null, + ): void { + const finishedAt = Date.now(); + this.db + .prepare( + `UPDATE workflow_runs + SET status = ?, finished_at = ?, cancelled_by = ? + WHERE run_id = ?`, + ) + .run(status, finishedAt, cancelledBy, runId); + + this.broadcastRunFrame({ + runId, + workflowId, + status, + triggerSource, + startedAt, + finishedAt, + }); + } + + private broadcastRunFrame(frame: { + runId: string; + workflowId: string; + status: WorkflowRunStatus; + triggerSource: string; + startedAt: number; + finishedAt?: number | null; + }): void { + this.wsHub.broadcastChannel(WS_CHANNELS.WORKFLOWS, { + type: 'workflow:run', + ...frame, + }); + } + + private pruneRetainedStreams(): void { + const doneRuns = [...this.runsById.values()].filter((r) => r.done); + while (doneRuns.length > MAX_RETAINED_STREAM_RUNS) { + const oldest = doneRuns.shift()!; + this.runsById.delete(oldest.runId); + } + } +}