UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

232 lines • 9.8 kB
/** * Pure state machine behind the `/loop` extension. * * Everything time-related or timer-related is injected: a {@link LoopClock} supplies * `now`, and a {@link LoopTimerPort} owns the single armed timeout per loop. This module * performs NO I/O, never calls `setTimeout`/`Date.now`, and never persists anything * itself — the caller mirrors {@link LoopScheduler.getState} into the sidecar store. That * keeps every invariant below testable with a fake clock and zero real waiting. * * The load-bearing invariants: * - At most ONE queued or running tick per loop. A fire that lands while one is in flight * sets `coalescedFirePending` instead of enqueuing a second delivery, so a sleeping * laptop or a long turn can never produce a tick storm. * - `nextFireAt` is ALWAYS recomputed from `now`, never from the stale due time, so all * occurrences missed during sleep collapse into exactly one catch-up tick. * - 7-day expiry from `createdAt` is checked at arm, fire, re-entry and restore, is never * extended by a new wakeup, and no tick fires at or after it. * - At most {@link MAX_ACTIVE_LOOPS} active loops; a further creation returns a typed * rejection and leaves existing loops armed. * - A dispatched-tick budget (default {@link DEFAULT_MAX_TICKS}) ends the loop with * `tick_budget_exhausted` so a forgotten fast loop cannot spend without bound. * - Keepalive is a two-strike device on dynamic loops only, and a user abort PAUSES a * loop instead of ending it (and is never counted as a keepalive omission). * - Shutdown SUSPENDS: every senpi shutdown reason leaves the session resumable, so there * is deliberately no `session_closed` terminal reason. * - A provider/turn error is never terminal. */ import type { DeliveryId, EffectiveInterval, EpochMs, LoopEndReason, LoopId, LoopPayload, LoopState, RequestedInterval, WakeupId } from "./types.ts"; /** Absolute lifetime of a loop, measured from `createdAt`. */ export declare const LOOP_EXPIRY_MS: number; /** Hard cap on simultaneously active loops per session. */ export declare const MAX_ACTIVE_LOOPS = 5; /** Fallback wakeup length when a dynamic iteration forgets to reschedule. */ export declare const DEFAULT_KEEPALIVE_SECONDS = 1200; export declare const MIN_KEEPALIVE_SECONDS = 60; export declare const MAX_KEEPALIVE_SECONDS = 3600; export declare const KEEPALIVE_SECONDS_ENV = "SENPI_LOOP_KEEPALIVE_SECONDS"; /** Dispatched-tick budget per loop. */ export declare const DEFAULT_MAX_TICKS = 2000; export declare const MIN_MAX_TICKS = 1; export declare const MAX_TICKS_ENV = "SENPI_LOOP_MAX_TICKS"; export interface LoopClock { now(): EpochMs; } /** * Owns the ONE live timeout per loop. Implementations must apply the generation-counter * discipline of `cache-keepalive/index.ts`: re-arming a key replaces its previous * callback, and a cancelled callback must never run. */ export interface LoopTimerPort { arm(key: string, dueAt: EpochMs, callback: () => void): void; cancel(key: string): void; cancelAll(): void; } export interface LoopIdFactory { loopId(): LoopId; wakeupId(): WakeupId; deliveryId(): DeliveryId; } export interface LoopSchedulerDeps { readonly sessionId: string; readonly clock: LoopClock; readonly timers: LoopTimerPort; readonly ids: LoopIdFactory; /** Defaults to `process.env`; injected so tests never mutate the real environment. */ readonly env?: Record<string, string | undefined>; /** Previously persisted state, e.g. on session start. */ readonly initialState?: LoopState; /** Called after every state revision so the caller can persist it. */ readonly onStateChanged?: (state: LoopState) => void; /** * Invoked when an armed timer fires. The owner is expected to run the due decision AND its * side effects (persist + dispatch). Without it the scheduler only advances its own state, * which would deliver a loop's first tick and then silently never recur. */ readonly onFire?: (loopId: LoopId) => void; } export interface CreateFixedRequest { readonly originalArgs: string; readonly reentryPrompt: string; readonly payload: LoopPayload; readonly requestedInterval: RequestedInterval; readonly effectiveInterval: EffectiveInterval; readonly cronExpression: string; readonly intervalMs: number; } export interface CreateDynamicRequest { readonly originalArgs: string; readonly reentryPrompt: string; readonly payload: LoopPayload; } /** One dispatchable delivery. The caller turns this into a message; a tick for a busy session steers. */ export interface LoopTick { readonly loopId: LoopId; readonly deliveryId: DeliveryId; /** Occurrence this delivery represents; equal to the `now` it was decided at. */ readonly scheduledForAt: EpochMs; readonly deliverAs: "steer"; /** True when this delivery drains a coalesced or recovered occurrence. */ readonly coalesced: boolean; } export type CreateRejectionReason = "active_loop_cap"; export type CreateResult = { readonly ok: true; readonly loopId: LoopId; readonly supersededLoopId?: LoopId; } | { readonly ok: false; readonly reason: CreateRejectionReason; readonly cap: number; readonly activeLoopIds: readonly LoopId[]; readonly message: string; }; export type DueResult = { readonly action: "dispatch"; readonly tick: LoopTick; } | { readonly action: "coalesce"; } | { readonly action: "expire"; }; export type TickOutcome = "completed" | "error" | "retrying"; export interface TickSettledInput { readonly loopId: LoopId; readonly deliveryId: DeliveryId; readonly outcome: TickOutcome; } export type SettledResult = { readonly action: "dispatch"; readonly tick: LoopTick; } | { readonly action: "coalesce"; } | { readonly action: "expire"; } | { readonly action: "idle"; } | { readonly action: "in_progress"; } | { readonly action: "ended"; readonly endReason: LoopEndReason; } | { readonly action: "ignored"; }; export interface ScheduleWakeupInput { readonly loopId: LoopId; /** Already clamped to `[60, 3600]` by the tool executor. */ readonly delaySeconds: number; readonly requestedDelaySeconds: number; readonly reason: string; readonly prompt: string; readonly noop: boolean; } export type ScheduleWakeupResult = { readonly ok: true; readonly wakeupId: WakeupId; readonly replacedWakeupId?: WakeupId; readonly dueAt: EpochMs; readonly noopStreak: number; } | { readonly ok: false; readonly reason: "unknown_loop" | "not_dynamic" | "ended" | "expired"; }; export type KeepaliveResult = { readonly action: "keepalive_armed"; readonly wakeupId: WakeupId; readonly delaySeconds: number; readonly dueAt: EpochMs; } | { readonly action: "ended"; readonly endReason: "keepalive_exhausted" | "expired"; } | { readonly action: "ignored"; }; export interface AbortResult { readonly action: "paused" | "ignored"; } export interface TargetedResult { readonly affectedLoopIds: readonly LoopId[]; } export interface ShutdownResult { readonly suspendedLoopIds: readonly LoopId[]; } export interface RestoreOptions { /** * Loops the caller knows the user paused explicitly, which must stay paused instead of * being re-armed. `phase: "suspended"` alone cannot express this: shutdown suspends too, * and the persisted state has no field distinguishing the two. Omit it and every * suspended loop is treated as shutdown-suspended and re-armed, per the plan's resume * rule. */ readonly userPausedLoopIds?: readonly LoopId[]; } export interface RestoreResult { readonly recoveryTicks: readonly LoopTick[]; readonly expiredLoopIds: readonly LoopId[]; readonly rearmedLoopIds: readonly LoopId[]; /** Loops left paused because {@link RestoreOptions.userPausedLoopIds} named them. */ readonly stillPausedLoopIds: readonly LoopId[]; } export interface LoopScheduler { getState(): LoopState; /** State revisions applied so far; lets callers assert atomic multi-entry mutations. */ readonly mutationCount: number; /** Effective dispatched-tick budget after the env override and the minimum of 1. */ readonly maxTicks: number; /** Effective keepalive fallback length in seconds after clamping. */ readonly keepaliveSeconds: number; /** Delivery id of the queued/running tick of a loop, when one is in flight. */ currentDeliveryId(loopId: LoopId): DeliveryId | undefined; createFixed(request: CreateFixedRequest): CreateResult; createDynamic(request: CreateDynamicRequest): CreateResult; onDue(loopId: LoopId, nowMs: EpochMs, sessionBusy: boolean, held?: boolean): DueResult; onTickSettled(input: TickSettledInput): SettledResult; onScheduleWakeup(request: ScheduleWakeupInput): ScheduleWakeupResult; /** * Keepalive for a dynamic iteration that ended without `schedule_wakeup`. `chargeCredit: false` * (a tick steered into a turn the loop did not start) arms the fallback without spending the * credit, so the user's own work can never exhaust the loop. */ onTurnEndedWithoutSchedule(loopId: LoopId, options?: { readonly chargeCredit?: boolean; }): KeepaliveResult; onUserAbort(loopId: LoopId): AbortResult; pause(target: LoopId | "all"): TargetedResult; resume(target: LoopId | "all"): TargetedResult; stop(target: LoopId | "all", detail: string): TargetedResult; onShutdown(): ShutdownResult; restore(nowMs: EpochMs, options?: RestoreOptions): RestoreResult; } export declare function createLoopScheduler(deps: LoopSchedulerDeps): LoopScheduler; //# sourceMappingURL=scheduler.d.ts.map