/** * Loop tasks: the schedule store, the pump that turns a due schedule into a * wake-up or a fire, and the pause/resume/complete/retune/delete transitions. * * A loop is a {@link PromptLoopTask} or a {@link CmdLoopTask} record like a process * task is a {@link ProcessTask}; all of them live in one session record file * through {@link TaskSessions}. Nothing here starts a timer. The caller owns the * clock and calls {@link LoopTasks.pump} with the instant it wants handled, which * is what lets tests push a fake clock. * * An prompt loop's fire is a wake-up the caller delivers into the session. A cmd * loop's fire is a process task started through `onCommandFire`; this file never * spawns it, so a fire reuses the one process path instead of a second one. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ import { type TaskScope } from "../base/runtime-state.js"; import type { CmdLoopTask, FireRecord, KillReason, PromptLoopTask, TaskStatus } from "../base/task.js"; import type { OwnedTaskSession, TaskSessions } from "../base/task-sessions.js"; import type { TurnOutcome } from "./iteration.js"; /** Either kind of loop record; everything the panel and the tool share is on {@link LoopBase}. */ export type LoopTask = PromptLoopTask | CmdLoopTask; /** One due wake-up; the caller sends its prompt into the session. */ export interface LoopFire { readonly task: PromptLoopTask; /** Epoch ms the pump handled the fire at. */ readonly at: number; /** One-based fire number, already recorded on the task. */ readonly fire: number; /** The session the fire belongs to, so the iteration can be persisted as it opens. */ readonly session: OwnedTaskSession; /** * The text this wake carries, read from the loop's prompt file at fire time * (ADR-0024). A snapshot: editing the file affects the next fire, never one * already queued or running. */ readonly prompt: string; /** * This fire used the last of `maxFires`, so the loop is already completed. * The wake still belongs to the model even though the loop stopped. */ readonly final: boolean; } /** One due cmd-loop fire; the caller starts a process task for it. */ export interface CommandFire { readonly task: CmdLoopTask; /** Epoch ms the pump handled the fire at. */ readonly at: number; /** One-based fire number, already recorded on the task as running. */ readonly fire: number; readonly session: OwnedTaskSession; /** The scope the loop was created in, so the child lands in the same session. */ readonly scope: TaskScope; } /** What the process runner reports back when a fire's child ends. */ export interface FireResult { /** The loop that owns the child. */ readonly parentId: string; readonly taskId: string; readonly fire: number; readonly status: TaskStatus; readonly exitCode?: number | null; readonly outputPath: string; readonly outputBytes: number; readonly durationMs: number; readonly killReason?: KillReason; readonly error?: string; /** When the child ended; defaults to now. */ readonly endedAt?: number; } /** A fire that just got its outcome, for the caller that reports failures. */ export interface CompletedFire { readonly loop: CmdLoopTask; readonly fire: FireRecord; /** Exit code non-zero, killed by the output cap, or never started. */ readonly failed: boolean; /** The exit code was one the loop declared as a signal, so this is not a failure (ADR-0018). */ readonly signalled: boolean; /** True when this signalled fire raised the latch, so the caller wakes exactly once. */ readonly raised: boolean; } /** * What one settled turn means for one loop's failure account (ticket #46). A turn * can fire more than one loop — every loop that came due while the agent was busy * is bound and delivered into the same turn — so a settle reports one of these per * loop and the loop that owns each fire is the one that counts it. */ export interface IterationResult { /** The loop that fired. */ readonly id: string; /** The fire whose turn this is: the newest one the loop had bound. */ readonly fire: number; readonly end: TurnOutcome; /** What the provider said, when it gave up and said something. */ readonly error?: string; } export interface CreateLoopInput extends TaskScope { /** * Raw recurrence text: interval shorthand such as `30s`, `10m`, `2h`, or a * five-field cron expression such as `0 9 * * 1-5` read in local time. */ schedule: string; /** Text sent into the session on each fire; mutually exclusive with `command`. */ prompt?: string; /** Shell command run as a background process on each fire; exclusive with `prompt`. */ command?: string; /** Working directory of a command loop; only valid with `command`. */ workingDirectory?: string; /** Extra environment variables of a command loop; only valid with `command`. */ env?: Record; /** Send a notice when a fire fails; only valid with `command`. Defaults to on. */ wakeOnFailure?: boolean; /** * Exit codes that mean "the check has something to report" rather than "the * loop is broken" (ADR-0018); declaring them makes this loop a subscriber that * wakes once per raised condition and keeps its schedule. Only valid with * `command`. */ notifyExitCodes?: readonly number[]; name?: string; /** Stop after this many fires; omitted means no limit. */ maxFires?: number; /** Stop at this much time after creation, in the same shorthand. */ expiresIn?: string; } /** * What one `pretty_task_loop_update` call asks for: a transition, a retune, a new * prompt, or any of them together. The retune is applied first, so resuming onto a * new schedule is one call. */ export interface UpdateLoopInput extends TaskScope { readonly id: string; /** Transition to apply; omit it to change only the schedule or the prompt. */ readonly action?: LoopUpdateAction; /** New schedule expression; a running loop re-arms from this moment. */ readonly schedule?: string; /** * New text for the prompt file every fire reads, replacing what is in it now. * The record keeps the creation prompt as its seed (ADR-0024), so refining the * wording costs neither the fire count nor a recorded iteration. */ readonly prompt?: string; } /** * What became of a prompt an update was asked to write. A failure is a fact the * caller has to see, not an exception: the file keeps the text it had, and the * schedule or transition that travelled with it still applies. */ export type PromptWriteResult = { readonly outcome: "written"; } | { readonly outcome: "failed"; readonly error: string; }; /** A loop as the tools and the panel read it. */ export interface LoopTaskView { readonly task: LoopTask; /** Time left before the next fire; absent while paused or finished. */ readonly untilNextFireMs?: number; /** * Where a prompt loop keeps the text it sends, derived from the id rather * than stored (ADR-0024). Absent for a cmd loop. */ readonly promptFile?: string; } /** A transition `pretty_task_loop_update` can apply. A retune travels in `schedule`, not here. */ export type LoopUpdateAction = "pause" | "resume" | "complete" | "rearm" | "clear-signal"; export type LoopUpdateOutcome = "paused" | "resumed" | "completed" /** The schedule changed; `rescheduled` is not a status, the loop keeps its own. */ | "rescheduled" | "already-paused" | "already-running" | "already-completed" | "completed-at-limit" | "completed-expired" | "failed" /** The next fire was realigned onto the schedule; the expression did not change. */ | "rearmed" /** The outstanding signal was dropped without waiting for a healthy round. */ | "signal-cleared" /** A clear-signal request on a loop that was not reporting anything. */ | "no-signal" /** The prompt text was replaced; nothing about the timing or the status changed. */ | "prompt-updated" /** The prompt text could not be written; the file still holds the previous text. */ | "prompt-write-failed"; export interface LoopUpdateResult { readonly view: LoopTaskView; readonly outcome: LoopUpdateOutcome; /** What became of an update that carried a prompt; absent when it did not. */ readonly promptWrite?: PromptWriteResult; } /** A loop input the user can correct; the message is meant to be shown as-is. */ export declare class LoopInputError extends Error { constructor(message: string); } /** The session limit from the product scope. Finished loops do not count. */ export declare const MAX_LOOPS = 50; /** * The shortest gap between one fire and the next. A fire that starts off its * slot can otherwise take a boundary that is only seconds away and collide with * the slot it just passed (ADR-0018). */ export declare const MIN_FIRE_GAP_MS = 30000; export interface LoopTasksOptions { readonly sessions: TaskSessions; /** Clock seam for tests; defaults to `Date.now`. */ readonly now?: () => number; /** * Called once per due fire, after the record with its new count is persisted. * Awaited, so the caller's own record of the fire (its iteration) is durable * before the pump returns and before any flush can deliver the wake. */ readonly onFire?: (fire: LoopFire) => Promise | void; /** * Called once per due cmd-loop fire, after the fire is recorded as running and * persisted. Returns the id of the process task it started, or nothing when no * runner is configured; a throw or a missing id marks the fire failed and backs * the schedule off exactly like a non-zero exit. */ readonly onCommandFire?: ((fire: CommandFire) => Promise<{ taskId: string; } | undefined>) | ((fire: CommandFire) => { taskId: string; } | undefined); /** * Called when a loop stopped before waking the model for a recorded fire: it * was paused, completed or deleted while the wake waited. The caller drops * that queued wake — pi's follow-up queue cannot be recalled once sent — and * stops any child a cmd loop still has running. */ readonly onCancel?: (taskId: string) => Promise | void; } export declare class LoopTasks { private readonly sessions; private readonly now; private readonly onFire; private readonly onCommandFire; private readonly onCancel; /** * The scopes this extension owns, keyed by state directory: the session it runs * in, plus any scope it wrote to. Only these are pumped. A {@link TaskScope} * carries the cwd and session id a fired command's process store is keyed by, * which a {@link TaskSession} does not. * * Looking at another session's loops is a read, and a read never lands here: * otherwise a due schedule of a session we merely displayed would fire in this * one — waking this session and writing that session's records. */ private readonly owned; /** The pump in flight, so a timer tick and a turn end cannot interleave. */ private inFlight; constructor(options: LoopTasksOptions); /** * Take ownership of the session at `session_start`, so the pump sees its loops * even before the first loop-tool call. */ attach(scope: TaskScope): Promise; create(input: CreateLoopInput): Promise; /** * Loops of the session, in record order, finished ones included as history. A * read of another session's loops is the panel's "others" view: it goes through * {@link readSession}, so displaying them never makes them this session's to fire. */ list(scope: TaskScope): Promise; get(scope: TaskScope, id: string): Promise; /** * Change one loop: a pause/resume/complete transition, a retune, a new prompt, or * any of them in one call. A retune re-arms a running loop from `now` — never from * the slot the old schedule had already picked — and only stores the expression on * a paused one, which arms onto it when resumed. A new prompt rewrites the file * every fire reads and leaves the recorded seed alone, so the wording can be * refined without rebuilding the loop: the id, the fire count and every recorded * iteration survive. Nothing is rebuilt and nothing is thrown for a write that * fails — the file keeps its text and the result says so. An unusable expression * is refused before the record changes, on the same message * `pretty_task_loop_create` gives (ADR-0006). */ update(input: UpdateLoopInput): Promise; /** * Run one fire now, outside the schedule (ADR-0018). It is a probe, not a * report: the fire is numbered from the negative side so it never takes a * schedule number, `nextFireAt` does not move, and the outcome touches neither * the failure streak nor the signal latch. The record and its output file are * the whole result, which is what makes a typo cost one command instead of a * slot and a backoff. */ fireNow(input: TaskScope & { readonly id: string; }): Promise; delete(scope: TaskScope, id: string): Promise; /** * Handle every loop whose next fire is due at `at`, across every session this * extension has loaded. Each due loop fires at most once per call: a pump that * arrives late drops the missed fires instead of replaying them in a storm. * The new count is persisted before `onFire` is called, so a crash cannot * wake the model twice for the same fire. * * Calls are serialized: a timer tick and a `turn_end` can ask at the same * moment, and two pumps reading the same `nextFireAt` would fire one loop * twice. A pump that arrives while another runs waits for it and then sees the * advanced `nextFireAt`. * * Returns the llm wakes only; a cmd fire is started through `onCommandFire` * before this promise resolves, so the caller never sees a fire unstarted. */ pump(at: number): Promise; /** * How a fire ended for the reader: a completed command succeeded, a stop by the * user interrupted it, a reported exit code signalled, and anything else failed. */ private fireOutcome; /** * Record the end of a fire's child process: outcome, exit code, bytes and the * failure backoff. Returns nothing when the loop or its fire is already gone * (deleted, or history trimmed), so a late child can never resurrect a record. */ completeFire(result: FireResult): Promise; /** * Charge a settled turn to every loop that had a fire in it (ticket #46). One * turn can be the fire of several loops: every loop that came due while the * agent was busy is bound and delivered into the same turn, so the settle hands * over one entry per loop and each loop moves its own schedule. * * A failed turn is a failed fire like a command's: it leaves its error and time * on the record and backs the schedule off. A turn that finished is the healthy * round that clears the streak. A turn the user stopped changes nothing — the * person behind the loop is not a broken provider — and so does a turn nothing * was observed about: no evidence must not read as a success. * * The closed iterations and the loops they are charged to are one record, so this * writes the session once for the whole settle rather than once per half of it. */ completeTurns(scope: TaskScope, turns: readonly IterationResult[]): Promise; private pumpOnce; /** * The checks both kinds share: the cap, expiry, a schedule that no longer * parses, a record with no due time, and the due test itself. */ private commonDueCheck; /** Cap, then the next due time; a schedule with no future fire ends the loop. */ private advanceSchedule; private startCommandFire; private pushFire; /** * True when a finished fire's exit code means "the check has something to * report" rather than "the loop is broken" (ADR-0018). Exit 0 is success by * definition and a kill by the user is not the command's own word, so neither * can be a signal. */ private isSignal; /** * A failed fire doubles the wait, up to one hour, counting from the failure. * The next natural fire time is never pulled earlier: a long schedule keeps * its spacing and a short one gets the room the failure asked for. */ private noteFailure; /** A scope this extension runs in or writes to: the only kind the pump drives. */ private ownScope; /** * The session a read looks at. A scope this extension owns is the shared, live * session; any other is read from disk and never joins the hub, so a session * that is only being displayed cannot be pumped, woken or written. */ private readSession; /** * The sessions the pump drives, each with the scope that fires its commands. * Deliberately not `TaskSessions.loaded()`: that set also holds sessions a panel * merely visited, and a visit must never fire their schedules. */ private ownedSessions; private findLoop; private findCmdLoop; /** * Write an update's new prompt text through the same helper the create path uses, * and report a failure instead of throwing: the file keeps the text it had, which * is what the caller needs to be able to count on (ADR-0024). */ private replacePromptText; private finish; /** * A loop as its callers read it. `directory` is the session's task directory: * the prompt file's address is derived from it, never stored (ADR-0024). */ private view; }