UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

638 lines (637 loc) • 26.7 kB
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /** * Managed-subprocess primitive. * * The battle-tested spawn/timeout/abort/capture core, extracted from the agent * CLI spawn wrapper so non-agent subprocess callers (task commands, setup * probes/installers) get the same guarantees the agent path already had: * * • Process-GROUP spawn (`detached: true` ON POSIX when capturing or when akm * has no controlling terminal) so a negative-pid kill reaps the whole * descendant tree — no orphaned children. See {@link childGroup} for the * decision and why Windows is excluded. * • A SIGINT→SIGTERM→SIGKILL kill ladder on timeout/abort — SIGINT first, as * a Ctrl-C would, so a program that treats an interrupt as a stop can wind * the run down; a child that ignores it is terminated, and one that ignores * that is force-killed, each after a grace period, instead of wedging forever. * • Time-bounded output capture ({@link readStream}) that cannot block past * the wall budget even when the child leaves a pipe endpoint open, plus an * OPT-IN RETENTION cap (`maxOutputBytes`); see {@link readStream} for what * the cap does and does not bound. * • Injectable `spawnFn`/`setTimeoutFn`/`clearTimeoutFn` seams so callers * can drive the machinery deterministically in tests. * * Runtime boundary: the default spawn comes from `../runtime`; this module * never touches `Bun.*` directly. It also never imports from `integrations/` * or `tasks/` — it is a leaf primitive those layers consume. */ import fs from "node:fs"; import { spawn as runtimeSpawn } from "../runtime.js"; import { endBySignal, guardSignal, hasSignalOwner } from "./signal-observers.js"; /** * Whether this process has a controlling terminal: the kernel's answer to opening `/dev/tty`, not a guess * from whether the standard streams are terminals. */ export function hasControllingTerminal() { try { // asset-io: host controlling terminal fs.closeSync(fs.openSync("/dev/tty", "r")); return true; } catch { return false; } } /** * Which process group a child runs in. * * `"own"` on POSIX when output is captured, or when akm has no controlling terminal (cron, systemd, CI, an * agent's shell tool): `detached` is `setsid()`, which is what makes {@link killGroup}'s * `process.kill(-pid, …)` reap the whole descendant tree. It does not touch the child's stdio. * * `"shared"` for an uncaptured child on a terminal: a session of its own would take the controlling * terminal away, so no `/dev/tty` prompts, no job control, and Ctrl-C and Ctrl-Z would reach akm's group * only. The child stays in akm's group and the terminal's signals reach it directly. * * Windows is always `"shared"`: there `detached` means something unrelated and actively harmful. It maps to * `DETACHED_PROCESS`, so the child is created WITHOUT A CONSOLE; a console host started that way * (powershell.exe, cmd.exe) allocates its own console during startup, which REPLACES the std handles it was * handed, and everything it writes goes to that phantom console instead of our pipe. The command still runs * and its exit code still propagates — the output just vanishes, which is exactly how it failed: a scheduled * `akm --version` logged `exit_code=0` with both captured streams empty. Windows gains nothing in return, * because `process.kill(-pid, …)` is a POSIX process-group call that throws there. * * Exported for direct unit testing with explicit inputs. */ export function childGroup(capture, platform, hasTerminal) { if (platform === "win32") return "shared"; return capture || !hasTerminal ? "own" : "shared"; } /** * The exact options one managed run hands its spawn — pure, so the platform * dependency above is testable on any host rather than only on the platform * that would break. */ export function buildSpawnOptions(opts, group) { const capture = opts.capture; return { stdin: capture ? (opts.stdin !== undefined ? "pipe" : "ignore") : "inherit", stdout: capture ? "pipe" : "inherit", stderr: capture ? "pipe" : "inherit", ...(opts.env ? { env: opts.env } : {}), ...(opts.cwd ? { cwd: opts.cwd } : {}), ...(group === "own" ? { detached: true } : {}), ...(opts.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), }; } /** * Signal `proc`: its whole process group when it leads one of its own, falling back to * `proc.kill(signal)` when `proc.pid` is unavailable (e.g. test fakes) or the group is gone. A child that * shares akm's group is signalled alone, never through `-pid`. * * Passing a negative PID to `process.kill` targets the entire process * group, so opencode's child processes (the .opencode binary, etc.) are * reaped alongside the node wrapper. */ export function killGroup(proc, signal, group = "own") { if (group === "own" && typeof proc.pid === "number") { try { process.kill(-proc.pid, signal); return; } catch { // Process may have already exited; fall through to direct kill. } } try { proc.kill(signal); } catch { /* ignore */ } } /** Whether anything still runs in `proc`'s own process group (the leader included), or the leader has not exited. */ function groupRunning(proc, group) { if (group === "own" && typeof proc.pid === "number") { try { process.kill(-proc.pid, 0); return true; } catch { // No member is left, or the child leads no group of its own: only the leader's own exit tells. } } return proc.exitCode === null; } /** * SIGINT→SIGTERM→SIGKILL kill ladder shared by the timeout and abort paths. * No-op when the child has already exited; otherwise runs `onKill` * (the caller's reason flag — `timedOut` / `aborted` — set BEFORE the first * signal, exactly as the inlined copies did) and interrupts the process group. * SIGTERM follows when `graceMs` runs out or as soon as the leader exits, * whichever is first, because members of the group can outlive it: a job a * shell started in the background ignores SIGINT. SIGKILL follows another * `graceMs` later if anything in the group still runs. The timers are unref'ed * so they never pin the event loop. * * SIGINT goes first because it is what a person's Ctrl-C sends, and a program * that records how a run ended acts on it: the OpenCode 2 CLI marks its session * interrupted and releases its claim, where on SIGTERM or SIGKILL the session * stays suspended and OpenCode's own service may resume it later. */ export function scheduleKillLadder(proc, opts) { const group = opts.group ?? "own"; if (!proc || !groupRunning(proc, group)) return; opts.onKill(); const afterGrace = (run) => { const timer = opts.setTimeoutFn(run, opts.graceMs ?? 5000); if (typeof timer !== "number") timer.unref?.(); }; killGroup(proc, "SIGINT", group); let terminated = false; const terminate = () => { if (terminated || !groupRunning(proc, group)) return; terminated = true; killGroup(proc, "SIGTERM", group); afterGrace(() => { if (groupRunning(proc, group)) killGroup(proc, "SIGKILL", group); }); }; afterGrace(terminate); proc.exited.then(terminate, terminate); } const liveChildren = new Set(); let removeGuardListeners; function removeSignalGuard() { for (const remove of removeGuardListeners ?? []) remove(); removeGuardListeners = undefined; } /** * Every signal the guard takes, for every child; what each child gets is decided per child when one arrives. * A child in its own process group is out of reach of the terminal's Ctrl-C and of a `kill <akm-pid>`: * without the guard, a signal to akm ended akm and left the harness CLI (and everything it started) * running. It takes the same ladder as a timeout, and once every child is gone the signal is re-raised so * akm ends by the signal itself. * * A child that shares akm's group got the terminal's SIGINT and SIGQUIT already. akm ignores them while the * child lives and ends with the child's status, as `system(3)` does: a child that handles Ctrl-C and goes on * (a shell at its prompt) keeps akm waiting. SIGTERM and SIGHUP reach akm alone, so they are forwarded to * the child and re-raised once it has exited. * * The guard reaches every live child. A process that owns a signal (a listener that is not one of akm's * own observers: a host that embeds akm, `workflow run`, task runs, `index`) decides how akm ends, and the * guard leaves the exit to it. With no owner, akm ends by the signal once its children are gone. * * They go in BEFORE the spawn ({@link installSignalGuard}): a signal that lands between the spawn and the * registration would otherwise meet the default disposition, end akm, and leave the new group running * (#1230). The listener runs on the event loop, so it always sees the child registered here. */ function registerLiveChild(child) { liveChildren.add(child); return () => { liveChildren.delete(child); if (liveChildren.size === 0) removeSignalGuard(); }; } function installSignalGuard() { if (removeGuardListeners) return; let reraise; const removers = []; for (const signal of ["SIGINT", "SIGQUIT", "SIGTERM", "SIGHUP"]) { const handler = () => { if (reraise) return; const children = [...liveChildren]; const reachesAkmAlone = signal === "SIGTERM" || signal === "SIGHUP"; let stoppedOwn = false; for (const live of children) { if (live.group === "own") { live.terminate(); stoppedOwn = true; } else if (reachesAkmAlone) live.proc.kill(signal); } // Only the terminal's signals to shared children remain: they have it, akm just waits. if (!reachesAkmAlone && !stoppedOwn) return; if (hasSignalOwner(signal)) return; reraise = signal; void Promise.allSettled(children.map((live) => live.proc.exited)).then(() => { removeSignalGuard(); endBySignal(signal); process.exit(); }); }; removers.push(guardSignal(signal, handler)); } removeGuardListeners = removers; } /** * The joined, human-readable reason ONE managed run's capture is incomplete, or * `undefined` when both pipes drained cleanly. * * Shared so every caller that promotes captured output treats an incomplete * capture the same way. A pipe that errored, or that hit the stream-drain * timeout because a background descendant kept the fd open after the leader * exited 0, yields a PARTIAL string — and a caller that reads only `exitCode` * would promote that partial as if it were the command's whole output. * `maxBytes` overflow is deliberately NOT reported here: it is a distinct, * caller-classified condition (see {@link StreamReadResult.overflowed}), not a * drain malfunction. */ export function streamCaptureFailure(stdout, stderr) { const failures = []; if (stdout.error) failures.push(`stdout read failed: ${errorText(stdout.error)}`); if (stderr.error) failures.push(`stderr read failed: ${errorText(stderr.error)}`); if (stdout.timedOut) failures.push("stdout drain timed out"); if (stderr.timedOut) failures.push("stderr drain timed out"); return failures.length === 0 ? undefined : failures.join("; "); } function errorText(error) { return error instanceof Error ? error.message : String(error); } const STREAM_READ_TIMEOUT = Symbol("stream-read-timeout"); /** * Index at or before `limit` where a UTF-8 CHARACTER starts, so a retention cut * never lands inside a multi-byte sequence. Continuation bytes are `10xxxxxx`; * a well-formed sequence has at most three of them, so this walks back at most * three positions. */ function utf8BoundaryAtOrBefore(value, limit) { let cut = limit; while (cut > 0 && (value[cut] & 0xc0) === 0x80) cut--; return cut; } /** * Drain a readable stream to text, optionally racing each read against a * timeout so a process that is killed via SIGINT/SIGTERM/SIGKILL but whose pipe * endpoints stay open (e.g. background threads still holding the fd) cannot * block the caller indefinitely. On timeout we return whatever was decoded * before the pipe stopped draining. * * ## The `maxBytes` cap bounds MEMORY, not the child * * The drain ALWAYS runs to the end of the stream. `maxBytes` caps only what is * RETAINED: once the cap is reached the loop keeps calling `reader.read()` and * throws the bytes away. That is what makes the cap safe to impose on a * process that is still running — a reader that stopped pulling would fill the * pipe buffer and BLOCK the child on its next write, turning "the output got * long" into "the command hangs until the wall timeout". Draining and * discarding costs nothing but the reads, and the child finishes normally. */ export async function readStream(stream, opts) { if (!stream) return { text: "", timedOut: false, overflowed: false, bytesRead: 0, retainedBytes: 0 }; const reader = stream.getReader(); const decoder = new TextDecoder(); const maxBytes = opts?.maxBytes; let text = ""; let bytesRead = 0; let retainedBytes = 0; let overflowed = false; /** * Common per-chunk accumulate. Uncapped it appends everything. Capped, it * appends until the cap and then only COUNTS — the caller's loop keeps reading * either way, which is the whole point. */ const absorb = (value) => { bytesRead += value.byteLength; if (maxBytes === undefined) { retainedBytes += value.byteLength; text += decoder.decode(value, { stream: true }); return; } // Already past the cap: discard. Never resume retaining — a gap in the // middle would splice two disjoint regions into one string. if (overflowed) return; if (retainedBytes + value.byteLength <= maxBytes) { retainedBytes += value.byteLength; text += decoder.decode(value, { stream: true }); return; } overflowed = true; const keep = utf8BoundaryAtOrBefore(value, maxBytes - retainedBytes); if (keep > 0) { retainedBytes += keep; text += decoder.decode(value.subarray(0, keep), { stream: true }); } }; if (!opts?.timeoutMs) { try { while (true) { const chunk = await reader.read(); if (chunk.done) break; absorb(chunk.value); } text += decoder.decode(); return { text, timedOut: false, overflowed, bytesRead, retainedBytes }; } catch (error) { return { text, timedOut: false, error, overflowed, bytesRead, retainedBytes }; } finally { try { reader.releaseLock(); } catch { /* ignore */ } } } const setTimeoutImpl = opts.setTimeoutFn ?? setTimeout; const clearTimeoutImpl = opts.clearTimeoutFn ?? clearTimeout; const timeoutMs = opts.timeoutMs; let timer; let drained = false; const timeoutPromise = new Promise((resolve) => { const arm = () => { // The drain already finished while the deadline was still waiting to be // armed; a timer started now would belong to nobody. if (drained) return; timer = setTimeoutImpl(() => { timer = undefined; resolve(STREAM_READ_TIMEOUT); }, timeoutMs); if (typeof timer !== "number") timer.unref?.(); }; if (opts.armTimeoutAfter) void opts.armTimeoutAfter.then(arm, arm); else arm(); }); try { while (true) { const chunk = await Promise.race([reader.read(), timeoutPromise]); if (chunk === STREAM_READ_TIMEOUT) { void reader.cancel().catch(() => { }); return { text, timedOut: true, overflowed, bytesRead, retainedBytes }; } if (chunk.done) break; absorb(chunk.value); } text += decoder.decode(); return { text, timedOut: false, overflowed, bytesRead, retainedBytes }; } catch (error) { return { text, timedOut: false, error, overflowed, bytesRead, retainedBytes }; } finally { drained = true; if (timer !== undefined) { clearTimeoutImpl(timer); } try { reader.releaseLock(); } catch { /* ignore */ } } } const EMPTY_READ = { text: "", timedOut: false, overflowed: false, bytesRead: 0, retainedBytes: 0, }; /** * How long a captured pipe may stay open after the pipe's owner left, with or without a wall budget: the * child exited, or (a child that survived its own kill ladder) the budget expired. Anything still holding * the fd open then is a background descendant, not the command. It bounds only what a pipe does after its * owner is gone, so it never caps the run itself. */ const POST_EXIT_STREAM_DRAIN_GRACE_MS = 2_000; function toError(err) { return err instanceof Error ? err : new Error(String(err)); } /** * Spawn `cmd` and manage its lifecycle: process-group spawn, hard timeout and * cooperative abort (both via the SIGINT→SIGTERM→SIGKILL {@link scheduleKillLadder}), * bounded output capture, and an optional stdin payload. Never throws for a * spawn/exit failure — those surface as {@link ManagedSubprocessResult.spawnError}. */ export async function runManagedSubprocess(cmd, opts) { const setTimeoutImpl = opts.setTimeoutFn ?? setTimeout; const clearTimeoutImpl = opts.clearTimeoutFn ?? clearTimeout; const drainGraceMs = opts.drainGraceMs ?? POST_EXIT_STREAM_DRAIN_GRACE_MS; const spawnFn = opts.spawnFn ?? runtimeSpawn; const capture = opts.capture; const timeoutMs = opts.timeoutMs; // Refuse to spawn at all when the caller's signal is already aborted. if (opts.signal?.aborted) { return { exitCode: null, signal: null, stdout: "", stderr: "", timedOut: false, aborted: true, stdoutRead: EMPTY_READ, stderrRead: EMPTY_READ, }; } // A termination signal to this process reaches the child too (see installSignalGuard). const group = childGroup(capture, process.platform, !capture && hasControllingTerminal()); const guardsChild = process.platform !== "win32"; if (guardsChild) installSignalGuard(); let proc; try { proc = spawnFn(cmd, buildSpawnOptions(opts, group)); } catch (err) { if (guardsChild && liveChildren.size === 0) removeSignalGuard(); return { exitCode: null, signal: null, stdout: "", stderr: "", timedOut: false, aborted: false, spawnError: toError(err), stdoutRead: EMPTY_READ, stderrRead: EMPTY_READ, }; } opts.onSpawn?.(proc); // Hard timeout: SIGINT now, SIGTERM and SIGKILL after each grace period if ignored. // Skipped entirely when timeoutMs is null. let timedOut = false; let timer; // Settles when a bounded run's wall budget expires — the second way (after // the child's own exit) a captured pipe can stop belonging to a live command. // See the drain-deadline note below. let onBudgetExpiry; const budgetExpired = capture && timeoutMs !== null ? new Promise((resolve) => { onBudgetExpiry = resolve; }) : undefined; // The kill ladder starts at most once, whichever of the timeout, the abort and the signal guard starts it. let stopping = false; const stop = (onKill) => { if (stopping) return; stopping = true; scheduleKillLadder(proc, { onKill, group, setTimeoutFn: setTimeoutImpl, ...(opts.graceMs !== undefined ? { graceMs: opts.graceMs } : {}), }); }; if (timeoutMs !== null) { timer = setTimeoutImpl(() => { onBudgetExpiry?.(); stop(() => { timedOut = true; }); }, timeoutMs); } // Cooperative cancel: same ladder, flagged separately so the caller can tell // a budget/user abort from a wall-clock expiry. let aborted = false; const abortSignal = opts.signal; const onAbort = () => { stop(() => { aborted = true; }); }; if (abortSignal) { // A signal that aborted between the pre-spawn check and here fires the // listener directly (the "abort" event would otherwise never re-dispatch). if (abortSignal.aborted) onAbort(); else abortSignal.addEventListener("abort", onAbort, { once: true }); } const unregisterLiveChild = guardsChild ? registerLiveChild({ proc, group, terminate: onAbort }) : () => { }; // Stream-drain timeout: a short grace once nothing living owns the pipe any more, counted from the child's // exit (never from capture) and, for a bounded run, from the wall budget's expiry if that came first. // // It is not armed while the command is still running: every byte up to then is a live process's, and // cancelling the reader would discard the output of work that is still going. A leader exiting in // milliseconds does not hold the drain (and with it the unit, and with it a fan-out slot) open for a // budget it never came close to spending. // Settles on a rejected `proc.exited` too: either way the child is gone. const childSettled = capture ? proc.exited.catch(() => undefined) : undefined; // What the leader left behind in its own process group is stopped once the drain has had its grace (see // below), so a daemon that holds the pipe cannot keep the run waiting. One that wants to outlive the run // starts its own session. const { promise: bothDrained, resolve: drainStarted } = Promise.withResolvers(); const leftoversStopped = childSettled?.then(async () => { if (group !== "own") return; let graceTimer; await Promise.race([ bothDrained, new Promise((resolve) => { graceTimer = setTimeoutImpl(resolve, drainGraceMs); if (typeof graceTimer !== "number") graceTimer.unref?.(); }), ]); clearTimeoutImpl(graceTimer); if (groupRunning(proc, group)) stop(() => { }); }); const pipeOwnerGone = leftoversStopped && budgetExpired ? Promise.race([leftoversStopped, budgetExpired]) : leftoversStopped; const readOpts = { timeoutMs: drainGraceMs, setTimeoutFn: setTimeoutImpl, clearTimeoutFn: clearTimeoutImpl, ...(pipeOwnerGone ? { armTimeoutAfter: pipeOwnerGone } : {}), ...(opts.maxOutputBytes !== undefined ? { maxBytes: opts.maxOutputBytes } : {}), }; const stdoutPromise = capture ? readStream(proc.stdout ?? null, readOpts) : Promise.resolve(EMPTY_READ); const stderrPromise = capture ? readStream(proc.stderr ?? null, readOpts) : Promise.resolve(EMPTY_READ); drainStarted(Promise.all([stdoutPromise, stderrPromise])); // Optional stdin payload (captured mode only). Race the write/close against // proc.exited so a child that never drains stdin cannot pin us past the // timeout. if (opts.stdin !== undefined && capture && proc.stdin) { const stdinPayload = opts.stdin; const stdinStream = proc.stdin; const stdinDone = (async () => { try { // Bun.spawn's pipe is a FileSink (write/end), not a WritableStream. const sink = stdinStream; if (typeof sink.write === "function" && typeof sink.end === "function" && !("getWriter" in stdinStream)) { sink.write(stdinPayload); await sink.end(); } else { const writer = stdinStream.getWriter(); await writer.write(new TextEncoder().encode(stdinPayload)); await writer.close(); } } catch { // Best-effort: ignore stdin write failures, the child will get EOF. } })(); await Promise.race([stdinDone, proc.exited.catch(() => undefined)]); } let exitCode = null; try { exitCode = await proc.exited; } catch (err) { if (timer !== undefined) clearTimeoutImpl(timer); abortSignal?.removeEventListener("abort", onAbort); unregisterLiveChild(); // Drain readers so they don't surface as unhandled rejections. The streams // carry their own drain timeout so this cannot block indefinitely. await Promise.allSettled([stdoutPromise, stderrPromise]); return { exitCode: null, signal: null, stdout: "", stderr: "", timedOut: false, aborted: false, spawnError: toError(err), stdoutRead: EMPTY_READ, stderrRead: EMPTY_READ, }; } clearTimeoutImpl(timer); abortSignal?.removeEventListener("abort", onAbort); unregisterLiveChild(); const [stdoutRead, stderrRead] = await Promise.all([stdoutPromise, stderrPromise]); return { exitCode, signal: proc.signalCode ?? null, stdout: stdoutRead.text, stderr: stderrRead.text, timedOut, aborted, stdoutRead, stderrRead, }; }