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.
- package/CHANGELOG.md +1077 -0
- package/README.md +61 -228
- package/TOOLS.md +12 -14
- package/build-info.json +4 -4
- package/dist/extensions/cognitive/metacognition/handlers/think.js +9 -0
- package/dist/extensions/core/polyfill/index.d.ts +3 -4
- package/dist/extensions/core/polyfill/index.js +34 -131
- package/dist/extensions/core/skills-tool/index.js +47 -26
- package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
- package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
- package/dist/extensions/enforcement/session-health.d.ts +52 -4
- package/dist/extensions/enforcement/session-health.js +75 -5
- package/dist/extensions/enforcement/whisper.js +15 -1
- package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
- package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
- package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
- package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
- package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
- package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
- package/dist/extensions/manifest.js +6 -0
- package/dist/extensions/memory/context-lifecycle/index.js +11 -10
- package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
- package/dist/extensions/memory/context-manager/analysis.js +6 -2
- package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
- package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
- package/dist/extensions/self/path-miss/detect.d.ts +30 -0
- package/dist/extensions/self/path-miss/detect.js +67 -0
- package/dist/extensions/self/path-miss/index.d.ts +33 -0
- package/dist/extensions/self/path-miss/index.js +118 -0
- package/dist/extensions/self/watchdog/engine.d.ts +8 -1
- package/dist/extensions/self/watchdog/engine.js +25 -2
- package/dist/extensions/self/watchdog/index.js +14 -1
- package/dist/lib/ai/llm-call.js +23 -0
- package/dist/lib/ai/model-resolver.d.ts +11 -10
- package/dist/lib/ai/model-resolver.js +16 -19
- package/dist/lib/ai/presend-budget.d.ts +68 -0
- package/dist/lib/ai/presend-budget.js +83 -0
- package/dist/lib/config/braid-settings.d.ts +38 -0
- package/dist/lib/config/braid-settings.js +84 -0
- package/dist/lib/config/per-tool-settings.d.ts +4 -4
- package/dist/lib/config/per-tool-settings.js +4 -4
- package/dist/lib/core/event-names.d.ts +1 -0
- package/dist/lib/core/event-names.js +1 -0
- package/dist/lib/detection/context-tiers.d.ts +18 -5
- package/dist/lib/detection/context-tiers.js +51 -33
- package/dist/lib/detection/context-usage.d.ts +62 -1
- package/dist/lib/detection/context-usage.js +158 -1
- package/dist/lib/errors/llm-error.d.ts +14 -0
- package/dist/lib/errors/llm-error.js +44 -1
- package/dist/lib/state/global-state.d.ts +4 -8
- package/dist/lib/state/global-state.js +11 -28
- package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
- package/dist/lib/telemetry/context-heartbeat.js +18 -8
- package/dist/lib/utils/argument-report.d.ts +41 -0
- package/dist/lib/utils/argument-report.js +95 -0
- package/dist/lib/utils/wake-gate.d.ts +6 -0
- package/dist/lib/utils/wake-gate.js +52 -4
- package/docs/SETUP.md +7 -6
- package/package.json +11 -13
- package/src/extensions/cognitive/metacognition/handlers/think.ts +9 -0
- package/src/extensions/core/polyfill/index.ts +29 -157
- package/src/extensions/core/skills-tool/index.ts +60 -37
- package/src/extensions/enforcement/AGENTS.md +38 -1
- package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
- package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
- package/src/extensions/enforcement/session-health.ts +94 -5
- package/src/extensions/enforcement/whisper.ts +15 -1
- package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
- package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
- package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
- package/src/extensions/manifest.ts +6 -0
- package/src/extensions/memory/AGENTS.md +37 -38
- package/src/extensions/memory/context-lifecycle/index.ts +11 -10
- package/src/extensions/memory/context-manager/analysis.ts +8 -1
- package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
- package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
- package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
- package/src/extensions/scheduling/timer/AGENTS.md +14 -4
- package/src/extensions/self/AGENTS.md +2 -1
- package/src/extensions/self/path-miss/AGENTS.md +39 -0
- package/src/extensions/self/path-miss/detect.ts +78 -0
- package/src/extensions/self/path-miss/index.ts +135 -0
- package/src/extensions/self/watchdog/AGENTS.md +36 -18
- package/src/extensions/self/watchdog/engine.ts +30 -2
- package/src/extensions/self/watchdog/index.ts +13 -1
- package/src/lib/ai/AGENTS.md +2 -0
- package/src/lib/ai/llm-call.ts +30 -0
- package/src/lib/ai/model-resolver.ts +16 -19
- package/src/lib/ai/presend-budget.ts +117 -0
- package/src/lib/config/braid-settings.ts +125 -0
- package/src/lib/config/per-tool-settings.ts +4 -4
- package/src/lib/core/event-names.ts +1 -0
- package/src/lib/detection/context-tiers.ts +52 -41
- package/src/lib/detection/context-usage.ts +211 -2
- package/src/lib/errors/llm-error.ts +55 -1
- package/src/lib/state/global-state.ts +11 -29
- package/src/lib/telemetry/context-heartbeat.ts +27 -7
- package/src/lib/utils/AGENTS.md +1 -0
- package/src/lib/utils/argument-report.ts +105 -0
- package/src/lib/utils/wake-gate.ts +59 -4
|
@@ -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
|
|
@@ -32,7 +32,7 @@ import { getSessionIdSafe } from "../../../lib/state/extension-state.js";
|
|
|
32
32
|
import { deriveProjectIdFromCwd } from "../../../lib/memory/past-insights.js";
|
|
33
33
|
import { shouldWriteOutcomeEpisode } from "../../../lib/memory/write-quality.js";
|
|
34
34
|
import { getMemoryWriteGateConfig } from "../../../lib/config/braid-settings.js";
|
|
35
|
-
import {
|
|
35
|
+
import { nowOrOverride } from "../../../lib/utils/local-time.js";
|
|
36
36
|
/** Derive a short project id from the current working directory. */
|
|
37
37
|
function deriveProject(ctx) {
|
|
38
38
|
return typeof ctx.cwd === "string" ? deriveProjectIdFromCwd(ctx.cwd) : "unknown";
|
|
@@ -96,7 +96,12 @@ const _heartbeatWhisperBuffer = new Map();
|
|
|
96
96
|
// lastWriteAt is owned here (module scope, survives across sessions within the
|
|
97
97
|
// process) so the cooldown actually throttles back-to-back session ends.
|
|
98
98
|
let _lastOutcomeWriteAt = 0;
|
|
99
|
-
|
|
99
|
+
/**
|
|
100
|
+
* Buffer one whisper for the next delivery. Exported because it and
|
|
101
|
+
* flushDelayedWhispers are the delivery boundary a fixture must drive to
|
|
102
|
+
* assert on the text that ships (the same pair before_agent_start calls).
|
|
103
|
+
*/
|
|
104
|
+
export function bufferHeartbeatWhisper(sessionId, message, priority, source, family) {
|
|
100
105
|
let buffer = _heartbeatWhisperBuffer.get(sessionId);
|
|
101
106
|
if (!buffer) {
|
|
102
107
|
buffer = [];
|
|
@@ -106,70 +111,27 @@ function bufferHeartbeatWhisper(sessionId, message, priority, source) {
|
|
|
106
111
|
// ticks can pile up while the session is idle (no before_agent_start to
|
|
107
112
|
// flush). Cap at 100 entries per session, drop-oldest — stale heartbeat
|
|
108
113
|
// messages past 100 are noise by definition.
|
|
109
|
-
pushBounded(buffer, { message, priority, source }, 100);
|
|
114
|
+
pushBounded(buffer, { message, priority, source, family }, 100);
|
|
110
115
|
}
|
|
111
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Drain the delayed buffer as one delivery per priority tier.
|
|
118
|
+
*
|
|
119
|
+
* The sample is taken here, at delivery, and is the only source of the
|
|
120
|
+
* numbers and of the tier the context family is re-labelled with: a family
|
|
121
|
+
* rendered from an older reading is what printed a label beside numbers it
|
|
122
|
+
* never measured.
|
|
123
|
+
*/
|
|
124
|
+
export function flushDelayedWhispers(sessionId, pi, sample) {
|
|
112
125
|
const buffer = _heartbeatWhisperBuffer.get(sessionId);
|
|
113
126
|
if (!buffer || buffer.length === 0)
|
|
114
127
|
return;
|
|
115
128
|
const batch = buffer.splice(0);
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
// Context percentage messages: "Context at 40%. context_tag..."
|
|
123
|
-
if (/^Context at \d+%/.test(message))
|
|
124
|
-
return "context-percentage";
|
|
125
|
-
// Duplicate count messages: "39 near-duplicate messages..."
|
|
126
|
-
if (/^\d+ near-duplicate messages/.test(message))
|
|
127
|
-
return "duplicate-count";
|
|
128
|
-
// Context density messages
|
|
129
|
-
if (/^Low context density/.test(message))
|
|
130
|
-
return "density-low";
|
|
131
|
-
if (/^High density/.test(message))
|
|
132
|
-
return "density-high";
|
|
133
|
-
if (/^Context density still low/.test(message))
|
|
134
|
-
return "density-low-persistent";
|
|
135
|
-
// Proactive projection messages
|
|
136
|
-
if (/^\[proactive\]/.test(message))
|
|
137
|
-
return "proactive-projection";
|
|
138
|
-
// Degradation messages
|
|
139
|
-
if (/^Degradation detected/.test(message))
|
|
140
|
-
return "degradation";
|
|
141
|
-
// Fallback: use first 80 chars
|
|
142
|
-
return message.slice(0, 80);
|
|
143
|
-
}
|
|
144
|
-
const deduped = [];
|
|
145
|
-
const seen = new Set();
|
|
146
|
-
for (const entry of batch) {
|
|
147
|
-
const key = dedupKey(entry.message);
|
|
148
|
-
if (seen.has(key))
|
|
149
|
-
continue;
|
|
150
|
-
seen.add(key);
|
|
151
|
-
deduped.push({ message: entry.message, priority: entry.priority });
|
|
152
|
-
}
|
|
153
|
-
// Aggregate by priority tier
|
|
154
|
-
const groups = new Map();
|
|
155
|
-
for (const entry of deduped) {
|
|
156
|
-
const p = entry.priority;
|
|
157
|
-
if (!groups.has(p))
|
|
158
|
-
groups.set(p, []);
|
|
159
|
-
groups.get(p).push(entry.message);
|
|
160
|
-
}
|
|
161
|
-
for (const [, messages] of groups) {
|
|
162
|
-
// Fresh clock: every Heartbeat Summary carries a `now:` line (date +
|
|
163
|
-
// owner-TZ time via the ONE formatter) so a long session never reasons on
|
|
164
|
-
// a stale clock — the heartbeat is the only mid-session channel guaranteed
|
|
165
|
-
// to re-fire. One context-health line follows the clock (tokens /
|
|
166
|
-
// cache-hit / near-dups / tok-s trend), so every heartbeat delivery is
|
|
167
|
-
// also a self-state checkpoint.
|
|
168
|
-
const nowLine = `now: ${formatLocalTime(new Date(), true)}`;
|
|
169
|
-
const selfStateSuffix = selfState ? `\n${selfState}` : "";
|
|
170
|
-
const text = messages.length === 1
|
|
171
|
-
? `${nowLine}${selfStateSuffix}\n${messages[0]}`
|
|
172
|
-
: `[Heartbeat Summary]\n${nowLine}${selfStateSuffix}\n${messages.map((m, i) => `${i + 1}. ${m}`).join("\n")}`;
|
|
129
|
+
const deliveries = renderDelayedDelivery(batch, {
|
|
130
|
+
at: nowOrOverride(),
|
|
131
|
+
contextPercent: sample?.contextPercent ?? null,
|
|
132
|
+
selfState: buildSelfStateLine(sample),
|
|
133
|
+
});
|
|
134
|
+
for (const text of deliveries) {
|
|
173
135
|
try {
|
|
174
136
|
sendTrackedMessage(pi, {
|
|
175
137
|
customType: "heartbeat",
|
|
@@ -216,13 +178,14 @@ export function sendSopCoachWhisper(pi, message) {
|
|
|
216
178
|
}, { delivery: "park", deliverAs: "steer" }, { type: "context", source: "heartbeat/sop-coach" });
|
|
217
179
|
}
|
|
218
180
|
// Whisper Batching
|
|
219
|
-
// flushWhisperBuffer
|
|
220
|
-
//
|
|
221
|
-
|
|
222
|
-
|
|
181
|
+
// flushWhisperBuffer and the delayed-delivery renderer live in
|
|
182
|
+
// ./whisper-batcher.ts. This file owns the buffer and the send channel; the
|
|
183
|
+
// batcher owns the text, so the shipped delivery and the tested delivery are
|
|
184
|
+
// the same function.
|
|
185
|
+
import { flushWhisperBuffer, buildSelfStateLine, renderDelayedDelivery, } from "./whisper-batcher.js";
|
|
223
186
|
import { getSelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
|
|
224
187
|
// Tick Engine
|
|
225
|
-
function tick(pi, state, config, ctx
|
|
188
|
+
function tick(pi, state, config, ctx) {
|
|
226
189
|
state.stats.totalTicks++;
|
|
227
190
|
// Real telemetry: collect live context/RSS/session metrics, append the
|
|
228
191
|
// JSONL heartbeat line, and feed recordTurnMetrics real values (not
|
|
@@ -296,7 +259,7 @@ function tick(pi, state, config, ctx, turnEvent) {
|
|
|
296
259
|
log.warn(`[heartbeat] pending-compaction advisory failed: ${err}`);
|
|
297
260
|
}
|
|
298
261
|
try {
|
|
299
|
-
maybeArmAutoCompaction(pi, ctx
|
|
262
|
+
maybeArmAutoCompaction(pi, ctx);
|
|
300
263
|
}
|
|
301
264
|
catch (err) {
|
|
302
265
|
log.warn(`[heartbeat] context auto-arm check failed: ${err}`);
|
|
@@ -496,12 +459,9 @@ export default function heartbeatExtension(pi) {
|
|
|
496
459
|
const interval = getAdaptiveInterval(state);
|
|
497
460
|
if (state.turnCount % interval !== 0)
|
|
498
461
|
return;
|
|
499
|
-
// The
|
|
500
|
-
//
|
|
501
|
-
|
|
502
|
-
// fixture, so one drives the real handler end to end:
|
|
503
|
-
// test/runtime/heartbeat/test-turn-boundary-arm-wiring.mjs.
|
|
504
|
-
tick(pi, state, config, ctx, event);
|
|
462
|
+
// The tick arms the usage-driven auto compaction on its own cadence. The
|
|
463
|
+
// arm only queues; the queue drains at settle (or the 0.90W backstop).
|
|
464
|
+
tick(pi, state, config, ctx);
|
|
505
465
|
});
|
|
506
466
|
// Event: before_agent_start - flush delayed whispers
|
|
507
467
|
// Deliver buffered heartbeat whispers as part of the turn context,
|
|
@@ -519,9 +479,11 @@ export default function heartbeatExtension(pi) {
|
|
|
519
479
|
if (typeof prompt === "string" && prompt.length > 0) {
|
|
520
480
|
getTurnStartPrompt(ctx).prompt = prompt;
|
|
521
481
|
}
|
|
522
|
-
//
|
|
523
|
-
//
|
|
524
|
-
|
|
482
|
+
// The sample is taken here, at delivery: the self-state line and the
|
|
483
|
+
// context family's arm are both rendered from it, so one delivery never
|
|
484
|
+
// prints two ages of one fact. Sampling never throws; missing telemetry
|
|
485
|
+
// renders "n/a".
|
|
486
|
+
flushDelayedWhispers(sid, pi, getSelfStateSample(ctx));
|
|
525
487
|
});
|
|
526
488
|
// Event: tool_call
|
|
527
489
|
pi.on(TOOL_CALL, async (event, ctx) => {
|
|
@@ -644,9 +606,9 @@ export default function heartbeatExtension(pi) {
|
|
|
644
606
|
// (below) still delivers immediately because it uses
|
|
645
607
|
// deliverAs:"steer" and is time-critical (at ≥90% context the
|
|
646
608
|
// whisper may never get a next turn — steer it into the current run).
|
|
647
|
-
(msg) => {
|
|
609
|
+
(msg, family) => {
|
|
648
610
|
const sid = getSessionIdSafe(ctx) ?? "anonymous";
|
|
649
|
-
bufferHeartbeatWhisper(sid, msg, "medium", "heartbeat/policy");
|
|
611
|
+
bufferHeartbeatWhisper(sid, msg, "medium", "heartbeat/policy", family);
|
|
650
612
|
}, (msg) => {
|
|
651
613
|
sendTrackedMessage(pi, {
|
|
652
614
|
customType: "heartbeat",
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { Policy } from "../../../lib/store/belief-store.js";
|
|
9
9
|
import type { ToolTracking } from "./types.js";
|
|
10
|
+
import type { WhisperFamily } from "./whisper-batcher.js";
|
|
10
11
|
export declare const VERIFICATION_TOOLS: Set<string>;
|
|
11
12
|
export declare const WEB_TOOLS: Set<string>;
|
|
12
13
|
export declare const CODE_TOOLS: Set<string>;
|
|
@@ -17,5 +18,5 @@ export declare function bashCommandIsVerification(command: string): boolean;
|
|
|
17
18
|
* bash by the command's shape. Every other tool is not verification.
|
|
18
19
|
*/
|
|
19
20
|
export declare function isVerificationToolCall(toolName: string, input: unknown): boolean;
|
|
20
|
-
export declare function createDefaultPolicies(getToolTracking: () => ToolTracking, onSignal: (type: string, data: Record<string, unknown>) => void, sendWhisper: (msg: string) => void, sendSteerMessage: (msg: string) => void): Policy[];
|
|
21
|
+
export declare function createDefaultPolicies(getToolTracking: () => ToolTracking, onSignal: (type: string, data: Record<string, unknown>) => void, sendWhisper: (msg: string, family?: WhisperFamily) => void, sendSteerMessage: (msg: string) => void): Policy[];
|
|
21
22
|
//# sourceMappingURL=policies.d.ts.map
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* and proactive context monitoring with auto-finalize at 90%.
|
|
7
7
|
*/
|
|
8
8
|
import { createLogger } from "../../../lib/core/logger.js";
|
|
9
|
-
import {
|
|
10
|
-
import { CONTEXT_USAGE_TIERS, getContextUsage, } from "../../../lib/detection/context-tiers.js";
|
|
9
|
+
import { USAGE_WHISPER_CRITICAL, USAGE_FIRED_RESET_BELOW, } from "../../../lib/detection/context-thresholds.js";
|
|
10
|
+
import { CONTEXT_USAGE_TIERS, contextUsageTierMessage, getContextUsage, } from "../../../lib/detection/context-tiers.js";
|
|
11
11
|
const log = createLogger("heartbeat:policies");
|
|
12
12
|
/**
|
|
13
13
|
* Persist fired threshold set across invocations so the context-monitor
|
|
@@ -413,9 +413,10 @@ export function createDefaultPolicies(getToolTracking, onSignal, sendWhisper, se
|
|
|
413
413
|
return turnsSince >= 10 && t.totalToolsUsed > 3;
|
|
414
414
|
},
|
|
415
415
|
action: async (ctx) => {
|
|
416
|
+
// One instruction, not a menu. The agent does not need to be asked
|
|
417
|
+
// whether it is sure; it needs the step that would settle it.
|
|
416
418
|
sendWhisper("No verification (grep/read/search) in 10+ turns. " +
|
|
417
|
-
"
|
|
418
|
-
"Verify with grep or read to confirm.");
|
|
419
|
+
"Verify with grep or read before continuing.");
|
|
419
420
|
onSignal("verification_reminder", {
|
|
420
421
|
turn: ctx.turnNumber,
|
|
421
422
|
turnsSinceVerification: ctx.turnNumber - getToolTracking().lastVerificationTurn,
|
|
@@ -480,35 +481,32 @@ export function createDefaultPolicies(getToolTracking, onSignal, sendWhisper, se
|
|
|
480
481
|
// subset). Values are always present per the wiring (heartbeat-scheduler
|
|
481
482
|
// index.ts), so these defaults never fire — preserved from the original
|
|
482
483
|
// required-typed destructure.
|
|
483
|
-
const { percent = 0
|
|
484
|
+
const { percent = 0 } = usage;
|
|
484
485
|
if (percent < USAGE_FIRED_RESET_BELOW && _firedThresholds.size > 0) {
|
|
485
486
|
_firedThresholds.clear();
|
|
486
487
|
}
|
|
487
|
-
// Threshold ladder: soft -> advisory -> warning -> critical
|
|
488
|
-
//
|
|
489
|
-
//
|
|
490
|
-
//
|
|
491
|
-
//
|
|
492
|
-
//
|
|
493
|
-
//
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
warning: `Context at ${USAGE_WHISPER_WARNING}%. Deep compaction: tag + archive now. Pipeline: context_navigate(action="tag") -> context_compress(action="archive") -> compact if needed.`,
|
|
498
|
-
critical: `CRITICAL: Context at ${USAGE_WHISPER_CRITICAL}%. FORCE IMMEDIATE HYGIENE. Pipeline: context_navigate(action="tag") -> context_compress(action="archive") -> context_compress(action="slide"). Do not continue work until done.`,
|
|
499
|
-
};
|
|
488
|
+
// Threshold ladder: soft -> advisory -> warning -> critical, each
|
|
489
|
+
// firing ONCE until usage resets below USAGE_FIRED_RESET_BELOW.
|
|
490
|
+
//
|
|
491
|
+
// A rung decides WHETHER a whisper fires; it is never what the
|
|
492
|
+
// whisper prints. A threshold is a configuration value, and a delivery
|
|
493
|
+
// that prints it puts a number where a reader expects a reading. The
|
|
494
|
+
// wording lives with the meter in lib/detection/context-tiers.ts (one
|
|
495
|
+
// owner for both the enforcement ladder and this one), and the number
|
|
496
|
+
// the reader acts on is the measurement sampled at delivery, carrying
|
|
497
|
+
// its own provenance word.
|
|
500
498
|
const thresholds = CONTEXT_USAGE_TIERS.filter((t) => t.tier !== "compact")
|
|
501
499
|
.slice()
|
|
502
|
-
.reverse()
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
sendSteerMessage(
|
|
500
|
+
.reverse();
|
|
501
|
+
for (const { tier, threshold } of thresholds) {
|
|
502
|
+
if (percent >= threshold && !_firedThresholds.has(threshold)) {
|
|
503
|
+
_firedThresholds.add(threshold);
|
|
504
|
+
// The family marker lets the batcher re-render this instruction
|
|
505
|
+
// from the measurement taken at delivery, so the arm named here and
|
|
506
|
+
// the percent printed beside it are one snapshot.
|
|
507
|
+
sendWhisper(contextUsageTierMessage(tier), "context-tier");
|
|
508
|
+
if (threshold === USAGE_WHISPER_CRITICAL) {
|
|
509
|
+
sendSteerMessage(contextUsageTierMessage("critical"));
|
|
512
510
|
log.warn(`Auto-finalize triggered at ${USAGE_WHISPER_CRITICAL}%`);
|
|
513
511
|
}
|
|
514
512
|
break;
|
|
@@ -1,52 +1,83 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Whisper batcher
|
|
2
|
+
* Whisper batcher: the ONE place the shape of a heartbeat delivery is built.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* Two buffers feed it. The tick batcher collects module whispers and flushes
|
|
5
|
+
* them once per tick; the delayed buffer collects policy whispers and flushes
|
|
6
|
+
* them on the next before_agent_start. Both deliver the same shape: one
|
|
7
|
+
* clock line, one self-state line, numbered bodies. The shape has one
|
|
8
|
+
* owner here instead of a copy per flush site.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* Two rules make the delivered text trustworthy, and each is enforced by the
|
|
11
|
+
* way this module is written rather than by the emitter remembering it:
|
|
12
|
+
*
|
|
13
|
+
* 1. One snapshot per delivery. The clock comes from the seam, and a
|
|
14
|
+
* family that renders a measurement is re-rendered from the sample
|
|
15
|
+
* taken at delivery, so a label cannot outlive the number beside it.
|
|
16
|
+
* 2. Last arrival wins in a collapse. Keeping the first arrival per
|
|
17
|
+
* family is what printed the oldest label beside the newest numbers:
|
|
18
|
+
* the newest instruction is the only one whose advice can still apply.
|
|
13
19
|
*/
|
|
14
20
|
import type { SelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
|
|
21
|
+
/**
|
|
22
|
+
* Families whose body is a rendering of a live measurement. The emitter
|
|
23
|
+
* declares the family so the batcher can re-render it from the delivery
|
|
24
|
+
* sample; a family sniffed from the prose silently stops collapsing the day
|
|
25
|
+
* the prose changes.
|
|
26
|
+
*/
|
|
27
|
+
export type WhisperFamily = "context-tier";
|
|
15
28
|
export interface WhisperBufferEntry {
|
|
16
29
|
message: string;
|
|
17
30
|
priority: string;
|
|
31
|
+
/** Set by the emitter for a family the batcher must own at delivery. */
|
|
32
|
+
family?: WhisperFamily;
|
|
18
33
|
}
|
|
19
34
|
export type WhisperSendFn = (msg: string, opts?: {
|
|
20
35
|
category?: string;
|
|
21
36
|
priority?: string;
|
|
22
37
|
}) => void;
|
|
23
38
|
/**
|
|
24
|
-
* Self-state line
|
|
25
|
-
* summary makes the agent self-aware of its own context health. ONE line,
|
|
26
|
-
* <= 40 tokens, appended to every heartbeat summary:
|
|
39
|
+
* Self-state line: ONE line, appended to every heartbeat delivery.
|
|
27
40
|
*
|
|
28
|
-
* self-state: ctx
|
|
41
|
+
* self-state: ctx 413K tok (41.3% measured)
|
|
29
42
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
43
|
+
* The count and the percent are one meter reading from one snapshot, and the
|
|
44
|
+
* provenance word is the meter's own (context-usage describeUsage), so the two
|
|
45
|
+
* cannot disagree and a reader can tell a large context from a badly counted
|
|
46
|
+
* one. A percent whose provenance is missing is not rendered at all: an
|
|
47
|
+
* unlabelled percentage is the class that cost a session its window.
|
|
48
|
+
*
|
|
49
|
+
* Metrics this line no longer carries (cache-hit share, near-duplicate count,
|
|
50
|
+
* tok/s trend, hygiene acts) name no action at the moment they are read. They
|
|
51
|
+
* stay in the telemetry JSONL and in the tools an agent calls while
|
|
52
|
+
* diagnosing, where a reader has already decided to look. An unavailable
|
|
53
|
+
* metric renders "n/a", never zero: a zero looks like a healthy reading.
|
|
32
54
|
*/
|
|
33
55
|
export declare function buildSelfStateLine(sample: Partial<SelfStateSample> | null | undefined): string;
|
|
56
|
+
export interface DeliveryRenderOptions {
|
|
57
|
+
/** Self-state line, rendered from the same sample as the rest of the delivery. */
|
|
58
|
+
selfState?: string;
|
|
59
|
+
/** Clock instant for the `now:` line; the clock seam applies when omitted. */
|
|
60
|
+
at?: Date;
|
|
61
|
+
}
|
|
34
62
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
63
|
+
* Render one batched delivery. The clock is read through the seam the envelope
|
|
64
|
+
* formatter uses, never from a fresh `Date` at flush time: a delivery that was
|
|
65
|
+
* delayed must not claim an instant it never observed.
|
|
66
|
+
*/
|
|
67
|
+
export declare function renderHeartbeatDelivery(bodies: readonly string[], opts?: DeliveryRenderOptions): string;
|
|
68
|
+
/**
|
|
69
|
+
* Flush the tick buffer: group by priority tier, render one delivery per tier.
|
|
70
|
+
* Self-state (when a sample was taken) lands right after the clock line, so
|
|
71
|
+
* every heartbeat summary is also a self-state checkpoint.
|
|
72
|
+
*/
|
|
73
|
+
export declare function flushWhisperBuffer(buffer: WhisperBufferEntry[], send: WhisperSendFn | undefined, selfState?: string, at?: Date): void;
|
|
74
|
+
export interface DelayedRenderOptions extends DeliveryRenderOptions {
|
|
75
|
+
/** Context percent measured at delivery, or null when nothing was measured. */
|
|
76
|
+
contextPercent?: number | null;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Collapse the delayed buffer and render its deliveries: last arrival wins per
|
|
80
|
+
* key, then one delivery per priority tier.
|
|
50
81
|
*/
|
|
51
|
-
export declare function
|
|
82
|
+
export declare function renderDelayedDelivery(batch: readonly WhisperBufferEntry[], opts?: DelayedRenderOptions): string[];
|
|
52
83
|
//# sourceMappingURL=whisper-batcher.d.ts.map
|