pi-braid 0.42.1 → 0.43.1

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 (81) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +61 -228
  3. package/TOOLS.md +12 -14
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/polyfill/index.d.ts +3 -4
  6. package/dist/extensions/core/polyfill/index.js +34 -131
  7. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
  8. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
  9. package/dist/extensions/enforcement/session-health.d.ts +52 -4
  10. package/dist/extensions/enforcement/session-health.js +75 -5
  11. package/dist/extensions/enforcement/whisper.js +15 -1
  12. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
  13. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
  14. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
  15. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
  16. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
  17. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
  18. package/dist/extensions/memory/context-lifecycle/index.js +11 -10
  19. package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
  20. package/dist/extensions/memory/context-manager/analysis.js +6 -2
  21. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
  22. package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
  23. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
  24. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
  25. package/dist/extensions/self/watchdog/engine.d.ts +8 -1
  26. package/dist/extensions/self/watchdog/engine.js +25 -2
  27. package/dist/extensions/self/watchdog/index.js +14 -1
  28. package/dist/lib/ai/llm-call.js +23 -0
  29. package/dist/lib/ai/model-resolver.d.ts +11 -10
  30. package/dist/lib/ai/model-resolver.js +16 -19
  31. package/dist/lib/ai/presend-budget.d.ts +68 -0
  32. package/dist/lib/ai/presend-budget.js +83 -0
  33. package/dist/lib/config/braid-settings.d.ts +38 -0
  34. package/dist/lib/config/braid-settings.js +84 -0
  35. package/dist/lib/config/per-tool-settings.d.ts +4 -4
  36. package/dist/lib/config/per-tool-settings.js +4 -4
  37. package/dist/lib/detection/context-tiers.d.ts +18 -5
  38. package/dist/lib/detection/context-tiers.js +51 -33
  39. package/dist/lib/detection/context-usage.d.ts +62 -1
  40. package/dist/lib/detection/context-usage.js +158 -1
  41. package/dist/lib/errors/llm-error.d.ts +14 -0
  42. package/dist/lib/errors/llm-error.js +44 -1
  43. package/dist/lib/state/global-state.d.ts +4 -8
  44. package/dist/lib/state/global-state.js +11 -28
  45. package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
  46. package/dist/lib/telemetry/context-heartbeat.js +18 -8
  47. package/dist/lib/utils/wake-gate.d.ts +6 -0
  48. package/dist/lib/utils/wake-gate.js +52 -4
  49. package/docs/SETUP.md +7 -6
  50. package/package.json +8 -11
  51. package/src/extensions/core/polyfill/index.ts +29 -157
  52. package/src/extensions/enforcement/AGENTS.md +38 -1
  53. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
  54. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
  55. package/src/extensions/enforcement/session-health.ts +94 -5
  56. package/src/extensions/enforcement/whisper.ts +15 -1
  57. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
  58. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
  59. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
  60. package/src/extensions/memory/AGENTS.md +37 -38
  61. package/src/extensions/memory/context-lifecycle/index.ts +11 -10
  62. package/src/extensions/memory/context-manager/analysis.ts +8 -1
  63. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
  64. package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
  65. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
  66. package/src/extensions/scheduling/timer/AGENTS.md +14 -4
  67. package/src/extensions/self/watchdog/AGENTS.md +36 -18
  68. package/src/extensions/self/watchdog/engine.ts +30 -2
  69. package/src/extensions/self/watchdog/index.ts +13 -1
  70. package/src/lib/ai/AGENTS.md +2 -0
  71. package/src/lib/ai/llm-call.ts +30 -0
  72. package/src/lib/ai/model-resolver.ts +16 -19
  73. package/src/lib/ai/presend-budget.ts +117 -0
  74. package/src/lib/config/braid-settings.ts +125 -0
  75. package/src/lib/config/per-tool-settings.ts +4 -4
  76. package/src/lib/detection/context-tiers.ts +52 -41
  77. package/src/lib/detection/context-usage.ts +211 -2
  78. package/src/lib/errors/llm-error.ts +55 -1
  79. package/src/lib/state/global-state.ts +11 -29
  80. package/src/lib/telemetry/context-heartbeat.ts +27 -7
  81. package/src/lib/utils/wake-gate.ts +59 -4
@@ -3,10 +3,9 @@
3
3
  *
4
4
  * Three concerns:
5
5
  * 1. Model selection: /utility-model (the merged role) opens the
6
- * ModelSelectorComponent UI; /max-power-model is a deprecated alias of it
7
- * and /vision-model is a deprecated alias kept for one release. Model
8
- * resolution is handled by src/lib/ai/model-resolver.ts (used by
9
- * vision/metacognition tools directly).
6
+ * ModelSelectorComponent UI. Model resolution is handled by
7
+ * src/lib/ai/model-resolver.ts (used by vision/metacognition tools
8
+ * directly).
10
9
  * 2. Session manager patches: context_navigate and context_compress tools
11
10
  * need SessionManager methods in --no-session mode.
12
11
  * 3. Context window plumb: the session model reports braid's configured
@@ -24,7 +23,7 @@
24
23
  * naming the value to set.
25
24
  */
26
25
  import { ModelSelectorComponent, SettingsManager } from "@earendil-works/pi-coding-agent";
27
- import { resolveUtilityModel, resolveVisionModel, normaliseRoleSetting, } from "../../../lib/ai/model-resolver.js";
26
+ import { resolveUtilityModel, normaliseRoleSetting } from "../../../lib/ai/model-resolver.js";
28
27
  import { applyCompactionReserveTokens, applyConfiguredContextWindow, } from "../../../lib/config/braid-settings.js";
29
28
  import { onEvent } from "../../../lib/events/event-types.js";
30
29
  import { SESSION_START, SESSION_SHUTDOWN } from "../../../lib/core/event-names.js";
@@ -33,12 +32,7 @@ import { readSettingsFile, updateSettings } from "../../../lib/config/per-tool-s
33
32
  import { createLogger } from "../../../lib/core/logger.js";
34
33
  const log = createLogger("polyfill");
35
34
  /** Custom settings keys managed by the model commands */
36
- import { getCustomModelKey, getCustomModelKeys, consumeMaxPowerDeprecationNotice, UTILITY_MODEL_KEY, VISION_MODEL_KEY, MAX_POWER_MODEL_KEY, } from "../../../lib/state/global-state.js";
37
- // Type guard for checking if a model has image input capability
38
- function hasImageInput(model) {
39
- const input = model.input;
40
- return Array.isArray(input) && input.includes("image");
41
- }
35
+ import { getCustomModelKey, getCustomModelKeys, UTILITY_MODEL_KEY, } from "../../../lib/state/global-state.js";
42
36
  /** Shared sessionManager reference - used by patchSessionManagerMethods */
43
37
  import { getExtensionState } from "../../../lib/state/extension-state.js";
44
38
  function getPolyfillState(ctx) {
@@ -91,18 +85,13 @@ async function setRoleSettingFromArgs(ctx, key, roleLabel, note, argsText) {
91
85
  "(tried in order; the first entry the provider layer reports usable wins)", "info");
92
86
  }
93
87
  /**
94
- * The /utility-model command body. The deprecated /max-power-model alias
95
- * drives the same function: the roles merged, so both commands write the one
96
- * canonical key and differ only in the deprecation notice.
88
+ * The /utility-model command body. The role it configures is also the one
89
+ * vision analysis falls back to, so there is no separate vision command.
97
90
  */
98
- async function runUtilityModelCommand(args, ctx, viaDeprecatedAlias) {
99
- if (viaDeprecatedAlias) {
100
- ctx.ui.notify("/max-power-model is deprecated: the max-power role merged into the utility role. " +
101
- "Use /utility-model; the alias is removed next release.", "warning");
102
- }
91
+ async function runUtilityModelCommand(args, ctx) {
103
92
  if (!args || args.trim() === "") {
104
93
  if (ctx.hasUI) {
105
- await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", null, resolveUtilityModel);
94
+ await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", resolveUtilityModel);
106
95
  }
107
96
  else {
108
97
  const model = resolveUtilityModel(ctx);
@@ -134,9 +123,6 @@ function persistCustomKeys() {
134
123
  for (const [key, value] of map) {
135
124
  settings[key] = value;
136
125
  }
137
- // Any role write retires the legacy key in the same transaction: a
138
- // stale alias left on disk is resurrected by the next load.
139
- delete settings[MAX_POWER_MODEL_KEY];
140
126
  });
141
127
  }
142
128
  catch {
@@ -144,37 +130,17 @@ function persistCustomKeys() {
144
130
  }
145
131
  }
146
132
  /**
147
- * Load custom keys from pi's settings.json into the in-memory map.
148
- * A role key carries either one pattern or an ordered list; both land in the
149
- * map in the list form the resolver walks. A value with no usable pattern is
133
+ * Load the utility role from pi's settings.json into the in-memory map.
134
+ * The key carries either one pattern or an ordered list; both land in the map
135
+ * in the list form the resolver walks. A value with no usable pattern is
150
136
  * treated as unset rather than stored as something that resolves to nothing.
151
137
  */
152
138
  function loadCustomKeysFromDisk() {
153
139
  try {
154
140
  const settings = readSettingsFile();
155
- const map = getCustomModelKeys();
156
- for (const key of [VISION_MODEL_KEY, UTILITY_MODEL_KEY]) {
157
- const value = toRoleSettingValue(normaliseRoleSetting(settings[key]));
158
- if (value !== undefined)
159
- map.set(key, value);
160
- }
161
- // Deprecated alias: a legacy maxPowerModel value loads under the canonical
162
- // key when that key carries no usable value on disk (canonical wins when
163
- // both are present). The legacy key is never stored under its own name;
164
- // one process-global notice tells the user to move the value before the
165
- // alias is removed.
166
- const canonical = toRoleSettingValue(normaliseRoleSetting(settings[UTILITY_MODEL_KEY]));
167
- if (canonical === undefined) {
168
- const legacy = toRoleSettingValue(normaliseRoleSetting(settings[MAX_POWER_MODEL_KEY]));
169
- if (legacy !== undefined) {
170
- map.set(UTILITY_MODEL_KEY, legacy);
171
- if (consumeMaxPowerDeprecationNotice()) {
172
- log.warn(`${MAX_POWER_MODEL_KEY} is deprecated and now loads as ${UTILITY_MODEL_KEY}. ` +
173
- `Move the value to ${UTILITY_MODEL_KEY} (for example /utility-model <pattern>); ` +
174
- "the legacy key is removed next release.");
175
- }
176
- }
177
- }
141
+ const value = toRoleSettingValue(normaliseRoleSetting(settings[UTILITY_MODEL_KEY]));
142
+ if (value !== undefined)
143
+ getCustomModelKeys().set(UTILITY_MODEL_KEY, value);
178
144
  }
179
145
  catch {
180
146
  // Non-fatal: no prior settings or parse error
@@ -253,48 +219,7 @@ export default function polyfillExtension(pi) {
253
219
  "No args = show current setting. Smaller/faster models preferred. " +
254
220
  "Examples: /utility-model provider/model-id, /utility-model a/b,c/d, " +
255
221
  "/utility-model clear",
256
- handler: (args, ctx) => runUtilityModelCommand(args, ctx, false),
257
- });
258
- pi.registerCommand("vision-model", {
259
- description: "Set or show the vision model. Accepts one model or an ordered list " +
260
- "(comma-separated); every entry must accept image input. " +
261
- "No args opens the (vision-filtered) selector UI. " +
262
- "Examples: /vision-model provider/model-id, /vision-model a/b,c/d, /vision-model clear",
263
- handler: async (args, ctx) => {
264
- ctx.ui.notify("/vision-model is deprecated: image analysis falls back to the utility list's first " +
265
- "image-capable model. The setting keeps priority this release; the command is removed next release.", "warning");
266
- if (!args || args.trim() === "") {
267
- if (ctx.hasUI) {
268
- const visionFilter = (m) => hasImageInput(m);
269
- await openModelSelectorUI(ctx, VISION_MODEL_KEY, "Vision", visionFilter);
270
- }
271
- else {
272
- const model = resolveVisionModel(ctx);
273
- const patterns = configuredRolePatterns(VISION_MODEL_KEY);
274
- ctx.ui.notify(patterns.length === 0
275
- ? `Vision model: ${model?.id ?? "none"} (auto-detected)`
276
- : `Vision model${patterns.length > 1 ? "s" : ""}: ${patterns.join(" -> ")}` +
277
- ` (using: ${model?.id ?? "none"})`, "info");
278
- }
279
- return;
280
- }
281
- const text = args.trim();
282
- if (text === "clear" || text === "reset") {
283
- await clearModelSetting(VISION_MODEL_KEY);
284
- ctx.ui.notify("Vision model cleared (will auto-detect)", "info");
285
- return;
286
- }
287
- await setRoleSettingFromArgs(ctx, VISION_MODEL_KEY, "Vision", "", text);
288
- },
289
- });
290
- // Max-power model command (deprecated alias)
291
- pi.registerCommand("max-power-model", {
292
- description: "Deprecated alias of /utility-model: the max-power role merged into the " +
293
- "utility role. Set/show/clear operate on the canonical utility setting; " +
294
- "the alias is removed next release. " +
295
- "Examples: /max-power-model provider/model-id, /max-power-model a/b,c/d, " +
296
- "/max-power-model clear",
297
- handler: (args, ctx) => runUtilityModelCommand(args, ctx, true),
222
+ handler: (args, ctx) => runUtilityModelCommand(args, ctx),
298
223
  });
299
224
  }
300
225
  // Helpers
@@ -308,11 +233,9 @@ async function clearModelSetting(key) {
308
233
  getCustomModelKeys().delete(key);
309
234
  // persistCustomKeys writes only the keys still in the map, so deleting from
310
235
  // the map alone left the old value in settings.json and the next session
311
- // resurrected it. "Clear" has to clear the stored setting as well, and a
312
- // clear is a role write: it retires the deprecated legacy key too.
236
+ // resurrected it. "Clear" has to clear the stored setting as well.
313
237
  updateSettings((settings) => {
314
238
  delete settings[key];
315
- delete settings[MAX_POWER_MODEL_KEY];
316
239
  });
317
240
  }
318
241
  /** Resolve a model from a "provider/model-id" or bare "model-id" pattern. */
@@ -337,7 +260,7 @@ function resolveModelPattern(ctx, pattern) {
337
260
  * - Capture the selected model in the onSelect callback.
338
261
  * - After ctx.ui.custom() resolves, call pi.setModel() and setModelSetting().
339
262
  */
340
- async function openModelSelectorUI(ctx, settingKey, roleLabel, scopeFilter, resolveFn = resolveVisionModel) {
263
+ async function openModelSelectorUI(ctx, settingKey, roleLabel, resolveFn) {
341
264
  const modelRegistry = ctx.modelRegistry;
342
265
  // ModelSelectorComponent writes through an in-memory SettingsManager:
343
266
  // setDefaultModelAndProvider() sets fields in memory but never persists,
@@ -355,45 +278,25 @@ async function openModelSelectorUI(ctx, settingKey, roleLabel, scopeFilter, reso
355
278
  const mainModel = ctx.model;
356
279
  const prefProvider = currentRoleModel?.provider ?? mainModel?.provider;
357
280
  const allModels = modelRegistry.getAvailable();
358
- let scopedModels;
359
- if (scopeFilter) {
360
- const filtered = allModels.filter(scopeFilter);
361
- filtered.sort((a, b) => {
362
- if (currentRoleModel && a.id === currentRoleModel.id)
363
- return -1;
364
- if (currentRoleModel && b.id === currentRoleModel.id)
365
- return 1;
366
- if (prefProvider && a.provider === prefProvider)
367
- return -1;
368
- if (prefProvider && b.provider === prefProvider)
369
- return 1;
370
- return a.id.localeCompare(b.id);
371
- });
372
- scopedModels = filtered.map((m) => ({ model: m }));
373
- }
374
- else {
375
- allModels.sort((a, b) => {
376
- if (currentRoleModel && a.id === currentRoleModel.id)
377
- return -1;
378
- if (currentRoleModel && b.id === currentRoleModel.id)
379
- return 1;
380
- if (prefProvider && a.provider === prefProvider)
381
- return -1;
382
- if (prefProvider && b.provider === prefProvider)
383
- return 1;
384
- return a.id.localeCompare(b.id);
385
- });
386
- scopedModels = allModels.map((m) => ({ model: m }));
387
- }
281
+ allModels.sort((a, b) => {
282
+ if (currentRoleModel && a.id === currentRoleModel.id)
283
+ return -1;
284
+ if (currentRoleModel && b.id === currentRoleModel.id)
285
+ return 1;
286
+ if (prefProvider && a.provider === prefProvider)
287
+ return -1;
288
+ if (prefProvider && b.provider === prefProvider)
289
+ return 1;
290
+ return a.id.localeCompare(b.id);
291
+ });
292
+ const scopedModels = allModels.map((m) => ({
293
+ model: m,
294
+ }));
388
295
  // Capture selected model from the dialog
389
296
  let selectedModel;
390
297
  await ctx.ui.custom(async (tui, _theme, _keybindings, done) => {
391
298
  const onSelect = async (model) => {
392
299
  selectedModel = model;
393
- // Warn if a non-vision model was picked for the vision role
394
- if (scopeFilter && !hasImageInput(model)) {
395
- ctx.ui.notify(`[warn] ${model.id} does not support image input. Vision analysis may fail.`, "warning");
396
- }
397
300
  done(model);
398
301
  };
399
302
  const onCancel = () => done(undefined);
@@ -421,8 +324,8 @@ async function openModelSelectorUI(ctx, settingKey, roleLabel, scopeFilter, reso
421
324
  if (!selectedModel)
422
325
  return;
423
326
  // Store the role-specific key only. Do NOT call pi.setModel() - that would change
424
- // the default model, which is NOT what we want for utility/vision role selection.
425
- // model-resolver.ts reads these custom keys and uses them directly.
327
+ // the default model, which is NOT what we want for utility role selection.
328
+ // model-resolver.ts reads this custom key and uses it directly.
426
329
  const pattern = `${selectedModel.provider}/${selectedModel.id}`;
427
330
  await setModelSetting(settingKey, pattern);
428
331
  ctx.ui.notify(`${roleLabel} model set to: ${selectedModel.id}`, "info");
@@ -11,6 +11,8 @@ import { getState } from "../state.js";
11
11
  import { classify } from "../../../lib/ai/text-classifier.js";
12
12
  import { CRITICS } from "../../../lib/ai/critic-registry.js";
13
13
  import { errorTypeFallback } from "../../../lib/ai/critic-fallbacks.js";
14
+ import { classifyLlmError } from "../../../lib/errors/llm-error.js";
15
+ import { recordRouteFailure } from "../session-health.js";
14
16
  export function registerAgentEndApiErrorHandler(pi) {
15
17
  pi.on(AGENT_END, async (event, ctx) => {
16
18
  if (!getState(ctx).enforcementActive)
@@ -27,6 +29,17 @@ export function registerAgentEndApiErrorHandler(pi) {
27
29
  return;
28
30
  const finalError = lastAssistant.errorMessage ?? "Unknown error";
29
31
  getState(ctx).validationFailures++;
32
+ // Count the failure for the route-failure latch BEFORE the nudge cooldown
33
+ // below: the cooldown throttles the message, not the observation. A run
34
+ // that ends on a provider error is the only evidence the latch has, and
35
+ // the auxiliary calls classifyRetryError makes are excluded from it by
36
+ // design (they are what releases the latch, never what feeds it).
37
+ try {
38
+ recordRouteFailure(ctx, classifyLlmError(finalError).category);
39
+ }
40
+ catch {
41
+ // A broken counter must never suppress the nudge.
42
+ }
30
43
  const now = Date.now();
31
44
  if (now - getState(ctx).lastNudgeTime < getState(ctx).nudgeCooldownMs)
32
45
  return;
@@ -52,7 +52,7 @@ import { isCompactionActive, getCmState } from "../../memory/context-manager/han
52
52
  import { snapBoundaryOutsideToolBatch } from "../../memory/context-manager/handlers/tool-batch-boundary.js";
53
53
  import { USAGE_COMPACT_AGGRESSIVE, HYGIENE_AUTO_COMPACT_MIN_TURNS, } from "../../../lib/detection/context-thresholds.js";
54
54
  import { resolveContextNudge, findContextNudgeRung, contextNudgeFellBelow, contextNudgeCrossed, } from "../../../lib/detection/context-tiers.js";
55
- import { measureLiveUsage, tokenArms, formatTokensK, } from "../../../lib/detection/context-usage.js";
55
+ import { describeUsage, measureLiveUsage, tokenArms, formatTokensK, } from "../../../lib/detection/context-usage.js";
56
56
  import { recordCompaction, recordHygieneAct, recordHygieneSkip, recordLiveUsageSample, } from "../substate/context-hygiene-state.js";
57
57
  const log = createLogger("enforcement:turn-end-hygiene");
58
58
  // Pre-save safety: flush scratchpad + write resume.json
@@ -171,12 +171,14 @@ async function checkContextUsage(pi, ctx, event) {
171
171
  let usagePercent = 0;
172
172
  let usageTokens = 0;
173
173
  let usageWindow;
174
+ let usageProvenance;
174
175
  try {
175
176
  const live = measureLiveUsage(ctx);
176
177
  if (live) {
177
178
  usagePercent = live.percent;
178
179
  usageTokens = live.tokens;
179
180
  usageWindow = live.contextWindow;
181
+ usageProvenance = describeUsage(live);
180
182
  }
181
183
  }
182
184
  catch {
@@ -282,7 +284,7 @@ async function checkContextUsage(pi, ctx, event) {
282
284
  // token warning 0.45W, advisory 50%, warning 65%, critical 75%, compact
283
285
  // 80%. The strongest rung reached wins, so no token arm can shadow a
284
286
  // percent tier above it (see lib/detection/context-tiers.ts).
285
- const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow);
287
+ const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow, usageProvenance);
286
288
  if (nudge) {
287
289
  const lastFired = findContextNudgeRung(state.contextNudgeRung, usageWindow);
288
290
  if (state.contextNudgeSent) {
@@ -301,7 +303,10 @@ async function checkContextUsage(pi, ctx, event) {
301
303
  }
302
304
  state.contextNudgeSent = true;
303
305
  state.contextNudgeRung = nudge.id;
304
- sendEnforcementWhisper(pi, ctx, nudge.message);
306
+ // Queued for the next user prompt, never steered into the run: the line is
307
+ // advice about a run that may still dispatch, and a steer at this boundary
308
+ // is exactly the delivery that kept a compaction-armed loop alive.
309
+ sendEnforcementWhisper(pi, ctx, nudge.message, false, { deliverAs: "nextTurn" });
305
310
  }
306
311
  }
307
312
  /**
@@ -58,6 +58,26 @@ export interface SessionHealthState {
58
58
  * the current episode. Diagnostic; cleared together with the counter.
59
59
  */
60
60
  breakerOpenedAt?: number;
61
+ /**
62
+ * Provider failures of any class except context_window/abort since the last
63
+ * successful LLM call. The route-failure latch reads this; only an explicit
64
+ * reset (clean turn, provider success, route change, owner recovery,
65
+ * session start) lowers it.
66
+ */
67
+ routeErrorsSinceHealthyTurn: number;
68
+ /**
69
+ * ms timestamp of the first time routeErrorsSinceHealthyTurn reached the
70
+ * configured threshold in the current episode. One half of the floor's
71
+ * clock; undefined while the latch has never opened.
72
+ */
73
+ routeLatchOpenedAt?: number;
74
+ /**
75
+ * ms timestamp of the last turn the floor released while the latch stayed
76
+ * open. The other half of the floor's clock: the predicate allows exactly
77
+ * one self-started turn per `floorMs`, then this stamp closes the gate for
78
+ * the next window.
79
+ */
80
+ routeLatchLastReleaseAt?: number;
61
81
  }
62
82
  /**
63
83
  * Terminal-category errors (auth/balance) that must accumulate since the last
@@ -73,12 +93,40 @@ export declare function getSessionHealth(ctx: ExtensionContext): SessionHealthSt
73
93
  * terminally? Latch state only — no provider/model/error names, so callers in
74
94
  * generic layers (the timer wake path) cannot learn a domain fact from it.
75
95
  *
76
- * `threshold` lets a caller pass the configured bound; the default keeps the
77
- * built-in N. Open-ness is derived from the monotonic counter, which only the
78
- * explicit reset signals (session_start, owner recovery, route change) and a
79
- * clean wake turn lower — hence "latch".
96
+ * `threshold` lets a caller pass the configured bound for the terminal
97
+ * counter; the default keeps the built-in N. Open-ness is derived from the
98
+ * monotonic counter, which only the explicit reset signals (session_start,
99
+ * owner recovery, route change) and a clean wake turn lower — hence "latch".
100
+ *
101
+ * The route disjunct is the second latch on the same question: a route that
102
+ * fails every self-started turn parks them too, on its own configured
103
+ * threshold and floor. It is asked here, once, so the three seams that
104
+ * self-start turns cannot each keep their own answer.
80
105
  */
81
106
  export declare function isTurnStartBlocked(ctx: ExtensionContext, threshold?: number): boolean;
107
+ /**
108
+ * Is the route-failure latch open right now? The route-only half of
109
+ * `isTurnStartBlocked`, for the two seams that must not inherit the terminal
110
+ * wake policy: a watchdog escalation and an explicitly-waking whisper never
111
+ * consulted the terminal breaker, so their demotion has to key on the route
112
+ * fact alone. `braid.session.routeBreaker.enabled = false` answers false
113
+ * unconditionally, which is what makes the off switch inert rather than
114
+ * partial.
115
+ *
116
+ * The floor is a release, not a bypass: while the latch stays open the
117
+ * predicate lets exactly one self-started turn through per `floorMs` and
118
+ * stamps the release, so a parked session cannot starve and cannot loop.
119
+ */
120
+ export declare function isRouteLatchOpen(ctx: ExtensionContext): boolean;
121
+ /**
122
+ * Count one provider failure for the route latch. The category decides
123
+ * whether it counts: a context-window overflow and an operator abort are not
124
+ * evidence about the route, and counting them would park the very wakes a
125
+ * recovery needs. Read by `isRouteLatchOpen` only — deliberately not folded
126
+ * into `recordLlmError`, whose consumers (mode, terminal counter, degraded
127
+ * rows) must keep their own semantics.
128
+ */
129
+ export declare function recordRouteFailure(ctx: ExtensionContext, category: LlmErrorCategory): void;
82
130
  /** Clear the latch and its counter (the reset signals share this). */
83
131
  export declare function clearTerminalBreaker(ctx: ExtensionContext): void;
84
132
  export declare function recordLlmError(ctx: ExtensionContext, err: ClassifiedLlmError): void;
@@ -23,6 +23,7 @@
23
23
  * the L1 environment hook, the session_health tool).
24
24
  */
25
25
  import { getExtensionState } from "../../lib/state/extension-state.js";
26
+ import { getRouteBreakerConfig } from "../../lib/config/braid-settings.js";
26
27
  function emptyCategoryCounts() {
27
28
  return {
28
29
  balance: 0,
@@ -42,6 +43,7 @@ const DEFAULT_STATE = {
42
43
  providerSuccessCount: 0,
43
44
  consolidationSkipsByMode: {},
44
45
  terminalErrorsSinceHealthyTurn: 0,
46
+ routeErrorsSinceHealthyTurn: 0,
45
47
  };
46
48
  /**
47
49
  * Terminal-category errors (auth/balance) that must accumulate since the last
@@ -69,6 +71,9 @@ export function getSessionHealth(ctx) {
69
71
  if (typeof s.terminalErrorsSinceHealthyTurn !== "number") {
70
72
  s.terminalErrorsSinceHealthyTurn = 0;
71
73
  }
74
+ if (typeof s.routeErrorsSinceHealthyTurn !== "number") {
75
+ s.routeErrorsSinceHealthyTurn = 0;
76
+ }
72
77
  return s;
73
78
  }
74
79
  /**
@@ -76,20 +81,80 @@ export function getSessionHealth(ctx) {
76
81
  * terminally? Latch state only — no provider/model/error names, so callers in
77
82
  * generic layers (the timer wake path) cannot learn a domain fact from it.
78
83
  *
79
- * `threshold` lets a caller pass the configured bound; the default keeps the
80
- * built-in N. Open-ness is derived from the monotonic counter, which only the
81
- * explicit reset signals (session_start, owner recovery, route change) and a
82
- * clean wake turn lower — hence "latch".
84
+ * `threshold` lets a caller pass the configured bound for the terminal
85
+ * counter; the default keeps the built-in N. Open-ness is derived from the
86
+ * monotonic counter, which only the explicit reset signals (session_start,
87
+ * owner recovery, route change) and a clean wake turn lower — hence "latch".
88
+ *
89
+ * The route disjunct is the second latch on the same question: a route that
90
+ * fails every self-started turn parks them too, on its own configured
91
+ * threshold and floor. It is asked here, once, so the three seams that
92
+ * self-start turns cannot each keep their own answer.
83
93
  */
84
94
  export function isTurnStartBlocked(ctx, threshold = TERMINAL_BREAKER_N) {
85
95
  const s = getSessionHealth(ctx);
86
- return s.terminalErrorsSinceHealthyTurn >= threshold;
96
+ return s.terminalErrorsSinceHealthyTurn >= threshold || isRouteLatchOpen(ctx);
97
+ }
98
+ /**
99
+ * Is the route-failure latch open right now? The route-only half of
100
+ * `isTurnStartBlocked`, for the two seams that must not inherit the terminal
101
+ * wake policy: a watchdog escalation and an explicitly-waking whisper never
102
+ * consulted the terminal breaker, so their demotion has to key on the route
103
+ * fact alone. `braid.session.routeBreaker.enabled = false` answers false
104
+ * unconditionally, which is what makes the off switch inert rather than
105
+ * partial.
106
+ *
107
+ * The floor is a release, not a bypass: while the latch stays open the
108
+ * predicate lets exactly one self-started turn through per `floorMs` and
109
+ * stamps the release, so a parked session cannot starve and cannot loop.
110
+ */
111
+ export function isRouteLatchOpen(ctx) {
112
+ const cfg = getRouteBreakerConfig();
113
+ if (!cfg.enabled)
114
+ return false;
115
+ const s = getSessionHealth(ctx);
116
+ if (s.routeErrorsSinceHealthyTurn < cfg.threshold)
117
+ return false;
118
+ const anchor = Math.max(s.routeLatchOpenedAt ?? 0, s.routeLatchLastReleaseAt ?? 0);
119
+ if (Date.now() - anchor < cfg.floorMs)
120
+ return true;
121
+ s.routeLatchLastReleaseAt = Date.now();
122
+ return false;
123
+ }
124
+ /**
125
+ * Count one provider failure for the route latch. The category decides
126
+ * whether it counts: a context-window overflow and an operator abort are not
127
+ * evidence about the route, and counting them would park the very wakes a
128
+ * recovery needs. Read by `isRouteLatchOpen` only — deliberately not folded
129
+ * into `recordLlmError`, whose consumers (mode, terminal counter, degraded
130
+ * rows) must keep their own semantics.
131
+ */
132
+ export function recordRouteFailure(ctx, category) {
133
+ if (category === "context_window" || category === "abort")
134
+ return;
135
+ const s = getSessionHealth(ctx);
136
+ s.routeErrorsSinceHealthyTurn++;
137
+ if (s.routeLatchOpenedAt === undefined) {
138
+ const cfg = getRouteBreakerConfig();
139
+ if (s.routeErrorsSinceHealthyTurn >= cfg.threshold)
140
+ s.routeLatchOpenedAt = Date.now();
141
+ }
142
+ }
143
+ /** Drop the route latch and every stamp the floor reads. */
144
+ function clearRouteLatch(s) {
145
+ s.routeErrorsSinceHealthyTurn = 0;
146
+ s.routeLatchOpenedAt = undefined;
147
+ s.routeLatchLastReleaseAt = undefined;
87
148
  }
88
149
  /** Clear the latch and its counter (the reset signals share this). */
89
150
  export function clearTerminalBreaker(ctx) {
90
151
  const s = getSessionHealth(ctx);
91
152
  s.terminalErrorsSinceHealthyTurn = 0;
92
153
  s.breakerOpenedAt = undefined;
154
+ // A clean turn, a route change, an owner recovery and a session start all
155
+ // mean the route is being retried from a fresh premise: the route latch
156
+ // releases on the same signals.
157
+ clearRouteLatch(s);
93
158
  }
94
159
  export function recordLlmError(ctx, err) {
95
160
  const s = getSessionHealth(ctx);
@@ -144,6 +209,11 @@ export function recordLlmSuccess(ctx) {
144
209
  s.providerSuccessCount++;
145
210
  s.consecutiveErrors = 0;
146
211
  s.consecutiveHealthyTurns++;
212
+ // Any successful provider call is a release signal for the route latch: the
213
+ // route just answered, so the premise the latch parks on ("every attempt on
214
+ // this route fails") is false. Deliberately not gated on a run outcome — a
215
+ // parked session makes no self-started call, so this is how it re-opens.
216
+ clearRouteLatch(s);
147
217
  // Recover from degraded/aborted after enough healthy turns.
148
218
  if (s.mode === "degraded" || s.mode === "aborted" || s.mode === "context_overflow") {
149
219
  if (s.consecutiveHealthyTurns >= HEALTHY_CLEAR_TURNS) {
@@ -6,6 +6,7 @@ import { eventBus } from "../../lib/events/event-bus.js";
6
6
  import { sendTrackedMessage } from "../../lib/utils/injection-tracker.js";
7
7
  import { recordNudgeSent } from "../../lib/reasoning/nudge-analytics.js";
8
8
  import { areCognitiveNudgesDisabled } from "../../lib/config/braid-settings.js";
9
+ import { isRouteLatchOpen } from "./session-health.js";
9
10
  const log = createLogger("enforcement");
10
11
  /**
11
12
  * Send an enforcement whisper immediately using sendTrackedMessage().
@@ -99,7 +100,20 @@ export function sendEnforcementWhisper(pi, ctx, message, critical = false, optio
99
100
  // mid-turn compaction (context_compress tool). Undefined `deliverAs` falls
100
101
  // through to the triggerTurn branch and calls agent.prompt(), the same wake
101
102
  // path the timer extension uses.
102
- const triggerTurn = options?.triggerTurn ?? false;
103
+ const requestedTriggerTurn = options?.triggerTurn ?? false;
104
+ // Route-failure latch: a whisper that asked to wake the agent must not
105
+ // start a turn into a route that has failed every attempt since the last
106
+ // successful call. The advisory is not withdrawn — the same text still
107
+ // reaches the session as the ordinary non-waking steer; only the wake is
108
+ // withheld, so the next self-started call is not a doomed one. Only the
109
+ // route half of the turn-start question applies here: an explicitly-waking
110
+ // whisper never consulted the terminal breaker, and making it do so now
111
+ // would park the post-compaction resume on a signal it never used to read.
112
+ const demoted = requestedTriggerTurn && isRouteLatchOpen(ctx);
113
+ if (demoted) {
114
+ log.info("[whisper] waking whisper demoted to non-waking (route latch open)");
115
+ }
116
+ const triggerTurn = requestedTriggerTurn && !demoted;
103
117
  const deliverAs = options?.deliverAs ?? (triggerTurn ? undefined : "steer");
104
118
  // Default class for a non-waking enforcement whisper: live. An enforcement
105
119
  // advisory's value is read during the run it fires in (see the delivery
@@ -15,6 +15,21 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
15
15
  import type { Episode } from "../../../lib/types/episode-types.js";
16
16
  import { reflectionConsolidatorModule } from "./modules/reflection-consolidator.js";
17
17
  export { reflectionConsolidatorModule as dreamerModule };
18
+ /**
19
+ * Buffer one whisper for the next delivery. Exported because it and
20
+ * flushDelayedWhispers are the delivery boundary a fixture must drive to
21
+ * assert on the text that ships (the same pair before_agent_start calls).
22
+ */
23
+ export declare function bufferHeartbeatWhisper(sessionId: string, message: string, priority: string, source: string, family?: WhisperFamily): void;
24
+ /**
25
+ * Drain the delayed buffer as one delivery per priority tier.
26
+ *
27
+ * The sample is taken here, at delivery, and is the only source of the
28
+ * numbers and of the tier the context family is re-labelled with: a family
29
+ * rendered from an older reading is what printed a label beside numbers it
30
+ * never measured.
31
+ */
32
+ export declare function flushDelayedWhispers(sessionId: string, pi: ExtensionAPI, sample?: SelfStateSample): void;
18
33
  /** Format SOP (3-tier hierarchy) for whispering to agent */
19
34
  export declare function formatSOPForWhisper(episode: Episode): string;
20
35
  /**
@@ -27,5 +42,7 @@ export declare function formatSOPForWhisper(episode: Episode): string;
27
42
  * is the delivery path; see `lib/utils/whisper-format.ts`.
28
43
  */
29
44
  export declare function sendSopCoachWhisper(pi: ExtensionAPI, message: string): void;
45
+ import { type WhisperFamily } from "./whisper-batcher.js";
46
+ import type { SelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
30
47
  export default function heartbeatExtension(pi: ExtensionAPI): void;
31
48
  //# sourceMappingURL=index.d.ts.map