pi-braid 0.42.1 → 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 +71 -0
- package/README.md +61 -228
- package/TOOLS.md +12 -14
- package/build-info.json +4 -4
- package/dist/extensions/core/polyfill/index.d.ts +3 -4
- package/dist/extensions/core/polyfill/index.js +34 -131
- 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/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/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/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/wake-gate.d.ts +6 -0
- package/dist/lib/utils/wake-gate.js +52 -4
- package/docs/SETUP.md +7 -6
- package/package.json +8 -11
- package/src/extensions/core/polyfill/index.ts +29 -157
- 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/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/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/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/wake-gate.ts +59 -4
|
@@ -1,24 +1,41 @@
|
|
|
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
|
|
|
15
|
-
import { formatLocalTime } from "../../../lib/utils/local-time.js";
|
|
21
|
+
import { formatLocalTime, nowOrOverride } from "../../../lib/utils/local-time.js";
|
|
16
22
|
import { formatTokensK } from "../../../lib/detection/context-usage.js";
|
|
23
|
+
import { contextUsageTier, contextUsageTierMessage } from "../../../lib/detection/context-tiers.js";
|
|
17
24
|
import type { SelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
|
|
18
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Families whose body is a rendering of a live measurement. The emitter
|
|
28
|
+
* declares the family so the batcher can re-render it from the delivery
|
|
29
|
+
* sample; a family sniffed from the prose silently stops collapsing the day
|
|
30
|
+
* the prose changes.
|
|
31
|
+
*/
|
|
32
|
+
export type WhisperFamily = "context-tier";
|
|
33
|
+
|
|
19
34
|
export interface WhisperBufferEntry {
|
|
20
35
|
message: string;
|
|
21
36
|
priority: string;
|
|
37
|
+
/** Set by the emitter for a family the batcher must own at delivery. */
|
|
38
|
+
family?: WhisperFamily;
|
|
22
39
|
}
|
|
23
40
|
|
|
24
41
|
export type WhisperSendFn = (msg: string, opts?: { category?: string; priority?: string }) => void;
|
|
@@ -29,70 +46,155 @@ function renderTokensK(tokens: number): string {
|
|
|
29
46
|
}
|
|
30
47
|
|
|
31
48
|
/**
|
|
32
|
-
* Self-state line
|
|
33
|
-
*
|
|
34
|
-
*
|
|
49
|
+
* Self-state line: ONE line, appended to every heartbeat delivery.
|
|
50
|
+
*
|
|
51
|
+
* self-state: ctx 413K tok (41.3% measured)
|
|
35
52
|
*
|
|
36
|
-
*
|
|
53
|
+
* The count and the percent are one meter reading from one snapshot, and the
|
|
54
|
+
* provenance word is the meter's own (context-usage describeUsage), so the two
|
|
55
|
+
* cannot disagree and a reader can tell a large context from a badly counted
|
|
56
|
+
* one. A percent whose provenance is missing is not rendered at all: an
|
|
57
|
+
* unlabelled percentage is the class that cost a session its window.
|
|
37
58
|
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
59
|
+
* Metrics this line no longer carries (cache-hit share, near-duplicate count,
|
|
60
|
+
* tok/s trend, hygiene acts) name no action at the moment they are read. They
|
|
61
|
+
* stay in the telemetry JSONL and in the tools an agent calls while
|
|
62
|
+
* diagnosing, where a reader has already decided to look. An unavailable
|
|
63
|
+
* metric renders "n/a", never zero: a zero looks like a healthy reading.
|
|
40
64
|
*/
|
|
41
65
|
export function buildSelfStateLine(sample: Partial<SelfStateSample> | null | undefined): string {
|
|
42
66
|
const s = sample ?? {};
|
|
43
67
|
const ctxTok =
|
|
44
68
|
typeof s.contextTokens === "number" ? `${renderTokensK(s.contextTokens)} tok` : "n/a";
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
69
|
+
const percent =
|
|
70
|
+
typeof s.contextPercent === "number" &&
|
|
71
|
+
typeof s.contextProvenance === "string" &&
|
|
72
|
+
s.contextProvenance.length > 0
|
|
73
|
+
? ` (${s.contextPercent.toFixed(1)}% ${s.contextProvenance})`
|
|
74
|
+
: "";
|
|
75
|
+
return `self-state: ctx ${ctxTok}${percent}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface DeliveryRenderOptions {
|
|
79
|
+
/** Self-state line, rendered from the same sample as the rest of the delivery. */
|
|
80
|
+
selfState?: string;
|
|
81
|
+
/** Clock instant for the `now:` line; the clock seam applies when omitted. */
|
|
82
|
+
at?: Date;
|
|
51
83
|
}
|
|
52
84
|
|
|
53
85
|
/**
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
86
|
+
* Render one batched delivery. The clock is read through the seam the envelope
|
|
87
|
+
* formatter uses, never from a fresh `Date` at flush time: a delivery that was
|
|
88
|
+
* delayed must not claim an instant it never observed.
|
|
89
|
+
*/
|
|
90
|
+
export function renderHeartbeatDelivery(
|
|
91
|
+
bodies: readonly string[],
|
|
92
|
+
opts: DeliveryRenderOptions = {},
|
|
93
|
+
): string {
|
|
94
|
+
const nowLine = `now: ${formatLocalTime(opts.at ?? nowOrOverride(), true)}`;
|
|
95
|
+
const selfStateSuffix = opts.selfState ? `\n${opts.selfState}` : "";
|
|
96
|
+
const head = `${nowLine}${selfStateSuffix}`;
|
|
97
|
+
if (bodies.length === 1) return `${head}\n${bodies[0]}`;
|
|
98
|
+
return `[Heartbeat Summary]\n${head}\n${bodies.map((m, i) => `${i + 1}. ${m}`).join("\n")}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Flush the tick buffer: group by priority tier, render one delivery per tier.
|
|
103
|
+
* Self-state (when a sample was taken) lands right after the clock line, so
|
|
104
|
+
* every heartbeat summary is also a self-state checkpoint.
|
|
69
105
|
*/
|
|
70
106
|
export function flushWhisperBuffer(
|
|
71
107
|
buffer: WhisperBufferEntry[],
|
|
72
108
|
send: WhisperSendFn | undefined,
|
|
73
109
|
selfState?: string,
|
|
110
|
+
at?: Date,
|
|
74
111
|
): void {
|
|
75
112
|
if (buffer.length === 0 || !send) return;
|
|
76
113
|
|
|
77
114
|
const groups = new Map<string, string[]>();
|
|
78
115
|
for (const entry of buffer) {
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
groups.
|
|
116
|
+
const group = groups.get(entry.priority) ?? [];
|
|
117
|
+
group.push(entry.message);
|
|
118
|
+
groups.set(entry.priority, group);
|
|
82
119
|
}
|
|
83
120
|
|
|
84
|
-
// Flush one message per priority tier
|
|
85
121
|
for (const [priority, messages] of groups) {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
category: "cognitive",
|
|
91
|
-
priority: priority,
|
|
92
|
-
});
|
|
93
|
-
} else {
|
|
94
|
-
const combined = `[Heartbeat Summary]\n${nowLine}${selfStateSuffix}\n${messages.map((m, i) => `${i + 1}. ${m}`).join("\n")}`;
|
|
95
|
-
send(combined, { category: "cognitive", priority: priority });
|
|
96
|
-
}
|
|
122
|
+
send(renderHeartbeatDelivery(messages, { selfState, at }), {
|
|
123
|
+
category: "cognitive",
|
|
124
|
+
priority,
|
|
125
|
+
});
|
|
97
126
|
}
|
|
98
127
|
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Collapse key for the delayed buffer. A declared family is its own key (the
|
|
131
|
+
* emitter knows what it measured). The prose rules below cover emitters that
|
|
132
|
+
* still describe themselves by their first line: each one is a coupling, so a
|
|
133
|
+
* copy change there must come with a look at this list.
|
|
134
|
+
*/
|
|
135
|
+
function dedupKey(entry: WhisperBufferEntry): string {
|
|
136
|
+
if (entry.family) return `family:${entry.family}`;
|
|
137
|
+
const message = entry.message;
|
|
138
|
+
// Duplicate count messages: "39 near-duplicate messages..."
|
|
139
|
+
if (/^\d+ near-duplicate messages/.test(message)) return "duplicate-count";
|
|
140
|
+
// Context density messages
|
|
141
|
+
if (/^Low context density/.test(message)) return "density-low";
|
|
142
|
+
if (/^High density/.test(message)) return "density-high";
|
|
143
|
+
if (/^Context density still low/.test(message)) return "density-low-persistent";
|
|
144
|
+
// Proactive projection messages
|
|
145
|
+
if (/^\[proactive\]/.test(message)) return "proactive-projection";
|
|
146
|
+
// Degradation messages
|
|
147
|
+
if (/^Degradation detected/.test(message)) return "degradation";
|
|
148
|
+
// Fallback: use first 80 chars
|
|
149
|
+
return message.slice(0, 80);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The body to deliver for one entry.
|
|
154
|
+
*
|
|
155
|
+
* A declared family is re-rendered from the delivery sample, so the
|
|
156
|
+
* instruction and the number beside it describe one measurement. When the
|
|
157
|
+
* measured state no longer reaches the family's first arm, the entry is
|
|
158
|
+
* silence: advice about a condition that has passed is worse than none.
|
|
159
|
+
* With no measurement in hand the emitter's own wording stands: it carries no
|
|
160
|
+
* number, so it cannot contradict one.
|
|
161
|
+
*/
|
|
162
|
+
function deliveryBody(entry: WhisperBufferEntry, contextPercent: number | null): string | null {
|
|
163
|
+
if (entry.family !== "context-tier") return entry.message;
|
|
164
|
+
if (contextPercent === null) return entry.message;
|
|
165
|
+
const tier = contextUsageTier(contextPercent);
|
|
166
|
+
return tier ? contextUsageTierMessage(tier.tier) : null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface DelayedRenderOptions extends DeliveryRenderOptions {
|
|
170
|
+
/** Context percent measured at delivery, or null when nothing was measured. */
|
|
171
|
+
contextPercent?: number | null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Collapse the delayed buffer and render its deliveries: last arrival wins per
|
|
176
|
+
* key, then one delivery per priority tier.
|
|
177
|
+
*/
|
|
178
|
+
export function renderDelayedDelivery(
|
|
179
|
+
batch: readonly WhisperBufferEntry[],
|
|
180
|
+
opts: DelayedRenderOptions = {},
|
|
181
|
+
): string[] {
|
|
182
|
+
const collapsed = new Map<string, WhisperBufferEntry>();
|
|
183
|
+
for (const entry of batch) {
|
|
184
|
+
// Last arrival wins: the newest instruction is the only one whose advice
|
|
185
|
+
// can still be right, and the keystroke of keying on the first arrival is
|
|
186
|
+
// what printed the oldest label beside the newest numbers.
|
|
187
|
+
collapsed.set(dedupKey(entry), entry);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const groups = new Map<string, string[]>();
|
|
191
|
+
for (const entry of collapsed.values()) {
|
|
192
|
+
const body = deliveryBody(entry, opts.contextPercent ?? null);
|
|
193
|
+
if (body === null) continue;
|
|
194
|
+
const group = groups.get(entry.priority) ?? [];
|
|
195
|
+
group.push(body);
|
|
196
|
+
groups.set(entry.priority, group);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return [...groups.values()].map((bodies) => renderHeartbeatDelivery(bodies, opts));
|
|
200
|
+
}
|
|
@@ -47,53 +47,52 @@ The `cancelTimersByTag` helper from `extensions/scheduling/timer/index.ts` is th
|
|
|
47
47
|
## Parallel-tool-call constraint
|
|
48
48
|
|
|
49
49
|
`context_compress` returns its result immediately and defers the actual
|
|
50
|
-
`ctx.compact()` to
|
|
51
|
-
`context-manager/handlers/tools/context-compress.ts`)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
`tool_execution_end`
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
50
|
+
`ctx.compact()` to `agent_settled` (batch-settle scheduler in
|
|
51
|
+
`context-manager/handlers/tools/context-compress.ts`), the one drain where the
|
|
52
|
+
run cannot dispatch: pi-core emits it after the run-active flag is cleared, so
|
|
53
|
+
`compact()`'s abort is a no-op. A `turn_end` is not a safe drain: the loop
|
|
54
|
+
polls its steering queue AFTER the boundary handlers return, and a single
|
|
55
|
+
queued steer dispatches a request that the deferred compaction would abort
|
|
56
|
+
mid-stream. The single exception is the 0.90W hard backstop, which cuts a run
|
|
57
|
+
that would otherwise reach overflow with the queue still armed. Active calls
|
|
58
|
+
are tracked by `toolCallId`, registered at `tool_execution_start` and released
|
|
59
|
+
by its own `tool_execution_end` or by a boundary event whose `toolResults`
|
|
60
|
+
carry that id; `agent_settled` clears whatever is left. The earlier in-flight
|
|
61
|
+
COUNT was decremented only by the exact end event it waited for, so one missed
|
|
62
|
+
`tool_execution_end` left it positive and every later boundary returned before
|
|
63
|
+
the armed compaction could drain; identity cannot drift that way, and an id
|
|
64
|
+
with no result stays protective. This removes the old mid-batch abort race: a
|
|
65
|
+
still-executing parallel sibling's tool result is delivered BEFORE the aborting
|
|
66
|
+
compact fires and is no longer discarded (pinned by
|
|
67
|
+
`test/runtime/memory/test-compress-batch-settle.mjs`,
|
|
68
|
+
`test/runtime/memory/test-compress-drain-boundaries.mjs` and
|
|
69
|
+
`test/runtime/memory/test-armed-compaction-steer-abort.mjs`). The
|
|
66
70
|
degraded path (batch-settle bookkeeping unavailable) uses a bounded
|
|
67
71
|
`DEGRADED_DEFERRAL_MS` (150ms) deferral - never a raw `setTimeout(0)`.
|
|
68
72
|
|
|
69
73
|
The agent-facing guidance in the tool description still warns against
|
|
70
74
|
parallel batches ("Never in a parallel batch (it aborts the turn)"): the
|
|
71
|
-
deferred `ctx.compact()`
|
|
72
|
-
compaction remains a
|
|
73
|
-
mechanism is loss-preserving; the
|
|
75
|
+
deferred `ctx.compact()` fires when the run settles (or at the 0.90W
|
|
76
|
+
backstop), so compaction remains a boundary action, not a mid-batch one. The
|
|
77
|
+
mechanism is loss-preserving; the batch discipline stands.
|
|
74
78
|
|
|
75
79
|
### The turn-boundary rule
|
|
76
80
|
|
|
77
|
-
Which boundaries may abort a run is one rule in one home,
|
|
78
|
-
`lib/events/turn-boundary.ts`, read by the
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
loop anyway.
|
|
87
|
-
|
|
88
|
-
The rule is narrower than the safety property it stands for. The loop still
|
|
81
|
+
Which turn boundaries may abort a run is one rule in one home,
|
|
82
|
+
`lib/events/turn-boundary.ts`, read by the enforcement hygiene act
|
|
83
|
+
(`enforcement/handlers/register-turn-end-hygiene.ts`). It is an allow-list over
|
|
84
|
+
`message.stopReason`: the reasons that end a turn's work (`stop`, `length`,
|
|
85
|
+
`error`, `aborted`) fire, `toolUse` parks, and so does any boundary it cannot
|
|
86
|
+
read or does not recognize (`pending`, `deferred`, a missing or misspelled
|
|
87
|
+
reason, an empty object). The 0.90W hard backstop cuts a live loop anyway.
|
|
88
|
+
|
|
89
|
+
The rule is narrower than the safety property it stands for: the loop still
|
|
89
90
|
dispatches when a tool call rides a non-`toolUse` stop reason, and when a steer
|
|
90
|
-
is queued at any boundary (pi polls steering after the `turn_end` emit)
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
heartbeat's forwarding of the boundary into the arm path end to end in
|
|
96
|
-
`test/runtime/heartbeat/test-turn-boundary-arm-wiring.mjs`.
|
|
91
|
+
is queued at any boundary (pi polls steering after the `turn_end` emit). That
|
|
92
|
+
is why the compaction queue does not read it: the queue waits for
|
|
93
|
+
`agent_settled`, where no request can be in flight, and the rule governs only
|
|
94
|
+
the hygiene act. Its truth table is pinned in
|
|
95
|
+
`test/runtime/memory/test-compress-drain-boundaries.mjs`.
|
|
97
96
|
|
|
98
97
|
## Whisper wake-up policy in this module
|
|
99
98
|
|
|
@@ -25,7 +25,6 @@ import { Type, type Static } from "typebox";
|
|
|
25
25
|
|
|
26
26
|
import { createLogger } from "../../../lib/core/logger.js";
|
|
27
27
|
import { applyWhisperEnvelope } from "../../../lib/utils/whisper-format.js";
|
|
28
|
-
import { formatTokensK } from "../../../lib/detection/context-usage.js";
|
|
29
28
|
import { existsSync, readFileSync } from "node:fs";
|
|
30
29
|
import * as path from "node:path";
|
|
31
30
|
import { braidDir, tagsSlugFromCwd } from "../../../lib/config/braid-paths.js";
|
|
@@ -204,14 +203,15 @@ function sendCompactNudge(
|
|
|
204
203
|
// >= USAGE_TOKENS_ESCALATE (0.85W) escalated wording (archive-or-handoff)
|
|
205
204
|
// >= HARD_BACKSTOP (0.90W) or usage >= 80 full pipeline message
|
|
206
205
|
// else light tag/checkout message
|
|
207
|
-
// Percent stays as the secondary trigger (sub-1M windows).
|
|
208
|
-
|
|
206
|
+
// Percent stays as the secondary trigger (sub-1M windows). The text names
|
|
207
|
+
// the deadline and the action, never the number: the bars own the number,
|
|
208
|
+
// and a percentage copied into prose drifts from the meter.
|
|
209
209
|
const pipelineMsg =
|
|
210
210
|
tokens >= USAGE_TOKENS_ESCALATE()
|
|
211
|
-
? `
|
|
211
|
+
? `Escalated: an armed compaction fires when the run settles. Archive the current phase with context_compress(action="archive"), or hand off to a fresh session (write a handoff note first).`
|
|
212
212
|
: usage >= 80 || tokens >= HYGIENE_AUTO_COMPACT_HARD_BACKSTOP()
|
|
213
|
-
? `
|
|
214
|
-
: `
|
|
213
|
+
? `An armed compaction fires when the run settles. Pipeline: context_navigate(action="tag") -> context_navigate(action="checkout") -> context_compress(action="archive") -> context_compress(action="slide").`
|
|
214
|
+
: `An armed compaction fires when the run settles. Tag with context_navigate(action="tag"), then context_navigate(action="checkout") to branch with a summary before the next task.`;
|
|
215
215
|
|
|
216
216
|
sendTrackedMessage(
|
|
217
217
|
pi,
|
|
@@ -226,7 +226,7 @@ function sendCompactNudge(
|
|
|
226
226
|
display: true,
|
|
227
227
|
details: { [BRAID_INJECTED]: true, [BRAID_SOURCE]: "context-lifecycle/compact-suggestion" },
|
|
228
228
|
},
|
|
229
|
-
{
|
|
229
|
+
{ deliverAs: "nextTurn" },
|
|
230
230
|
{ type: "context" as const, source: "context-lifecycle/compact-suggestion" },
|
|
231
231
|
);
|
|
232
232
|
log.info(
|
|
@@ -332,7 +332,7 @@ function executeAction(
|
|
|
332
332
|
content: [{ type: "text" as const, text: msg }],
|
|
333
333
|
display: true,
|
|
334
334
|
},
|
|
335
|
-
{
|
|
335
|
+
{ deliverAs: "nextTurn" },
|
|
336
336
|
{ type: "context", source: "context-lifecycle/nudge" },
|
|
337
337
|
);
|
|
338
338
|
}
|
|
@@ -360,7 +360,8 @@ function hasConcreteCompressionSignal(evaluated: EvaluatedAction): boolean {
|
|
|
360
360
|
/**
|
|
361
361
|
* Proposals triggered by PERSISTENT conditions - usage %, token counts,
|
|
362
362
|
* density - stay true across turns, so the policy re-fires every cooldown
|
|
363
|
-
* with a fresh copy of the SAME advice ("
|
|
363
|
+
* with a fresh copy of the SAME advice ("an armed compaction fires when the
|
|
364
|
+
* run settles").
|
|
364
365
|
* This is the measured 33% exact-repeat class. Event-triggered proposals
|
|
365
366
|
* (topic_shift, task_boundary, task_complexity, decision_density,
|
|
366
367
|
* task_completion_candidate) fire on discrete moments and are NOT this class
|
|
@@ -659,7 +660,7 @@ async function queueProposal(
|
|
|
659
660
|
content: [{ type: "text" as const, text: msg }],
|
|
660
661
|
display: true,
|
|
661
662
|
},
|
|
662
|
-
{ deliverAs: "
|
|
663
|
+
{ deliverAs: "nextTurn" },
|
|
663
664
|
{ type: "context", source: "context-lifecycle/phase-boundary-enforcement" },
|
|
664
665
|
);
|
|
665
666
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getContextUsage } from "../../../lib/detection/context-tiers.js";
|
|
2
2
|
import { formatTokensK } from "../../../lib/detection/context-usage.js";
|
|
3
3
|
import {
|
|
4
|
+
describeUsage,
|
|
4
5
|
measureLiveUsage,
|
|
5
6
|
tokenArms,
|
|
6
7
|
resolveWindow,
|
|
@@ -27,6 +28,8 @@ export interface AuditResult {
|
|
|
27
28
|
usage: { percent: number; tokens: number; contextWindow: number };
|
|
28
29
|
/** How the usage number was produced (live working set vs fallback). */
|
|
29
30
|
usageSource: string;
|
|
31
|
+
/** The short provenance word for the number: measured or estimated. */
|
|
32
|
+
usageSourceKind: "measured" | "estimated" | "unavailable";
|
|
30
33
|
/** Whole-branch token sum - labeled "not sent" wherever displayed. */
|
|
31
34
|
branchTokens: number;
|
|
32
35
|
branchLength: number;
|
|
@@ -81,6 +84,7 @@ export function analyzeSession(ctx: any): AuditResult {
|
|
|
81
84
|
|
|
82
85
|
let usage = { percent: 0, tokens: 0, contextWindow: 0 };
|
|
83
86
|
let usageSource = "unavailable";
|
|
87
|
+
let usageSourceKind: "measured" | "estimated" | "unavailable" = "unavailable";
|
|
84
88
|
let branchTokens = 0;
|
|
85
89
|
try {
|
|
86
90
|
const live = measureLiveUsage(ctx);
|
|
@@ -90,7 +94,8 @@ export function analyzeSession(ctx: any): AuditResult {
|
|
|
90
94
|
tokens: live.tokens,
|
|
91
95
|
contextWindow: live.contextWindow,
|
|
92
96
|
};
|
|
93
|
-
usageSource = `session tree
|
|
97
|
+
usageSource = `session tree, ${live.windowSource} window, ${describeUsage(live)}`;
|
|
98
|
+
usageSourceKind = live.source;
|
|
94
99
|
branchTokens = live.branchTokens;
|
|
95
100
|
} else {
|
|
96
101
|
// No session tree available - fall back to the duck-typed accessor,
|
|
@@ -103,6 +108,7 @@ export function analyzeSession(ctx: any): AuditResult {
|
|
|
103
108
|
contextWindow: ctxUsage?.contextWindow ?? window.contextWindow,
|
|
104
109
|
};
|
|
105
110
|
usageSource = "ctx.getContextUsage fallback";
|
|
111
|
+
usageSourceKind = "estimated";
|
|
106
112
|
branchTokens = usage.tokens;
|
|
107
113
|
}
|
|
108
114
|
} catch {
|
|
@@ -309,6 +315,7 @@ export function analyzeSession(ctx: any): AuditResult {
|
|
|
309
315
|
return {
|
|
310
316
|
usage,
|
|
311
317
|
usageSource,
|
|
318
|
+
usageSourceKind,
|
|
312
319
|
branchTokens,
|
|
313
320
|
branchLength: branch.length,
|
|
314
321
|
treeDepth: tree.length,
|
|
@@ -134,7 +134,7 @@ export async function handleOverflowFailure(
|
|
|
134
134
|
const analysis = await analyzeSession(ctx);
|
|
135
135
|
if (analysis.usage.percent >= 75) {
|
|
136
136
|
log.warn(
|
|
137
|
-
`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% - triggering emergency rotation (overflow)`,
|
|
137
|
+
`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% ${analysis.usageSourceKind} - triggering emergency rotation (overflow)`,
|
|
138
138
|
);
|
|
139
139
|
triggerEmergencyRotation(pi, ctx);
|
|
140
140
|
return;
|
|
@@ -222,7 +222,7 @@ export async function handleTransientError(
|
|
|
222
222
|
const analysis = await analyzeSession(ctx);
|
|
223
223
|
if (analysis.usage.percent >= 75) {
|
|
224
224
|
log.warn(
|
|
225
|
-
`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% - triggering emergency rotation (transient)`,
|
|
225
|
+
`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% ${analysis.usageSourceKind} - triggering emergency rotation (transient)`,
|
|
226
226
|
);
|
|
227
227
|
triggerEmergencyRotation(pi, ctx);
|
|
228
228
|
return;
|
|
@@ -360,7 +360,7 @@ export async function handleThresholdFailure(
|
|
|
360
360
|
const analysis = await analyzeSession(ctx);
|
|
361
361
|
if (analysis.usage.percent >= 75) {
|
|
362
362
|
log.warn(
|
|
363
|
-
`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% - triggering emergency rotation (threshold)`,
|
|
363
|
+
`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% ${analysis.usageSourceKind} - triggering emergency rotation (threshold)`,
|
|
364
364
|
);
|
|
365
365
|
triggerEmergencyRotation(pi, ctx);
|
|
366
366
|
return;
|
|
@@ -27,6 +27,11 @@ import { determineCompressionLevel } from "../../../../lib/detection/compression
|
|
|
27
27
|
import { semanticCompress } from "../semantic-compress.js";
|
|
28
28
|
import { updateContextDensity } from "../../../heartbeat/analytics/index.js";
|
|
29
29
|
import { AGENT_END } from "../../../../lib/core/event-names.js";
|
|
30
|
+
import {
|
|
31
|
+
clearRequestShapeFailure,
|
|
32
|
+
noteRequestShapeFailure,
|
|
33
|
+
} from "../../../../lib/utils/wake-gate.js";
|
|
34
|
+
import { isContextLengthRequestShape } from "../../../../lib/errors/llm-error.js";
|
|
30
35
|
import {
|
|
31
36
|
log,
|
|
32
37
|
getCmState,
|
|
@@ -167,9 +172,21 @@ export function registerAgentEndApiErrorHandler(pi: ExtensionAPI): void {
|
|
|
167
172
|
break;
|
|
168
173
|
}
|
|
169
174
|
}
|
|
170
|
-
if (!lastAssistant || lastAssistant.stopReason !== "error")
|
|
175
|
+
if (!lastAssistant || lastAssistant.stopReason !== "error") {
|
|
176
|
+
// A turn that ended without an error means a request fit and came back:
|
|
177
|
+
// the shape verdict from an earlier refusal no longer applies.
|
|
178
|
+
clearRequestShapeFailure();
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
171
181
|
const finalError: string = lastAssistant.errorMessage ?? "Unknown error";
|
|
172
182
|
|
|
183
|
+
// A context-length refusal is the request's shape, not the provider's
|
|
184
|
+
// mood. Record it here so the wake gate can keep failed-open wakes from
|
|
185
|
+
// re-firing a request that cannot succeed.
|
|
186
|
+
if (isContextLengthRequestShape(finalError)) {
|
|
187
|
+
noteRequestShapeFailure(finalError.slice(0, 200));
|
|
188
|
+
}
|
|
189
|
+
|
|
173
190
|
sendTrackedMessage(
|
|
174
191
|
pi,
|
|
175
192
|
{
|