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/tui.ts
CHANGED
|
@@ -67,7 +67,7 @@ import { collapseRunsForHistory, retryableRuns, sweepStaleLiveSubagents, type Se
|
|
|
67
67
|
import { getAgent } from "./session-manager";
|
|
68
68
|
import { visibleRunEntriesForSession } from "./recovery-surface";
|
|
69
69
|
import { computeSLAMetrics, computeCostTrend, formatSparkline } from "./metrics";
|
|
70
|
-
import { formatElapsed, formatOutcomeSymbol, liveRowName, liveSpinner, formatLiveRowDim, runHistoryStatus, runHistoryStatusLabel, buildRetryOfferMessage, runDisplayName, formatMenuValue, formatTemplateSummary, menuSection } from "./tui-format";
|
|
70
|
+
import { formatElapsed, formatOutcomeSymbol, liveRowName, liveSpinner, formatLiveRowDim, formatBudget, sortLiveSessions, runHistoryStatus, runHistoryStatusLabel, buildRetryOfferMessage, runDisplayName, formatMenuValue, formatTemplateSummary, menuSection } from "./tui-format";
|
|
71
71
|
import {
|
|
72
72
|
renderTranscriptMessages,
|
|
73
73
|
type TranscriptLineStyle,
|
|
@@ -495,7 +495,7 @@ export async function showSLAStats(
|
|
|
495
495
|
ctx: ExtensionContext,
|
|
496
496
|
state: SessionState,
|
|
497
497
|
): Promise<void> {
|
|
498
|
-
const runs = state.
|
|
498
|
+
const runs = state.getLogicalRunEntries(ctx).slice(0, state.config.slaWindowSize);
|
|
499
499
|
if (runs.length === 0) {
|
|
500
500
|
ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
|
|
501
501
|
return;
|
|
@@ -542,7 +542,7 @@ export async function showFileAccessReport(
|
|
|
542
542
|
ctx: ExtensionContext,
|
|
543
543
|
state: SessionState,
|
|
544
544
|
): Promise<void> {
|
|
545
|
-
const runs = state.
|
|
545
|
+
const runs = state.getLogicalRunEntries(ctx);
|
|
546
546
|
if (runs.length === 0) {
|
|
547
547
|
ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
|
|
548
548
|
return;
|
|
@@ -577,7 +577,7 @@ export async function showSecretsExposureReport(
|
|
|
577
577
|
ctx: ExtensionContext,
|
|
578
578
|
state: SessionState,
|
|
579
579
|
): Promise<void> {
|
|
580
|
-
const runs = state.
|
|
580
|
+
const runs = state.getLogicalRunEntries(ctx);
|
|
581
581
|
if (runs.length === 0) {
|
|
582
582
|
ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
|
|
583
583
|
return;
|
|
@@ -634,7 +634,7 @@ export async function showFullComplianceSummary(
|
|
|
634
634
|
ctx: ExtensionContext,
|
|
635
635
|
state: SessionState,
|
|
636
636
|
): Promise<void> {
|
|
637
|
-
const runs = state.
|
|
637
|
+
const runs = state.getLogicalRunEntries(ctx);
|
|
638
638
|
if (runs.length === 0) {
|
|
639
639
|
ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
|
|
640
640
|
return;
|
|
@@ -1269,7 +1269,7 @@ export async function showConfigMenu(
|
|
|
1269
1269
|
* run that exists only in the durable registry.
|
|
1270
1270
|
*/
|
|
1271
1271
|
function recoverableRunEntries(ctx: ExtensionContext, state: SessionState): SubagentRun[] {
|
|
1272
|
-
return visibleRunEntriesForSession(state.
|
|
1272
|
+
return visibleRunEntriesForSession(state.getLogicalRunEntries(ctx), getAgent);
|
|
1273
1273
|
}
|
|
1274
1274
|
|
|
1275
1275
|
export async function showRunHistory(
|
|
@@ -1558,6 +1558,11 @@ export async function showMonitor(
|
|
|
1558
1558
|
// Selected row index (0-based). Clamped to the map size on every
|
|
1559
1559
|
// render — entries can be swept while the monitor is open.
|
|
1560
1560
|
let selectedIndex = 0;
|
|
1561
|
+
// Issue #423: the id list from the LAST paint. Selection identity is an
|
|
1562
|
+
// index over what was RENDERED, not over the live map: a spawn or a
|
|
1563
|
+
// finalize between paint and Enter would otherwise shift the id list and
|
|
1564
|
+
// open an agent other than the highlighted row.
|
|
1565
|
+
let lastRenderedIds: string[] = [];
|
|
1561
1566
|
// Guards against stacking drill-in overlays on repeated Enter.
|
|
1562
1567
|
let detailOpen = false;
|
|
1563
1568
|
|
|
@@ -1567,13 +1572,17 @@ export async function showMonitor(
|
|
|
1567
1572
|
// render pass. Idempotent, so racing the poller is safe.
|
|
1568
1573
|
sweepStaleLiveSubagents(state, getAgent);
|
|
1569
1574
|
|
|
1575
|
+
// Issue #423: the shared display projection (settled ids out, deadline order).
|
|
1576
|
+
const entries = liveDisplayEntries(state);
|
|
1577
|
+
lastRenderedIds = entries.map(([id]) => id);
|
|
1578
|
+
|
|
1570
1579
|
const container = new Container();
|
|
1571
1580
|
container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
|
|
1572
1581
|
container.addChild(
|
|
1573
1582
|
new Text(
|
|
1574
1583
|
theme.fg(
|
|
1575
1584
|
"accent",
|
|
1576
|
-
theme.bold(`Subagent Monitor (${
|
|
1585
|
+
theme.bold(`Subagent Monitor (${entries.length} active)`),
|
|
1577
1586
|
),
|
|
1578
1587
|
1,
|
|
1579
1588
|
0,
|
|
@@ -1584,14 +1593,14 @@ export async function showMonitor(
|
|
|
1584
1593
|
);
|
|
1585
1594
|
container.addChild(new Text("", 0, 0));
|
|
1586
1595
|
|
|
1587
|
-
const entries = Array.from(state.subagentSessions.entries());
|
|
1588
1596
|
const selIdx = Math.min(selectedIndex, Math.max(0, entries.length - 1));
|
|
1597
|
+
const now = Date.now();
|
|
1589
1598
|
|
|
1590
1599
|
let idx = 0;
|
|
1591
1600
|
for (const [id, session] of entries) {
|
|
1592
|
-
const elapsedStr = formatElapsed(
|
|
1601
|
+
const elapsedStr = formatElapsed(now - session.startedAt);
|
|
1593
1602
|
const name = liveRowName(session.label, session.task);
|
|
1594
|
-
const spinner = liveSpinner(
|
|
1603
|
+
const spinner = liveSpinner(now);
|
|
1595
1604
|
// Selection marker: a "›" prefix on the selected row only. The
|
|
1596
1605
|
// rest of the row (spinner/name/dim/muted lines) is unchanged.
|
|
1597
1606
|
const marker = idx === selIdx ? "› " : "";
|
|
@@ -1601,7 +1610,14 @@ export async function showMonitor(
|
|
|
1601
1610
|
theme.fg("accent", `${marker}${spinner} ${name}`) +
|
|
1602
1611
|
theme.fg(
|
|
1603
1612
|
"dim",
|
|
1604
|
-
formatLiveRowDim(
|
|
1613
|
+
formatLiveRowDim(
|
|
1614
|
+
id,
|
|
1615
|
+
session.usage,
|
|
1616
|
+
elapsedStr,
|
|
1617
|
+
// Issue #423: used / budget (percent left); `—` when the run has
|
|
1618
|
+
// no timer at all (a foreground run with no timeout).
|
|
1619
|
+
formatBudget(session.startedAt, session.deadlineAt, now),
|
|
1620
|
+
),
|
|
1605
1621
|
),
|
|
1606
1622
|
1,
|
|
1607
1623
|
0,
|
|
@@ -1652,15 +1668,17 @@ export async function showMonitor(
|
|
|
1652
1668
|
done();
|
|
1653
1669
|
return;
|
|
1654
1670
|
}
|
|
1655
|
-
// up / down: move the selection, wrapping like SelectList.
|
|
1671
|
+
// up / down: move the selection, wrapping like SelectList. The bound is
|
|
1672
|
+
// the list the LAST paint rendered (issue #423), so the highlight can
|
|
1673
|
+
// never run past a row the human cannot see.
|
|
1656
1674
|
if (_kb.matches(data, "tui.select.up")) {
|
|
1657
|
-
const count =
|
|
1675
|
+
const count = lastRenderedIds.length;
|
|
1658
1676
|
selectedIndex = count > 0 ? (selectedIndex - 1 + count) % count : 0;
|
|
1659
1677
|
tui.requestRender();
|
|
1660
1678
|
return;
|
|
1661
1679
|
}
|
|
1662
1680
|
if (_kb.matches(data, "tui.select.down")) {
|
|
1663
|
-
const count =
|
|
1681
|
+
const count = lastRenderedIds.length;
|
|
1664
1682
|
selectedIndex = count > 0 ? (selectedIndex + 1) % count : 0;
|
|
1665
1683
|
tui.requestRender();
|
|
1666
1684
|
return;
|
|
@@ -1668,9 +1686,11 @@ export async function showMonitor(
|
|
|
1668
1686
|
// enter: open the full-screen drill-in overlay for the selected agent.
|
|
1669
1687
|
// The overlay's done() returns to the list — the monitor stays open
|
|
1670
1688
|
// beneath it (fire-and-forget; handleInput is synchronous).
|
|
1689
|
+
// Issue #423: the id resolves against the RENDERED list, so a spawn or
|
|
1690
|
+
// a finalize between paint and Enter cannot open a different agent than
|
|
1691
|
+
// the highlighted row (a stale id falls through to the not-found path).
|
|
1671
1692
|
if (_kb.matches(data, "tui.select.confirm")) {
|
|
1672
|
-
const
|
|
1673
|
-
const id = ids[Math.min(selectedIndex, ids.length - 1)];
|
|
1693
|
+
const id = lastRenderedIds[selectedIndex];
|
|
1674
1694
|
if (id && !detailOpen) {
|
|
1675
1695
|
detailOpen = true;
|
|
1676
1696
|
showAgentDetail(ctx, state, id).finally(() => {
|
|
@@ -1982,7 +2002,7 @@ function compactDuration(ms: number): string {
|
|
|
1982
2002
|
/** The per-row live-session slice the Active Subagents panel renders. */
|
|
1983
2003
|
export type ActiveSubagentSlice = Pick<
|
|
1984
2004
|
LiveSubagent,
|
|
1985
|
-
"label" | "task" | "startedAt" | "usage"
|
|
2005
|
+
"label" | "task" | "startedAt" | "deadlineAt" | "usage"
|
|
1986
2006
|
>;
|
|
1987
2007
|
|
|
1988
2008
|
/** Panel 1 — header: the dashboard title plus the refresh stamp. */
|
|
@@ -2001,15 +2021,35 @@ export function renderDashboardHeader(theme: Theme, refreshStr: string): Compone
|
|
|
2001
2021
|
/**
|
|
2002
2022
|
* Panel 2 — active subagents: the live count in the title, one row per entry.
|
|
2003
2023
|
*
|
|
2004
|
-
*
|
|
2005
|
-
* and
|
|
2024
|
+
* Issue #423: the rows arrive as an ORDERED array (the call site filters
|
|
2025
|
+
* finalized ids and sorts by the soonest deadline) rather than the raw map, so
|
|
2026
|
+
* the panel cannot render a settled row or an order the monitor disagrees with,
|
|
2027
|
+
* and `activeCount` is the rendered length instead of `map.size` (which counted
|
|
2028
|
+
* finalized-but-lingering entries).
|
|
2029
|
+
*
|
|
2030
|
+
* `now` is injected (the composer passes the wall clock) so the spinner frame,
|
|
2031
|
+
* the elapsed suffix and the budget stay testable; it is sampled per render.
|
|
2032
|
+
*/
|
|
2033
|
+
/**
|
|
2034
|
+
* Issue #423: the monitor and the dashboard render the same projection — settled
|
|
2035
|
+
* ids removed (a 3 s lingering row must not show a live deadline) and rows
|
|
2036
|
+
* ordered by the soonest deadline. One definition, so the surfaces cannot
|
|
2037
|
+
* disagree (review 425, DRY).
|
|
2006
2038
|
*/
|
|
2039
|
+
export function liveDisplayEntries(state: SessionState): Array<[string, LiveSubagent]> {
|
|
2040
|
+
return sortLiveSessions(
|
|
2041
|
+
Array.from(state.subagentSessions.entries()).filter(
|
|
2042
|
+
([id]) => !state.isLiveEntryFinalized(id),
|
|
2043
|
+
),
|
|
2044
|
+
);
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2007
2047
|
export function renderDashboardActivePanel(
|
|
2008
2048
|
theme: Theme,
|
|
2009
|
-
sessions:
|
|
2049
|
+
sessions: ReadonlyArray<readonly [string, ActiveSubagentSlice]>,
|
|
2010
2050
|
now: () => number = Date.now,
|
|
2011
2051
|
): Component[] {
|
|
2012
|
-
const activeCount = sessions.
|
|
2052
|
+
const activeCount = sessions.length;
|
|
2013
2053
|
const components: Component[] = [
|
|
2014
2054
|
new Text(
|
|
2015
2055
|
theme.fg("accent", theme.bold(`Active Subagents (${activeCount})`)),
|
|
@@ -2022,15 +2062,22 @@ export function renderDashboardActivePanel(
|
|
|
2022
2062
|
} else {
|
|
2023
2063
|
let idx = 0;
|
|
2024
2064
|
for (const [id, session] of sessions) {
|
|
2025
|
-
const
|
|
2065
|
+
const nowMs = now();
|
|
2066
|
+
const elapsedStr = formatElapsed(nowMs - session.startedAt);
|
|
2026
2067
|
const name = liveRowName(session.label, session.task);
|
|
2027
|
-
const spinner = liveSpinner(
|
|
2068
|
+
const spinner = liveSpinner(nowMs);
|
|
2028
2069
|
components.push(
|
|
2029
2070
|
new Text(
|
|
2030
2071
|
theme.fg("accent", ` ${spinner} ${name}`) +
|
|
2031
2072
|
theme.fg(
|
|
2032
2073
|
"dim",
|
|
2033
|
-
formatLiveRowDim(
|
|
2074
|
+
formatLiveRowDim(
|
|
2075
|
+
id,
|
|
2076
|
+
session.usage,
|
|
2077
|
+
elapsedStr,
|
|
2078
|
+
// Issue #423: used / budget (percent left); `—` when no timer.
|
|
2079
|
+
formatBudget(session.startedAt, session.deadlineAt, nowMs),
|
|
2080
|
+
),
|
|
2034
2081
|
),
|
|
2035
2082
|
1,
|
|
2036
2083
|
0,
|
|
@@ -2234,10 +2281,11 @@ export async function showDashboard(
|
|
|
2234
2281
|
append(renderDashboardHeader(theme, refreshStr));
|
|
2235
2282
|
|
|
2236
2283
|
// ---- Panel 2: Active subagents ----
|
|
2237
|
-
|
|
2284
|
+
// Issue #423: the panel takes the same ordered projection as the monitor.
|
|
2285
|
+
append(renderDashboardActivePanel(theme, liveDisplayEntries(state), Date.now));
|
|
2238
2286
|
|
|
2239
2287
|
// ---- Panel 3: SLA Summary ----
|
|
2240
|
-
const allRuns = state.
|
|
2288
|
+
const allRuns = state.getLogicalRunEntries(ctx);
|
|
2241
2289
|
const recentRuns = allRuns.slice(0, state.config.slaWindowSize || 50);
|
|
2242
2290
|
const metrics = recentRuns.length > 0 ? computeSLAMetrics(recentRuns) : null;
|
|
2243
2291
|
append(renderDashboardSlaPanel(theme, metrics, recentRuns.length));
|
package/src/types.ts
CHANGED
|
@@ -35,6 +35,28 @@ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhi
|
|
|
35
35
|
|
|
36
36
|
export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Issue #443: the ONE membership test for a thinking level — the guard every
|
|
40
|
+
* seam that can launch a subagent calls before a DECLARED level is resolved.
|
|
41
|
+
*
|
|
42
|
+
* Why it is not `resolveThinkingLevel`: that function CLAMPS, and it cannot
|
|
43
|
+
* report failure. An unknown value (`"bogus"`, `"MAX"`, `" high"`) has index
|
|
44
|
+
* -1, so `THINKING_LEVELS[Math.min(-1, maxIdx)]` is `undefined` — the level is
|
|
45
|
+
* then erased into argv as `--thinking undefined`, pi warns and runs at ITS OWN
|
|
46
|
+
* default, and the configured cap is bypassed rather than a launch refused.
|
|
47
|
+
* Callers therefore check membership first and keep `resolveThinkingLevel`
|
|
48
|
+
* exactly as it is for valid input.
|
|
49
|
+
*
|
|
50
|
+
* Case- and whitespace-exact by construction (`THINKING_LEVELS.includes`), so
|
|
51
|
+
* `"High"` and `" high"` are rejected too. `""` is NOT a level: the dispatch
|
|
52
|
+
* seams preserve its existing meaning (top level → the configured maximum,
|
|
53
|
+
* per unit → the global level), so the empty string is handled by them, not
|
|
54
|
+
* here. pi's own `max` is not a delegated level.
|
|
55
|
+
*/
|
|
56
|
+
export function isThinkingLevel(value: unknown): value is ThinkingLevel {
|
|
57
|
+
return typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value);
|
|
58
|
+
}
|
|
59
|
+
|
|
38
60
|
export type Priority = "critical" | "high" | "normal" | "low";
|
|
39
61
|
|
|
40
62
|
export const PRIORITY_ORDER: Record<Priority, number> = {
|
|
@@ -80,6 +102,14 @@ export const SUBAGENT_ABORTED_MESSAGE = "Subagent aborted by user";
|
|
|
80
102
|
// SUBAGENT_ABORTED_MESSAGE match) — keep the literal in sync with classifyError.
|
|
81
103
|
export const SUBAGENT_SIGNAL_KILLED_MESSAGE = "Subagent killed by external signal";
|
|
82
104
|
|
|
105
|
+
// Issue #447: the honest stamp for a dispatch that never reached
|
|
106
|
+
// `session.prompt()`. Shared by the in-process pre-start cleanup
|
|
107
|
+
// (session-manager) and the boot scan's never-started finalize (recovery) so
|
|
108
|
+
// the two surfaces cannot describe the same non-event differently. It carries
|
|
109
|
+
// no classifyError keyword on purpose — a pre-start failure is `unknown`, not a
|
|
110
|
+
// timeout, an abort, or an exit error.
|
|
111
|
+
export const PROMPT_NEVER_ISSUED_MESSAGE = "Subagent prompt was never issued";
|
|
112
|
+
|
|
83
113
|
/**
|
|
84
114
|
* Classify a subagent result into an error category based on its errorMessage,
|
|
85
115
|
* stopReason, exitCode, and stderr content. Inspects patterns in priority order.
|
|
@@ -382,6 +412,20 @@ export interface SubagentRun {
|
|
|
382
412
|
// Option B U3 (D4): the recovery posture in force when this run was
|
|
383
413
|
// dispatched. Additive: a pre-U3 record lacks it and reads as "offer".
|
|
384
414
|
recoveryPosture?: RecoveryMode;
|
|
415
|
+
/**
|
|
416
|
+
* Issue #447: the acceptance marker. `null` at creation — the dispatch is
|
|
417
|
+
* TRACKED (agent record + run entry + registry entry written) but has not
|
|
418
|
+
* reached `session.prompt()`; an ISO timestamp written immediately before
|
|
419
|
+
* the prompt; absent on records written before the field existed.
|
|
420
|
+
*
|
|
421
|
+
* The tri-state IS the compatibility contract: `null` cannot be produced by
|
|
422
|
+
* a pre-upgrade record (JSON keeps `null`, where `undefined` would vanish),
|
|
423
|
+
* so the boot scan reads `null` as never-started without taking the retry
|
|
424
|
+
* offer away from a legacy record. It is NOT a display status — the
|
|
425
|
+
* vocabulary stays running | completed | failed | stopped, and "started,
|
|
426
|
+
* outcome unknown" remains #439's business (see `isInterruptedRun`).
|
|
427
|
+
*/
|
|
428
|
+
acceptedAt?: string | null;
|
|
385
429
|
startedAt: string;
|
|
386
430
|
finishedAt?: string;
|
|
387
431
|
durationMs?: number;
|
|
@@ -406,6 +450,13 @@ export interface LiveSubagent {
|
|
|
406
450
|
// Issue #114: per-unit priority for the drill-in header (`p:critical` etc.).
|
|
407
451
|
priority?: string;
|
|
408
452
|
startedAt: number;
|
|
453
|
+
/**
|
|
454
|
+
* Issue #423: absolute deadline (epoch ms) for this run, when it has a timer.
|
|
455
|
+
* Absent for a foreground run with no explicit timeout (foreground has no
|
|
456
|
+
* default deadline) and for a background run with no persisted budget (an
|
|
457
|
+
* old record). Display only — the kill remains the timer owner's business.
|
|
458
|
+
*/
|
|
459
|
+
deadlineAt?: number;
|
|
409
460
|
liveOutput: string;
|
|
410
461
|
usage: { input: number; output: number };
|
|
411
462
|
ctx: ExtensionContext;
|
|
@@ -769,6 +820,13 @@ export interface BackgroundAgent {
|
|
|
769
820
|
status: AgentStatus;
|
|
770
821
|
startedAt: number;
|
|
771
822
|
completedAt?: number;
|
|
823
|
+
/**
|
|
824
|
+
* Issue #423: the EFFECTIVE budget of this background run (explicit timeout,
|
|
825
|
+
* else the 30 m default), persisted at spawn so the result and wake can
|
|
826
|
+
* state it after the closure that armed the timer is gone. Absent on records
|
|
827
|
+
* written before the field existed — read as "no budget known".
|
|
828
|
+
*/
|
|
829
|
+
timeoutMs?: number;
|
|
772
830
|
task: string;
|
|
773
831
|
model: string;
|
|
774
832
|
thinkingLevel: ThinkingLevel;
|
|
@@ -777,6 +835,13 @@ export interface BackgroundAgent {
|
|
|
777
835
|
error?: string;
|
|
778
836
|
result?: SubagentResult;
|
|
779
837
|
finalOutput?: string;
|
|
838
|
+
/**
|
|
839
|
+
* Issue #465: the work branch this run's `gitMode=branch` isolation created,
|
|
840
|
+
* stamped when the branch is created so a DURABLE record names it even if the
|
|
841
|
+
* run never settles (a stuck owner never writes `result.gitBranch`, which is
|
|
842
|
+
* settle-only). Serializable on purpose — a refusal's message is built from it.
|
|
843
|
+
*/
|
|
844
|
+
workBranch?: string;
|
|
780
845
|
/** @internal — session reference for live monitor polling */
|
|
781
846
|
_sessionRef?: import('@earendil-works/pi-coding-agent').AgentSession;
|
|
782
847
|
/**
|
|
@@ -802,10 +867,59 @@ export interface BackgroundAgent {
|
|
|
802
867
|
recoveryPosture?: RecoveryMode;
|
|
803
868
|
}
|
|
804
869
|
|
|
870
|
+
/**
|
|
871
|
+
* Issue #439: the part of a spawned background run that is needed to REPORT it,
|
|
872
|
+
* captured as a plain record the instant the spawn returns.
|
|
873
|
+
*
|
|
874
|
+
* Why a separate record rather than the agent itself: everything after the
|
|
875
|
+
* spawn is contained (a fault there must classify the run as STARTED, never as
|
|
876
|
+
* a failed spawn), and a containment whose degraded path still formats from the
|
|
877
|
+
* live agent re-opens the window it exists to close. Callers format from these
|
|
878
|
+
* fields only; `label` is `description` under the name `delegate_task` takes it
|
|
879
|
+
* from the caller, so a fan-out can render its unit label from the same record.
|
|
880
|
+
*/
|
|
881
|
+
export interface BackgroundAgentIdentity {
|
|
882
|
+
id: string;
|
|
883
|
+
label?: string;
|
|
884
|
+
description: string;
|
|
885
|
+
task: string;
|
|
886
|
+
status: AgentStatus;
|
|
887
|
+
model: string;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* Issue #439: what the background-spawn tail returns. `agent` is the live
|
|
892
|
+
* record the tail's own poller/deadline close over; `identity` is the plain
|
|
893
|
+
* reporting record (all callers format from it); `tailFailures` is the
|
|
894
|
+
* containments' ledger — empty when the whole tail attached.
|
|
895
|
+
*
|
|
896
|
+
* A non-empty `tailFailures` means exactly one thing: **the run started and its
|
|
897
|
+
* monitoring is degraded**. It is never a spawn failure, so no caller may
|
|
898
|
+
* classify it as an error (the transport retry reads `isError` as "did not
|
|
899
|
+
* start" and would surface a false source failure).
|
|
900
|
+
*/
|
|
901
|
+
export interface BackgroundAgentSpawnResult {
|
|
902
|
+
agent: BackgroundAgent;
|
|
903
|
+
identity: BackgroundAgentIdentity;
|
|
904
|
+
tailFailures: string[];
|
|
905
|
+
}
|
|
906
|
+
|
|
805
907
|
// ---------------------------------------------------------------------------
|
|
806
908
|
// Helper functions
|
|
807
909
|
// ---------------------------------------------------------------------------
|
|
808
910
|
|
|
911
|
+
/**
|
|
912
|
+
* The approval modes that make a background spawn impossible (W5, issue #28).
|
|
913
|
+
*
|
|
914
|
+
* ONE definition, two consumers — `rejectApprovalAlwaysInBackground`
|
|
915
|
+
* (prelude.ts, the background gates) and `resolveThinkingDispatchSwitch`
|
|
916
|
+
* (params.ts, the dispatch pre-flight that must not switch a dispatch into a
|
|
917
|
+
* rejection — issue #433). A re-spelled `=== "always"` at either site is the
|
|
918
|
+
* drift this helper exists to prevent: widening or narrowing what background
|
|
919
|
+
* can accept must change the pre-flight's verdict in the same edit.
|
|
920
|
+
*/
|
|
921
|
+
export const approvalBlocksBackground = (m: ApprovalMode): boolean => m === "always";
|
|
922
|
+
|
|
809
923
|
export function resolveThinkingLevel(
|
|
810
924
|
requested: ThinkingLevel | undefined,
|
|
811
925
|
maxAllowed: ThinkingLevel,
|
|
@@ -816,6 +930,26 @@ export function resolveThinkingLevel(
|
|
|
816
930
|
return THINKING_LEVELS[Math.min(requestedIdx, maxIdx)];
|
|
817
931
|
}
|
|
818
932
|
|
|
933
|
+
/**
|
|
934
|
+
* Issue #443: the value that actually REACHES resolution — the per-call
|
|
935
|
+
* declaration, else the selected preset's — before any clamping.
|
|
936
|
+
*
|
|
937
|
+
* ONE spelling, three readers: `resolveSubagentParams` merges it, and both
|
|
938
|
+
* dispatch seams guard it (`execute` and `spawnBackgroundRun`, the latter for
|
|
939
|
+
* the transport auto-retry). A guard that computed this differently would
|
|
940
|
+
* judge a value the merge never uses, which is the silent-drift class this
|
|
941
|
+
* helper removes; `resolveThinkingLevel` then clamps what it returns.
|
|
942
|
+
*
|
|
943
|
+
* `undefined` (omitted) and `""` are returned unchanged on purpose — they are
|
|
944
|
+
* existing declarations, not values to judge (see `isThinkingLevel`).
|
|
945
|
+
*/
|
|
946
|
+
export function declaredThinkingLevel(
|
|
947
|
+
callLevel: string | undefined,
|
|
948
|
+
presetLevel: string | undefined,
|
|
949
|
+
): string | undefined {
|
|
950
|
+
return callLevel ?? presetLevel;
|
|
951
|
+
}
|
|
952
|
+
|
|
819
953
|
export function formatTokens(count: number): string {
|
|
820
954
|
if (count < 1000) return count.toString();
|
|
821
955
|
if (count < 10_000) return `${(count / 1000).toFixed(1)}k`;
|
|
@@ -948,6 +1082,30 @@ export interface TerminalOutcome {
|
|
|
948
1082
|
errorCategory?: ErrorCategory;
|
|
949
1083
|
}
|
|
950
1084
|
|
|
1085
|
+
/**
|
|
1086
|
+
* Issue #449: what the settle site saw in the session's PROJECTED message array.
|
|
1087
|
+
*
|
|
1088
|
+
* `"absent"` means exactly ONE thing: the array was READ and contained no
|
|
1089
|
+
* assistant message. It is supplied only by the background settle site, which
|
|
1090
|
+
* reads the projection the SDK rewrote before settling; a missing or throwing
|
|
1091
|
+
* `messages` getter is `"unknown"` (it never reaches the classifier — the settle
|
|
1092
|
+
* handler's catch-all owns it), and a projection holding an assistant message is
|
|
1093
|
+
* `"present"` whatever that message contains.
|
|
1094
|
+
*/
|
|
1095
|
+
export type AssistantEvidence = "present" | "absent" | "unknown";
|
|
1096
|
+
|
|
1097
|
+
/**
|
|
1098
|
+
* Issue #449: the fixed failure headline for a run that settled with no
|
|
1099
|
+
* assistant output. The omitted message cannot be recovered, so this asserts the
|
|
1100
|
+
* OBSERVATION (no output) and only offers truncation as a possibility — it never
|
|
1101
|
+
* claims truncation as fact. Deliberately free of every TRANSPORT_SIGNATURES
|
|
1102
|
+
* substring (transport-retry.ts), so an automatic transport retry cannot fire on
|
|
1103
|
+
* this class; its `incomplete` category is independently excluded by that
|
|
1104
|
+
* predicate's class gate.
|
|
1105
|
+
*/
|
|
1106
|
+
export const NO_ASSISTANT_OUTPUT_REASON =
|
|
1107
|
+
"Run settled with no assistant output — the provider's response may have been truncated and omitted by the SDK (see #449)";
|
|
1108
|
+
|
|
951
1109
|
/**
|
|
952
1110
|
* Issue #179 (D1): classify a run's terminal outcome from its final assistant
|
|
953
1111
|
* stopReason. This is the settle-time counterpart to classifyError/isSubagentError
|
|
@@ -955,16 +1113,25 @@ export interface TerminalOutcome {
|
|
|
955
1113
|
*
|
|
956
1114
|
* | stopReason | status | errorCategory |
|
|
957
1115
|
* |--------------------------|-----------|----------------------------|
|
|
958
|
-
* | stop
|
|
1116
|
+
* | stop | completed | — |
|
|
1117
|
+
* | undefined | completed | — |
|
|
1118
|
+
* | undefined + absent (449) | failed | incomplete |
|
|
959
1119
|
* | aborted | stopped | aborted |
|
|
960
1120
|
* | error | failed | from classifyError |
|
|
961
1121
|
* | length | failed | truncated |
|
|
962
1122
|
* | toolUse/deferred/pending | failed | incomplete |
|
|
1123
|
+
*
|
|
1124
|
+
* Issue #449: `extra.assistantEvidence` defaults to `"unknown"`, so every caller
|
|
1125
|
+
* that does not pass it keeps the pre-#449 result byte for byte. Only an already-
|
|
1126
|
+
* KNOWN terminal outcome (the switch arms above) beats the evidence; the evidence
|
|
1127
|
+
* decides the formerly-default case alone. The omitted message is unrecoverable,
|
|
1128
|
+
* so this is a structural guard: it cannot tell a truncation omission from any
|
|
1129
|
+
* other resolve-with-no-assistant-message.
|
|
963
1130
|
*/
|
|
964
1131
|
export function classifyTerminalOutcome(
|
|
965
1132
|
stopReason: string | undefined,
|
|
966
1133
|
errorMessage?: string,
|
|
967
|
-
extra?: { stderr?: string; exitCode?: number },
|
|
1134
|
+
extra?: { stderr?: string; exitCode?: number; assistantEvidence?: AssistantEvidence },
|
|
968
1135
|
): TerminalOutcome {
|
|
969
1136
|
switch (stopReason) {
|
|
970
1137
|
case "aborted":
|
|
@@ -986,6 +1153,14 @@ export function classifyTerminalOutcome(
|
|
|
986
1153
|
}),
|
|
987
1154
|
};
|
|
988
1155
|
default:
|
|
1156
|
+
// Issue #449: no terminal stopReason at all. A projection READ as an
|
|
1157
|
+
// array holding no assistant message is not a success — the still-open
|
|
1158
|
+
// turn has no answer to show for itself. Only the MISSING reason can be
|
|
1159
|
+
// decided by the evidence: any stopReason the caller observed (including
|
|
1160
|
+
// "stop") is an already-known outcome and keeps its existing result.
|
|
1161
|
+
if (stopReason === undefined && extra?.assistantEvidence === "absent") {
|
|
1162
|
+
return { status: "failed", errorCategory: "incomplete" };
|
|
1163
|
+
}
|
|
989
1164
|
return { status: "completed" };
|
|
990
1165
|
}
|
|
991
1166
|
}
|
package/src/unit-run.ts
CHANGED
|
@@ -269,13 +269,21 @@ export function pruneHistoryIfNeeded(
|
|
|
269
269
|
* `labelOverride` supplies the live entry's label when the caller wants one
|
|
270
270
|
* that differs from `run.label` (e.g. chain's unlabeled-step fallback).
|
|
271
271
|
* When omitted the live label defaults to `run.label`.
|
|
272
|
+
*
|
|
273
|
+
* `timeoutMs` is the run's MERGED timeout (param/preset/template) — never the
|
|
274
|
+
* raw caller param (issue #423). It becomes the live entry's absolute
|
|
275
|
+
* `deadlineAt`, anchored on the run's own start clock. Absent or non-positive
|
|
276
|
+
* means "no deadline": a foreground run has no default deadline.
|
|
272
277
|
*/
|
|
273
278
|
export function registerLiveRun(
|
|
274
279
|
state: SessionState,
|
|
275
280
|
run: SubagentRun,
|
|
276
281
|
ctx: ExtensionContext,
|
|
277
282
|
labelOverride?: string,
|
|
283
|
+
timeoutMs?: number,
|
|
278
284
|
): void {
|
|
285
|
+
const startedAt = new Date(run.startedAt).getTime();
|
|
286
|
+
const deadlineAt = timeoutMs && timeoutMs > 0 ? startedAt + timeoutMs : undefined;
|
|
279
287
|
state.registerLiveSubagent(run.id, {
|
|
280
288
|
id: run.id,
|
|
281
289
|
label: labelOverride ?? run.label,
|
|
@@ -283,7 +291,8 @@ export function registerLiveRun(
|
|
|
283
291
|
model: run.model,
|
|
284
292
|
thinkingLevel: run.thinkingLevel,
|
|
285
293
|
priority: run.priority,
|
|
286
|
-
startedAt
|
|
294
|
+
startedAt,
|
|
295
|
+
...(deadlineAt !== undefined ? { deadlineAt } : {}),
|
|
287
296
|
ctx,
|
|
288
297
|
});
|
|
289
298
|
}
|
package/src/validate.ts
CHANGED
|
@@ -38,12 +38,19 @@ export interface ValidateConfig {
|
|
|
38
38
|
cwd?: string;
|
|
39
39
|
/**
|
|
40
40
|
* delegate_task's `noJev` param — the STATED bypass for the Jev-line check
|
|
41
|
-
* (issue #412, ADR 0018).
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
41
|
+
* (issue #412, ADR 0018). It downgrades the rejection to a warning that
|
|
42
|
+
* carries the reason, so the bypass is visible in the result, never silent.
|
|
43
|
+
* It bypasses ONLY the line check: every capability conflict still rejects
|
|
44
|
+
* (unlike `force`, which is capability-only).
|
|
45
|
+
*
|
|
46
|
+
* Typed `unknown` on purpose (issue #419, ADR 0020): the schema DECLARES a
|
|
47
|
+
* non-empty string, but the harness validates with `coerce: true` and
|
|
48
|
+
* pi-schema's string rule stringifies booleans/numbers before the handler
|
|
49
|
+
* runs, so the value that arrives is not guaranteed to be the declared type
|
|
50
|
+
* (a direct caller can pass anything at all). `readNoJevReason` is the
|
|
51
|
+
* runtime guard, and it is the ONLY place this value may be read.
|
|
45
52
|
*/
|
|
46
|
-
noJev?:
|
|
53
|
+
noJev?: unknown;
|
|
47
54
|
}
|
|
48
55
|
|
|
49
56
|
export interface ValidateResult {
|
|
@@ -305,6 +312,55 @@ export function diagnoseFailure(config: DiagnoseConfig): string[] {
|
|
|
305
312
|
return suggestions;
|
|
306
313
|
}
|
|
307
314
|
|
|
315
|
+
// ── The noJev bypass reason (issue #419, ADR 0020) ───────────────────
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* What the harness's coercion turns a non-string reason INTO: `compile(schema,
|
|
319
|
+
* { coerce: true })` stringifies booleans and numbers, so `noJev: true`
|
|
320
|
+
* reaches the handler as `"true"` — a value that passes `Type.String({
|
|
321
|
+
* minLength: 1 })` and is NOT a stated reason. Matching the coerced text is the
|
|
322
|
+
* only way to tell it apart from a real one at this seam.
|
|
323
|
+
*/
|
|
324
|
+
const COERCED_PRIMITIVE_RE = /^(true|false|-?\d+(\.\d+)?)$/i;
|
|
325
|
+
|
|
326
|
+
/** The three outcomes of reading `noJev`: no bypass, a usable reason, or a refusal. */
|
|
327
|
+
type NoJevVerdict =
|
|
328
|
+
| { kind: 'absent' }
|
|
329
|
+
| { kind: 'reason'; reason: string }
|
|
330
|
+
| { kind: 'invalid'; problem: string };
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Reads `noJev` defensively. The schema declares a non-empty string, but that
|
|
334
|
+
* is a DECLARATION, not a runtime guarantee: coercion stringifies primitives
|
|
335
|
+
* (above), and a direct caller can pass any value. So: never `.trim()` a
|
|
336
|
+
* non-string, and treat a coerced primitive (or an empty/whitespace reason) as
|
|
337
|
+
* an INVALID bypass rather than a usable one — a boolean must neither bypass
|
|
338
|
+
* the check nor crash it.
|
|
339
|
+
*/
|
|
340
|
+
function readNoJevReason(value: unknown): NoJevVerdict {
|
|
341
|
+
// Omitted, or an optional `null` (pi-schema drops those during coercion):
|
|
342
|
+
// no bypass was stated, so the caller gets the plain missing-line error.
|
|
343
|
+
if (value === undefined || value === null) return { kind: 'absent' };
|
|
344
|
+
if (typeof value !== 'string') {
|
|
345
|
+
const shape = Array.isArray(value) ? 'array' : typeof value;
|
|
346
|
+
return { kind: 'invalid', problem: `expected a non-empty reason string, got ${shape}` };
|
|
347
|
+
}
|
|
348
|
+
const reason = value.trim();
|
|
349
|
+
if (reason === '') {
|
|
350
|
+
return { kind: 'invalid', problem: 'the reason is empty' };
|
|
351
|
+
}
|
|
352
|
+
if (COERCED_PRIMITIVE_RE.test(reason)) {
|
|
353
|
+
const coerced = /^(true|false)$/i.test(reason) ? 'boolean' : 'number';
|
|
354
|
+
return {
|
|
355
|
+
kind: 'invalid',
|
|
356
|
+
problem:
|
|
357
|
+
`\`${reason}\` is a coerced ${coerced}, not a stated reason — the tool-argument validator ` +
|
|
358
|
+
`stringifies booleans and numbers before the handler sees them`,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
return { kind: 'reason', reason };
|
|
362
|
+
}
|
|
363
|
+
|
|
308
364
|
// ── Main validation ──────────────────────────────────────────────────
|
|
309
365
|
|
|
310
366
|
export function validatePreTask(config: ValidateConfig): ValidateResult {
|
|
@@ -327,15 +383,24 @@ export function validatePreTask(config: ValidateConfig): ValidateResult {
|
|
|
327
383
|
// dispatch is never rejected for a missing line. The flag read is fail-open
|
|
328
384
|
// (`src/project-flags.ts`). `noJev` — a stated reason — downgrades the
|
|
329
385
|
// rejection to a WARNING that names the reason, so the bypass is surfaced
|
|
330
|
-
// rather than silent (ADR 0007's pattern).
|
|
386
|
+
// rather than silent (ADR 0007's pattern). The reason itself is read through
|
|
387
|
+
// a runtime guard, never off the declared type (issue #419, ADR 0020): a
|
|
388
|
+
// boolean/number arrives here coercion-stringified, and it must be refused
|
|
389
|
+
// as the missing line, not accepted as a bypass.
|
|
331
390
|
if (isProcessChecksEnabled(config.cwd)) {
|
|
332
391
|
const verdict = parseDispatchLine(taskText);
|
|
333
392
|
if (!verdict.ok) {
|
|
334
|
-
|
|
393
|
+
const bypass = readNoJevReason(config.noJev);
|
|
394
|
+
if (bypass.kind === 'reason') {
|
|
335
395
|
warnings.push(
|
|
336
|
-
`noJev override: the Jev dispatch line was skipped — ${
|
|
396
|
+
`noJev override: the Jev dispatch line was skipped — ${bypass.reason} (${verdict.reason})`,
|
|
337
397
|
);
|
|
338
398
|
} else {
|
|
399
|
+
if (bypass.kind === 'invalid') {
|
|
400
|
+
errors.push(
|
|
401
|
+
`invalid noJev: ${bypass.problem}. Pass the reason the line was skipped as a non-empty string (e.g. noJev: "classifier unreachable; maintainer approved"), or append the line.`,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
339
404
|
errors.push(
|
|
340
405
|
`missing Jev dispatch line: ${verdict.reason}. ` +
|
|
341
406
|
`Classify with the Jev classifier, format the answer with \`jev-check --line '<json>'\` (it prints the line verbatim), and append it to the task as: ${DISPATCH_LINE_FORM}. ` +
|
|
@@ -456,3 +521,17 @@ export function normalizeTimeout(timeout: number | undefined): number | undefine
|
|
|
456
521
|
if (timeout >= 2 ** 31 - 1) return undefined;
|
|
457
522
|
return timeout;
|
|
458
523
|
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* The EFFECTIVE budget of a BACKGROUND run: the normalized explicit `timeout`,
|
|
527
|
+
* or {@link DEFAULT_BACKGROUND_DEADLINE_MS} when there is none (issue #423).
|
|
528
|
+
*
|
|
529
|
+
* The single definition of "30 m default" for the background path — the W3
|
|
530
|
+
* timer, the persisted record's `timeoutMs` and every display of the budget
|
|
531
|
+
* derive from here, so a displayed deadline cannot drift from the armed timer.
|
|
532
|
+
* Not used by the foreground path: a foreground run has NO default deadline,
|
|
533
|
+
* so an absent timeout there means "no deadline", not 30 m.
|
|
534
|
+
*/
|
|
535
|
+
export function effectiveBackgroundBudget(timeout: number | undefined): number {
|
|
536
|
+
return normalizeTimeout(timeout) ?? DEFAULT_BACKGROUND_DEADLINE_MS;
|
|
537
|
+
}
|