/** * The process-task store: the one place that knows which tasks a session has, * how they are identified, and how a running process becomes a finished record. * * Every session owns one `TaskStore` under its state directory, and every change * to a record is followed by a save. Loading the first time a session is touched * is what makes history survive a restart: records come back from disk, and a * record that still says `running` is marked `interrupted` because whatever ran * it is gone. Nothing is adopted and nothing is killed on load — the store reads * files and leaves every process alone. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ import { type OutputTail } from "../base/output.js"; import { type TaskScope } from "../base/runtime-state.js"; import type { KillReason, ProcessTask } from "../base/task.js"; import type { OwnedTaskSession, TaskSessions } from "../base/task-sessions.js"; import { type ShellChoice, type ShellPolicy } from "./shell.js"; import { type RunningProcess, type StartProcessOptions } from "./supervisor.js"; export type { TaskScope }; export interface StartProcessTaskInput extends TaskScope { command: string; name?: string; /** * Runtime cap in whole milliseconds, measured from the start. The tool parses * seconds; the record and the timer speak milliseconds. */ timeoutMs?: number; /** Shell for this command; the configured one unless the call picks another. */ shell?: ShellChoice; /** * Directory for this call, relative to the session's cwd unless it is absolute. * Resolved once, before a record exists; the record keeps the absolute path. */ workingDirectory?: string; /** * Variables for the child only, merged over the extension's environment. Not * recorded: a task file is not a safe place for a token, and the child already * has what it needs. */ env?: Record; /** * The cmd loop whose fire starts this process (ADR-0014). The child keeps an * ordinary process id and carries the link in its record, never in the id. */ parentId?: string; /** One-based fire number of the owning loop; always given with `parentId`. */ fire?: number; } /** An id and an output file held for a command that runs in the foreground (ADR-0020). */ export interface ForegroundReservation { readonly id: string; /** Directory the command runs in, resolved before the spawn. */ readonly cwd: string; /** File the supervisor writes the command's output to. */ readonly outputPath: string; } /** What a foreground command needs before it can be spawned. */ export interface ReserveForegroundInput extends TaskScope { /** * Directory for this call, relative to the session's cwd unless it is absolute. * Same rule as a background task: resolved once, before anything is spawned. */ readonly workingDirectory?: string; } /** A reserved foreground command, handed to the supervisor. */ export interface SpawnForegroundInput { readonly command: string; readonly cwd: string; readonly outputPath: string; readonly env?: Record; readonly shell?: ShellChoice; /** Called once when a chunk is dropped for crossing the output cap. */ readonly onOutputCap?: () => void; } /** What a reservation becomes once a process stands behind it. */ export interface AdoptForegroundInput extends TaskScope { readonly command: string; readonly reservation: ForegroundReservation; /** The process already running: the one thing a detach hands over. */ readonly running: RunningProcess; /** * When the process itself started, before it was a task. The record's age and * its `createdAt` come from here, so a caller reporting a detached command does * not under-report how long it has been running. */ readonly startedAt?: number; readonly name?: string; } /** A task as it looks right now: the record plus the values that keep moving. */ export interface ProcessTaskView { task: ProcessTask; /** Milliseconds from creation to end, or to now while it runs. */ elapsedMs: number; /** Bytes in the output file, live for a running task. */ outputBytes: number; } /** What a stop is asked for. The reason defaults to the user's own kill. */ export interface StopTaskOptions { reason?: KillReason; /** Overrides the store's grace period, mostly for tests. */ graceMs?: number; /** Overrides the store's forced-kill confirmation window. */ confirmMs?: number; } /** How `stop` answered. */ export type StopTaskOutcome = "killed" | "already-finished" | "tree-survived"; export interface StopTaskResult { /** The record after the stop: finished whenever the outcome is `killed`. */ view: ProcessTaskView; outcome: StopTaskOutcome; /** Milliseconds the stop took. */ tookMs: number; /** * How long the polite signal was allowed to wait. Absent when nothing was * signalled, because a command that had already ended never reached a grace. */ graceMs?: number; /** What the system said, when the tree could not be confirmed gone. */ detail?: string; } /** How a wait answered: the record, and whether the wait caught the end. */ export interface WaitTaskResult { /** The record as it stood when the wait returned. */ view: ProcessTaskView; /** * True when the task ended before the deadline, false when the deadline * passed first and the view is still running. A deadline is not an error. */ waited: boolean; /** * True when the caller aborted the wait before the task ended. The task is * untouched: a cancelled wait is the user stopping the watch, not the work. */ cancelled: boolean; } /** What a follow read answered: the new bytes, and where the cursor now sits. */ export interface FollowTaskResult { /** The record as it stood when the read returned. */ view: ProcessTaskView; /** Output appended since this task's previous follow read, decoded as text. */ delta: string; /** Offset the read started at. */ from: number; /** Offset just past the bytes read; the next follow read starts here. */ offset: number; /** Bytes in `delta`. */ deltaBytes: number; /** True when the task has ended and the file has been read to its end. */ finished: boolean; /** True when the window passed with no new bytes; the task may still be running. */ timedOut: boolean; } export interface ProcessTasksOptions { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; /** Clock seam for tests; defaults to `Date.now`. */ now?: () => number; /** Grace a polite kill gets before it is forced; defaults to the supervisor's. */ killGraceMs?: number; /** How long a forced kill gets to clear the tree; defaults to the supervisor's. */ killConfirmMs?: number; /** Bytes a task's output may hold; defaults to the documented 20 MiB. */ outputCapBytes?: number; /** * How many process tasks one session may run at once, children included: * defaults to the documented 20. A fire and a chain step are records of this * store too, so they meet the same ceiling (ADR-0014). */ maxRunningTasks?: number; /** * How a spawned command is supervised. Absent, the supervisor spawns a real * process and signals a real tree. A test supplies a fake so it can answer a * stop with `tree-survived` — a real `taskkill /T /F` nearly always wins, so * the surviving tree has no other deterministic seam. */ supervise?: (options: StartProcessOptions) => RunningProcess; /** * How long a stop that lost to a surviving tree waits before it is tried again; * defaults to a second. A kill that could not clear the tree has not ended the * task, so the wait between attempts is what keeps the record honest. */ survivedRetryMs?: number; /** * How often a follow call looks at the output file while it waits for new * bytes; defaults to 50ms. A test lowers it so the answer comes as soon as the * bytes land instead of on the next tick of a timer, without changing a single * thing the follow answers. */ followPollMs?: number; /** * Called once for every task that ends, with the record as it stands after * the final status was written. Announcing the task — a session message, a * panel refresh — is the caller's business, so this store stays silent. */ onFinish?: (view: ProcessTaskView) => void; /** Shared session loader; one instance is passed to every kind of store. */ sessions: TaskSessions; /** * Shell resolved at load time. Absent, the store resolves one from `env`: a task * started by a test still runs in the platform's default shell. */ shellPolicy?: ShellPolicy; } /** A readable default name from the command, for when the caller gives none. */ export declare function deriveTaskName(command: string): string; export declare class ProcessTasks { private readonly platform; private readonly env; private readonly now; /** * Keyed by state directory, not session id: the directory already encodes cwd * and session, and the promise keeps two turns from loading the same history * twice. */ private readonly sessions; private readonly killGraceMs; private readonly killConfirmMs; private readonly outputCapBytes; /** The ceiling `docs/scope-v1.md` promises, and the key that moves it. */ private readonly maxRunningTasks; private readonly supervise; /** How long a stop that lost to a surviving tree waits before trying again. */ private readonly survivedRetryMs; /** How often a follow read looks at the output file while it waits. */ private readonly followPollMs; private readonly onFinish; /** The shell every task starts in, resolved once so a bad config fails at load. */ private readonly shellPolicy; /** Loads and saves the shared record set; both kinds write through it. */ private readonly hub; constructor(options: ProcessTasksOptions); /** Start a command in the background and return its record immediately. */ start(input: StartProcessTaskInput): Promise; /** * Queue a step without starting it (ADR-0013): a chain owns the queue and says * when a step's turn comes. The record exists right away so the caller can quote * its id and a reader can see what is ahead, but nothing is spawned until * `launch`. A queued step is `waiting` and carries its chain in `parentId`, which * is also what keeps it out of the processes list (ADR-0014). */ queueStep(input: StartProcessTaskInput): Promise; /** * Start a queued step now. Undefined means there was nothing to launch: the * session has no such task, or the step is no longer `waiting` because it has * already run or a stop settled it. A step that cannot be spawned ends `failed` * here instead of staying `waiting`, because the chain behind it is waiting for * an end, not for a process. */ launch(session: OwnedTaskSession, id: string): Promise; /** * Reserve the id and the output file a foreground command will use, before it * is spawned (ADR-0020). * * Both have to exist before the process does: the supervisor opens the output * file at spawn, so the directory must be there first, and the id has to be * settled while the command is still in the foreground — a detach then changes * who is waiting, not what the task is called. */ reserveForeground(input: ReserveForegroundInput): Promise; /** * Spawn a reserved command into the foreground. Same supervisor, same shell * policy, same output cap as a background task; the difference is who holds the * handle. The caller keeps it, and that handle is what makes a detach possible: * nothing has to be signalled, respawned or renamed. */ spawnForeground(input: SpawnForegroundInput): RunningProcess; /** * Turn a running foreground command into an ordinary task (ADR-0020): the * record appears under the id the run already used, the process that is already * running is booked under it, and its exit ends the task like any other end. * Nothing is spawned and the pid does not change, so the command never notices. * * The ceiling is checked before the record exists, for the reason a start checks * it: a refused detach leaves nothing behind, and the caller keeps waiting — a * command that cannot become a task stays a foreground command rather than * disappearing. */ adoptForeground(input: AdoptForegroundInput): Promise; /** * Build a process record. The directory is settled before the record exists: a * cwd that cannot be used rejects the call instead of leaving a task that never * started. */ private record; /** * Hand one command to the supervisor. The shell, the variables and the cap are * not part of a record (a task file is no place for a token), so they arrive here * as the plan the caller kept: `start` builds one from its input, a queued step * keeps one until its turn comes. */ /** * The one ladder a spawn walks: spawn, book, persist, cap. `fail` decides what a * refusal means to the caller, which is the only thing a start and a launch * ever disagreed about — a start has a call to throw at, a launch has a record * to write the reason into. */ private ignite; private spawn; /** * The refusal a start gets when the session already runs as many process tasks * as it may, or `undefined` when there is room. * * Counting records rather than calling the supervisor keeps fires and chain * steps inside the ceiling: a fire is a process record with a loop for a parent, * a step one with a chain for a parent, and a child of `pretty_task_bg_run` is a record too * (ADR-0014). One pass over the loaded records is the count, so nothing has to be * kept in step with the running map. */ private capRefusal; /** * Attach the supervisor to a record: the pid, the running entry, and the exit * that ends the task. `start` and `launch` both end here, so a step's end is * booked exactly like the end of a task the user started. */ private book; /** * Start one task's command again as a new record. The old row stays: rerunning * adds history rather than rewriting it, so the reader keeps both outcomes. */ rerun(scope: TaskScope, id: string): Promise; /** * Every process record of the session, children included, oldest first. The panel * counts them (ADR-0014) and resolves a chain's steps through it; a row still * stands for a root only. */ listAll(scope: TaskScope): Promise; /** Every root process task of the session, oldest first, including loaded history. */ list(scope: TaskScope): Promise; get(scope: TaskScope, id: string): Promise; /** The tail of a task's output. Undefined when the session has no such task. */ logs(scope: TaskScope, id: string, options: { lines: number; maxBytes?: number; }): Promise<{ view: ProcessTaskView; tail: OutputTail; } | undefined>; /** * The output appended to a task's file since this task's previous follow read. * Undefined when the session has no such task. The cursor is in memory and * belongs to the session: it starts at the beginning of the file, moves only * past bytes an answer actually carried, and a plain tail read leaves it * alone. `finished` says the record has ended, so no later read will grow. * A read waits up to `timeoutMs` for new bytes and returns as soon as some * arrive; an empty delta with `timedOut` is an answer, not an error. */ follow(scope: TaskScope, id: string, timeoutMs: number): Promise; /** * Wait for one task to end, for `timeoutMs` to pass, or for `signal` to abort. * Undefined means the session has no such task. The deadline is an answer, not * an error: the view is whatever the record says then, and `waited` says which * happened. An aborted wait answers at once and leaves the task running. */ wait(scope: TaskScope, id: string, timeoutMs: number, signal?: AbortSignal): Promise; /** * Stop one task and everything its command started. Undefined means the * session has no such task; every other case is an answer, including a task * that had already finished on its own. */ stop(scope: TaskScope, id: string, options?: StopTaskOptions): Promise; /** * Stop every running child of one loop, across loaded sessions. The loop's * own stop path goes through here so a paused or deleted command loop never * leaves a process running that no root row points at (ADR-0014). */ stopChildren(parentId: string, options?: StopTaskOptions): Promise; private stopRecord; private view; private finish; /** Release every pending wait on a task whose record just got its end. */ private settleWaiters; /** * Stop the task when its runtime cap passes. The stop is the same one the user * would ask for, with the reason recorded, so a task that outlived its cap ends * `killed` / `timeout` rather than `failed`. */ private scheduleRuntimeCap; /** * Arm the stop at `delayMs` from now, replacing the timer already armed for the * task: one task waits on one stop at a time, whether that stop comes from a * deadline, a cap, or a kill that has to be tried again. */ private scheduleStop; /** * Say on the record that a kill could not clear its tree. The record is still * running, so this is the only place a reader — the panel, `pretty_task_bg_status`, the next * `pretty_task_bg_kill` — can learn that the task outlived a stop that was already paid for. */ private noteSurvival; /** Cancel a task's runtime cap; a task that ends on its own leaves no timer. */ private clearRuntimeCap; /** * Hand the current records to the store. The store queues its own writes and * treats persistence as best effort, so a save never fails a turn and a full * disk never fails a task. Callers that need the record durable (a fresh task * whose id is about to be handed out) await it; the process exit does not. */ private persist; private session; /** * The runtime half of a session another store already holds: the processes this * store supervises, keyed by the records both stores share. A chain hands its * session in when it launches a step, so the queue and the process it starts * work on one map of records instead of two copies of the same history. */ private attached; private attach; /** * Resolve the directory this call runs in and make sure it is usable. A * relative request is resolved against the session's cwd, the same base the * task record uses; without a request the session's cwd is used as it is. */ private resolveWorkingDirectory; /** * A record read from disk carries the output size it was last written with. The * file itself is the truth: a crash can lose the last save, not the bytes. */ private withCurrentOutput; private createId; }