brl-subagent 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT.md +2 -2
- package/README.md +17 -9
- package/package.json +5 -5
- package/src/concurrency.ts +25 -2
- package/src/engineering-bar.ts +69 -0
- package/src/event-bus.ts +10 -0
- package/src/git.ts +58 -1
- package/src/headstate.ts +471 -0
- package/src/index.ts +787 -239
- package/src/kill-escalation.ts +87 -7
- package/src/loader.ts +46 -0
- package/src/notify-completion.ts +146 -5
- package/src/params.ts +198 -25
- package/src/prelude.ts +79 -3
- package/src/presets.ts +84 -15
- package/src/project-flags.ts +3 -3
- package/src/recovery-engine.ts +10 -0
- package/src/recovery.ts +155 -19
- package/src/run-registry.ts +20 -0
- package/src/runner.ts +34 -4
- package/src/schema.ts +37 -7
- package/src/session-manager.ts +782 -196
- package/src/state.ts +118 -16
- package/src/templates.ts +41 -14
- package/src/tui-format.ts +174 -6
- package/src/tui.ts +74 -26
- package/src/types.ts +177 -2
- package/src/unit-run.ts +10 -1
- package/src/validate.ts +87 -8
package/src/state.ts
CHANGED
|
@@ -78,17 +78,24 @@ export const STALE_FINALIZE_GRACE_MS = POLLER_TICK_MS + 1000;
|
|
|
78
78
|
* preference rule. Recovery's `dedupeRunEntriesById` delegates here, so the
|
|
79
79
|
* boot scan and every display/retry lookup agree by construction.
|
|
80
80
|
*
|
|
81
|
-
* Each run writes
|
|
82
|
-
* entry (status "
|
|
83
|
-
*
|
|
84
|
-
* settle
|
|
81
|
+
* Each run writes a spawn entry (status "running", carrying `originalParams`)
|
|
82
|
+
* FIRST, then its terminal entry (status "done"/"failed", stamped with
|
|
83
|
+
* fullOutput/cost/duration) at settle. A run stopped by the deadline writes ONE
|
|
84
|
+
* MORE terminal entry at the late settle — a payload AMENDMENT of the deadline's
|
|
85
|
+
* classification snapshot (issue #453, ADR 0023 decision 4). Preference, in order:
|
|
85
86
|
*
|
|
86
|
-
* 1.
|
|
87
|
+
* 1. the LAST terminal entry (status !== "running") — with an amendment that
|
|
88
|
+
* is the amended payload; without one it is the only terminal entry, so
|
|
89
|
+
* this is unchanged for every pre-#453 run (mutant M5 is `find` here);
|
|
87
90
|
* 2. among non-terminal entries, one carrying the D3 `interruptedAt` mark —
|
|
88
91
|
* append-only stores keep the original spawn entry forever, so the marked
|
|
89
92
|
* clone is the authoritative RECOVERED state U3's shared lookup reads;
|
|
90
93
|
* 3. otherwise the first match (the pre-finalize spawn shape).
|
|
91
94
|
*
|
|
95
|
+
* Ordering contract: callers pass a store-ordered list (`getRunEntries` is
|
|
96
|
+
* newest-first with a STABLE sort, so a run's entries stay in append order —
|
|
97
|
+
* spawn, snapshot, amendment). "Last" therefore means "appended last".
|
|
98
|
+
*
|
|
92
99
|
* Returns undefined when no entry matches.
|
|
93
100
|
*/
|
|
94
101
|
export function resolveTerminalRunEntry(
|
|
@@ -98,12 +105,39 @@ export function resolveTerminalRunEntry(
|
|
|
98
105
|
const matching = entries.filter((r) => r.id === id);
|
|
99
106
|
if (matching.length === 0) return undefined;
|
|
100
107
|
return (
|
|
101
|
-
matching.
|
|
108
|
+
matching.findLast((r) => r.status !== "running") ??
|
|
102
109
|
matching.find((r) => r.interruptedAt) ??
|
|
103
110
|
matching[0]
|
|
104
111
|
);
|
|
105
112
|
}
|
|
106
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Issue #453 (ADR 0023 decision 4): ONE logical run per id — the projection every
|
|
116
|
+
* raw-entry consumer reads.
|
|
117
|
+
*
|
|
118
|
+
* A run that hits its deadline and settles late has three entries sharing its id
|
|
119
|
+
* (spawn, `failed/timeout` snapshot, payload amendment). Aggregates that take the
|
|
120
|
+
* raw list count it two or three times and sum two full payloads (measured: 3
|
|
121
|
+
* runs / $5 for a $2 snapshot + $3 amendment pair). This yields, per id, the LAST
|
|
122
|
+
* entry in the input's order: the amendment when there is one (so the amended
|
|
123
|
+
* payload — the real cost/tokens/output — is what readers see), the terminal entry
|
|
124
|
+
* for an ordinary run, the spawn entry for a run still in flight.
|
|
125
|
+
*
|
|
126
|
+
* ORDER: the output keeps each id's FIRST-seen position and drops repeats, so a
|
|
127
|
+
* caller's window (`slice(0, n)`) applied AFTER this projects runs, not entries.
|
|
128
|
+
* That is the contract — apply the projection BEFORE any window or cap, or a
|
|
129
|
+
* window can split one run's entries across its edge.
|
|
130
|
+
*/
|
|
131
|
+
export function projectLogicalRuns(entries: SubagentRun[]): SubagentRun[] {
|
|
132
|
+
const lastById = new Map<string, SubagentRun>();
|
|
133
|
+
const order: string[] = [];
|
|
134
|
+
for (const entry of entries) {
|
|
135
|
+
if (!lastById.has(entry.id)) order.push(entry.id);
|
|
136
|
+
lastById.set(entry.id, entry);
|
|
137
|
+
}
|
|
138
|
+
return order.map((id) => lastById.get(id)!);
|
|
139
|
+
}
|
|
140
|
+
|
|
107
141
|
/**
|
|
108
142
|
* Run-history display projection (issue #259): ONE record per SETTLED run.
|
|
109
143
|
*
|
|
@@ -111,7 +145,8 @@ export function resolveTerminalRunEntry(
|
|
|
111
145
|
* "running") first, then the terminal entry at settle — so a raw entry list
|
|
112
146
|
* renders every run twice and the spawn row shows a stale "running" forever.
|
|
113
147
|
* This collapses each id to its terminal-preferred entry via the ONE shared
|
|
114
|
-
* rule (`resolveTerminalRunEntry`).
|
|
148
|
+
* rule (`resolveTerminalRunEntry`). Callers pass the LOGICAL list
|
|
149
|
+
* (`getLogicalRunEntries`) since #453, so an amended run is already one entry. Runs still in flight (spawn entry, no
|
|
115
150
|
* terminal entry yet) are omitted: live state belongs to the monitor. U3 (D1)
|
|
116
151
|
* carves ONE exception — an INTERRUPTED run (running + `interruptedAt`, per
|
|
117
152
|
* `isInterruptedRun`) is surfaced, because the human must see it to recover or
|
|
@@ -217,6 +252,14 @@ export class SessionState {
|
|
|
217
252
|
*/
|
|
218
253
|
private _finalizedLiveIds = new Set<string>();
|
|
219
254
|
|
|
255
|
+
/**
|
|
256
|
+
* The pending deferred-delete handle per finalized id (issue #423). Kept so
|
|
257
|
+
* a RE-registration can cancel it: a retry inside the 3 s window re-claims
|
|
258
|
+
* the id, and a stale delete would otherwise evict the fresh live row that
|
|
259
|
+
* the display surfaces just started rendering again.
|
|
260
|
+
*/
|
|
261
|
+
private _finalizeTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
262
|
+
|
|
220
263
|
/** Loaded built-in presets */
|
|
221
264
|
builtinPresets = new Array<import("./types").SubagentPreset>();
|
|
222
265
|
|
|
@@ -389,8 +432,13 @@ export class SessionState {
|
|
|
389
432
|
// Run entry access
|
|
390
433
|
// -------------------------------------------------------------------
|
|
391
434
|
|
|
392
|
-
|
|
393
|
-
|
|
435
|
+
/**
|
|
436
|
+
* The RAW run-entry store, session order (oldest append first), uncapped.
|
|
437
|
+
* Two callers only: {@link getRunEntries} (the raw view) and
|
|
438
|
+
* {@link getLogicalRunEntries} (the one every aggregate reads).
|
|
439
|
+
*/
|
|
440
|
+
private readRunEntries(ctx: ExtensionContext): SubagentRun[] {
|
|
441
|
+
return ctx.sessionManager
|
|
394
442
|
.getEntries()
|
|
395
443
|
.filter((e: { type: string; customType?: string }) =>
|
|
396
444
|
e.type === "custom" && e.customType === CUSTOM_ENTRY_TYPES.run,
|
|
@@ -402,7 +450,32 @@ export class SessionState {
|
|
|
402
450
|
return undefined;
|
|
403
451
|
})
|
|
404
452
|
.filter((r): r is SubagentRun => r !== undefined);
|
|
405
|
-
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* The RAW run-entry view, newest-first and capped at `maxHistoryEntries`
|
|
457
|
+
* ENTRIES. Not the display/aggregate view — a run has two entries (spawn +
|
|
458
|
+
* terminal) and a deadline-stopped one has three, so a consumer that counts,
|
|
459
|
+
* sums or windows these sees one run several times. It remains the right view
|
|
460
|
+
* for `findSpawnRunById` (which deliberately wants the SPAWN entry) and for
|
|
461
|
+
* raw-store bookkeeping.
|
|
462
|
+
*/
|
|
463
|
+
getRunEntries(ctx: ExtensionContext): SubagentRun[] {
|
|
464
|
+
return cleanupRuns(this.readRunEntries(ctx), this.config.maxHistoryEntries);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Issue #453: the LOGICAL run-entry view — one entry per run id, carrying the
|
|
469
|
+
* amended payload when the deadline and a late settle both wrote (see
|
|
470
|
+
* {@link projectLogicalRuns}). Every aggregate/display consumer uses THIS:
|
|
471
|
+
* metrics, cost accounting, history, the reports and the dashboard.
|
|
472
|
+
*
|
|
473
|
+
* The projection runs BEFORE the cap, so `maxHistoryEntries` counts RUNS: an
|
|
474
|
+
* amended run cannot be half-kept, and its amendment can never be windowed
|
|
475
|
+
* away from the snapshot it amends.
|
|
476
|
+
*/
|
|
477
|
+
getLogicalRunEntries(ctx: ExtensionContext): SubagentRun[] {
|
|
478
|
+
return cleanupRuns(projectLogicalRuns(this.readRunEntries(ctx)), this.config.maxHistoryEntries);
|
|
406
479
|
}
|
|
407
480
|
|
|
408
481
|
/**
|
|
@@ -422,7 +495,10 @@ export class SessionState {
|
|
|
422
495
|
* `fullOutput`, `cost`, `durationMs`, `errorCategory`.
|
|
423
496
|
*/
|
|
424
497
|
findTerminalRunById(ctx: ExtensionContext, id: string): SubagentRun | undefined {
|
|
425
|
-
|
|
498
|
+
// #453 review: the LOGICAL view, not the raw capped list — at the
|
|
499
|
+
// `maxHistoryEntries` edge a raw read can return the deadline snapshot while
|
|
500
|
+
// every other surface shows the later amendment (the run's real payload).
|
|
501
|
+
return resolveTerminalRunEntry(this.getLogicalRunEntries(ctx), id);
|
|
426
502
|
}
|
|
427
503
|
|
|
428
504
|
// -------------------------------------------------------------------
|
|
@@ -430,6 +506,11 @@ export class SessionState {
|
|
|
430
506
|
// -------------------------------------------------------------------
|
|
431
507
|
|
|
432
508
|
registerLiveSubagent(id: string, data: Omit<LiveSubagent, "liveOutput" | "usage">): void {
|
|
509
|
+
// Issue #423: a registration means the id is live AGAIN — a retry
|
|
510
|
+
// re-registers inside the 3 s linger window, and every display surface
|
|
511
|
+
// filters finalized ids, so the claim (and its pending delete) must not
|
|
512
|
+
// survive the re-registration.
|
|
513
|
+
this.clearLiveFinalize(id);
|
|
433
514
|
this.subagentSessions.set(id, { ...data, liveOutput: "", usage: { input: 0, output: 0 } });
|
|
434
515
|
}
|
|
435
516
|
|
|
@@ -459,13 +540,30 @@ export class SessionState {
|
|
|
459
540
|
// review: the poller must not decrement when the sweep already did).
|
|
460
541
|
if (this._finalizedLiveIds.has(id)) return false;
|
|
461
542
|
this._finalizedLiveIds.add(id);
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
543
|
+
this._finalizeTimers.set(
|
|
544
|
+
id,
|
|
545
|
+
setTimeout(() => {
|
|
546
|
+
this._finalizeTimers.delete(id);
|
|
547
|
+
this.subagentSessions.delete(id);
|
|
548
|
+
this._finalizedLiveIds.delete(id);
|
|
549
|
+
}, FINALIZE_RESET_WINDOW_MS),
|
|
550
|
+
);
|
|
466
551
|
return true;
|
|
467
552
|
}
|
|
468
553
|
|
|
554
|
+
/**
|
|
555
|
+
* Drop a pending finalize claim AND its deferred delete (issue #423). Called
|
|
556
|
+
* by {@link registerLiveSubagent} when an id is registered again.
|
|
557
|
+
*/
|
|
558
|
+
private clearLiveFinalize(id: string): void {
|
|
559
|
+
const handle = this._finalizeTimers.get(id);
|
|
560
|
+
if (handle !== undefined) {
|
|
561
|
+
clearTimeout(handle);
|
|
562
|
+
this._finalizeTimers.delete(id);
|
|
563
|
+
}
|
|
564
|
+
this._finalizedLiveIds.delete(id);
|
|
565
|
+
}
|
|
566
|
+
|
|
469
567
|
/** True when the live entry has been finalized (deferred delete pending). */
|
|
470
568
|
isLiveEntryFinalized(id: string): boolean {
|
|
471
569
|
return this._finalizedLiveIds.has(id);
|
|
@@ -509,6 +607,8 @@ export class SessionState {
|
|
|
509
607
|
* would no-op on an id a stale claim still remembers (PR #71 review).
|
|
510
608
|
*/
|
|
511
609
|
resetLiveFinalizeClaims(): void {
|
|
610
|
+
for (const handle of this._finalizeTimers.values()) clearTimeout(handle);
|
|
611
|
+
this._finalizeTimers.clear();
|
|
512
612
|
this._finalizedLiveIds.clear();
|
|
513
613
|
}
|
|
514
614
|
|
|
@@ -604,7 +704,9 @@ export class SessionState {
|
|
|
604
704
|
* Sum the cost of all completed runs in the current session.
|
|
605
705
|
*/
|
|
606
706
|
getSessionTotalCost(ctx: ExtensionContext): number {
|
|
607
|
-
|
|
707
|
+
// Issue #453: one row per run — a deadline snapshot and its amendment both
|
|
708
|
+
// carry a full cost, so summing raw entries would charge the run twice.
|
|
709
|
+
const runs = this.getLogicalRunEntries(ctx);
|
|
608
710
|
return runs.reduce((acc, r) => acc + (r.cost ?? 0), 0);
|
|
609
711
|
}
|
|
610
712
|
|
package/src/templates.ts
CHANGED
|
@@ -27,7 +27,8 @@ import * as path from "node:path";
|
|
|
27
27
|
import type { TaskTemplate, ThinkingLevel, SubagentPreset } from "./types";
|
|
28
28
|
import { TEMPLATE_PARAM_RE, THINKING_LEVELS } from "./types";
|
|
29
29
|
import type { Logger } from "./logging";
|
|
30
|
-
import { loadMarkdownRecords } from "./loader";
|
|
30
|
+
import { applyFrontmatterMappers, loadMarkdownRecords } from "./loader";
|
|
31
|
+
import type { FrontmatterFieldMapper, FrontmatterMapContext } from "./loader";
|
|
31
32
|
import { sanitizeFileName } from "./presets";
|
|
32
33
|
import { pkgPath } from "./paths";
|
|
33
34
|
|
|
@@ -174,6 +175,43 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
|
|
|
174
175
|
return errors;
|
|
175
176
|
}
|
|
176
177
|
|
|
178
|
+
// ---------------------------------------------------------------------------
|
|
179
|
+
// Frontmatter → TaskTemplate mapping
|
|
180
|
+
// ---------------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Per-key return types: same shape as `PresetFieldMappers` (src/presets.ts), so
|
|
184
|
+
* a mapper that returns the wrong type — `timeout: () => "soon"` — fails at the
|
|
185
|
+
* row instead of at the assembly cast.
|
|
186
|
+
*/
|
|
187
|
+
type TemplateFieldMappers = {
|
|
188
|
+
[K in keyof TaskTemplate]: FrontmatterFieldMapper<TaskTemplate[K]>;
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* THE declaration of which frontmatter keys reach a `TaskTemplate` — every
|
|
193
|
+
* field (no omission allowlist), so a new declared field is a missing-key
|
|
194
|
+
* compile error and a stale key is an excess-property error.
|
|
195
|
+
*
|
|
196
|
+
* `task` comes from the markdown body (multiline by construction), and
|
|
197
|
+
* `timeout` is the one numeric coercion: frontmatter values are strings.
|
|
198
|
+
*/
|
|
199
|
+
const TEMPLATE_FIELD_MAPPERS = {
|
|
200
|
+
name: (_meta, ctx) => ctx.name,
|
|
201
|
+
description: (meta) => (meta.description as string) || undefined,
|
|
202
|
+
task: (_meta, ctx) => ctx.body,
|
|
203
|
+
preset: (meta) => (meta.preset as string) || undefined,
|
|
204
|
+
thinkingLevel: (meta) => (meta.thinkingLevel as string) || undefined,
|
|
205
|
+
outputFile: (meta) => (meta.outputFile as string) || undefined,
|
|
206
|
+
timeout: (meta) => (meta.timeout !== undefined ? Number(meta.timeout) : undefined),
|
|
207
|
+
tools: (meta) => (Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined),
|
|
208
|
+
excludeTools: (meta) =>
|
|
209
|
+
Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
|
|
210
|
+
noBuiltinTools: (meta) => (meta.noBuiltinTools === "true" ? true : undefined),
|
|
211
|
+
inheritSystemPrompt: (meta) =>
|
|
212
|
+
(meta.inheritSystemPrompt === "false" ? false : undefined),
|
|
213
|
+
} satisfies TemplateFieldMappers;
|
|
214
|
+
|
|
177
215
|
// ---------------------------------------------------------------------------
|
|
178
216
|
// Loading
|
|
179
217
|
// ---------------------------------------------------------------------------
|
|
@@ -187,19 +225,8 @@ function templateFromFrontmatter(
|
|
|
187
225
|
body: string,
|
|
188
226
|
name: string,
|
|
189
227
|
): TaskTemplate {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
description: (meta.description as string) || undefined,
|
|
193
|
-
task: body,
|
|
194
|
-
preset: (meta.preset as string) || undefined,
|
|
195
|
-
thinkingLevel: (meta.thinkingLevel as string) || undefined,
|
|
196
|
-
outputFile: (meta.outputFile as string) || undefined,
|
|
197
|
-
timeout: meta.timeout !== undefined ? Number(meta.timeout) : undefined,
|
|
198
|
-
tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
|
|
199
|
-
excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
|
|
200
|
-
noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
|
|
201
|
-
inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
|
|
202
|
-
};
|
|
228
|
+
const ctx: FrontmatterMapContext = { name, body };
|
|
229
|
+
return applyFrontmatterMappers<TaskTemplate>(TEMPLATE_FIELD_MAPPERS, meta, ctx);
|
|
203
230
|
}
|
|
204
231
|
|
|
205
232
|
/**
|
package/src/tui-format.ts
CHANGED
|
@@ -82,6 +82,73 @@ export interface ProgressStatusInput {
|
|
|
82
82
|
modeContext?: ModeContext;
|
|
83
83
|
/** Epoch ms at which the oldest active run started; absent → no elapsed suffix. */
|
|
84
84
|
activeSinceMs?: number;
|
|
85
|
+
/**
|
|
86
|
+
* Issue #423: the live map's own clock, when the caller has one. Supersedes
|
|
87
|
+
* `activeSinceMs` for the age (it is the age of the OLDEST still-running
|
|
88
|
+
* agent, not the burst anchor) and adds the nearest deadline.
|
|
89
|
+
*/
|
|
90
|
+
times?: ProgressTimes;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The one live-entry clock {@link computeProgressTimes} needs. */
|
|
94
|
+
export interface LiveBudgetInput {
|
|
95
|
+
startedAt: number;
|
|
96
|
+
deadlineAt?: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The footer's two derived clocks, both already filtered of settled runs. */
|
|
100
|
+
export interface ProgressTimes {
|
|
101
|
+
/** Age of the OLDEST still-running entry (ms), clamped at 0. */
|
|
102
|
+
ranMs?: number;
|
|
103
|
+
/** The soonest deadline: time left, and the fraction of its budget left. */
|
|
104
|
+
next?: { remainingMs: number; fraction: number };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Clamp a fraction into [0, 1]; a non-positive budget has nothing left. */
|
|
108
|
+
function clampFraction(value: number): number {
|
|
109
|
+
if (!Number.isFinite(value)) return 0;
|
|
110
|
+
return Math.min(1, Math.max(0, value));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Derive the footer's clocks from the live entries (issue #423). Pure.
|
|
115
|
+
*
|
|
116
|
+
* `ranMs` is the age of the OLDEST still-running agent — `now - min(startedAt)`
|
|
117
|
+
* — not the burst anchor: with a queue, the burst anchor predates the row the
|
|
118
|
+
* human is watching. An EMPTY list yields no `ranMs` so the caller can fall back
|
|
119
|
+
* to `activeSinceMs` (the pre-#423 line).
|
|
120
|
+
*
|
|
121
|
+
* `next` is the SOONEST deadline, and its `fraction` is measured against that
|
|
122
|
+
* entry's own budget, so a long-running agent with a long budget does not read
|
|
123
|
+
* as nearly-exhausted. Remaining time clamps at 0; a backwards clock jump makes
|
|
124
|
+
* the age 0 rather than negative.
|
|
125
|
+
*/
|
|
126
|
+
export function computeProgressTimes(
|
|
127
|
+
live: ReadonlyArray<LiveBudgetInput>,
|
|
128
|
+
now: number,
|
|
129
|
+
): ProgressTimes {
|
|
130
|
+
if (live.length === 0) return {};
|
|
131
|
+
|
|
132
|
+
let oldestStartedAt = Infinity;
|
|
133
|
+
let soonest: LiveBudgetInput | undefined;
|
|
134
|
+
for (const entry of live) {
|
|
135
|
+
oldestStartedAt = Math.min(oldestStartedAt, entry.startedAt);
|
|
136
|
+
if (entry.deadlineAt === undefined) continue;
|
|
137
|
+
if (soonest?.deadlineAt === undefined || entry.deadlineAt < soonest.deadlineAt) {
|
|
138
|
+
soonest = entry;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const times: ProgressTimes = { ranMs: Math.max(0, now - oldestStartedAt) };
|
|
143
|
+
if (soonest?.deadlineAt !== undefined) {
|
|
144
|
+
const remainingMs = Math.max(0, soonest.deadlineAt - now);
|
|
145
|
+
const budgetMs = soonest.deadlineAt - soonest.startedAt;
|
|
146
|
+
times.next = {
|
|
147
|
+
remainingMs,
|
|
148
|
+
fraction: budgetMs > 0 ? clampFraction(remainingMs / budgetMs) : 0,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return times;
|
|
85
152
|
}
|
|
86
153
|
|
|
87
154
|
/** One coloured run of text on the footer line. */
|
|
@@ -95,6 +162,24 @@ const DONE_SYMBOL = "\u2713";
|
|
|
95
162
|
const FAILED_SYMBOL = "\u2717";
|
|
96
163
|
/** Separator before the elapsed suffix — " · ", muted with the duration. */
|
|
97
164
|
const ELAPSED_SEPARATOR = " \u00b7 ";
|
|
165
|
+
/** Issue #423 — the labels of the two clock segments, in one place. */
|
|
166
|
+
const RAN_LABEL = "ran: ";
|
|
167
|
+
const DEADLINE_LABEL = "deadline in ";
|
|
168
|
+
const DEADLINE_STOPPING = "deadline: stopping";
|
|
169
|
+
/**
|
|
170
|
+
* Issue #423 — the deadline segment's colour bands, by the fraction of budget
|
|
171
|
+
* left. The text always carries the value, so colour is redundant, never
|
|
172
|
+
* load-bearing.
|
|
173
|
+
*/
|
|
174
|
+
const DEADLINE_ERROR_FRACTION = 0.05;
|
|
175
|
+
const DEADLINE_WARNING_FRACTION = 0.2;
|
|
176
|
+
|
|
177
|
+
/** The deadline clock's colour: exhausted/almost → error, tight → warning. */
|
|
178
|
+
function deadlineColor(next: { remainingMs: number; fraction: number }): ProgressStatusColor {
|
|
179
|
+
if (next.remainingMs <= 0 || next.fraction <= DEADLINE_ERROR_FRACTION) return "error";
|
|
180
|
+
if (next.fraction <= DEADLINE_WARNING_FRACTION) return "warning";
|
|
181
|
+
return "muted";
|
|
182
|
+
}
|
|
98
183
|
|
|
99
184
|
/** The verdict a run or step settled on — the input to {@link formatOutcomeSymbol}. */
|
|
100
185
|
export type OutcomeKind = "success" | "failure";
|
|
@@ -189,10 +274,29 @@ export function formatProgressSegments(
|
|
|
189
274
|
});
|
|
190
275
|
}
|
|
191
276
|
|
|
192
|
-
if (active
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
277
|
+
if (active) {
|
|
278
|
+
const times = state.times;
|
|
279
|
+
if (times?.ranMs !== undefined) {
|
|
280
|
+
// Clamp again here: the formatter is public and may be handed a raw age.
|
|
281
|
+
segments.push({
|
|
282
|
+
color: "muted",
|
|
283
|
+
text: `${ELAPSED_SEPARATOR}${RAN_LABEL}${formatElapsed(Math.max(0, times.ranMs))}`,
|
|
284
|
+
});
|
|
285
|
+
} else if (state.activeSinceMs !== undefined) {
|
|
286
|
+
// Pre-#423 fallback (no live clock known): the burst anchor, unchanged.
|
|
287
|
+
// Clamp at zero: a clock jump backwards must never print a negative age.
|
|
288
|
+
const elapsed = formatElapsed(Math.max(0, now - state.activeSinceMs));
|
|
289
|
+
segments.push({ color: "muted", text: `${ELAPSED_SEPARATOR}${elapsed}` });
|
|
290
|
+
}
|
|
291
|
+
if (times?.next !== undefined) {
|
|
292
|
+
segments.push({
|
|
293
|
+
color: deadlineColor(times.next),
|
|
294
|
+
text:
|
|
295
|
+
times.next.remainingMs <= 0
|
|
296
|
+
? `${ELAPSED_SEPARATOR}${DEADLINE_STOPPING}`
|
|
297
|
+
: `${ELAPSED_SEPARATOR}${DEADLINE_LABEL}${formatElapsed(times.next.remainingMs)}`,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
196
300
|
}
|
|
197
301
|
|
|
198
302
|
return segments;
|
|
@@ -213,13 +317,77 @@ export function formatProgressStatus(
|
|
|
213
317
|
.join("");
|
|
214
318
|
}
|
|
215
319
|
|
|
216
|
-
/** Dim section of a live row: short id + token counts + elapsed. */
|
|
320
|
+
/** Dim section of a live row: short id + token counts + elapsed (+ budget). */
|
|
217
321
|
export function formatLiveRowDim(
|
|
218
322
|
id: string,
|
|
219
323
|
usage: { input: number; output: number },
|
|
220
324
|
elapsedStr: string,
|
|
325
|
+
// Issue #423: the budget segment, when the run has a known deadline.
|
|
326
|
+
budget?: string,
|
|
327
|
+
): string {
|
|
328
|
+
return ` [${id.slice(0, 8)}] \u2191${formatTokens(usage.input)} \u2193${formatTokens(usage.output)} ${elapsedStr}${budget ? ` \u00b7 ${budget}` : ""}`;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ---------------------------------------------------------------------------
|
|
332
|
+
// Issue #423 — budget display (footer, monitor rows, dashboard)
|
|
333
|
+
// ---------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* A budget/used/left duration: a whole number of minutes as `30m` (a budget is
|
|
337
|
+
* read as a round number), otherwise the compact `4m 12s` form. Pure.
|
|
338
|
+
*/
|
|
339
|
+
export function formatBudgetDuration(ms: number): string {
|
|
340
|
+
const safe = Math.max(0, ms);
|
|
341
|
+
const minutes = safe / 60_000;
|
|
342
|
+
return Number.isInteger(minutes) && minutes > 0 ? `${minutes}m` : formatElapsed(safe);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** The no-deadline token: the run has no timer, so there is nothing to state. */
|
|
346
|
+
const NO_BUDGET = "\u2014";
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* One live row's budget: `4m 12s / 30m (86% left)`. Pure.
|
|
350
|
+
*
|
|
351
|
+
* `startedAt` + `deadlineAt` are the entry's own clocks; a missing deadline
|
|
352
|
+
* renders {@link NO_BUDGET} (a foreground run with no timeout, or an old
|
|
353
|
+
* record) rather than inventing a 30m default the run does not have. An
|
|
354
|
+
* exhausted budget states `0% left` — the remaining time is clamped, never
|
|
355
|
+
* negative.
|
|
356
|
+
*/
|
|
357
|
+
export function formatBudget(
|
|
358
|
+
startedAt: number,
|
|
359
|
+
deadlineAt: number | undefined,
|
|
360
|
+
now: number,
|
|
221
361
|
): string {
|
|
222
|
-
|
|
362
|
+
if (deadlineAt === undefined) return NO_BUDGET;
|
|
363
|
+
const budgetMs = deadlineAt - startedAt;
|
|
364
|
+
const usedMs = Math.max(0, now - startedAt);
|
|
365
|
+
const remainingMs = Math.max(0, deadlineAt - now);
|
|
366
|
+
const percentLeft =
|
|
367
|
+
budgetMs > 0 ? Math.max(0, Math.min(100, Math.floor((remainingMs / budgetMs) * 100))) : 0;
|
|
368
|
+
return `${formatBudgetDuration(usedMs)} / ${formatBudgetDuration(budgetMs)} (${percentLeft}% left)`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Order live rows for display: soonest deadline first (undated last), then
|
|
373
|
+
* oldest first, then id for a stable total order. Pure; returns a copy.
|
|
374
|
+
*
|
|
375
|
+
* Ordering by `deadlineAt` IS ordering by remaining time (same `now`), so the
|
|
376
|
+
* list does not reorder between paints as the clock advances — only a
|
|
377
|
+
* registration or a deadline change moves a row.
|
|
378
|
+
*/
|
|
379
|
+
export function sortLiveSessions<T extends LiveBudgetInput>(
|
|
380
|
+
entries: ReadonlyArray<readonly [string, T]>,
|
|
381
|
+
): Array<[string, T]> {
|
|
382
|
+
return entries
|
|
383
|
+
.map(([id, entry]) => [id, entry] as [string, T])
|
|
384
|
+
.sort(([aId, a], [bId, b]) => {
|
|
385
|
+
const aDeadline = a.deadlineAt ?? Number.POSITIVE_INFINITY;
|
|
386
|
+
const bDeadline = b.deadlineAt ?? Number.POSITIVE_INFINITY;
|
|
387
|
+
if (aDeadline !== bDeadline) return aDeadline - bDeadline;
|
|
388
|
+
if (a.startedAt !== b.startedAt) return a.startedAt - b.startedAt;
|
|
389
|
+
return aId < bId ? -1 : aId > bId ? 1 : 0;
|
|
390
|
+
});
|
|
223
391
|
}
|
|
224
392
|
|
|
225
393
|
/**
|