|
| 1 | +/** |
| 2 | + * LatencyBudget — a cumulative tool-chain deadline, sibling to BudgetGuard. |
| 3 | + * |
| 4 | + * BudgetGuard stops an agent before its next call crosses a USD ceiling; |
| 5 | + * LatencyBudget stops it before the next call would blow an end-user SLA: |
| 6 | + * |
| 7 | + * ```ts |
| 8 | + * const deadline = new LatencyBudget(5000); |
| 9 | + * ... |
| 10 | + * deadline.check(800); // throws DeadlineExceeded when projected over |
| 11 | + * if (deadline.advisory().nearDeadline) useFasterModel(); |
| 12 | + * router.pick({ maxLatencyMs: deadline.remainingMs }); |
| 13 | + * ``` |
| 14 | + * |
| 15 | + * Design notes (mirroring `src/floe_guard/latency.py`): |
| 16 | + * - **Monotonic clock** — `performance.now()`, never wall time. |
| 17 | + * - **Cooperative, not preemptive** — the guard provides the deadline signal; |
| 18 | + * aborting a stalled in-flight call is the framework's job (AbortSignal). |
| 19 | + * `check()` prevents the NEXT call from starting. |
| 20 | + * - **Advisory symmetry** — `nearDeadline` / `usedBps` / `remainingMs` are the |
| 21 | + * latency twin of BudgetGuard's `nearLimit` / `usedBps` / `remainingUsd`. |
| 22 | + * - **In-process scope** — one instance per request/run; distributed latency |
| 23 | + * tracking is out of scope. |
| 24 | + */ |
| 25 | + |
| 26 | +import { DeadlineExceeded } from "./errors.js"; |
| 27 | + |
| 28 | +/** A context-aware deadline signal — the latency twin of {@link BudgetAdvisory}. |
| 29 | + * Soft by design; the hard-stop is {@link LatencyBudget.check}. */ |
| 30 | +export interface LatencyAdvisory { |
| 31 | + nearDeadline: boolean; |
| 32 | + /** SLA consumed, basis points 0..10000 (8500 = 85%). */ |
| 33 | + usedBps: number; |
| 34 | + remainingMs: number; |
| 35 | + slaMs: number; |
| 36 | + elapsedMs: number; |
| 37 | +} |
| 38 | + |
| 39 | +export interface LatencyBudgetOptions { |
| 40 | + /** |
| 41 | + * Utilization (basis points, 0..10000) at which {@link LatencyBudget.advisory} |
| 42 | + * flags `nearDeadline` so an agent can downshift to a faster path before the |
| 43 | + * wall. Default 8000 (80%), matching BudgetGuard's `nearLimitBps`. |
| 44 | + */ |
| 45 | + nearDeadlineBps?: number; |
| 46 | + /** Invoked with `(elapsedMs, slaMs)` right before {@link DeadlineExceeded} is thrown. */ |
| 47 | + onBlock?: (elapsedMs: number, slaMs: number) => void; |
| 48 | + /** Milliseconds-returning monotonic clock, injectable for tests. Defaults to `performance.now`. */ |
| 49 | + clock?: () => number; |
| 50 | +} |
| 51 | + |
| 52 | +export class LatencyBudget { |
| 53 | + readonly slaMs: number; |
| 54 | + readonly nearDeadlineBps: number; |
| 55 | + private readonly onBlock?: (elapsedMs: number, slaMs: number) => void; |
| 56 | + private readonly clock: () => number; |
| 57 | + private readonly startedAt: number; |
| 58 | + |
| 59 | + /** The budget starts counting at construction — build it when the request |
| 60 | + * (and its SLA) starts. */ |
| 61 | + constructor(slaMs: number, options: LatencyBudgetOptions = {}) { |
| 62 | + if (!(Number.isFinite(slaMs) && slaMs > 0)) { |
| 63 | + throw new RangeError("slaMs must be > 0"); |
| 64 | + } |
| 65 | + const nearDeadlineBps = options.nearDeadlineBps ?? 8000; |
| 66 | + if (!Number.isInteger(nearDeadlineBps) || nearDeadlineBps < 0 || nearDeadlineBps > 10000) { |
| 67 | + throw new RangeError("nearDeadlineBps must be an integer 0..10000"); |
| 68 | + } |
| 69 | + this.slaMs = slaMs; |
| 70 | + this.nearDeadlineBps = nearDeadlineBps; |
| 71 | + this.onBlock = options.onBlock; |
| 72 | + this.clock = options.clock ?? (() => performance.now()); |
| 73 | + this.startedAt = this.clock(); |
| 74 | + } |
| 75 | + |
| 76 | + /** Milliseconds since construction (monotonic). */ |
| 77 | + get elapsedMs(): number { |
| 78 | + return this.clock() - this.startedAt; |
| 79 | + } |
| 80 | + |
| 81 | + /** Milliseconds left before the SLA, floored at 0 — the readable signal a |
| 82 | + * router uses to pick a faster fallback or truncate work mid-chain. */ |
| 83 | + get remainingMs(): number { |
| 84 | + return Math.max(0, this.slaMs - this.elapsedMs); |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Throw {@link DeadlineExceeded} when the projected elapsed time (now + |
| 89 | + * `expectedMs` for the upcoming call) would blow the SLA. Call it |
| 90 | + * immediately before each tool/model call; pass 0 to only gate on time |
| 91 | + * already spent. |
| 92 | + */ |
| 93 | + check(expectedMs = 0): void { |
| 94 | + if (!(Number.isFinite(expectedMs) && expectedMs >= 0)) { |
| 95 | + throw new RangeError("expectedMs must be >= 0"); |
| 96 | + } |
| 97 | + const elapsed = this.elapsedMs; |
| 98 | + if (elapsed + expectedMs > this.slaMs) { |
| 99 | + this.onBlock?.(elapsed, this.slaMs); |
| 100 | + throw new DeadlineExceeded(elapsed, this.slaMs); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + /** The soft near-deadline signal — symmetric to `BudgetGuard.advisory()`. */ |
| 105 | + advisory(): LatencyAdvisory { |
| 106 | + const elapsed = this.elapsedMs; |
| 107 | + // round (not floor) — matches the Python twin; float clock arithmetic can |
| 108 | + // land a hair under an exact boundary. |
| 109 | + const usedBps = elapsed > 0 ? Math.min(10000, Math.round((elapsed * 10000) / this.slaMs)) : 0; |
| 110 | + return { |
| 111 | + nearDeadline: usedBps >= this.nearDeadlineBps, |
| 112 | + usedBps, |
| 113 | + remainingMs: Math.max(0, this.slaMs - elapsed), |
| 114 | + slaMs: this.slaMs, |
| 115 | + elapsedMs: elapsed, |
| 116 | + }; |
| 117 | + } |
| 118 | +} |
0 commit comments