/** * The status file: how a detached transfer reports to a command that may not * exist yet. * * Raycast unloads a command on Escape, so progress cannot live in memory. The * runner writes JSON to disk; any later command instance reads it. That makes * this the coordination point between processes, and every rule below exists * because a naive implementation loses or corrupts data: * * - Writes are atomic (tmp + rename). A reader must never see half-written JSON. * - Liveness is `(pid, startedAtMs)`, never a bare pid. macOS `kern.maxproc` is * 16000; a recycled pid would let Cancel kill an unrelated process. * - `heartbeatAt` (process alive) and `lastByteAt` (bytes moving) are separate. * Conflated, a hung-but-alive transfer reads as healthy forever. * - Adoption takes a lease. Two Raycast windows must not both resume the same * download and write the same file. * - Every read-modify-write of a status file holds a cross-process lock. A * command reading `downloading`, the runner writing `completed`, then the * command writing its stale snapshot back is a LOST COMPLETION, and the two * are separate OS processes, so no in-process mutex can see it. */ export type DownloadState = "starting" | "generating" | "downloading" | "finalizing" | "completed" | "failed" | "cancelled"; export declare function isTerminal(state: DownloadState): boolean; /** Fields every status carries, whichever transport wrote it. */ export interface StatusBase { id: string; /** Process group leader of the detached runner. `process.kill(-pid)` targets the group. */ pid: number; /** * Runner start time, epoch ms. Together with `pid` this identifies the process: * a recycled pid necessarily has a later start time than the one recorded here. */ startedAtMs: number; state: DownloadState; filename: string; bytesDownloaded: number; totalBytes?: number; speedBytesPerSec?: number; etaSeconds?: number; /** Process-alive signal. Advances even when no bytes move. */ heartbeatAt: number; /** Bytes-moving signal. Stall detection keys off this, never off `heartbeatAt`. */ lastByteAt?: number; startedAt: number; finishedAt?: number; error?: { code: string; message: string; httpStatus?: number; }; /** * Which command instance currently owns this download, and until when. * Adoption is a compare-and-swap on this field. */ ownerId?: string; leaseUntil?: number; /** * Opaque per-consumer payload. Deliberately NOT the source URL: signed URLs are * bearer credentials. Store an identifier here and re-resolve instead. */ meta?: Record; } /** A download from a URL, written by `startDownload`. */ export interface CurlStatus extends StatusBase { /** Bumped only on incompatible shape changes; readers reject unknown versions. */ schema: 1; /** Absent on every status a 0.2.x runner wrote; `"curl"` is the same thing. */ transport?: "curl"; outputPath: string; /** Where bytes land until the transfer is verified. Retained on failure for `curl -C -`. */ partPath: string; /** * The partial file at `partPath` MUST NOT be resumed: delete or replace it * before starting another attempt against this path. Set when the runner put * something in that file that does not belong to the download — a redirect * body — and could not then prove it safe; a resume would compute its offset * from the contaminated length and splice the real file onto the end of it. * * Separate from `error.code` because it answers a separate question: `code` * is why THIS attempt failed, this is whether the bytes on disk may be * reused. Absence means no contamination was RECORDED, not that the partial * was verified safe — a runner older than 0.1.3 cannot set this field. */ partialUnsafe?: boolean; } /** * A foreign command run by `startCommand`. * * The command owns its own filenames, so the package records no `partPath` * at all, and an `outputPath` only when `resolveOutput` found one. A status * claiming a `.part` the package never writes would read true and be false. * * Schema 2, so a 0.2.x reader, which accepts only schema 1, skips it rather * than reading a status with no paths as a curl download. */ export interface CommandStatus extends StatusBase { schema: 2; transport: "command"; /** The command's output, when `resolveOutput` matched a file after a successful exit. */ outputPath?: string; partPath?: never; partialUnsafe?: never; /** * The command's stdout and stderr, captured to files under `statusDir`. * Each is capped at about 1 MiB: the head and the tail are kept and the * middle is dropped, because an error usually ends the stream. Retained * after the run ends; removed with the status by `clearStatus` and * `pruneStatuses`. */ stdoutPath: string; stderrPath: string; /** The command's exit code, once it has exited. */ exitCode?: number; /** The signal that ended the command, when one did. */ exitSignal?: string; /** * The files to delete if the run fails or is canceled. Recorded here so * `killDownload` and `reconcile` can delete them when the runner is too dead * to do it itself — which they do only if its whole process group is gone. */ cleanupOnFailure?: { dir: string; namePrefix: string; suffixes: string[]; }[]; /** * The command's own process identity, recorded once it has started. `pid` * names the runner, and stops describing the work if the runner alone is * killed: the command keeps running, and keeps writing under its prefix. */ commandPid?: number; commandStartedAtMs?: number; } /** * One status file. Narrow on `transport` before reading paths: * `status.transport === "command"` is a `CommandStatus`, anything else a * `CurlStatus`. */ export type DownloadStatus = CurlStatus | CommandStatus; /** True for a status written by `startCommand`. */ export declare function isCommandStatus(status: DownloadStatus): status is CommandStatus; /** * True when the command a runner spawned is still running, and is the same * process: `(commandPid, commandStartedAtMs)`, never a bare pid. False when * either is missing or the start time cannot be read, so an unprovable * identity is never signalled and never blocks a retry. */ export declare function commandAlive(status: CommandStatus): boolean; /** * Directory holding status files. * * Prefers Raycast's `environment.supportPath`. Never `tmpdir()` — macOS purges * it while long transfers are still running. */ export declare function statusDir(override?: string): string; /** * Reject an id that could escape the status directory. * * Ids reach `join()` to build file paths, so `"../../etc/foo"` would write * outside `statusDir`. A consumer that derives ids from remote content — a * filename, an API field — would hand an attacker a same-user file write, and a * signed URL could land somewhere unintended. Validating here means no consumer * has to know that. * * Deliberately a strict allowlist rather than a traversal blacklist: ids are * machine-generated (the default is a UUID), so there is no legitimate need for * separators, dots, or anything exotic. */ export declare function assertSafeId(id: string): void; export declare function statusPath(id: string, dir?: string): string; /** * The cross-process lock guarding one download's status file. * * A sibling of the status file rather than a single global lock: two unrelated * downloads finishing at the same moment must not serialize against each other. */ export declare function statusLockPath(id: string, dir?: string): string; /** * Run `fn` while holding a download's status lock. * * Exported so a caller that must read a status, decide something, and act on it * can do so without the runner changing the file underneath — `reconcileHistory` * deleting a status only if it is still the attempt it reconciled, for instance. */ export declare function withStatusLock(id: string, dir: string | undefined, fn: () => T): T; /** * Write atomically: a full file appears under the final name, or nothing does. * `renameSync` within one directory is atomic on macOS/APFS, so a concurrent * reader sees either the previous status or the new one — never a partial write. */ export declare function writeStatus(status: DownloadStatus, dir?: string, options?: { clearLease?: boolean; }): void; export declare function readStatus(id: string, dir?: string): DownloadStatus | null; export declare function listStatuses(dir?: string): DownloadStatus[]; export declare function clearStatus(id: string, dir?: string): void; /** * Where `startCommand` captures a command's output: beside the status, named * by id. A retry under the same id truncates them, like it replaces the status. */ export declare function commandLogPaths(id: string, dir?: string): [stdoutPath: string, stderrPath: string]; export declare function isAlive(status: DownloadStatus, now?: number): boolean; /** True when this platform can prove a pid belongs to the process we started. */ export declare function canVerifyProcessIdentity(): boolean; /** * Process start time in epoch ms, via `ps -o lstart`. Returns undefined when the * process is gone or unreadable. */ export declare function processStartTimeMs(pid: number): number | undefined; /** A transfer whose process lives but whose bytes have stopped moving. */ export declare function isStalled(status: DownloadStatus, stallAfterMs: number, now?: number): boolean; export interface AcquireLeaseOptions { ownerId: string; leaseMs?: number; dir?: string; now?: number; } /** * Take ownership of a download, if it is free. * * Succeeds when unowned, already ours, or the previous lease expired. The * re-read after writing is the compare-and-swap: two instances racing both write, * but only the one whose value survives the final rename keeps the lease. */ export declare function acquireLease(id: string, options: AcquireLeaseOptions): DownloadStatus | null; export declare function releaseLease(id: string, ownerId: string, dir?: string): void; export interface WatchOptions { intervalMs?: number; dir?: string; /** * Consecutive polls with no change before checking whether the runner is * still alive. A dead runner that never wrote a terminal state would * otherwise be watched forever, leaving the UI stuck on "Downloading". * Default 20 (≈8s at the default interval). */ stalePollsBeforeLivenessCheck?: number; } export interface StatusWatcher { stop(): void; } /** * Poll a status file for changes. * * Polling rather than `fs.watch`: atomic writes replace the inode, so a watcher * bound to the original file silently stops firing after the first update. */ export declare function watchStatus(id: string, handlers: { onChange?: (status: DownloadStatus) => void; onSettled?: (status: DownloadStatus) => void; onMissing?: () => void; /** The runner died without recording an outcome. */ onAbandoned?: (status: DownloadStatus) => void; }, options?: WatchOptions): StatusWatcher; export interface PruneOptions { olderThanMs?: number; dir?: string; now?: number; } /** * Remove finished/abandoned status files and their orphaned partial downloads. * * Without this, every crashed runner leaves a `.part` file that nothing will * ever finish and nothing will ever clean up. */ export declare function pruneStatuses(options?: PruneOptions): number; //# sourceMappingURL=status.d.ts.map