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
@@ -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
@@ -31,11 +30,7 @@ import type {
31
30
  } from "@earendil-works/pi-coding-agent";
32
31
  import { ModelSelectorComponent, SettingsManager } from "@earendil-works/pi-coding-agent";
33
32
  import type { Model, Api } from "@earendil-works/pi-ai";
34
- import {
35
- resolveUtilityModel,
36
- resolveVisionModel,
37
- normaliseRoleSetting,
38
- } from "../../../lib/ai/model-resolver.js";
33
+ import { resolveUtilityModel, normaliseRoleSetting } from "../../../lib/ai/model-resolver.js";
39
34
  import {
40
35
  applyCompactionReserveTokens,
41
36
  applyConfiguredContextWindow,
@@ -52,10 +47,7 @@ const log = createLogger("polyfill");
52
47
  import {
53
48
  getCustomModelKey,
54
49
  getCustomModelKeys,
55
- consumeMaxPowerDeprecationNotice,
56
50
  UTILITY_MODEL_KEY,
57
- VISION_MODEL_KEY,
58
- MAX_POWER_MODEL_KEY,
59
51
  } from "../../../lib/state/global-state.js";
60
52
  import type { CustomModelKeyValue } from "../../../lib/state/global-state.js";
61
53
 
@@ -80,12 +72,6 @@ interface SessionManagerLike {
80
72
  getContextUsage?(): unknown;
81
73
  }
82
74
 
83
- // Type guard for checking if a model has image input capability
84
- function hasImageInput(model: { input?: unknown }): boolean {
85
- const input = model.input;
86
- return Array.isArray(input) && (input as unknown[]).includes("image");
87
- }
88
-
89
75
  /** Shared sessionManager reference - used by patchSessionManagerMethods */
90
76
  import { getExtensionState } from "../../../lib/state/extension-state.js";
91
77
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -153,26 +139,13 @@ async function setRoleSettingFromArgs(
153
139
  }
154
140
 
155
141
  /**
156
- * The /utility-model command body. The deprecated /max-power-model alias
157
- * drives the same function: the roles merged, so both commands write the one
158
- * canonical key and differ only in the deprecation notice.
142
+ * The /utility-model command body. The role it configures is also the one
143
+ * vision analysis falls back to, so there is no separate vision command.
159
144
  */
160
- async function runUtilityModelCommand(
161
- args: string,
162
- ctx: ExtensionCommandContext,
163
- viaDeprecatedAlias: boolean,
164
- ): Promise<void> {
165
- if (viaDeprecatedAlias) {
166
- ctx.ui.notify(
167
- "/max-power-model is deprecated: the max-power role merged into the utility role. " +
168
- "Use /utility-model; the alias is removed next release.",
169
- "warning",
170
- );
171
- }
172
-
145
+ async function runUtilityModelCommand(args: string, ctx: ExtensionCommandContext): Promise<void> {
173
146
  if (!args || args.trim() === "") {
174
147
  if (ctx.hasUI) {
175
- await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", null, resolveUtilityModel);
148
+ await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", resolveUtilityModel);
176
149
  } else {
177
150
  const model = resolveUtilityModel(ctx);
178
151
  const patterns = configuredRolePatterns(UTILITY_MODEL_KEY);
@@ -215,9 +188,6 @@ function persistCustomKeys(): void {
215
188
  for (const [key, value] of map) {
216
189
  settings[key] = value;
217
190
  }
218
- // Any role write retires the legacy key in the same transaction: a
219
- // stale alias left on disk is resurrected by the next load.
220
- delete settings[MAX_POWER_MODEL_KEY];
221
191
  });
222
192
  } catch {
223
193
  // Non-fatal: settings won't persist but everything else still works
@@ -225,39 +195,16 @@ function persistCustomKeys(): void {
225
195
  }
226
196
 
227
197
  /**
228
- * Load custom keys from pi's settings.json into the in-memory map.
229
- * A role key carries either one pattern or an ordered list; both land in the
230
- * map in the list form the resolver walks. A value with no usable pattern is
198
+ * Load the utility role from pi's settings.json into the in-memory map.
199
+ * The key carries either one pattern or an ordered list; both land in the map
200
+ * in the list form the resolver walks. A value with no usable pattern is
231
201
  * treated as unset rather than stored as something that resolves to nothing.
232
202
  */
233
203
  function loadCustomKeysFromDisk(): void {
234
204
  try {
235
205
  const settings = readSettingsFile();
236
- const map = getCustomModelKeys();
237
- for (const key of [VISION_MODEL_KEY, UTILITY_MODEL_KEY]) {
238
- const value = toRoleSettingValue(normaliseRoleSetting(settings[key]));
239
- if (value !== undefined) map.set(key, value);
240
- }
241
-
242
- // Deprecated alias: a legacy maxPowerModel value loads under the canonical
243
- // key when that key carries no usable value on disk (canonical wins when
244
- // both are present). The legacy key is never stored under its own name;
245
- // one process-global notice tells the user to move the value before the
246
- // alias is removed.
247
- const canonical = toRoleSettingValue(normaliseRoleSetting(settings[UTILITY_MODEL_KEY]));
248
- if (canonical === undefined) {
249
- const legacy = toRoleSettingValue(normaliseRoleSetting(settings[MAX_POWER_MODEL_KEY]));
250
- if (legacy !== undefined) {
251
- map.set(UTILITY_MODEL_KEY, legacy);
252
- if (consumeMaxPowerDeprecationNotice()) {
253
- log.warn(
254
- `${MAX_POWER_MODEL_KEY} is deprecated and now loads as ${UTILITY_MODEL_KEY}. ` +
255
- `Move the value to ${UTILITY_MODEL_KEY} (for example /utility-model <pattern>); ` +
256
- "the legacy key is removed next release.",
257
- );
258
- }
259
- }
260
- }
206
+ const value = toRoleSettingValue(normaliseRoleSetting(settings[UTILITY_MODEL_KEY]));
207
+ if (value !== undefined) getCustomModelKeys().set(UTILITY_MODEL_KEY, value);
261
208
  } catch {
262
209
  // Non-fatal: no prior settings or parse error
263
210
  }
@@ -347,59 +294,7 @@ export default function polyfillExtension(pi: ExtensionAPI) {
347
294
  "No args = show current setting. Smaller/faster models preferred. " +
348
295
  "Examples: /utility-model provider/model-id, /utility-model a/b,c/d, " +
349
296
  "/utility-model clear",
350
- handler: (args, ctx) => runUtilityModelCommand(args, ctx, false),
351
- });
352
-
353
- pi.registerCommand("vision-model", {
354
- description:
355
- "Set or show the vision model. Accepts one model or an ordered list " +
356
- "(comma-separated); every entry must accept image input. " +
357
- "No args opens the (vision-filtered) selector UI. " +
358
- "Examples: /vision-model provider/model-id, /vision-model a/b,c/d, /vision-model clear",
359
- handler: async (args, ctx) => {
360
- ctx.ui.notify(
361
- "/vision-model is deprecated: image analysis falls back to the utility list's first " +
362
- "image-capable model. The setting keeps priority this release; the command is removed next release.",
363
- "warning",
364
- );
365
- if (!args || args.trim() === "") {
366
- if (ctx.hasUI) {
367
- const visionFilter = (m: Model<Api>) => hasImageInput(m as { input?: unknown });
368
- await openModelSelectorUI(ctx, VISION_MODEL_KEY, "Vision", visionFilter);
369
- } else {
370
- const model = resolveVisionModel(ctx);
371
- const patterns = configuredRolePatterns(VISION_MODEL_KEY);
372
- ctx.ui.notify(
373
- patterns.length === 0
374
- ? `Vision model: ${model?.id ?? "none"} (auto-detected)`
375
- : `Vision model${patterns.length > 1 ? "s" : ""}: ${patterns.join(" -> ")}` +
376
- ` (using: ${model?.id ?? "none"})`,
377
- "info",
378
- );
379
- }
380
- return;
381
- }
382
-
383
- const text = args.trim();
384
- if (text === "clear" || text === "reset") {
385
- await clearModelSetting(VISION_MODEL_KEY);
386
- ctx.ui.notify("Vision model cleared (will auto-detect)", "info");
387
- return;
388
- }
389
-
390
- await setRoleSettingFromArgs(ctx, VISION_MODEL_KEY, "Vision", "", text);
391
- },
392
- });
393
-
394
- // Max-power model command (deprecated alias)
395
- pi.registerCommand("max-power-model", {
396
- description:
397
- "Deprecated alias of /utility-model: the max-power role merged into the " +
398
- "utility role. Set/show/clear operate on the canonical utility setting; " +
399
- "the alias is removed next release. " +
400
- "Examples: /max-power-model provider/model-id, /max-power-model a/b,c/d, " +
401
- "/max-power-model clear",
402
- handler: (args, ctx) => runUtilityModelCommand(args, ctx, true),
297
+ handler: (args, ctx) => runUtilityModelCommand(args, ctx),
403
298
  });
404
299
  }
405
300
 
@@ -416,11 +311,9 @@ async function clearModelSetting(key: string): Promise<void> {
416
311
  getCustomModelKeys().delete(key);
417
312
  // persistCustomKeys writes only the keys still in the map, so deleting from
418
313
  // the map alone left the old value in settings.json and the next session
419
- // resurrected it. "Clear" has to clear the stored setting as well, and a
420
- // clear is a role write: it retires the deprecated legacy key too.
314
+ // resurrected it. "Clear" has to clear the stored setting as well.
421
315
  updateSettings((settings) => {
422
316
  delete settings[key];
423
- delete settings[MAX_POWER_MODEL_KEY];
424
317
  });
425
318
  }
426
319
 
@@ -454,8 +347,7 @@ async function openModelSelectorUI(
454
347
  ctx: ExtensionCommandContext,
455
348
  settingKey: string,
456
349
  roleLabel: string,
457
- scopeFilter: ((m: Model<Api>) => boolean) | null,
458
- resolveFn: (ctx: ExtensionContext) => Model<Api> | undefined = resolveVisionModel,
350
+ resolveFn: (ctx: ExtensionContext) => Model<Api> | undefined,
459
351
  ): Promise<void> {
460
352
  const modelRegistry = ctx.modelRegistry;
461
353
 
@@ -478,28 +370,17 @@ async function openModelSelectorUI(
478
370
  const prefProvider = currentRoleModel?.provider ?? mainModel?.provider;
479
371
 
480
372
  const allModels = modelRegistry.getAvailable();
481
- let scopedModels: { model: Model<Api>; thinkingLevel?: string }[];
482
-
483
- if (scopeFilter) {
484
- const filtered = allModels.filter(scopeFilter);
485
- filtered.sort((a, b) => {
486
- if (currentRoleModel && a.id === currentRoleModel.id) return -1;
487
- if (currentRoleModel && b.id === currentRoleModel.id) return 1;
488
- if (prefProvider && a.provider === prefProvider) return -1;
489
- if (prefProvider && b.provider === prefProvider) return 1;
490
- return a.id.localeCompare(b.id);
491
- });
492
- scopedModels = filtered.map((m) => ({ model: m }));
493
- } else {
494
- allModels.sort((a, b) => {
495
- if (currentRoleModel && a.id === currentRoleModel.id) return -1;
496
- if (currentRoleModel && b.id === currentRoleModel.id) return 1;
497
- if (prefProvider && a.provider === prefProvider) return -1;
498
- if (prefProvider && b.provider === prefProvider) return 1;
499
- return a.id.localeCompare(b.id);
500
- });
501
- scopedModels = allModels.map((m) => ({ model: m }));
502
- }
373
+
374
+ allModels.sort((a, b) => {
375
+ if (currentRoleModel && a.id === currentRoleModel.id) return -1;
376
+ if (currentRoleModel && b.id === currentRoleModel.id) return 1;
377
+ if (prefProvider && a.provider === prefProvider) return -1;
378
+ if (prefProvider && b.provider === prefProvider) return 1;
379
+ return a.id.localeCompare(b.id);
380
+ });
381
+ const scopedModels: { model: Model<Api>; thinkingLevel?: string }[] = allModels.map((m) => ({
382
+ model: m,
383
+ }));
503
384
 
504
385
  // Capture selected model from the dialog
505
386
  let selectedModel: Model<Api> | undefined;
@@ -507,15 +388,6 @@ async function openModelSelectorUI(
507
388
  await ctx.ui.custom(async (tui, _theme, _keybindings, done) => {
508
389
  const onSelect = async (model: Model<Api>) => {
509
390
  selectedModel = model;
510
-
511
- // Warn if a non-vision model was picked for the vision role
512
- if (scopeFilter && !hasImageInput(model as { input?: unknown })) {
513
- ctx.ui.notify(
514
- `[warn] ${model.id} does not support image input. Vision analysis may fail.`,
515
- "warning",
516
- );
517
- }
518
-
519
391
  done(model);
520
392
  };
521
393
  const onCancel = () => done(undefined as unknown);
@@ -561,8 +433,8 @@ async function openModelSelectorUI(
561
433
  if (!selectedModel) return;
562
434
 
563
435
  // Store the role-specific key only. Do NOT call pi.setModel() - that would change
564
- // the default model, which is NOT what we want for utility/vision role selection.
565
- // model-resolver.ts reads these custom keys and uses them directly.
436
+ // the default model, which is NOT what we want for utility role selection.
437
+ // model-resolver.ts reads this custom key and uses it directly.
566
438
  const pattern = `${selectedModel.provider}/${selectedModel.id}`;
567
439
  await setModelSetting(settingKey, pattern);
568
440
 
@@ -34,6 +34,7 @@
34
34
 
35
35
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
36
36
  import { Type } from "typebox";
37
+ import type { Static } from "typebox";
37
38
  import { createLogger } from "../../../lib/core/logger.js";
38
39
  import { getSkillsRankingMode } from "../../../lib/config/braid-settings.js";
39
40
  import type { SkillsRankingMode } from "../../../lib/config/braid-settings.js";
@@ -55,6 +56,7 @@ import {
55
56
  readSkillReach,
56
57
  } from "./reach.js";
57
58
  import { getMonthlyAdoptionRollup } from "./session-records.js";
59
+ import { checkArgumentValues } from "../../../lib/utils/argument-report.js";
58
60
 
59
61
  const log = createLogger("skills-tool");
60
62
 
@@ -252,6 +254,52 @@ function rowOf(row: RankedSkill): RowRelevance {
252
254
 
253
255
  // Extension factory:
254
256
 
257
+ /**
258
+ * `list_skills` arguments: one action, one page of the catalog.
259
+ *
260
+ * The action is named here rather than inferred, because a pager call and a
261
+ * full-catalog call are the same call and the schema is what the model reads
262
+ * before choosing. The tool fills it when the call omits it (`prepareArguments`
263
+ * below), so a bare pager call behaves as the listing it obviously is while an
264
+ * unknown action is still refused.
265
+ */
266
+ const listSkillsSchema = Type.Object({
267
+ action: Type.Literal("list", {
268
+ description:
269
+ "list = paginated catalog with per-skill reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections)",
270
+ }),
271
+ page: Type.Optional(
272
+ Type.Number({
273
+ minimum: 1,
274
+ default: 1,
275
+ description: "Page number for list (1-based)",
276
+ }),
277
+ ),
278
+ pageSize: Type.Optional(
279
+ Type.Number({
280
+ minimum: 1,
281
+ maximum: 50,
282
+ default: 10,
283
+ description: "Entries per page for list",
284
+ }),
285
+ ),
286
+ sectionsMax: Type.Optional(
287
+ Type.Number({
288
+ minimum: 0,
289
+ maximum: SECTIONS_MAX_LIMIT,
290
+ default: DEFAULT_SECTIONS_MAX,
291
+ description: "Headings reported per skill; 0 omits the section list and keeps sectionCount",
292
+ }),
293
+ ),
294
+ rank: Type.Optional(
295
+ Type.Union([Type.Literal("relevance"), Type.Literal("catalog")], {
296
+ default: "relevance",
297
+ description:
298
+ "relevance (default) = order by fit to the current task; catalog = the plain catalog order, with no ranking fields",
299
+ }),
300
+ ),
301
+ });
302
+
255
303
  export default function skillsToolExtension(pi: ExtensionAPI): void {
256
304
  registerAutoInject(pi);
257
305
 
@@ -260,43 +308,18 @@ export default function skillsToolExtension(pi: ExtensionAPI): void {
260
308
  label: "List Skills",
261
309
  description:
262
310
  "Discover skills on demand: paginated catalog (name, filePath, description, source) plus each skill's reach (reachable, lines, bytes, chars, estTokens, sectionCount, section headings with line numbers), so the price of a read is visible before the read. Rows are ordered by relevance to the current task; a row with match evidence carries relevance {score, reason}, and the response carries ranking {tier, basis, policy}. Pass rank: 'catalog' for the plain catalog order. `read` a SKILL.md to load it.",
263
- parameters: Type.Object({
264
- action: Type.Literal("list", {
265
- description:
266
- "list = paginated catalog with per-skill reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections)",
267
- }),
268
- page: Type.Optional(
269
- Type.Number({
270
- minimum: 1,
271
- default: 1,
272
- description: "Page number for list (1-based)",
273
- }),
274
- ),
275
- pageSize: Type.Optional(
276
- Type.Number({
277
- minimum: 1,
278
- maximum: 50,
279
- default: 10,
280
- description: "Entries per page for list",
281
- }),
282
- ),
283
- sectionsMax: Type.Optional(
284
- Type.Number({
285
- minimum: 0,
286
- maximum: SECTIONS_MAX_LIMIT,
287
- default: DEFAULT_SECTIONS_MAX,
288
- description:
289
- "Headings reported per skill; 0 omits the section list and keeps sectionCount",
290
- }),
291
- ),
292
- rank: Type.Optional(
293
- Type.Union([Type.Literal("relevance"), Type.Literal("catalog")], {
294
- default: "relevance",
295
- description:
296
- "relevance (default) = order by fit to the current task; catalog = the plain catalog order, with no ranking fields",
297
- }),
298
- ),
299
- }),
311
+ parameters: listSkillsSchema,
312
+ // Paging without an action is a listing call: fill the action the call
313
+ // implies before pi validates, and refuse a guessed value with the accepted
314
+ // one named. The schema above stays the only description of the contract.
315
+ prepareArguments: (args: unknown) => {
316
+ const prepared =
317
+ args && typeof args === "object" && (args as { action?: unknown }).action == null
318
+ ? { ...args, action: "list" }
319
+ : args;
320
+ checkArgumentValues("list_skills", listSkillsSchema, prepared);
321
+ return prepared as Static<typeof listSkillsSchema>;
322
+ },
300
323
  execute: async (_id, params, signal, _onUpdate, ctx) => {
301
324
  const page = (params.page as number) ?? 1;
302
325
  const pageSize = (params.pageSize as number) ?? 10;
@@ -52,7 +52,7 @@ allow sub-state modules to be tested in isolation.
52
52
 
53
53
  - **Wake (`triggerTurn: true`)**: enforcement-critical, turn-outcome,
54
54
  reasoning, metacognition, auto-recovery, analytics-degrade,
55
- threshold-exhausted, emergency-rotation, navigation-checkout, context-80%+,
55
+ threshold-exhausted, emergency-rotation, navigation-checkout,
56
56
  three-memory-reliability, compaction-retry errors.
57
57
  - **No wake**: everything else. The delivery class decides how the message
58
58
  reaches the run (see the delivery contract in `lib/utils/injection-tracker.ts`):
@@ -66,8 +66,45 @@ allow sub-state modules to be tested in isolation.
66
66
  API-error guidance. Memory/hint/SOP channels park - they provide context
67
67
  for the agent's natural flow.
68
68
 
69
+ The context line from `register-turn-end-hygiene.ts` is `deliverAs:
70
+ "nextTurn"`: it is queued for the next user prompt, never steered into the
71
+ run it describes. A steer at a turn boundary is what kept a
72
+ compaction-armed loop alive, and the line names the deadline (an armed
73
+ compaction fires when the run settles) rather than restating a percentage.
74
+
69
75
  See individual handler files in `handlers/` for the per-source policy.
70
76
 
77
+ ### Route-failure latch (wake demotion)
78
+
79
+ `session-health.ts` owns a second latch on the same turn-start question. A run
80
+ that ends on a provider error (`agent_end` with an assistant `stopReason:
81
+ "error"`) feeds `recordRouteFailure(ctx, category)` with the category its raw
82
+ error text classifies to; every category counts except `context_window` and
83
+ `abort`, which are not evidence about the route. The counter is read only by
84
+ `isRouteLatchOpen(ctx)` and `isTurnStartBlocked(ctx)`, so the three seams that
85
+ self-start a turn cannot disagree:
86
+
87
+ - the timer wake path already asks `isTurnStartBlocked` once per fire and
88
+ demotes through `deliverDemotedFire` (no scheduling change);
89
+ - watchdog escalations ask it once per bark and deliver `quietWhisper` while
90
+ the tg line still fires;
91
+ - an explicitly-waking whisper (`triggerTurn: true`) in `whisper.ts` is
92
+ demoted to the ordinary non-waking steer.
93
+
94
+ The last two ask the route-only half, `isRouteLatchOpen`, deliberately: neither
95
+ seam ever consulted the terminal breaker, and the off switch has to make this
96
+ change inert rather than partially active.
97
+
98
+ Release signals: any successful provider call (`recordLlmSuccess`), a clean
99
+ wake turn, a route change (`model_select`), an owner recovery
100
+ (`setSessionHealthMode "healthy"`) and a session start. While the latch stays
101
+ open the predicate still releases one self-started turn per
102
+ `braid.session.routeBreaker.floorMs` and restamps the clock, so a parked
103
+ session neither starves nor loops. `braid.session.routeBreaker.enabled =
104
+ false` makes every part of this inert. Fixtures:
105
+ `test/runtime/lib/test-route-latch.mjs` (the six design fixtures and the
106
+ off-switch control family).
107
+
71
108
  ## Over-correction gate setting
72
109
 
73
110
  | Setting | Default | Effect | Read cadence |
@@ -13,6 +13,8 @@ import { getState } from "../state.js";
13
13
  import { classify } from "../../../lib/ai/text-classifier.js";
14
14
  import { CRITICS } from "../../../lib/ai/critic-registry.js";
15
15
  import { errorTypeFallback } from "../../../lib/ai/critic-fallbacks.js";
16
+ import { classifyLlmError } from "../../../lib/errors/llm-error.js";
17
+ import { recordRouteFailure } from "../session-health.js";
16
18
 
17
19
  export function registerAgentEndApiErrorHandler(pi: ExtensionAPI): void {
18
20
  pi.on(AGENT_END, async (event: any, ctx: ExtensionContext) => {
@@ -32,6 +34,17 @@ export function registerAgentEndApiErrorHandler(pi: ExtensionAPI): void {
32
34
 
33
35
  getState(ctx).validationFailures++;
34
36
 
37
+ // Count the failure for the route-failure latch BEFORE the nudge cooldown
38
+ // below: the cooldown throttles the message, not the observation. A run
39
+ // that ends on a provider error is the only evidence the latch has, and
40
+ // the auxiliary calls classifyRetryError makes are excluded from it by
41
+ // design (they are what releases the latch, never what feeds it).
42
+ try {
43
+ recordRouteFailure(ctx, classifyLlmError(finalError).category);
44
+ } catch {
45
+ // A broken counter must never suppress the nudge.
46
+ }
47
+
35
48
  const now = Date.now();
36
49
  if (now - getState(ctx).lastNudgeTime < getState(ctx).nudgeCooldownMs) return;
37
50
  getState(ctx).lastNudgeTime = now;
@@ -63,6 +63,7 @@ import {
63
63
  contextNudgeCrossed,
64
64
  } from "../../../lib/detection/context-tiers.js";
65
65
  import {
66
+ describeUsage,
66
67
  measureLiveUsage,
67
68
  tokenArms,
68
69
  formatTokensK,
@@ -205,12 +206,14 @@ async function checkContextUsage(
205
206
  let usagePercent = 0;
206
207
  let usageTokens = 0;
207
208
  let usageWindow: number | undefined;
209
+ let usageProvenance: string | undefined;
208
210
  try {
209
211
  const live = measureLiveUsage(ctx);
210
212
  if (live) {
211
213
  usagePercent = live.percent;
212
214
  usageTokens = live.tokens;
213
215
  usageWindow = live.contextWindow;
216
+ usageProvenance = describeUsage(live);
214
217
  }
215
218
  } catch {
216
219
  /* live measurement unavailable - the skip below records it */
@@ -336,7 +339,7 @@ async function checkContextUsage(
336
339
  // token warning 0.45W, advisory 50%, warning 65%, critical 75%, compact
337
340
  // 80%. The strongest rung reached wins, so no token arm can shadow a
338
341
  // percent tier above it (see lib/detection/context-tiers.ts).
339
- const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow);
342
+ const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow, usageProvenance);
340
343
  if (nudge) {
341
344
  const lastFired = findContextNudgeRung(state.contextNudgeRung, usageWindow);
342
345
  if (state.contextNudgeSent) {
@@ -355,7 +358,10 @@ async function checkContextUsage(
355
358
  }
356
359
  state.contextNudgeSent = true;
357
360
  state.contextNudgeRung = nudge.id;
358
- sendEnforcementWhisper(pi, ctx, nudge.message);
361
+ // Queued for the next user prompt, never steered into the run: the line is
362
+ // advice about a run that may still dispatch, and a steer at this boundary
363
+ // is exactly the delivery that kept a compaction-armed loop alive.
364
+ sendEnforcementWhisper(pi, ctx, nudge.message, false, { deliverAs: "nextTurn" });
359
365
  }
360
366
  }
361
367