pi-braid 0.42.0 → 0.43.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.
Files changed (102) hide show
  1. package/CHANGELOG.md +1077 -0
  2. package/README.md +61 -228
  3. package/TOOLS.md +12 -14
  4. package/build-info.json +4 -4
  5. package/dist/extensions/cognitive/metacognition/handlers/think.js +9 -0
  6. package/dist/extensions/core/polyfill/index.d.ts +3 -4
  7. package/dist/extensions/core/polyfill/index.js +34 -131
  8. package/dist/extensions/core/skills-tool/index.js +47 -26
  9. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
  10. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
  11. package/dist/extensions/enforcement/session-health.d.ts +52 -4
  12. package/dist/extensions/enforcement/session-health.js +75 -5
  13. package/dist/extensions/enforcement/whisper.js +15 -1
  14. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
  15. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
  16. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
  17. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
  18. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
  19. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
  20. package/dist/extensions/manifest.js +6 -0
  21. package/dist/extensions/memory/context-lifecycle/index.js +11 -10
  22. package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
  23. package/dist/extensions/memory/context-manager/analysis.js +6 -2
  24. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
  25. package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
  26. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
  27. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
  28. package/dist/extensions/self/path-miss/detect.d.ts +30 -0
  29. package/dist/extensions/self/path-miss/detect.js +67 -0
  30. package/dist/extensions/self/path-miss/index.d.ts +33 -0
  31. package/dist/extensions/self/path-miss/index.js +118 -0
  32. package/dist/extensions/self/watchdog/engine.d.ts +8 -1
  33. package/dist/extensions/self/watchdog/engine.js +25 -2
  34. package/dist/extensions/self/watchdog/index.js +14 -1
  35. package/dist/lib/ai/llm-call.js +23 -0
  36. package/dist/lib/ai/model-resolver.d.ts +11 -10
  37. package/dist/lib/ai/model-resolver.js +16 -19
  38. package/dist/lib/ai/presend-budget.d.ts +68 -0
  39. package/dist/lib/ai/presend-budget.js +83 -0
  40. package/dist/lib/config/braid-settings.d.ts +38 -0
  41. package/dist/lib/config/braid-settings.js +84 -0
  42. package/dist/lib/config/per-tool-settings.d.ts +4 -4
  43. package/dist/lib/config/per-tool-settings.js +4 -4
  44. package/dist/lib/core/event-names.d.ts +1 -0
  45. package/dist/lib/core/event-names.js +1 -0
  46. package/dist/lib/detection/context-tiers.d.ts +18 -5
  47. package/dist/lib/detection/context-tiers.js +51 -33
  48. package/dist/lib/detection/context-usage.d.ts +62 -1
  49. package/dist/lib/detection/context-usage.js +158 -1
  50. package/dist/lib/errors/llm-error.d.ts +14 -0
  51. package/dist/lib/errors/llm-error.js +44 -1
  52. package/dist/lib/state/global-state.d.ts +4 -8
  53. package/dist/lib/state/global-state.js +11 -28
  54. package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
  55. package/dist/lib/telemetry/context-heartbeat.js +18 -8
  56. package/dist/lib/utils/argument-report.d.ts +41 -0
  57. package/dist/lib/utils/argument-report.js +95 -0
  58. package/dist/lib/utils/wake-gate.d.ts +6 -0
  59. package/dist/lib/utils/wake-gate.js +52 -4
  60. package/docs/SETUP.md +7 -6
  61. package/package.json +11 -13
  62. package/src/extensions/cognitive/metacognition/handlers/think.ts +9 -0
  63. package/src/extensions/core/polyfill/index.ts +29 -157
  64. package/src/extensions/core/skills-tool/index.ts +60 -37
  65. package/src/extensions/enforcement/AGENTS.md +38 -1
  66. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
  67. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
  68. package/src/extensions/enforcement/session-health.ts +94 -5
  69. package/src/extensions/enforcement/whisper.ts +15 -1
  70. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
  71. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
  72. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
  73. package/src/extensions/manifest.ts +6 -0
  74. package/src/extensions/memory/AGENTS.md +37 -38
  75. package/src/extensions/memory/context-lifecycle/index.ts +11 -10
  76. package/src/extensions/memory/context-manager/analysis.ts +8 -1
  77. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
  78. package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
  79. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
  80. package/src/extensions/scheduling/timer/AGENTS.md +14 -4
  81. package/src/extensions/self/AGENTS.md +2 -1
  82. package/src/extensions/self/path-miss/AGENTS.md +39 -0
  83. package/src/extensions/self/path-miss/detect.ts +78 -0
  84. package/src/extensions/self/path-miss/index.ts +135 -0
  85. package/src/extensions/self/watchdog/AGENTS.md +36 -18
  86. package/src/extensions/self/watchdog/engine.ts +30 -2
  87. package/src/extensions/self/watchdog/index.ts +13 -1
  88. package/src/lib/ai/AGENTS.md +2 -0
  89. package/src/lib/ai/llm-call.ts +30 -0
  90. package/src/lib/ai/model-resolver.ts +16 -19
  91. package/src/lib/ai/presend-budget.ts +117 -0
  92. package/src/lib/config/braid-settings.ts +125 -0
  93. package/src/lib/config/per-tool-settings.ts +4 -4
  94. package/src/lib/core/event-names.ts +1 -0
  95. package/src/lib/detection/context-tiers.ts +52 -41
  96. package/src/lib/detection/context-usage.ts +211 -2
  97. package/src/lib/errors/llm-error.ts +55 -1
  98. package/src/lib/state/global-state.ts +11 -29
  99. package/src/lib/telemetry/context-heartbeat.ts +27 -7
  100. package/src/lib/utils/AGENTS.md +1 -0
  101. package/src/lib/utils/argument-report.ts +105 -0
  102. package/src/lib/utils/wake-gate.ts +59 -4
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Path-miss steer — the tool failure that says what would have worked.
3
+ *
4
+ * A turn that guesses paths spends calls discovering a layout a listing would
5
+ * have named. The failure itself is the one moment the cheaper move is
6
+ * obvious, so it is where the line belongs: one steer per turn, the path that
7
+ * missed, and the three instruments that answer it (`ls`, `find`,
8
+ * `explore_paths`).
9
+ *
10
+ * Delivery is the standard whisper funnel (`sendTrackedMessage`), so this
11
+ * emitter inherits the envelope, the flood cap and the live-steer resolution
12
+ * every other whisper uses. The event is pi's existing `tool_result`, the only
13
+ * seat that carries both the failure text and the arguments the call made —
14
+ * the call's own `path` is more reliable than parsing the error wording.
15
+ *
16
+ * Budget: one line per turn, at most one line per path per session. A path
17
+ * already steered is not steered again, because a repeat tells the agent
18
+ * nothing it was not told, and the second occurrence usually means the agent
19
+ * chose to proceed rather than that it failed to read.
20
+ */
21
+
22
+ import { dirname } from "node:path";
23
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
24
+ import { createLogger } from "../../../lib/core/logger.js";
25
+ import { INPUT, TOOL_RESULT } from "../../../lib/core/event-names.js";
26
+ import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
27
+ import { detectPathMiss } from "./detect.js";
28
+
29
+ const log = createLogger("path-miss");
30
+
31
+ /**
32
+ * Sessions whose steered paths are remembered. A session id is stable for the
33
+ * life of a session and a long-lived process can host more than one, so the
34
+ * map is bounded rather than trusted to stay small.
35
+ */
36
+ const MAX_TRACKED_SESSIONS = 16;
37
+
38
+ /** Paths already steered, per session. */
39
+ const steeredPaths = new Map<string, Set<string>>();
40
+
41
+ /** Turn-scoped: the first path miss of a turn is the one worth a line. */
42
+ let steeredThisTurn = false;
43
+
44
+ function sessionKey(ctx: ExtensionContext | undefined): string {
45
+ const manager = ctx?.sessionManager as
46
+ | { getSessionId?: () => string; getSessionFile?: () => string | undefined }
47
+ | undefined;
48
+ return manager?.getSessionId?.() ?? manager?.getSessionFile?.() ?? "unknown";
49
+ }
50
+
51
+ function remember(session: string, path: string): void {
52
+ const paths = steeredPaths.get(session) ?? new Set<string>();
53
+ paths.add(path);
54
+ steeredPaths.set(session, paths);
55
+ if (steeredPaths.size > MAX_TRACKED_SESSIONS) {
56
+ // Insertion order: the oldest session is the first key.
57
+ const oldest = steeredPaths.keys().next().value;
58
+ if (oldest !== undefined && oldest !== session) steeredPaths.delete(oldest);
59
+ }
60
+ }
61
+
62
+ function alreadySteered(session: string, path: string): boolean {
63
+ return steeredPaths.get(session)?.has(path) ?? false;
64
+ }
65
+
66
+ /** The error text of a tool result, with any non-text parts ignored. */
67
+ function resultText(content: unknown): string {
68
+ if (typeof content === "string") return content;
69
+ if (!Array.isArray(content)) return "";
70
+ return content
71
+ .map((part) =>
72
+ part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"
73
+ ? (part as { text: string }).text
74
+ : "",
75
+ )
76
+ .join("\n");
77
+ }
78
+
79
+ /**
80
+ * One line: the path, and the cheaper moves next to it.
81
+ *
82
+ * The parent is named when the path has one, because `ls` needs an operand and
83
+ * a model that guessed a leaf usually had the parent wrong too — listing the
84
+ * parent is what tells it which of the two it got wrong.
85
+ */
86
+ export function pathMissLine(path: string): string {
87
+ const parent = dirname(path);
88
+ const listing = parent && parent !== "." && parent !== "/" ? `ls ${parent}` : "ls on its parent";
89
+ return `path miss: ${path} — ${listing} names the layout in one call; find and explore_paths when the parent is unknown too`;
90
+ }
91
+
92
+ /** Test hook: forget every steered path and the current turn's budget. */
93
+ export function _resetForTests(): void {
94
+ steeredPaths.clear();
95
+ steeredThisTurn = false;
96
+ }
97
+
98
+ export default function pathMissExtension(pi: ExtensionAPI): void {
99
+ // The same turn boundary the whisper family uses: a new user input opens a
100
+ // new turn, and a turn that has already been steered is done.
101
+ pi.on(INPUT, () => {
102
+ steeredThisTurn = false;
103
+ });
104
+
105
+ pi.on(TOOL_RESULT, (event, ctx) => {
106
+ if (steeredThisTurn) return;
107
+ if (!event?.isError) return;
108
+ const miss = detectPathMiss(event.toolName, event.input, resultText(event.content));
109
+ if (!miss) return;
110
+
111
+ const session = sessionKey(ctx);
112
+ if (alreadySteered(session, miss.path)) return;
113
+
114
+ steeredThisTurn = true;
115
+ const delivered = sendTrackedMessage(
116
+ pi,
117
+ {
118
+ customType: "path-miss",
119
+ content: [{ type: "text" as const, text: pathMissLine(miss.path) }],
120
+ display: true,
121
+ },
122
+ { delivery: "live" },
123
+ { type: "enforcement", source: "path-miss/steer" },
124
+ );
125
+ // A suppressed send must not spend the path's budget: the line did not
126
+ // arrive, so the next turn is still the first place the agent can read it.
127
+ if (!delivered) {
128
+ steeredThisTurn = false;
129
+ log.debug(`[path-miss] suppressed by the whisper funnel: ${miss.path}`);
130
+ return;
131
+ }
132
+ remember(session, miss.path);
133
+ log.debug(`[path-miss] steered ${miss.path} (${miss.tool})`);
134
+ });
135
+ }
@@ -1,28 +1,46 @@
1
1
  <!-- status: current -->
2
2
 
3
- # src/extensions/watchdog/ - Session Health Monitor
3
+ # src/extensions/watchdog/ - Session Health Monitor and Escalation Engine
4
4
 
5
- A **background monitor** that tracks session metrics (uptime, idle time, message
6
- count) and surfaces them via a TUI command. No LLM-callable tools.
7
-
8
- ## Disambiguation: this is NOT the only "watchdog" in the codebase
9
-
10
- This is the only thing called "watchdog" now. Previously there was an
11
- `auto-singleton/` watchdog (an agent-callable inactivity timer), but that
12
- was removed in the 2026-06 tool-inventory audit. The `timer` tool covers the
13
- use case it addressed.
14
-
15
- The Session watchdog is purely a **passive observer** (it doesn't act).
5
+ A **background monitor** with two layers: a passive per-session observer
6
+ (uptime, idle time, message count, surfaced via the `watchdog-status` TUI
7
+ command) and an active engine that detects stall/quota/tunnel/dead-wake
8
+ conditions with no model call and escalates them.
16
9
 
17
10
  ## Files
18
11
 
19
- | File | Purpose |
20
- | ---------- | --------------------------------------------------------------------------------------------------------------------------- |
21
- | `index.ts` | The only file. ~102L. Tracks per-session state in a Map keyed by session file path. Subscribes to `analytics_alert` events. |
12
+ | File | Purpose |
13
+ | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
14
+ | `index.ts` | Extension surface: per-session state, whisper/tg delivery, engine wiring, turn-progress feeds, session shutdown. |
15
+ | `engine.ts` | The state machine: condition latches, milestone ladders, escalation budget, stall classification, wake-delivery feed. |
16
+ | `config.ts` | `broker.watchdog` reader (mode, cadences, thresholds). Defaults live in `engine.ts`; invalid fields fall back to them. |
22
17
 
23
18
  ## Local Contracts
24
19
 
25
- - Module is opt-in (`disabledByDefault: true`).
26
- - Module id: `watchdog` (kebab-case).
27
- - Not LLM-callable. The agent cannot trigger it - only the user can, via the `watchdog-status` command.
20
+ - Default-ON (`manifest.ts` declares no `disabledByDefault`), module id `watchdog`, dependency `agent-environment`.
21
+ - Not LLM-callable: the agent cannot trigger it.
28
22
  - `broker.watchdog` is read when the extension factory loads. Restart the agent after changing it.
23
+
24
+ ## Escalation delivery
25
+
26
+ `fireEscalation` is the one escalation action: a whisper plus an optional
27
+ one-line tg signal. The whisper's delivery class follows the session's
28
+ route-failure latch (`isRouteLatchOpen` from the enforcement health module,
29
+ read once per bark, fail-open):
30
+
31
+ - latch closed: `wakeWhisper` (`triggerTurn: true`) - the bark wakes the agent;
32
+ - latch open: `quietWhisper` - the same text reaches the session on the next
33
+ turn, and the tg line still fires, because the page costs no provider call
34
+ and the turn the bark would have started is the call the latch exists to
35
+ save.
36
+
37
+ The route-failure latch and its settings are documented in
38
+ `extensions/enforcement/AGENTS.md`; fixture:
39
+ `test/runtime/lib/test-route-latch.mjs`.
40
+
41
+ ## Fixtures
42
+
43
+ - `test/runtime/self/test-watchdog-engine.mjs` - condition latches, ladders, budget.
44
+ - `test/runtime/self/test-watchdog-stall-ladder.mjs` - stall classification and remediation.
45
+ - `test/runtime/self/test-watchdog-wake-delivery.mjs` - the timer-to-watchdog dead-wake feed.
46
+ - `test/runtime/self/test-watchdog-unknown-failure-ring.mjs` - unclassified-failure retention.
@@ -20,7 +20,8 @@
20
20
  * 3. tunnel-down: ≥ tunnelFailures consecutive getUpdates failures
21
21
  * (telegram emits the transition; this engine hosts the
22
22
  * confirmation gate + escalation).
23
- * - ESCALATE: waking whisper (wakeWhisper) + optional 1-line tg signal
23
+ * - ESCALATE: waking whisper (wakeWhisper) + optional 1-line tg signal,
24
+ * or the quiet whisper when the session's route latch is open
24
25
  * (tgSignal). The FIRST escalation of an open condition always fires
25
26
  * (threshold crossing). Repeats while the condition stays continuously
26
27
  * open are milestone-throttled so one long outage cannot flood the owner
@@ -228,6 +229,12 @@ export interface WatchdogEngineDeps {
228
229
  /** True when a timer/wake is due for this session: a due wake legitimately
229
230
  * keeps a quiet session quiet, so the turn is not classified dead. */
230
231
  isWakeDue?: (key: string) => boolean;
232
+ /** True when a self-started turn would park right now (the session's route
233
+ * has failed every attempt since its last successful call). An escalation
234
+ * is then delivered through `quietWhisper` while the out-of-band signal
235
+ * still fires — the content is not withdrawn, only the turn it would
236
+ * start. Absent or throwing ⇒ never parked (fail-open). */
237
+ isTurnStartBlocked?: () => boolean;
231
238
  log?: (level: "debug" | "info" | "warn" | "error", message: string, ...rest: unknown[]) => void;
232
239
  }
233
240
 
@@ -484,8 +491,29 @@ export function createWatchdogEngine(
484
491
  return openConditions().length > 0;
485
492
  }
486
493
 
494
+ /**
495
+ * Fail-open read of the turn-start latch. A broken reader costs the gate,
496
+ * never the escalation: the bark still fires, it just wakes.
497
+ */
498
+ function turnStartBlocked(): boolean {
499
+ try {
500
+ return deps.isTurnStartBlocked?.() === true;
501
+ } catch {
502
+ return false;
503
+ }
504
+ }
505
+
487
506
  function fireEscalation(text: string, tg: string): void {
488
- wakeWhisper(text);
507
+ // While the route latch is open a waking bark would spend the very call
508
+ // the gate exists to save. The escalation is not dropped: the same text
509
+ // rides the quiet channel into the session, and the tg line — which costs
510
+ // no provider call — still fires, so the owner keeps the out-of-band
511
+ // signal.
512
+ if (turnStartBlocked()) {
513
+ quietWhisper(text);
514
+ } else {
515
+ wakeWhisper(text);
516
+ }
489
517
  try {
490
518
  tgSignal?.(tg);
491
519
  } catch {
@@ -56,7 +56,7 @@ import {
56
56
  import { loadWatchdogConfig } from "./config.js";
57
57
  import { createWatchdogEngine, type WatchdogEngine } from "./engine.js";
58
58
  import { appendContextHeartbeatLine } from "../../../lib/telemetry/context-heartbeat.js";
59
- import { getSessionHealth } from "../../enforcement/session-health.js";
59
+ import { getSessionHealth, isRouteLatchOpen } from "../../enforcement/session-health.js";
60
60
 
61
61
  const log = createLogger("watchdog");
62
62
 
@@ -310,6 +310,18 @@ export default function (pi: ExtensionAPI) {
310
310
  return false;
311
311
  }
312
312
  },
313
+ // Route-failure latch: the engine asks the health layer, once per
314
+ // escalation, whether a self-started turn would park. While it is
315
+ // open the bark rides the quiet channel and the tg line below still
316
+ // fires (see fireEscalation). Read-only, fail-open: a broken reader
317
+ // must never silence an escalation.
318
+ isTurnStartBlocked: () => {
319
+ try {
320
+ return isRouteLatchOpen(ctx);
321
+ } catch {
322
+ return false;
323
+ }
324
+ },
313
325
  log: (level, message, ...rest) => {
314
326
  switch (level) {
315
327
  case "debug":
@@ -20,11 +20,13 @@ and result parsing.
20
20
  | `llm-call.ts` | Auxiliary LLM calls: dispatched through the session's `ctx.modelRegistry.streamSimple` (pi-core resolves credential, headers, transport), with two-tier retry, backoff, rate-limit circuit breaker, and abort handling. |
21
21
  | `judge-budget.ts` | The consolidated judges' output-budget contract in one place: one judge completion across the model tiers (session → utility) with no `maxTokens` on the first attempt (callLlm sizes it from the prompt), plus exactly one retry at `min(8192, model.maxTokens)` when a completion ends at its own output ceiling without a verdict. Also owns the shared outcome vocabulary (`budget-exhausted` / `unparseable` / `invalid-fields` / `call-error`). Each judge supplies its own reader for the response. |
22
22
  | `payload-hygiene.ts` | Raw-payload hygiene at the LLM-call boundary: error text collapses to one line for logs/returns (status + excerpt + type + size, base64 redacted); request-body hygiene for edge/WAF page dumps plus in-place neutralization of the edge filter's request trigger (a space inserted, text kept). |
23
+ | `presend-budget.ts` | Pre-send budget: the calibrated payload estimate plus the requested output budget against the resolved window, the single actionable refusal line, and the guard that measures, compacts once, re-measures and only then allows the send. Lives here because only the layer that builds a request has all three numbers. |
23
24
  | `model-resolver.ts` | Resolves the merged role (utilityModel) and the deprecated vision alias to catalog models; each accepts a scalar or an ordered list. |
24
25
 
25
26
  ## Local Contracts
26
27
 
27
28
  - All LLM calls should go through `llm-call.ts` for consistent abort/retry behavior.
29
+ - **A request is compared against the window before it is sent.** `presend-budget.ts` owns that comparison (calibrated payload + output budget vs the resolved window); a send path that skips it hands the provider a request that cannot fit and pays a round trip to learn so.
28
30
  - **A consolidated judge (one prompt asking for a JSON verdict) goes through `judge-budget.ts`** - never a hand-rolled `callLlm` with a small explicit `maxTokens`. Thinking tokens count against `max_tokens` on reasoning models and the channel cannot always be switched off, so a small ceiling starves the answer; `judge-budget.ts` owns the budget, the bounded retry, and the tier walk.
29
31
  - All classifications should go through `text-classifier.ts` - it handles the utility-model-first gate via `critic-gate.ts`.
30
32
  - **All post-loop LLM calls (agent_end, post-turn analysis, reflection, etc.) should go through `post-loop-classify.ts`** - it bundles the 4 post-loop guarantees (signal thread, abort demotion, 8s default timeout, onFailure fallback) that hand-rolled callers have repeatedly gotten wrong. See `src/extensions/heartbeat/AGENTS.md` for the abort-handling contract.
@@ -54,6 +54,12 @@ import { createLogger } from "../core/logger.js";
54
54
  import { isRateLimitText } from "../errors/llm-error.js";
55
55
  import { isContextWindowErrorText } from "../errors/llm-error.js";
56
56
  import { sanitizeLlmErrorForLog, sanitizeLlmRequestText } from "./payload-hygiene.js";
57
+ import {
58
+ calibrateEstimate,
59
+ estimatePayloadTokens,
60
+ resolveWindow,
61
+ } from "../detection/context-usage.js";
62
+ import { guardAgainstDoomedSend } from "./presend-budget.js";
57
63
  import {
58
64
  getContextEmergencyOffloadRunner,
59
65
  getExtensionCtxProvider,
@@ -421,6 +427,30 @@ export async function callLlm(
421
427
  messages: [{ role: "user", content: userSafe.text, timestamp: Date.now() }],
422
428
  };
423
429
 
430
+ // ── pre-send budget ──
431
+ // A request over the window cannot succeed, and a provider 400 is a late,
432
+ // expensive way to learn it. Measure the payload the provider would receive
433
+ // (system + messages, calibrated against this session's own measured ratio),
434
+ // add the output budget, and compare against the resolved window - a
435
+ // configured cap binding below the model's window counts, because the
436
+ // provider will refuse what the cap already refused.
437
+ const resolvedWindow = resolveWindow((model as { contextWindow?: number }).contextWindow);
438
+ const budget = await guardAgainstDoomedSend({
439
+ measure: () =>
440
+ calibrateEstimate(
441
+ estimatePayloadTokens({ systemPrompt: context.systemPrompt, messages: context.messages }),
442
+ ).tokens,
443
+ outputTokens: maxTokens,
444
+ contextWindow: resolvedWindow.contextWindow,
445
+ // The only compaction available to an auxiliary call is the published
446
+ // offload: it shrinks the session's largest toolResults, which is where an
447
+ // oversized prompt came from. One attempt; nothing freed means still over.
448
+ compact: async () => (await runEmergencyOffloadForCall()) > 0,
449
+ onRefusal: (line) => log.error(line),
450
+ subject: "LLM call",
451
+ });
452
+ if (!budget.allowed) return { error: budget.line };
453
+
424
454
  // ── per-model concurrency limiter: acquire ONCE at function entry, release in finally ──
425
455
  // (One slot per callLlm invocation, not per retry - otherwise retries could
426
456
  // pile up beyond MAX_CONCURRENT_PER_MODEL.)
@@ -1,14 +1,14 @@
1
1
  /**
2
2
  * Model resolution helpers for pi-braid extensions.
3
3
  *
4
- * Resolves the merged auxiliary role (utilityModel) and the deprecated vision
5
- * alias: a setting may hold one model pattern or an ordered list, and the
4
+ * Resolves the merged auxiliary role (utilityModel) and the model a vision call
5
+ * needs: a setting may hold one model pattern or an ordered list, and the
6
6
  * resolver walks the list with the provider layer deciding per entry.
7
7
  */
8
8
 
9
9
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
10
  import type { Model, Api } from "@earendil-works/pi-ai";
11
- import { getCustomModelKey, UTILITY_MODEL_KEY, VISION_MODEL_KEY } from "../state/global-state.js";
11
+ import { getCustomModelKey, UTILITY_MODEL_KEY } from "../state/global-state.js";
12
12
  import { callLlm, isModelRouteUsable } from "./llm-call.js";
13
13
  import type { LlmCallOptions } from "./llm-call.js";
14
14
 
@@ -95,30 +95,27 @@ export function resolveUtilityModels(ctx: ExtensionContext): Model<Api>[] {
95
95
  }
96
96
 
97
97
  /**
98
- * Get the best vision model.
98
+ * The model a vision call should use.
99
+ *
99
100
  * Priority:
100
- * 1. Custom visionModel setting (deprecated alias, honored this release);
101
- * when it is an ordered list, the first entry that accepts image input
102
- * and whose route the provider layer reports usable
103
- * 2. Current model if vision-capable
104
- * 3. The merged role's first image-capable entry whose route the provider
105
- * layer reports usable (same ordered-list semantics as any role)
106
- * 4. First available vision model
101
+ * 1. The current model when it accepts images: the image stays in the call
102
+ * that already carries the prompt and the conversation
103
+ * 2. The merged role's first image-capable entry whose route the provider
104
+ * layer reports usable (the same ordered-list semantics as any role)
105
+ * 3. The first available model that accepts images
106
+ *
107
+ * A text-only entry is never selected for an image call.
107
108
  */
108
109
  export function resolveVisionModel(ctx: ExtensionContext): Model<Api> | undefined {
109
- // 1. Deprecated role key; still priority 1 for one release
110
- const custom = resolveRoleModel(ctx, VISION_MODEL_KEY, true);
111
- if (custom) return custom;
112
-
113
- // 2. Current model if vision-capable
110
+ // 1. Current model if vision-capable
114
111
  if (ctx.model?.input?.includes("image")) return ctx.model;
115
112
 
116
- // 3. The merged role supplies an image-capable entry, so the vision pin is
117
- // redundant after this release except as a determinism override.
113
+ // 2. The merged role supplies an image-capable entry; a text-only entry in
114
+ // the list is skipped rather than sent an image.
118
115
  const role = resolveRoleModel(ctx, UTILITY_MODEL_KEY, true);
119
116
  if (role) return role;
120
117
 
121
- // 4. First available vision model
118
+ // 3. First available vision model
122
119
  const available = ctx.modelRegistry.getAvailable();
123
120
  return available.find((m) => m?.input?.includes("image"));
124
121
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Pre-send budget: compare the request about to be sent against the model's
3
+ * resolved window, and refuse instead of letting the provider refuse.
4
+ *
5
+ * Why here: this is a request-layer decision. It needs three things at once -
6
+ * the outgoing payload, the requested output budget, and the resolved window -
7
+ * and only the layer that BUILDS the request has all three. A consumer that
8
+ * reads a percentage sees a number someone else measured; it cannot see what
9
+ * the provider is about to be handed.
10
+ *
11
+ * Why a guard and not a warning: a request over the window cannot succeed, so
12
+ * sending it buys nothing and costs a full round trip, a retry, and a session
13
+ * that looks wedged to whoever is watching. The remedy that actually frees
14
+ * space is compaction, and the caller owns it - so the guard runs it once and
15
+ * re-measures, and only then decides.
16
+ */
17
+
18
+ import { formatTokensK } from "../detection/context-usage.js";
19
+
20
+ export interface SendBudgetInput {
21
+ /** Calibrated tokens of the payload as it stands now. */
22
+ payloadTokens: number;
23
+ /** The output budget the request asks for; it is spent from the same window. */
24
+ outputTokens: number;
25
+ /** Resolved window (a configured cap may already bind below the model's). */
26
+ contextWindow: number;
27
+ }
28
+
29
+ export interface SendBudgetVerdict {
30
+ fits: boolean;
31
+ /** payloadTokens + outputTokens. */
32
+ projectedTokens: number;
33
+ contextWindow: number;
34
+ /** Tokens past the window; 0 when the request fits. */
35
+ overBy: number;
36
+ }
37
+
38
+ export function checkSendBudget(input: SendBudgetInput): SendBudgetVerdict {
39
+ const projectedTokens = input.payloadTokens + Math.max(0, input.outputTokens);
40
+ const contextWindow = input.contextWindow;
41
+ const overBy = contextWindow > 0 ? Math.max(0, projectedTokens - contextWindow) : 0;
42
+ return {
43
+ fits: contextWindow > 0 && overBy === 0,
44
+ projectedTokens,
45
+ contextWindow,
46
+ overBy,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The one line a refusal is allowed to say. It carries the three numbers a
52
+ * reader needs to act (payload, output budget, window) and names the remedy,
53
+ * because "context overflow" alone leaves nothing to do.
54
+ */
55
+ export function formatSendBudgetRefusal(verdict: SendBudgetVerdict, subject = "request"): string {
56
+ const window =
57
+ verdict.contextWindow > 0 ? formatTokensK(verdict.contextWindow) : "unknown window";
58
+ return (
59
+ `Context budget refused: ${subject} needs ${formatTokensK(verdict.projectedTokens)} ` +
60
+ `(payload + output budget) against a ${window} window, over by ${formatTokensK(verdict.overBy)}. ` +
61
+ `Nothing was sent. Compact first (\`context_compress action="archive"\`), or lower the output ` +
62
+ `budget, then retry.`
63
+ );
64
+ }
65
+
66
+ export type GuardedSend =
67
+ | { allowed: true; verdict: SendBudgetVerdict; compacted: boolean }
68
+ | { allowed: false; verdict: SendBudgetVerdict; line: string; compacted: boolean };
69
+
70
+ /**
71
+ * Decide whether the send may proceed: measure, compare, and when the request
72
+ * cannot fit, run the caller's compaction ONCE and measure again.
73
+ *
74
+ * `compact` returns true only when it actually freed context. A compaction
75
+ * that frees nothing must not re-open the door - the second measurement is the
76
+ * one that decides, and it is taken after the compaction, not assumed from it.
77
+ * `measure` is called fresh each time for the same reason: the payload after a
78
+ * compaction is a different payload.
79
+ */
80
+ export async function guardAgainstDoomedSend(params: {
81
+ measure: () => number;
82
+ outputTokens: number;
83
+ contextWindow: number;
84
+ compact?: () => Promise<boolean> | boolean;
85
+ onRefusal?: (line: string, verdict: SendBudgetVerdict) => void;
86
+ subject?: string;
87
+ }): Promise<GuardedSend> {
88
+ const window = params.contextWindow;
89
+ let verdict = checkSendBudget({
90
+ payloadTokens: params.measure(),
91
+ outputTokens: params.outputTokens,
92
+ contextWindow: window,
93
+ });
94
+ if (verdict.fits) return { allowed: true, verdict, compacted: false };
95
+
96
+ let compacted = false;
97
+ if (params.compact) {
98
+ try {
99
+ compacted = (await params.compact()) === true;
100
+ } catch {
101
+ // A failed compaction leaves the request where it was: still over.
102
+ compacted = false;
103
+ }
104
+ }
105
+ if (compacted) {
106
+ verdict = checkSendBudget({
107
+ payloadTokens: params.measure(),
108
+ outputTokens: params.outputTokens,
109
+ contextWindow: window,
110
+ });
111
+ if (verdict.fits) return { allowed: true, verdict, compacted: true };
112
+ }
113
+
114
+ const line = formatSendBudgetRefusal(verdict, params.subject);
115
+ params.onRefusal?.(line, verdict);
116
+ return { allowed: false, verdict, line, compacted };
117
+ }
@@ -159,6 +159,27 @@ interface BraidConfig {
159
159
  /** Terminal errors before the gate closes. Default 3. */
160
160
  threshold?: number;
161
161
  };
162
+ /**
163
+ * Route-failure wake breaker: while a session has accumulated
164
+ * `threshold` provider failures of any class except a context-window
165
+ * overflow or an abort since its last successful call, timer wakes,
166
+ * watchdog escalations and explicitly-waking whispers are delivered
167
+ * without starting a turn. `floorMs` is the one self-started turn the
168
+ * latch releases after that long with no successful release signal, so a
169
+ * parked session is never permanently starved of turns. Default
170
+ * { enabled: true, threshold: 3, floorMs: 3600000 }.
171
+ *
172
+ * Example:
173
+ * "braid": { "session": { "routeBreaker": { "enabled": false } } }
174
+ */
175
+ routeBreaker?: {
176
+ /** false makes the whole breaker inert (byte-identical to pre-breaker behavior). */
177
+ enabled?: boolean;
178
+ /** Provider failures since the last successful call before wakes park. Default 3. */
179
+ threshold?: number;
180
+ /** The one released turn's cadence while the latch stays open. Default 3600000 (1h). */
181
+ floorMs?: number;
182
+ };
162
183
  };
163
184
  timers?: {
164
185
  /**
@@ -1117,6 +1138,110 @@ export function getTerminalBreakerConfig(): TerminalBreakerConfig {
1117
1138
  return resolveTerminalBreaker(readSettings().braid?.session?.terminalBreaker);
1118
1139
  }
1119
1140
 
1141
+ // ── route-failure wake breaker (braid.session.routeBreaker) ────────────
1142
+
1143
+ /** Default provider-failure count before self-started turns park. */
1144
+ export const ROUTE_BREAKER_DEFAULT_THRESHOLD = 3;
1145
+ /** Upper bound for a configured threshold (guards a typo'd huge value). */
1146
+ export const ROUTE_BREAKER_THRESHOLD_MAX = 20;
1147
+ /**
1148
+ * Default cadence of the single released turn while the latch stays open.
1149
+ * One hour: long enough that a parked session does not spend a call per
1150
+ * retry against a route that is failing every time, short enough that an
1151
+ * owner who never touches the session still gets an automatic attempt.
1152
+ */
1153
+ export const ROUTE_BREAKER_DEFAULT_FLOOR_MS = 3_600_000;
1154
+ /** Bounds on a configured floor: below the slowest retry cadence it would
1155
+ * release a turn per retry; above a day it stops being a floor at all. */
1156
+ export const ROUTE_BREAKER_FLOOR_MIN_MS = 60_000;
1157
+ export const ROUTE_BREAKER_FLOOR_MAX_MS = 86_400_000;
1158
+
1159
+ export interface RouteBreakerConfig {
1160
+ /** Master gate. Default true. */
1161
+ enabled: boolean;
1162
+ /** Provider failures since the last successful call before wakes park. */
1163
+ threshold: number;
1164
+ /** The one released turn's cadence while the latch stays open. */
1165
+ floorMs: number;
1166
+ }
1167
+
1168
+ /** Warned once per process about an invalid routeBreaker field. */
1169
+ let _warnedInvalidRouteBreaker = false;
1170
+
1171
+ /** Once-per-process warning for an ignored routeBreaker value. */
1172
+ function _warnInvalidRouteBreaker(field: "threshold" | "floorMs", value: unknown): void {
1173
+ if (_warnedInvalidRouteBreaker) return;
1174
+ _warnedInvalidRouteBreaker = true;
1175
+ const expected =
1176
+ field === "threshold"
1177
+ ? `an integer 1..${ROUTE_BREAKER_THRESHOLD_MAX}`
1178
+ : `an integer ${ROUTE_BREAKER_FLOOR_MIN_MS}..${ROUTE_BREAKER_FLOOR_MAX_MS} (ms)`;
1179
+ const fallback =
1180
+ field === "threshold" ? ROUTE_BREAKER_DEFAULT_THRESHOLD : ROUTE_BREAKER_DEFAULT_FLOOR_MS;
1181
+ _log.warn(
1182
+ `Invalid braid.session.routeBreaker in settings.json - ignoring ${field} and ` +
1183
+ `using the default (${fallback}). Expected ${expected}.`,
1184
+ { field, value },
1185
+ );
1186
+ }
1187
+
1188
+ /**
1189
+ * Pure resolver for braid.session.routeBreaker. Absent block ⇒ default-on with
1190
+ * threshold 3 and a 1h floor. `enabled: false` ⇒ the breaker is inert. A
1191
+ * threshold or floor that is not a valid integer in range warns once and
1192
+ * falls back to its default; a non-object block counts as absent. Kept pure
1193
+ * so the validation is unit-testable without touching live settings.json.
1194
+ */
1195
+ export function resolveRouteBreaker(raw: unknown): RouteBreakerConfig {
1196
+ const defaults: RouteBreakerConfig = {
1197
+ enabled: true,
1198
+ threshold: ROUTE_BREAKER_DEFAULT_THRESHOLD,
1199
+ floorMs: ROUTE_BREAKER_DEFAULT_FLOOR_MS,
1200
+ };
1201
+ if (raw === undefined || raw === null || typeof raw !== "object") return defaults;
1202
+ const block = raw as { enabled?: unknown; threshold?: unknown; floorMs?: unknown };
1203
+ const enabled = block.enabled !== false;
1204
+ let threshold = defaults.threshold;
1205
+ if (block.threshold !== undefined) {
1206
+ const v = block.threshold;
1207
+ if (
1208
+ typeof v === "number" &&
1209
+ Number.isInteger(v) &&
1210
+ v >= 1 &&
1211
+ v <= ROUTE_BREAKER_THRESHOLD_MAX
1212
+ ) {
1213
+ threshold = v;
1214
+ } else {
1215
+ _warnInvalidRouteBreaker("threshold", v);
1216
+ }
1217
+ }
1218
+ let floorMs = defaults.floorMs;
1219
+ if (block.floorMs !== undefined) {
1220
+ const v = block.floorMs;
1221
+ if (
1222
+ typeof v === "number" &&
1223
+ Number.isInteger(v) &&
1224
+ v >= ROUTE_BREAKER_FLOOR_MIN_MS &&
1225
+ v <= ROUTE_BREAKER_FLOOR_MAX_MS
1226
+ ) {
1227
+ floorMs = v;
1228
+ } else {
1229
+ _warnInvalidRouteBreaker("floorMs", v);
1230
+ }
1231
+ }
1232
+ return { enabled, threshold, floorMs };
1233
+ }
1234
+
1235
+ /**
1236
+ * Read the effective route-failure wake-breaker config from settings.json,
1237
+ * fresh on every call (no caching), like the other readers. The predicate and
1238
+ * the feed read this once per call; the floor's clock leans on it, so a
1239
+ * runtime change takes effect on the next turn-start question.
1240
+ */
1241
+ export function getRouteBreakerConfig(): RouteBreakerConfig {
1242
+ return resolveRouteBreaker(readSettings().braid?.session?.routeBreaker);
1243
+ }
1244
+
1120
1245
  // ── wake-delivery stall alert (braid.timers.wakeAlert) ───────────────
1121
1246
 
1122
1247
  /** Default wake-delivery alerting: on, page after 2 outcome timeouts. */