brl-subagent 2.9.1 → 2.9.3

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.
Files changed (46) hide show
  1. package/AGENT.md +3 -0
  2. package/CHANGELOG.md +366 -0
  3. package/README.md +11 -5
  4. package/package.json +14 -11
  5. package/src/agent-tools.ts +178 -19
  6. package/src/atomic-write.ts +101 -0
  7. package/src/background-guard.ts +295 -0
  8. package/src/background-pipeline.ts +21 -5
  9. package/src/boot-recovery.ts +16 -0
  10. package/src/brief.ts +228 -0
  11. package/src/delegate-handler.ts +51 -12
  12. package/src/dispatch-header.ts +226 -0
  13. package/src/history.ts +0 -6
  14. package/src/index.ts +27 -5
  15. package/src/kill-escalation.ts +32 -9
  16. package/src/mode-prologue.ts +3 -11
  17. package/src/mode-runners.ts +0 -3
  18. package/src/notify-completion.ts +81 -12
  19. package/src/params.ts +10 -2
  20. package/src/prelude.ts +1 -9
  21. package/src/proc.ts +73 -15
  22. package/src/project-flags.ts +42 -6
  23. package/src/recovery-engine.ts +16 -2
  24. package/src/recovery.ts +29 -0
  25. package/src/retry-armed.ts +383 -0
  26. package/src/run-registry.ts +121 -1
  27. package/src/runner.ts +308 -10
  28. package/src/schema.ts +0 -11
  29. package/src/session-manager.ts +490 -54
  30. package/src/state.ts +16 -1
  31. package/src/stop-lineage.ts +280 -0
  32. package/src/templates.ts +97 -1
  33. package/src/terminal-notifier.ts +70 -4
  34. package/src/types.ts +110 -0
  35. package/src/unit-run.ts +7 -2
  36. package/src/validate.ts +47 -86
  37. package/templates/analyze-data.md +1 -0
  38. package/templates/code-review.md +1 -0
  39. package/templates/debug-issue.md +1 -0
  40. package/templates/implement-feature.md +1 -0
  41. package/templates/prototype.md +1 -0
  42. package/templates/refactor.md +1 -0
  43. package/templates/security-audit.md +1 -0
  44. package/templates/write-docs.md +1 -0
  45. package/templates/write-tests.md +1 -0
  46. package/src/dispatch-line.ts +0 -144
package/src/runner.ts CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import type { TranscriptMessage, TranscriptContentBlock, TranscriptToolCallBlock } from "./transcript-tail";
14
14
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
15
+ import type { Usage } from "@earendil-works/pi-ai";
15
16
  import { spawn, type ChildProcess } from "node:child_process";
16
17
  import * as fs from "node:fs";
17
18
  import * as path from "node:path";
@@ -29,6 +30,7 @@ import {
29
30
  SUBAGENT_SIGNAL_KILLED_MESSAGE,
30
31
  type SubagentResult,
31
32
  type SubagentToolOptions,
33
+ type SubagentUsageGroup,
32
34
  type UsageStats,
33
35
  type ThinkingLevel,
34
36
  } from "./types";
@@ -161,6 +163,59 @@ export function __registerActiveChildForTest(proc: ChildProcess, marker?: string
161
163
  };
162
164
  }
163
165
 
166
+ /**
167
+ * #244: the escalations this module started and nobody awaited. The abort handler
168
+ * and the timeout handler both `trackEscalation(...)` their `escalateKill(...)`
169
+ * — `launchForeground` settles on the child's `close`, which the escalation does
170
+ * NOT gate, so "the run returned" does not imply "the escalation finished". A
171
+ * test that resets its `/proc` fixtures on return would then be reading the
172
+ * kernel mid-escalation; `__awaitEscalationsForTest` is how it waits instead.
173
+ *
174
+ * Inert in production (an entry per escalation that removes itself on settle),
175
+ * and the AWAIT is gated, so no production caller can wait here.
176
+ */
177
+ const inFlightEscalations = new Set<Promise<unknown>>();
178
+
179
+ /**
180
+ * Register an escalation for test draining. Settles the entry on BOTH outcomes
181
+ * via `then` (not `.finally`, whose chained promise would carry a rejection
182
+ * nobody handles): `escalateKill` is documented as never rejecting over a target
183
+ * that vanished, but a throwing `sleep` still must not leave a stale entry that
184
+ * would hang `__awaitEscalationsForTest` forever.
185
+ */
186
+ function trackEscalation(escalation: Promise<unknown>): void {
187
+ inFlightEscalations.add(escalation);
188
+ const settle = () => {
189
+ inFlightEscalations.delete(escalation);
190
+ };
191
+ void escalation.then(settle, settle);
192
+ }
193
+
194
+ /**
195
+ * #244: TEST-ONLY drain of the in-flight abort/timeout escalations. Throws
196
+ * outside the test environment (same runtime gate as
197
+ * `__setEscalationTimingForTest`): production has no caller that should wait on
198
+ * a queue it never observes, and a stray import must not turn a kill into a
199
+ * join.
200
+ *
201
+ * Loops: `await`ing the CURRENT set can settle an escalation that spun off no
202
+ * new one, but a settled promise is removed by its own `then` BEFORE the await
203
+ * resumes only if it settled first — re-checking `size` after every await is
204
+ * what makes "empty" mean empty rather than "empty at the last sample". Never
205
+ * rejects on a failed escalation (`allSettled`): a test drains, it does not
206
+ * assert a kill's success.
207
+ */
208
+ export async function __awaitEscalationsForTest(): Promise<void> {
209
+ if (!isTestEnvironment()) {
210
+ throw new Error(
211
+ "__awaitEscalationsForTest() is test-only and cannot run in production.",
212
+ );
213
+ }
214
+ while (inFlightEscalations.size > 0) {
215
+ await Promise.allSettled([...inFlightEscalations]);
216
+ }
217
+ }
218
+
164
219
  /**
165
220
  * Escalation target for one spawned child. `verifyDeath` defaults to the
166
221
  * REAL-exit check (`childExited`) AND — on a group target — group emptiness, and
@@ -532,6 +587,242 @@ export function accumulateUsage(
532
587
  }
533
588
  }
534
589
 
590
+ // ---------------------------------------------------------------------------
591
+ // Issue #648: per-model usage groups (the footer's subagent spend)
592
+ // ---------------------------------------------------------------------------
593
+
594
+ /**
595
+ * Is this value a JSON object (a message, an entry, a usage record)?
596
+ * Kept local: the grouping helpers read untyped stream/session records.
597
+ */
598
+ function isRecord(value: unknown): value is Record<string, unknown> {
599
+ return typeof value === "object" && value !== null;
600
+ }
601
+
602
+ /** The model half of a usage record may be `model` or the responses-API `responseModel`. */
603
+ function nonEmptyString(value: unknown): string | undefined {
604
+ return typeof value === "string" && value.length > 0 ? value : undefined;
605
+ }
606
+
607
+ function emptyHostUsage(): Usage {
608
+ return {
609
+ input: 0,
610
+ output: 0,
611
+ cacheRead: 0,
612
+ cacheWrite: 0,
613
+ totalTokens: 0,
614
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
615
+ };
616
+ }
617
+
618
+ /** Add one host `Usage` onto an accumulated group. Absent fields contribute 0. */
619
+ function addHostUsage(target: Usage, src: Record<string, unknown>): void {
620
+ const cost = isRecord(src.cost) ? src.cost : {};
621
+ target.input += typeof src.input === "number" ? src.input : 0;
622
+ target.output += typeof src.output === "number" ? src.output : 0;
623
+ target.cacheRead += typeof src.cacheRead === "number" ? src.cacheRead : 0;
624
+ target.cacheWrite += typeof src.cacheWrite === "number" ? src.cacheWrite : 0;
625
+ target.totalTokens += typeof src.totalTokens === "number" ? src.totalTokens : 0;
626
+ target.cost.input += typeof cost.input === "number" ? cost.input : 0;
627
+ target.cost.output += typeof cost.output === "number" ? cost.output : 0;
628
+ target.cost.cacheRead += typeof cost.cacheRead === "number" ? cost.cacheRead : 0;
629
+ target.cost.cacheWrite += typeof cost.cacheWrite === "number" ? cost.cacheWrite : 0;
630
+ target.cost.total += typeof cost.total === "number" ? cost.total : 0;
631
+ }
632
+
633
+ /** "entirely zero" = every token bucket AND every cost component is 0 (the drop rule). */
634
+ function isZeroHostUsage(usage: Usage): boolean {
635
+ return (
636
+ usage.input === 0 &&
637
+ usage.output === 0 &&
638
+ usage.cacheRead === 0 &&
639
+ usage.cacheWrite === 0 &&
640
+ usage.totalTokens === 0 &&
641
+ usage.cost.input === 0 &&
642
+ usage.cost.output === 0 &&
643
+ usage.cost.cacheRead === 0 &&
644
+ usage.cost.cacheWrite === 0 &&
645
+ usage.cost.total === 0
646
+ );
647
+ }
648
+
649
+ /** A group addressable by the host's own `${provider}/${model}` breakdown key. */
650
+ interface GroupSlot {
651
+ provider: string;
652
+ model: string;
653
+ usage: Usage;
654
+ }
655
+
656
+ function groupKey(provider: string, model: string): string {
657
+ return `${provider}\u0000${model}`;
658
+ }
659
+
660
+ /** Fold one usage record into the group map. A record without usage is skipped. */
661
+ function foldUsage(
662
+ groups: Map<string, GroupSlot>,
663
+ provider: string,
664
+ model: string,
665
+ usage: unknown,
666
+ ): void {
667
+ if (!isRecord(usage)) return;
668
+ const key = groupKey(provider, model);
669
+ let group = groups.get(key);
670
+ if (!group) {
671
+ group = { provider, model, usage: emptyHostUsage() };
672
+ groups.set(key, group);
673
+ }
674
+ addHostUsage(group.usage, usage);
675
+ }
676
+
677
+ /** pi's breakdown key uses `responseModel ?? model`; absent names degrade honestly. */
678
+ function messageModel(msg: Record<string, unknown>): { provider: string; model: string } {
679
+ return {
680
+ provider: nonEmptyString(msg.provider) ?? "unknown",
681
+ model: nonEmptyString(msg.responseModel) ?? nonEmptyString(msg.model) ?? "unknown",
682
+ };
683
+ }
684
+
685
+ /** The model a compaction/branch-summary call is attributed to (it carries no model). */
686
+ function lastAssistantModel(
687
+ messages: ReadonlyArray<unknown> | undefined,
688
+ ): { provider: string; model: string } | undefined {
689
+ const list = messages ?? [];
690
+ for (let index = list.length - 1; index >= 0; index--) {
691
+ const msg = list[index];
692
+ if (isRecord(msg) && msg.role === "assistant") return messageModel(msg);
693
+ }
694
+ return undefined;
695
+ }
696
+
697
+ /** `provider/model-id` (the run record's folded model string) → its two halves. */
698
+ function parseModelString(model: string | undefined): { provider: string; model: string } | undefined {
699
+ if (!model) return undefined;
700
+ const slash = model.indexOf("/");
701
+ if (slash <= 0 || slash === model.length - 1) return undefined;
702
+ return { provider: model.slice(0, slash), model: model.slice(slash + 1) };
703
+ }
704
+
705
+ function finalizeGroups(groups: Map<string, GroupSlot>): SubagentUsageGroup[] {
706
+ return [...groups.values()].filter((group) => !isZeroHostUsage(group.usage));
707
+ }
708
+
709
+ /** The model a usage record that names no model is attributed to (it carries none). */
710
+ function provenanceAttribution(
711
+ messages: ReadonlyArray<unknown> | undefined,
712
+ fallbackModel?: string,
713
+ ): { provider: string; model: string } {
714
+ return (
715
+ lastAssistantModel(messages) ??
716
+ parseModelString(fallbackModel) ??
717
+ { provider: "unknown", model: "unknown" }
718
+ );
719
+ }
720
+
721
+ /**
722
+ * Fold one message list into the group map (one rule, two callers).
723
+ *
724
+ * Assistant turns key their OWN `provider` + `responseModel ?? model`. A
725
+ * `toolResult` message carries `Usage` (the tool's side spend) but NO model, so
726
+ * it joins the group of the run's last assistant message — the attribution rule
727
+ * the spec already accepts for compaction, and the same `Tools/summaries` bucket
728
+ * the host's own breakdown files it under (issue #648 review r2). Dropping it
729
+ * under-counts the money the footer exists to report.
730
+ */
731
+ function foldMessageUsage(
732
+ groups: Map<string, GroupSlot>,
733
+ messages: ReadonlyArray<unknown> | undefined,
734
+ attribution: { provider: string; model: string },
735
+ ): void {
736
+ for (const msg of messages ?? []) {
737
+ if (!isRecord(msg)) continue;
738
+ if (msg.role === "assistant") {
739
+ const { provider, model } = messageModel(msg);
740
+ foldUsage(groups, provider, model, msg.usage);
741
+ } else if (msg.role === "toolResult" && msg.usage) {
742
+ foldUsage(groups, attribution.provider, attribution.model, msg.usage);
743
+ }
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Issue #648 (Q3): group a run's messages into the host footer's per-model key
749
+ * — `provider` + `responseModel ?? model` — and sum each group's usage in the
750
+ * host's `Usage` shape. Groups whose usage is entirely zero are DROPPED: a run
751
+ * that measured nothing contributes no footer entry.
752
+ *
753
+ * Two sources come from `messages`: assistant turns, and `toolResult` usage (a
754
+ * tool's own spend, attributed like compaction — see {@link foldMessageUsage}).
755
+ * Pure: no I/O, no clock. The foreground path passes `result.messages`.
756
+ */
757
+ export function usageGroupsFrom(messages: ReadonlyArray<unknown> | undefined): SubagentUsageGroup[] {
758
+ const groups = new Map<string, GroupSlot>();
759
+ foldMessageUsage(groups, messages, provenanceAttribution(messages));
760
+ return finalizeGroups(groups);
761
+ }
762
+
763
+ /**
764
+ * Issue #648 (Q4/C): the BACKGROUND path's grouping. The child's own footer sums
765
+ * FOUR sources — assistant messages, `toolResult` usage, `type: "usage"` entries
766
+ * and `compaction`/`branch_summary` usage — so a run's recorded spend must
767
+ * include all four or it cannot equal what the child would have reported.
768
+ *
769
+ * A `usage` entry names its own provider/model. A compaction/branch-summary
770
+ * entry does NOT, so it is attributed to the model of the run's last assistant
771
+ * message (falling back to `fallbackModel`, the run record's folded
772
+ * `provider/model-id`); the spec states this so the number stays explainable.
773
+ * `toolResult` messages take the same attribution — {@link foldMessageUsage}.
774
+ * Pure, like {@link usageGroupsFrom}.
775
+ */
776
+ export function usageGroupsFromSession(
777
+ messages: ReadonlyArray<unknown> | undefined,
778
+ entries: ReadonlyArray<unknown> | undefined,
779
+ fallbackModel?: string,
780
+ ): SubagentUsageGroup[] {
781
+ const groups = new Map<string, GroupSlot>();
782
+ const attribution = provenanceAttribution(messages, fallbackModel);
783
+ foldMessageUsage(groups, messages, attribution);
784
+ for (const entry of entries ?? []) {
785
+ if (!isRecord(entry)) continue;
786
+ if (entry.type === "usage") {
787
+ foldUsage(
788
+ groups,
789
+ nonEmptyString(entry.provider) ?? attribution.provider,
790
+ nonEmptyString(entry.model) ?? attribution.model,
791
+ entry.usage,
792
+ );
793
+ } else if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
794
+ foldUsage(groups, attribution.provider, attribution.model, entry.usage);
795
+ }
796
+ }
797
+ return finalizeGroups(groups);
798
+ }
799
+
800
+ /** Token/cost totals for a group list — the run record's `cost`/`tokensIn`/… derive from this. */
801
+ export interface UsageGroupTotals {
802
+ input: number;
803
+ output: number;
804
+ cacheRead: number;
805
+ cacheWrite: number;
806
+ cost: number;
807
+ }
808
+
809
+ /**
810
+ * Sum the groups into the flattened totals our run record stores. Deriving the
811
+ * record's numbers from the SAME groups the footer receives is what makes the
812
+ * two agree by construction (issue #648).
813
+ */
814
+ export function sumUsageGroups(groups: ReadonlyArray<SubagentUsageGroup>): UsageGroupTotals {
815
+ const totals: UsageGroupTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
816
+ for (const group of groups) {
817
+ totals.input += group.usage.input;
818
+ totals.output += group.usage.output;
819
+ totals.cacheRead += group.usage.cacheRead;
820
+ totals.cacheWrite += group.usage.cacheWrite;
821
+ totals.cost += group.usage.cost.total;
822
+ }
823
+ return totals;
824
+ }
825
+
535
826
  // ---------------------------------------------------------------------------
536
827
  // Abort handler
537
828
  // ---------------------------------------------------------------------------
@@ -556,11 +847,15 @@ function attachAbortHandler(
556
847
  // a SIGTERM-ignoring child dead and skipped the force-kill. The same
557
848
  // poll/early-exit wait `reapActiveChildren` uses means a cooperative child
558
849
  // completes in ms while a stubborn one gets SIGKILL at the grace boundary.
559
- void escalateKill([childTarget(proc)], {
560
- graceMs: escalationTiming.graceMs,
561
- pollMs: escalationTiming.pollMs,
562
- sleep: realSleep,
563
- });
850
+ // #244: tracked (not bare `void`), so a test can drain the escalation
851
+ // before its `/proc` fixtures go away.
852
+ trackEscalation(
853
+ escalateKill([childTarget(proc)], {
854
+ graceMs: escalationTiming.graceMs,
855
+ pollMs: escalationTiming.pollMs,
856
+ sleep: realSleep,
857
+ }),
858
+ );
564
859
  };
565
860
  if (signal.aborted) killProc();
566
861
  else signal.addEventListener("abort", killProc, { once: true });
@@ -1293,11 +1588,14 @@ ${msgBlock}`;
1293
1588
  // Same REAL-exit check as the abort path (issue #303 — see there):
1294
1589
  // `child.killed` flips on signal-sent, not process-death, so it would
1295
1590
  // skip the SIGKILL for a SIGTERM-ignoring child.
1296
- void escalateKill([childTarget(proc)], {
1297
- graceMs: escalationTiming.graceMs,
1298
- pollMs: escalationTiming.pollMs,
1299
- sleep: realSleep,
1300
- });
1591
+ // #244: tracked, same as the abort handler above.
1592
+ trackEscalation(
1593
+ escalateKill([childTarget(proc)], {
1594
+ graceMs: escalationTiming.graceMs,
1595
+ pollMs: escalationTiming.pollMs,
1596
+ sleep: realSleep,
1597
+ }),
1598
+ );
1301
1599
  }, timeout);
1302
1600
  proc.on("close", () => clearTimeout(timer));
1303
1601
  }
package/src/schema.ts CHANGED
@@ -237,17 +237,6 @@ export const delegateTaskParamsSchema = Type.Object({
237
237
  "Warnings are surfaced either way. force never suppresses outputFile-without-write conflicts.",
238
238
  }),
239
239
  ),
240
- noJev: Type.Optional(
241
- Type.String({
242
- minLength: 1,
243
- description:
244
- "Stated bypass for the Jev dispatch-line pre-flight, which is active ONLY in a project whose package.json sets the `brl-subagent.processChecks` field (this repository). " +
245
- "A reason string that states WHY the line is missing: the dispatch proceeds and the reason is surfaced as a warning in the result, so the bypass is never silent. " +
246
- "The reason is validated when the dispatch is handled, not by this schema: the argument validator coerces loosely typed input, so a boolean or a number arrives as its text (`true` becomes \"true\") and is REFUSED exactly like an absent bypass. " +
247
- "It bypasses ONLY the line check — capability conflicts still reject (unlike force). " +
248
- "Append `jev: unavailable` to the task instead when the classifier did not run.",
249
- }),
250
- ),
251
240
  background: Type.Optional(
252
241
  Type.Boolean({
253
242
  description: