notesoup 0.58.3 → 0.59.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/README.md +1 -0
- package/dist/plugins/claude/src/helper.js +13 -0
- package/dist/plugins/claude/src/thresholds.js +17 -12
- package/dist/plugins/pi/budget.d.ts +3 -0
- package/dist/plugins/pi/budget.js +22 -11
- package/dist/plugins/pi/runtime.js +22 -6
- package/dist/src/budget/cap.d.ts +2 -0
- package/dist/src/budget/cap.js +11 -0
- package/dist/test/budget-settings.integration.test.js +45 -1
- package/dist/test/claude-mod.test.js +80 -21
- package/docs/claude-code-mod.md +5 -3
- package/docs/reset-lifecycle.md +3 -1
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +37 -9
- package/plugins/claude/hooks/register.ts +51 -5
- package/plugins/claude/src/helper.ts +11 -0
- package/plugins/claude/src/thresholds.ts +18 -11
- package/plugins/pi/budget.ts +21 -11
- package/plugins/pi/runtime.ts +18 -6
- package/src/budget/cap.ts +9 -0
package/README.md
CHANGED
|
@@ -50,6 +50,7 @@ pi -e npm:notesoup
|
|
|
50
50
|
- **Migration (0.40.0)**: parameters renamed: `order` → `from`, `before`/`after` → `before_seq`/`after_seq`, `limit_chars` → `max_chars`, `wastebasket` → `crumpled`, `pattern` → `glob` (the standalone library's options included), and `notes_update`'s `change_kind` value `file` → `moved`. Old names are refused.
|
|
51
51
|
|
|
52
52
|
- **Runtime toggle** — `/notesoup off` stops new automatic resets; `/notesoup on` re-enables them; bare `/notesoup` reports the state.
|
|
53
|
+
- **Context cap (Pi and Claude)** — `/notesoup cap 100k` limits the capacity used by notesoup's budget to `min(model window, 100000)`. Existing reserves and warning margins are deducted from that capacity; 100k is not the used-token reset point. `/notesoup cap` shows the configured cap and `/notesoup cap off` removes it. Whole tokens and decimal `k`/`m` suffixes are accepted; caps too small for the host's reserves are refused. The cap applies only to the running session, survives notesoup resets and model changes, and is lost on reload/restart/session switch. It never writes host settings or environment variables, changes the provider's advertised model window, or enables disabled automatic resets.
|
|
53
54
|
|
|
54
55
|
## Per-note policy
|
|
55
56
|
|
|
@@ -11,6 +11,7 @@ import { renderBootBlock } from "../../../src/boot/render.js";
|
|
|
11
11
|
import { selectContinuation } from "../../../src/budget/text.js";
|
|
12
12
|
import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
|
|
13
13
|
import { resolveClaudeLimits } from "./thresholds.js";
|
|
14
|
+
import { parseContextCap } from "../../../src/budget/cap.js";
|
|
14
15
|
import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
|
|
15
16
|
import { notesToolContext } from "../../../src/tools/notes-context.js";
|
|
16
17
|
const MAX_REQUEST_BYTES = 512 * 1024;
|
|
@@ -55,6 +56,18 @@ export async function dispatch(request, historyOptions = {}) {
|
|
|
55
56
|
if (!request || typeof request !== "object" || Array.isArray(request))
|
|
56
57
|
throw new Error("malformed request");
|
|
57
58
|
const value = request;
|
|
59
|
+
if (value.op === "cap") {
|
|
60
|
+
const cap = typeof value.value === "string" ? parseContextCap(value.value) : undefined;
|
|
61
|
+
if (cap === undefined)
|
|
62
|
+
throw new Error("Usage: /notesoup cap [100k|1m|tokens|off]");
|
|
63
|
+
if (cap !== null) {
|
|
64
|
+
const facts = value.facts && typeof value.facts === "object" ? value.facts : {};
|
|
65
|
+
const limits = resolveClaudeLimits({ ...facts, capTokens: undefined, usage: { window: cap }, breakdown: {} });
|
|
66
|
+
if (limits.reset <= 1)
|
|
67
|
+
throw new Error("Cap is too small for Claude's output, compaction and reset reserves");
|
|
68
|
+
}
|
|
69
|
+
return { cap };
|
|
70
|
+
}
|
|
58
71
|
if (value.op === "schemas")
|
|
59
72
|
return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
|
|
60
73
|
// The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
|
|
@@ -58,6 +58,11 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
|
|
|
58
58
|
native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
|
+
function windowPoint(window, autoCompact, pct) {
|
|
62
|
+
const available = window - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
63
|
+
const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
|
|
64
|
+
return autoCompact ? pct === undefined ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold) : available;
|
|
65
|
+
}
|
|
61
66
|
/**
|
|
62
67
|
* Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
|
|
63
68
|
* so a missing or malformed one degrades to the next source and finally to the percent
|
|
@@ -78,6 +83,13 @@ export function resolveClaudeLimits(facts) {
|
|
|
78
83
|
&& !presenceFlag(env.disableAutoCompact)
|
|
79
84
|
&& breakdown.isAutoCompactEnabled !== false;
|
|
80
85
|
const pct = percent(env.pctOverride);
|
|
86
|
+
const window = positiveNumber(usage.window);
|
|
87
|
+
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
88
|
+
const configured = configuredWindow(settings, env, breakdown.model);
|
|
89
|
+
const effective = Math.min(configured ?? capacity, capacity);
|
|
90
|
+
const cap = positiveInteger(root.capTokens);
|
|
91
|
+
const capped = cap !== undefined && cap < effective;
|
|
92
|
+
const nativeFromWindow = windowPoint(Math.min(effective, cap ?? Infinity), autoCompact, pct);
|
|
81
93
|
// (a) Claude's own point. It already includes the window, model settings and CLI flag; only
|
|
82
94
|
// the percent override is applied separately, on the window-after-output-reserve it is
|
|
83
95
|
// minted from (threshold + summary buffer). A malformed override that floors the point to
|
|
@@ -85,20 +97,13 @@ export function resolveClaudeLimits(facts) {
|
|
|
85
97
|
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
86
98
|
if (autoCompact && threshold !== undefined) {
|
|
87
99
|
const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
88
|
-
if (native > 0)
|
|
89
|
-
|
|
100
|
+
if (native > 0) {
|
|
101
|
+
const point = capped ? Math.min(native, nativeFromWindow) : native;
|
|
102
|
+
return tokenLimits(point < native ? "window" : "auto-compact", true, point, resetMargin, warningRunway);
|
|
103
|
+
}
|
|
90
104
|
}
|
|
91
105
|
// (b/c) Compute once, using the classic 200K capacity only when the host reports none.
|
|
92
|
-
const
|
|
93
|
-
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
94
|
-
const configured = configuredWindow(settings, env, breakdown.model);
|
|
95
|
-
const effective = Math.min(configured ?? capacity, capacity);
|
|
96
|
-
const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
97
|
-
const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
|
|
98
|
-
const native = autoCompact
|
|
99
|
-
? pct === undefined ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow)
|
|
100
|
-
: available;
|
|
101
|
-
const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
|
|
106
|
+
const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, nativeFromWindow, resetMargin, warningRunway);
|
|
102
107
|
if (window !== undefined)
|
|
103
108
|
return limits;
|
|
104
109
|
return {
|
|
@@ -11,6 +11,9 @@ export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolea
|
|
|
11
11
|
/** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
|
|
12
12
|
statusFor: (ctx: ExtensionContext) => {
|
|
13
13
|
remaining: number | null;
|
|
14
|
+
cap: number | undefined;
|
|
14
15
|
};
|
|
16
|
+
/** Runtime-only cap; reserve and all warning margins keep their existing meanings. */
|
|
17
|
+
setCap: (value: number | undefined, ctx: ExtensionContext) => string | undefined;
|
|
15
18
|
clear: () => void;
|
|
16
19
|
};
|
|
@@ -14,11 +14,12 @@ export const ContextRemainingOutputSchema = Type.Object({
|
|
|
14
14
|
remaining_tokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
|
|
15
15
|
}, { additionalProperties: false });
|
|
16
16
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
17
|
-
function remainingTokens(ctx) {
|
|
17
|
+
function remainingTokens(ctx, cap) {
|
|
18
18
|
const usage = windowUsage(ctx);
|
|
19
|
-
return !usage || usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
|
|
19
|
+
return !usage || usage.tokens === null ? null : Math.max(0, Math.min(usage.contextWindow, cap ?? Infinity) - usage.tokens);
|
|
20
20
|
}
|
|
21
21
|
export function registerBudget(pi, isEnabled, settingsManager) {
|
|
22
|
+
let cap;
|
|
22
23
|
let cachedPolicy;
|
|
23
24
|
const notifiedWarnings = new Set();
|
|
24
25
|
const resolvePolicy = (ctx) => {
|
|
@@ -41,17 +42,18 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
41
42
|
if (!automaticResetEnabled(ctx))
|
|
42
43
|
return false;
|
|
43
44
|
if (preSendMessages) {
|
|
44
|
-
const
|
|
45
|
-
if (!
|
|
45
|
+
const nativeWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
|
|
46
|
+
if (!nativeWindow || nativeWindow <= 0)
|
|
46
47
|
return false;
|
|
48
|
+
const contextWindow = Math.min(nativeWindow, cap ?? Infinity);
|
|
47
49
|
const { reserve } = thresholdsFor(ctx);
|
|
48
50
|
const estimate = estimateContextTokens(convertToLlm(preSendMessages));
|
|
49
51
|
if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve)
|
|
50
52
|
return false;
|
|
51
53
|
return contextWindow - estimate.tokens <= reserve;
|
|
52
54
|
}
|
|
53
|
-
const
|
|
54
|
-
return
|
|
55
|
+
const remaining = remainingTokens(ctx, cap);
|
|
56
|
+
return remaining !== null && remaining <= thresholdsFor(ctx).reserve;
|
|
55
57
|
};
|
|
56
58
|
let pendingGuidance;
|
|
57
59
|
let pendingWarning;
|
|
@@ -82,10 +84,10 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
82
84
|
details: { anchorEntryId },
|
|
83
85
|
}));
|
|
84
86
|
};
|
|
85
|
-
pi.on("session_start", (_event, ctx) => { resetForTransition(); thresholdsFor(ctx); });
|
|
87
|
+
pi.on("session_start", (_event, ctx) => { cap = undefined; resetForTransition(); thresholdsFor(ctx); });
|
|
86
88
|
pi.on("session_tree", resetForTransition);
|
|
87
89
|
pi.on("model_select", resetForTransition);
|
|
88
|
-
pi.on("session_shutdown", resetForTransition);
|
|
90
|
+
pi.on("session_shutdown", () => { cap = undefined; resetForTransition(); });
|
|
89
91
|
pi.on("agent_settled", clearStaged);
|
|
90
92
|
pi.on("context", (event, ctx) => {
|
|
91
93
|
if (!isEnabled())
|
|
@@ -102,7 +104,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
102
104
|
// Without automatic reset nothing gets cleared, so there is nothing to remind about.
|
|
103
105
|
if (!automaticResetEnabled(ctx))
|
|
104
106
|
return result();
|
|
105
|
-
const remaining = remainingTokens(ctx);
|
|
107
|
+
const remaining = remainingTokens(ctx, cap);
|
|
106
108
|
if (remaining === null)
|
|
107
109
|
return result();
|
|
108
110
|
const windowId = currentWindowId(ctx);
|
|
@@ -142,7 +144,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
142
144
|
outputSchema: ContextRemainingOutputSchema,
|
|
143
145
|
async execute(_id, _params, _signal, _update, ctx) {
|
|
144
146
|
// Report room to the hard-reserve wipe, including the warning runway.
|
|
145
|
-
const remaining = remainingTokens(ctx);
|
|
147
|
+
const remaining = remainingTokens(ctx, cap);
|
|
146
148
|
const value = { remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).reserve) };
|
|
147
149
|
return { ...output(value), structuredContent: value };
|
|
148
150
|
},
|
|
@@ -152,7 +154,16 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
152
154
|
hardReserveDue,
|
|
153
155
|
consumeTurnEnd,
|
|
154
156
|
/** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
|
|
155
|
-
statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).reserve) }),
|
|
157
|
+
statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx, cap), thresholdsFor(ctx).reserve), cap }),
|
|
158
|
+
/** Runtime-only cap; reserve and all warning margins keep their existing meanings. */
|
|
159
|
+
setCap: (value, ctx) => {
|
|
160
|
+
const reserve = thresholdsFor(ctx).reserve;
|
|
161
|
+
if (value !== undefined && value <= reserve)
|
|
162
|
+
return `Cap must exceed the ${reserve.toLocaleString("en-US")}-token reset reserve`;
|
|
163
|
+
cap = value;
|
|
164
|
+
clearStaged();
|
|
165
|
+
return undefined;
|
|
166
|
+
},
|
|
156
167
|
clear: () => { clearStaged(); notifiedWindows.clear(); },
|
|
157
168
|
};
|
|
158
169
|
}
|
|
@@ -17,6 +17,7 @@ import { buildBootMessage, sendBoot } from "./boot.js";
|
|
|
17
17
|
import { maybeSendMarker } from "./marker.js";
|
|
18
18
|
import { nextHistorySeq } from "./history.js";
|
|
19
19
|
import { errorMessage } from "../../src/error-message.js";
|
|
20
|
+
import { parseContextCap } from "../../src/budget/cap.js";
|
|
20
21
|
function readPackageVersion() {
|
|
21
22
|
for (const up of ["../../package.json", "../../../package.json"]) {
|
|
22
23
|
try {
|
|
@@ -157,11 +158,26 @@ export function registerContext(pi, settingsManager) {
|
|
|
157
158
|
}
|
|
158
159
|
});
|
|
159
160
|
pi.registerCommand("notesoup", {
|
|
160
|
-
description: "Show
|
|
161
|
-
getArgumentCompletions: (prefix) => ["on", "off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
|
|
161
|
+
description: "Show notesoup status, toggle context windows, or cap their capacity",
|
|
162
|
+
getArgumentCompletions: (prefix) => ["on", "off", "cap", "cap off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
|
|
162
163
|
handler: async (args, cmdCtx) => {
|
|
163
164
|
const arg = args.trim().toLowerCase();
|
|
164
|
-
|
|
165
|
+
const parts = arg.split(/\s+/);
|
|
166
|
+
if (parts[0] === "cap") {
|
|
167
|
+
if (parts.length > 1) {
|
|
168
|
+
const value = parts.length === 2 ? parseContextCap(parts[1]) : undefined;
|
|
169
|
+
if (value === undefined) {
|
|
170
|
+
cmdCtx.ui.notify("Usage: /notesoup cap [100k|1m|tokens|off]", "error");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const error = budget.setCap(value ?? undefined, cmdCtx);
|
|
174
|
+
if (error) {
|
|
175
|
+
cmdCtx.ui.notify(`🥣 ${error}`, "error");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else if (arg === "on") {
|
|
165
181
|
enabled = true;
|
|
166
182
|
const generation = ++lifecycleGeneration;
|
|
167
183
|
await ensureBoot(pi, cmdCtx, notifyIncompleteNotes, () => generation === lifecycleGeneration && enabled);
|
|
@@ -176,11 +192,11 @@ export function registerContext(pi, settingsManager) {
|
|
|
176
192
|
resets.clear();
|
|
177
193
|
}
|
|
178
194
|
else if (arg !== "") {
|
|
179
|
-
cmdCtx.ui.notify("Usage: /notesoup [on|off]", "error");
|
|
195
|
+
cmdCtx.ui.notify("Usage: /notesoup [on|off|cap [100k|1m|tokens|off]]", "error");
|
|
180
196
|
return;
|
|
181
197
|
}
|
|
182
|
-
const remaining = budget.statusFor(cmdCtx)
|
|
183
|
-
cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
|
|
198
|
+
const { remaining, cap } = budget.statusFor(cmdCtx);
|
|
199
|
+
cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION} · cap ${cap === undefined ? "off" : cap.toLocaleString("en-US")}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
|
|
184
200
|
},
|
|
185
201
|
});
|
|
186
202
|
const emptyBrainCommand = (name) => ({
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Parse a slash-command cap: decimal k/m suffixes, whole tokens, or off. */
|
|
2
|
+
export function parseContextCap(value) {
|
|
3
|
+
const text = value.trim().toLowerCase();
|
|
4
|
+
if (text === "off")
|
|
5
|
+
return null;
|
|
6
|
+
const match = /^(\d+(?:\.\d+)?)([km]?)$/.exec(text);
|
|
7
|
+
if (!match)
|
|
8
|
+
return undefined;
|
|
9
|
+
const tokens = Number(match[1]) * (match[2] === "m" ? 1_000_000 : match[2] === "k" ? 1_000 : 1);
|
|
10
|
+
return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined;
|
|
11
|
+
}
|
|
@@ -7,9 +7,10 @@ import { DEFAULT_REMINDER_MARGIN_TOKENS, DEFAULT_RESERVE_TOKENS } from "../src/b
|
|
|
7
7
|
import { tokenBudgetGuidance } from "../src/budget/text.js";
|
|
8
8
|
import { GUIDANCE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
|
|
9
9
|
import { deriveThresholds } from "../src/budget/policy.js";
|
|
10
|
+
import { parseContextCap } from "../src/budget/cap.js";
|
|
10
11
|
import { readThresholdSettings } from "../plugins/pi/thresholds.js";
|
|
11
12
|
import { NOTESOUP_SETTINGS_KEY } from "../src/settings.js";
|
|
12
|
-
import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultJson, runContextHook, runHandlers, sentOf, settingsFixture, writeJson, } from "./helpers/extension.js";
|
|
13
|
+
import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultJson, runContextHook, runHandlers, runCommand, sentOf, settingsFixture, writeJson, } from "./helpers/extension.js";
|
|
13
14
|
import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
|
|
14
15
|
const testEnvironment = installExtensionTestHooks("notesoup-integration");
|
|
15
16
|
const explicitBudgetSettings = {
|
|
@@ -31,6 +32,49 @@ test("budget derivation preserves defaults and validates overrides independently
|
|
|
31
32
|
}
|
|
32
33
|
assert.deepEqual(deriveThresholds(32_768, { reserveTokens: 8192, warningRunwayTokens: null }).thresholds, { reserve: 8192, reminder: 32_768, warning: 24_576 }, "an invalid runway does not discard a valid reserve");
|
|
33
34
|
});
|
|
35
|
+
test("context caps accept whole tokens and decimal k/m suffixes without lossy rounding", () => {
|
|
36
|
+
for (const [text, tokens] of [["100k", 100_000], ["100000", 100_000], [" 1M ", 1_000_000], ["1.5k", 1500], ["off", null]]) {
|
|
37
|
+
assert.equal(parseContextCap(text), tokens);
|
|
38
|
+
}
|
|
39
|
+
for (const text of ["", "0", "-1k", "1.5", "NaN", "Infinity", "100k extra", "1e5", "9007199254740992"])
|
|
40
|
+
assert.equal(parseContextCap(text), undefined, text);
|
|
41
|
+
});
|
|
42
|
+
test("Pi cap controls warning, reported room and hard wipe, without changing the model or settings", async () => {
|
|
43
|
+
const sm = manager();
|
|
44
|
+
appendText(sm, "user", "ongoing work");
|
|
45
|
+
const settings = SettingsManager.inMemory(explicitBudgetSettings);
|
|
46
|
+
const captured = makeExtension(sm, settings);
|
|
47
|
+
const at = (tokens, window = 200_000) => {
|
|
48
|
+
const ctx = context(sm, undefined, { tokens, percent: tokens / window * 100, contextWindow: window });
|
|
49
|
+
ctx.model = { provider: "test", id: "cap-model", contextWindow: window };
|
|
50
|
+
return ctx;
|
|
51
|
+
};
|
|
52
|
+
const native = at(0), beforeSettings = settings.getSettings();
|
|
53
|
+
const room = async (ctx = at(0)) => resultJson(await call(captured, "get_context_remaining", {}, ctx)).remaining_tokens;
|
|
54
|
+
await runCommand(captured, "notesoup", "cap 100k", native);
|
|
55
|
+
assert.equal(await room(), 83_616);
|
|
56
|
+
assert.equal(native.model?.contextWindow, 200_000);
|
|
57
|
+
assert.deepEqual(settings.getSettings(), beforeSettings);
|
|
58
|
+
for (const invalid of ["cap 0", "cap nonsense", "cap 100k extra", "cap 16k"]) {
|
|
59
|
+
assert.equal((await runCommand(captured, "notesoup", invalid, at(0)))[0]?.type, "error");
|
|
60
|
+
assert.equal(await room(), 83_616, "invalid caps leave the previous cap intact");
|
|
61
|
+
}
|
|
62
|
+
const warning = await runContextHook(captured, at(67_232));
|
|
63
|
+
assert.equal(warning?.messages[0]?.customType, WARNING_TYPE);
|
|
64
|
+
assert.equal(await room(at(83_615)), 1);
|
|
65
|
+
assert.equal((await commitTurnEndBoundary(captured, sm, at(83_615))).entries.some((e) => e.type === "custom" && e.customType === RESET_MARKER_TYPE), false);
|
|
66
|
+
const hard = await commitTurnEndBoundary(captured, sm, at(83_616));
|
|
67
|
+
assert.equal(hard.entries.filter((e) => e.type === "custom" && e.customType === RESET_MARKER_TYPE).length, 1);
|
|
68
|
+
assert.equal(await room(at(1000)), 82_616, "the cap survives a notesoup reset");
|
|
69
|
+
assert.equal(await room(at(1000, 64_000)), 46_616, "a cap cannot enlarge a smaller model window");
|
|
70
|
+
await runCommand(captured, "notesoup", "cap off", at(0));
|
|
71
|
+
assert.equal(await room(), 183_616);
|
|
72
|
+
await runCommand(captured, "notesoup", "cap 100k", at(0));
|
|
73
|
+
await runHandlers(captured, "model_select", {}, at(0, 64_000));
|
|
74
|
+
assert.equal(await room(at(0, 64_000)), 47_616, "switching models preserves the cap but uses the smaller window");
|
|
75
|
+
await runHandlers(captured, "session_start", {}, at(0));
|
|
76
|
+
assert.equal(await room(), 183_616, "a new/reloaded session does not inherit the runtime cap");
|
|
77
|
+
});
|
|
34
78
|
test("Pi budget settings merge per key without changing native compaction settings or enablement", async () => {
|
|
35
79
|
const fixture = settingsFixture({
|
|
36
80
|
reserveTokens: 32_768,
|
|
@@ -278,6 +278,14 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
|
|
|
278
278
|
assert.equal(absurdMargin.source, "percent");
|
|
279
279
|
assert.ok(absurdMargin.reset > 0 && absurdMargin.warn > 0, "an absurd margin cannot zero the percent fallback either");
|
|
280
280
|
});
|
|
281
|
+
test("Claude caps the capacity before deriving the same warning and hard points", () => {
|
|
282
|
+
const facts = { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000 }, capTokens: 100_000 };
|
|
283
|
+
assert.deepEqual(limitPoints(facts), { source: "window", unit: "tokens", autoCompact: true, native: 67_000, reset: 58_808, warn: 42_424 });
|
|
284
|
+
assert.equal(resolveClaudeLimits({ ...facts, capTokens: 1_000_000 }).reset, 158_808, "a cap never enlarges the model window");
|
|
285
|
+
assert.equal(resolveClaudeLimits({ usage: { window: 64_000 }, capTokens: 100_000 }).reset, 22_808, "a smaller model keeps its own limit");
|
|
286
|
+
assert.equal(resolveClaudeLimits({ ...facts, breakdown: { autoCompactThreshold: 50_000 } }).reset, 41_808, "an earlier native hard point still wins");
|
|
287
|
+
assert.equal(resolveClaudeLimits({ ...facts, settings: { autoCompactWindow: 80_000 }, breakdown: {} }).reset, 38_808, "a smaller configured window still wins");
|
|
288
|
+
});
|
|
281
289
|
test("Claude limits read margins from the notesoup settings shape and ignore garbage", () => {
|
|
282
290
|
const base = { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000, isAutoCompactEnabled: true } };
|
|
283
291
|
assert.deepEqual(limitPoints({ ...base, settings: { notesoup: { resetMarginTokens: 10_000, warningRunwayTokens: 5_000 } } }), { source: "auto-compact", unit: "tokens", autoCompact: true, native: 167_000, reset: 157_000, warn: 152_000 });
|
|
@@ -556,7 +564,7 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
|
|
|
556
564
|
assert.equal(crashed.isError, true);
|
|
557
565
|
assert.match(String(crashed.result), /^notesoup: helper execution failed: Error: spawn timed out after 10000ms$/, "the host's own reason survives the catch");
|
|
558
566
|
});
|
|
559
|
-
test("Claude Mod
|
|
567
|
+
test("Claude Mod clears at the shared hard point after successful settlement and retains one fresh boot", async (t) => {
|
|
560
568
|
const home = mkdtempSync(join(tmpdir(), "claude-reset-home-"));
|
|
561
569
|
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
562
570
|
const { host, registered, notifications } = fakeEngine(home);
|
|
@@ -564,7 +572,7 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
|
|
|
564
572
|
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
565
573
|
const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
|
|
566
574
|
assert.equal(handlers.has("session.measure"), false, "measure has no reset hook");
|
|
567
|
-
//
|
|
575
|
+
// Warning and automatic reset share the same native-derived points.
|
|
568
576
|
let tokens = 140_000;
|
|
569
577
|
let compactions = 0;
|
|
570
578
|
let kept = [];
|
|
@@ -597,16 +605,8 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
|
|
|
597
605
|
assert.equal(compactions, 0, "one token below the resolved reset point");
|
|
598
606
|
await invoke("turn.start");
|
|
599
607
|
tokens = 158_808;
|
|
600
|
-
assert.equal(compactions, 0, "
|
|
608
|
+
assert.equal(compactions, 0, "measurement alone cannot compact under a running turn");
|
|
601
609
|
assert.deepEqual(await invoke("turn.complete", turnComplete()), { sentinel: "turn.complete" });
|
|
602
|
-
assert.equal(compactions, 0, "the old reset point no longer clears at turn completion");
|
|
603
|
-
tokens = 190_000;
|
|
604
|
-
await invoke("turn.start");
|
|
605
|
-
await invoke("turn.complete", turnComplete());
|
|
606
|
-
assert.equal(compactions, 0, "even beyond the native threshold, only a native auto event or explicit request resets");
|
|
607
|
-
await invoke("turn.start");
|
|
608
|
-
await invoke("command.run", { command: "empty" });
|
|
609
|
-
await invoke("turn.complete", turnComplete());
|
|
610
610
|
await settleHooks();
|
|
611
611
|
assert.equal(compactions, 1);
|
|
612
612
|
assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
|
|
@@ -700,7 +700,7 @@ test("Claude headless resets through its own manual command, retries failure and
|
|
|
700
700
|
assert.match(kept[0].text, /claude:hook-session:2/);
|
|
701
701
|
assert.equal(kept.length, 2, "sticky is consumed once");
|
|
702
702
|
});
|
|
703
|
-
test("Claude headless warns
|
|
703
|
+
test("Claude headless warns, automatically resets at the hard point, and supports both manual aliases", async (t) => {
|
|
704
704
|
const home = mkdtempSync(join(tmpdir(), "claude-headless-auto-"));
|
|
705
705
|
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
706
706
|
const { host } = fakeEngine(home);
|
|
@@ -725,11 +725,8 @@ test("Claude headless warns without proactive resets and supports both manual al
|
|
|
725
725
|
await invoke("turn.start");
|
|
726
726
|
assert.equal(attempts, 0);
|
|
727
727
|
await invoke("turn.complete", turnComplete());
|
|
728
|
-
assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
|
|
729
|
-
await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
|
|
730
|
-
await invoke("turn.complete", turnComplete());
|
|
731
728
|
await settleHooks();
|
|
732
|
-
assert.equal(attempts, 1);
|
|
729
|
+
assert.equal(attempts, 1, "the hard point clears after successful settlement without a tool request");
|
|
733
730
|
for (const command of ["empty", "fresh-window"]) {
|
|
734
731
|
assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
|
|
735
732
|
await settleHooks();
|
|
@@ -817,7 +814,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
|
|
|
817
814
|
};
|
|
818
815
|
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
819
816
|
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
820
|
-
assert.deepEqual(commands.sort(), ["empty", "fresh-window"], "
|
|
817
|
+
assert.deepEqual(commands.sort(), ["empty", "fresh-window", "notesoup"], "the cap command and both reset aliases are registered");
|
|
821
818
|
assert.deepEqual(await invoke("command.run", { command: "empty-brain" }), {}, "the retired spelling passes through instead of resetting");
|
|
822
819
|
assert.equal(compactions, 0);
|
|
823
820
|
const command = await invoke("command.run", { command: "empty" });
|
|
@@ -1148,13 +1145,9 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
|
|
|
1148
1145
|
host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
|
|
1149
1146
|
host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
|
|
1150
1147
|
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
1151
|
-
await invoke("turn.start");
|
|
1152
|
-
await invoke("turn.complete", turnComplete());
|
|
1153
1148
|
await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
|
|
1154
1149
|
assert.equal(limitsCalls, 1, "the first limits round trip failed");
|
|
1155
1150
|
assert.equal(compactions, 0, "one failed resolution does not disable the window");
|
|
1156
|
-
await invoke("turn.start");
|
|
1157
|
-
await invoke("turn.complete", turnComplete());
|
|
1158
1151
|
const retried = await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
|
|
1159
1152
|
assert.deepEqual(retried.context, [CLAUDE_WARNING_PROMPT]);
|
|
1160
1153
|
assert.equal(limitsCalls, 2, "the retry runs in the same window");
|
|
@@ -1178,6 +1171,72 @@ async function retainedFixture(t) {
|
|
|
1178
1171
|
assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
|
|
1179
1172
|
return { home, host, invoke, context, boot, handlers, notifications };
|
|
1180
1173
|
}
|
|
1174
|
+
test("Claude runtime cap warns and clears at a safe main batch boundary, then survives the reset", async (t) => {
|
|
1175
|
+
const { host, invoke, handlers } = await retainedFixture(t);
|
|
1176
|
+
let tokens = 42_423, window = 200_000, resets = 0;
|
|
1177
|
+
const prompts = [];
|
|
1178
|
+
const settings = { autoCompactWindow: 200_000 };
|
|
1179
|
+
host.settings.read = async () => settings;
|
|
1180
|
+
host.session.usage = async () => ({ context: { tokens, window, breakdown: { autoCompactThreshold: window - 33_000, isAutoCompactEnabled: true, model: "claude" } } });
|
|
1181
|
+
host.prompt.submit = async ({ text }) => { prompts.push(text); return { text }; };
|
|
1182
|
+
host.command.run = async ({ command, args }) => {
|
|
1183
|
+
assert.equal(command, "compact", "the existing notes-only reset runs; /autocompact is never called");
|
|
1184
|
+
resets++;
|
|
1185
|
+
await nativeCompaction(host, handlers, args);
|
|
1186
|
+
tokens = undefined;
|
|
1187
|
+
return {};
|
|
1188
|
+
};
|
|
1189
|
+
const cap = async (args) => await invoke("command.run", { command: "notesoup", args });
|
|
1190
|
+
assert.match((await cap("cap 100k")).text, /100,000/);
|
|
1191
|
+
for (const value of ["cap 0", "cap garbage", "cap 100k extra", "cap 1k"]) {
|
|
1192
|
+
assert.match((await cap(value)).text, /Usage:|too small/);
|
|
1193
|
+
assert.match((await cap("cap")).text, /100,000/, "a refused cap keeps the previous one");
|
|
1194
|
+
}
|
|
1195
|
+
assert.equal((await invoke("tool.call", { tool: "Read" })).context, undefined);
|
|
1196
|
+
tokens = 42_424;
|
|
1197
|
+
assert.deepEqual((await invoke("tool.call", { tool: "Read" })).context, [CLAUDE_WARNING_PROMPT]);
|
|
1198
|
+
tokens = 58_807;
|
|
1199
|
+
await invoke("turn.start", { turnId: "main" });
|
|
1200
|
+
const step = handlers.get("turn.step");
|
|
1201
|
+
const chunks = async (agentId) => {
|
|
1202
|
+
const result = [];
|
|
1203
|
+
for await (const chunk of step(host, { turnId: "main", index: 1, ...(agentId ? { agentId } : {}) }, async function* () { yield { kind: "text", text: "model" }; return {}; }))
|
|
1204
|
+
result.push(chunk);
|
|
1205
|
+
return result;
|
|
1206
|
+
};
|
|
1207
|
+
assert.deepEqual(await chunks(), [{ kind: "text", text: "model" }]);
|
|
1208
|
+
tokens = 58_808;
|
|
1209
|
+
await Promise.all([invoke("tool.call", { tool: "Read" }), invoke("tool.call", { tool: "Bash" })]);
|
|
1210
|
+
assert.equal(resets, 0, "all sibling tool results finish before the hard point can act");
|
|
1211
|
+
assert.deepEqual(await chunks("child"), [{ kind: "text", text: "model" }], "child steps never reset the main brain");
|
|
1212
|
+
assert.deepEqual(await chunks(), [{ kind: "stop", stopReason: "end_turn", usage: null }]);
|
|
1213
|
+
await invoke("turn.complete", turnComplete({ turnId: "main", reason: "error" }));
|
|
1214
|
+
await settleHooks();
|
|
1215
|
+
assert.equal(resets, 0, "a failed turn cannot commit a budget reset");
|
|
1216
|
+
await invoke("turn.start", { turnId: "main" });
|
|
1217
|
+
await chunks();
|
|
1218
|
+
await invoke("turn.complete", turnComplete({ turnId: "main" }));
|
|
1219
|
+
await settleHooks();
|
|
1220
|
+
assert.equal(resets, 1);
|
|
1221
|
+
assert.equal(prompts.length, 1, "a confirmed automatic reset continues exactly once");
|
|
1222
|
+
assert.ok(FORCED_CONTINUATIONS.includes((await host.session.messages())[1].text), "only a real tool request uses the normal handoff pool");
|
|
1223
|
+
assert.match((await cap("cap")).text, /100,000/, "cap survives notesoup rollover");
|
|
1224
|
+
assert.deepEqual(settings, { autoCompactWindow: 200_000 }, "the user's settings stay untouched");
|
|
1225
|
+
await cap("cap off");
|
|
1226
|
+
tokens = 80_000;
|
|
1227
|
+
await invoke("turn.start", { turnId: "main" });
|
|
1228
|
+
assert.deepEqual(await chunks(), [{ kind: "text", text: "model" }], "off immediately restores the native budget");
|
|
1229
|
+
window = 64_000;
|
|
1230
|
+
tokens = 22_807;
|
|
1231
|
+
await cap("cap 100k");
|
|
1232
|
+
assert.deepEqual(await chunks(), [{ kind: "text", text: "model" }]);
|
|
1233
|
+
tokens++;
|
|
1234
|
+
await invoke("turn.complete", turnComplete({ turnId: "main" }));
|
|
1235
|
+
await settleHooks();
|
|
1236
|
+
assert.equal(resets, 2, "a smaller model clears at its own point, not at the cap's point");
|
|
1237
|
+
await invoke("session.end");
|
|
1238
|
+
assert.match((await cap("cap")).text, /cap off/, "a different session does not inherit the runtime cap");
|
|
1239
|
+
});
|
|
1181
1240
|
test("Claude empty_brain stops at the batch boundary, carries last_word, and resumes once after commit", async (t) => {
|
|
1182
1241
|
const { host, invoke, handlers } = await retainedFixture(t);
|
|
1183
1242
|
host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
|
package/docs/claude-code-mod.md
CHANGED
|
@@ -2,19 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers five notes tools as `mcp__notesoup__notes_*`, two history tools as `mcp__notesoup__history_*`, and `mcp__notesoup__empty_brain` and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `plugins/claude/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Warning and automatic clear use one budget policy. The existing warning and reset points are derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reach the sandboxed hooks module through the helper's `limits` operation. At the hard point, the next main `turn.step` ends the old turn after its whole tool batch; a successful main `turn.complete` also checks the point when no request is already pending. Both enter the existing non-held reset worker, without a separate cap-specific trigger. Measurement alone never clears context, child events cannot reset the main brain, and aborted/error/refusal turns do not commit a budget reset. The policy resolves its native point as follows:
|
|
6
6
|
|
|
7
7
|
1. `$.session.usage({breakdown:"summary"}).context.breakdown.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
|
|
8
8
|
2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer; `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` lowers this fallback point by the same formula. With auto-compaction off, the percent override is ignored;
|
|
9
9
|
3. otherwise the percent fallback, which assumes a classic 200K capacity, applies the same configured-window caps and token derivation, then converts the points to percentages.
|
|
10
10
|
|
|
11
|
-
The
|
|
11
|
+
The hard clear point is `resetMarginTokens` (default 8192) below the native point; the warning is another `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that. Resolved points are reused only while the current model, cap, threshold inputs and settings match; changing context fill alone does not invalidate them. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same warning margins still apply, but automatic notesoup clears are disabled too. Explicit resets remain available. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the budget warning. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, suppresses budget warnings and explicit resets, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored. Setting `NOTESOUP_DISABLED` (presence-style, the same convention as `DISABLE_COMPACT`) turns the whole mod off: `session.start` registers no tools or commands and logs once, every event passes through untouched, and native compaction behaves as if the mod were absent.
|
|
12
|
+
|
|
13
|
+
`/notesoup cap 100k` supplies a runtime-only capacity ceiling, clamped to the smaller model/configured window before the same reserves and margins are deducted. A reported native threshold can only be lowered, never raised. `/notesoup cap` (or bare `/notesoup`) shows the cap; `/notesoup cap off` restores the uncapped policy. Whole tokens and decimal `k`/`m` suffixes are accepted, with caps too small for reserves refused. The cap survives notesoup rollover and model changes but is cleared on plugin reload, session end or session identity change. It does not call `/autocompact`, alter the model, or write settings/environment variables. An already pending reset keeps its continuation/STOP policy when the cap changes.
|
|
12
14
|
|
|
13
15
|
Once per window, when the measured context crosses the warning point, main-agent tool results or prompt submission carry exactly the same budget warning as Pi, ending with `empty_brain` and the countdown. Delivery is consumed only when the downstream chain accepts the warning. The warned flag resets with the window ordinal. Its own `session.compact` hook answers native compaction in the main conversation instead of letting it summarize: an automatic compaction (threshold or prompt-too-long) becomes the freshly built notes boot followed by one randomly selected handoff paragraph (normal only when the model called `empty_brain`, otherwise forced), selected once for the new window and reused on retry — the same boot-then-handoff order as Pi — while user `/compact` and precompute are vetoed with a one-line notice. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block binds the shared reset sentence to `mcp__notesoup__empty_brain`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. A failed boot build falls back to Claude's own summary, which invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
|
|
14
16
|
|
|
15
17
|
The reset flow has three separate lifetimes. `ResetFlow.request` lasts until successful reset or cancellation; it owns the first valid tool call's sticky note and continuation policy. `ResetState.commit` lasts for one native command attempt and tracks proof that Claude kept the boot. The per-turn cutoff can outlive the request when native auto compaction consumes it before the next step. Successful explicit reset and automatic reset share the same window/boot bookkeeping. A failed compaction retains the request for retry; an aborted, failed, or refused main turn cancels it. Session changes discard the flow and invalidate asynchronous work by generation.
|
|
16
18
|
|
|
17
|
-
`empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
|
|
19
|
+
`empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. The automatic hard point uses the same cutoff and commit path; a budget reset uses the forced handoff pool and continues once only after a confirmed commit, unless manual STOP or natural input takes over. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
|
|
18
20
|
|
|
19
21
|
Accepted natural input owns its continuation. Input received within the running turn, including input accepted before the first tool latch, releases the cutoff at the next step for the whole subsequent tool workflow. Input not yet delivered to a model request prevents reset work from starting. A separately queued natural turn also runs normally. No input is replayed. Native auto compaction consumes a pending request without resetting twice, while preserving its armed cutoff until turn completion or natural-input delivery; further auto compaction does not disarm it. Once that reset has completed and natural input releases its cutoff, a new `empty_brain` owns its own sticky and `terminate` policy. A consumed request's STOP does not carry into the new request.
|
|
20
22
|
|
package/docs/reset-lifecycle.md
CHANGED
|
@@ -35,7 +35,7 @@ One public boundary draft contains, in order:
|
|
|
35
35
|
|
|
36
36
|
Boundary drafts cannot contain ordinary user entries. Pi's public custom-message conversion supplies role `user` to the provider, including text/image arrays. Carried inputs are appended atomically with the reset artifacts, not queued as separate prompts; any carried input returns `continue: true`.
|
|
37
37
|
|
|
38
|
-
The origin is `normal` for an actual tool request, otherwise `forced`; overflow recovery is always forced. Each origin has an approved complete-paragraph pool. Construction draws once and persists the paragraph verbatim; rendering, reads, reloads and repair never redraw an existing continuation. Legacy markers without a valid origin default to normal. Other hosts retain their own scheduling: dsh shares one draw across checkpoint and continuation; Claude caches its forced handoff per window.
|
|
38
|
+
The origin is `normal` for an actual tool request, otherwise `forced`; overflow recovery is always forced. Each origin has an approved complete-paragraph pool. Construction draws once and persists the paragraph verbatim; rendering, reads, reloads and repair never redraw an existing continuation. Legacy markers without a valid origin default to normal. Other hosts retain their own scheduling: dsh shares one draw across checkpoint and continuation; Claude caches its forced handoff per window and feeds its warning and hard clear from the same resolved budget, as described in [Claude Code Mod](claude-code-mod.md).
|
|
39
39
|
|
|
40
40
|
Raw session history remains available. The retain-none checkpoint excludes old conversational context while preserving Pi's empty summary wrapper and system/tool state. Marker-only legacy sessions use boot slicing as a compatibility fallback. A marker is checkpoint-backed only if it directly follows a self-retaining, empty native compaction.
|
|
41
41
|
|
|
@@ -60,6 +60,8 @@ After a manual safety reset, `context_with_system` checks the committed boundary
|
|
|
60
60
|
|
|
61
61
|
## Warnings, projection and repair
|
|
62
62
|
|
|
63
|
+
`/notesoup cap` is a runtime capacity ceiling, not a separate reset intent. Budget calculations use the smaller native window and cap, then deduct the same reserve and warning margins. Changing the cap does not enlarge a model window, enable disabled automatic resets, or change an already armed reset's continuation policy. The cap survives notesoup resets and model changes but not reload/session replacement.
|
|
64
|
+
|
|
63
65
|
Budget reminders are staged once per window at reserve plus reminder margin, then reserve plus warning runway. Hard reserve remains independent. Budget and command warnings use different types. The final budget warning notifies at first provider injection, not durability; early guidance stays UI-silent. Budget drafts are instance-local and discarded on abort, failed turn, transition or window mismatch. Active-window usage and the exact public `SettingsManager` authority determine thresholds.
|
|
64
66
|
|
|
65
67
|
Pi and Claude use the same budget warning: budget timing, the handoff checklist, note maintenance (including updating and trimming pinned pages, CHEATSHEET.md and MAP.md by default), a warning against large tool outputs, then `empty_brain` and the countdown. Pi's manual warnings replace the budget opening with the `/empty` notice inside `<notesoup:budget_notice>`. Optional command text sits after the closing tag as plain text for the closing model's notes; separate human input during close-out is intercepted and carried, never steered. The first-tier reminder reports the remaining room, explains that notes survive the wipe, asks for updated notes and offers an optional `empty_brain`, warning that it also clears what the model says to the human right before emptying. Pi's fixed system protocol retains its existing pre-reset hints; warnings no longer repeat those or the tool's `last_word` description.
|
package/package.json
CHANGED
|
@@ -11478,6 +11478,11 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
|
|
|
11478
11478
|
warningRunway
|
|
11479
11479
|
};
|
|
11480
11480
|
}
|
|
11481
|
+
function windowPoint(window, autoCompact, pct) {
|
|
11482
|
+
const available = window - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
11483
|
+
const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
|
|
11484
|
+
return autoCompact ? pct === void 0 ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold) : available;
|
|
11485
|
+
}
|
|
11481
11486
|
function resolveClaudeLimits(facts) {
|
|
11482
11487
|
const root = isPlainObject(facts) ? facts : {};
|
|
11483
11488
|
const usage = isPlainObject(root.usage) ? root.usage : {};
|
|
@@ -11489,19 +11494,22 @@ function resolveClaudeLimits(facts) {
|
|
|
11489
11494
|
const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
|
|
11490
11495
|
const autoCompact = settingFlag(settings2) !== false && !presenceFlag(env.disableAutoCompact) && breakdown.isAutoCompactEnabled !== false;
|
|
11491
11496
|
const pct = percent(env.pctOverride);
|
|
11492
|
-
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
11493
|
-
if (autoCompact && threshold !== void 0) {
|
|
11494
|
-
const native2 = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
11495
|
-
if (native2 > 0) return tokenLimits("auto-compact", true, native2, resetMargin, warningRunway);
|
|
11496
|
-
}
|
|
11497
11497
|
const window = positiveNumber(usage.window);
|
|
11498
11498
|
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
11499
11499
|
const configured = configuredWindow(settings2, env, breakdown.model);
|
|
11500
11500
|
const effective = Math.min(configured ?? capacity, capacity);
|
|
11501
|
-
const
|
|
11502
|
-
const
|
|
11503
|
-
const
|
|
11504
|
-
const
|
|
11501
|
+
const cap = positiveInteger(root.capTokens);
|
|
11502
|
+
const capped = cap !== void 0 && cap < effective;
|
|
11503
|
+
const nativeFromWindow = windowPoint(Math.min(effective, cap ?? Infinity), autoCompact, pct);
|
|
11504
|
+
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
11505
|
+
if (autoCompact && threshold !== void 0) {
|
|
11506
|
+
const native = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
11507
|
+
if (native > 0) {
|
|
11508
|
+
const point = capped ? Math.min(native, nativeFromWindow) : native;
|
|
11509
|
+
return tokenLimits(point < native ? "window" : "auto-compact", true, point, resetMargin, warningRunway);
|
|
11510
|
+
}
|
|
11511
|
+
}
|
|
11512
|
+
const limits = tokenLimits(window === void 0 ? "percent" : "window", autoCompact, nativeFromWindow, resetMargin, warningRunway);
|
|
11505
11513
|
if (window !== void 0) return limits;
|
|
11506
11514
|
return {
|
|
11507
11515
|
...limits,
|
|
@@ -11512,6 +11520,16 @@ function resolveClaudeLimits(facts) {
|
|
|
11512
11520
|
};
|
|
11513
11521
|
}
|
|
11514
11522
|
|
|
11523
|
+
// src/budget/cap.ts
|
|
11524
|
+
function parseContextCap(value) {
|
|
11525
|
+
const text = value.trim().toLowerCase();
|
|
11526
|
+
if (text === "off") return null;
|
|
11527
|
+
const match = /^(\d+(?:\.\d+)?)([km]?)$/.exec(text);
|
|
11528
|
+
if (!match) return void 0;
|
|
11529
|
+
const tokens = Number(match[1]) * (match[2] === "m" ? 1e6 : match[2] === "k" ? 1e3 : 1);
|
|
11530
|
+
return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : void 0;
|
|
11531
|
+
}
|
|
11532
|
+
|
|
11515
11533
|
// plugins/claude/src/helper.ts
|
|
11516
11534
|
var MAX_REQUEST_BYTES = 512 * 1024;
|
|
11517
11535
|
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
@@ -11549,6 +11567,16 @@ function historySource(value, sessionId) {
|
|
|
11549
11567
|
async function dispatch(request, historyOptions = {}) {
|
|
11550
11568
|
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
|
|
11551
11569
|
const value = request;
|
|
11570
|
+
if (value.op === "cap") {
|
|
11571
|
+
const cap = typeof value.value === "string" ? parseContextCap(value.value) : void 0;
|
|
11572
|
+
if (cap === void 0) throw new Error("Usage: /notesoup cap [100k|1m|tokens|off]");
|
|
11573
|
+
if (cap !== null) {
|
|
11574
|
+
const facts = value.facts && typeof value.facts === "object" ? value.facts : {};
|
|
11575
|
+
const limits = resolveClaudeLimits({ ...facts, capTokens: void 0, usage: { window: cap }, breakdown: {} });
|
|
11576
|
+
if (limits.reset <= 1) throw new Error("Cap is too small for Claude's output, compaction and reset reserves");
|
|
11577
|
+
}
|
|
11578
|
+
return { cap };
|
|
11579
|
+
}
|
|
11552
11580
|
if (value.op === "schemas") return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
|
|
11553
11581
|
if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
|
|
11554
11582
|
if (value.op === "continuation") {
|
|
@@ -39,12 +39,16 @@ class ResetFlow {
|
|
|
39
39
|
} else request.resume = false
|
|
40
40
|
return first
|
|
41
41
|
}
|
|
42
|
+
requestAutomatic() {
|
|
43
|
+
this.request ??= { resume: true }
|
|
44
|
+
this.cutoffTurnId = this.turnId
|
|
45
|
+
}
|
|
42
46
|
input(turnId?: string) {
|
|
43
47
|
if (turnId !== undefined) this.pendingInputTurnId = turnId
|
|
44
|
-
if (this.request
|
|
48
|
+
if (this.request) this.request.resume = false
|
|
45
49
|
}
|
|
46
50
|
start(turnId: string) {
|
|
47
|
-
if (this.request
|
|
51
|
+
if (this.request) this.request.resume = false
|
|
48
52
|
this.turnId = turnId
|
|
49
53
|
this.running = true
|
|
50
54
|
}
|
|
@@ -73,7 +77,7 @@ class ResetFlow {
|
|
|
73
77
|
if (auto && !request) return false
|
|
74
78
|
this.cutoffTurnId = auto && request && !request.resume ? this.cutoffTurnId ?? (!request.tool ? this.turnId : undefined) : undefined
|
|
75
79
|
this.request = undefined
|
|
76
|
-
return request?.
|
|
80
|
+
return request?.resume ?? false
|
|
77
81
|
}
|
|
78
82
|
cancel() {
|
|
79
83
|
this.request = undefined
|
|
@@ -85,7 +89,7 @@ type ResetState = {
|
|
|
85
89
|
headless: boolean; usageFailureLogged: boolean; commit?: { instructions: string; boot?: string; boundary: boolean; resolve: (kept: boolean) => void }; retainedBoot?: string
|
|
86
90
|
continuation?: { window: number; text: string }
|
|
87
91
|
compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsKey?: string
|
|
88
|
-
limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
|
|
92
|
+
capTokens?: number; limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
|
|
89
93
|
}
|
|
90
94
|
type ResetWork = { kind: "closeout" | "reset"; generation: number }
|
|
91
95
|
type ResetSignal = { wake?: (work: ResetWork) => void }
|
|
@@ -197,8 +201,10 @@ async function breakdownContext($: Engine): Promise<Record<string, unknown> | un
|
|
|
197
201
|
}
|
|
198
202
|
/** Threshold inputs only: changing fill must not invalidate the resolved points. */
|
|
199
203
|
async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Promise<Record<string, unknown>> {
|
|
204
|
+
const capTokens = state.capTokens
|
|
200
205
|
const breakdown = await breakdownContext($)
|
|
201
206
|
return {
|
|
207
|
+
capTokens,
|
|
202
208
|
usage: { window: usage.window },
|
|
203
209
|
breakdown: { model: breakdown?.model, autoCompactThreshold: breakdown?.autoCompactThreshold, isAutoCompactEnabled: breakdown?.isAutoCompactEnabled },
|
|
204
210
|
settings: await readSettings($, state),
|
|
@@ -236,6 +242,37 @@ function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | unde
|
|
|
236
242
|
if (usage.tokens !== undefined) return usage.tokens
|
|
237
243
|
return usage.percent !== undefined && usage.window !== undefined && usage.window > 0 ? (usage.percent / 100) * usage.window : undefined
|
|
238
244
|
}
|
|
245
|
+
/** The warning and hard clear share one policy; only a safe main-loop boundary acts on it. */
|
|
246
|
+
async function hardResetDue($: Engine, state: ResetState): Promise<boolean> {
|
|
247
|
+
if (state.disabled || state.compactDisabled || !state.identity || state.commit) return false
|
|
248
|
+
const generation = state.generation, window = state.window, cap = state.capTokens
|
|
249
|
+
const usage = await contextUsage($, state)
|
|
250
|
+
if (generation !== state.generation || usage === undefined) return false
|
|
251
|
+
const limits = await limitsOf($, state, usage)
|
|
252
|
+
if (generation !== state.generation || window !== state.window || cap !== state.capTokens || !limits?.autoCompact) return false
|
|
253
|
+
const measured = measuredValue(limits, usage)
|
|
254
|
+
return measured !== undefined && measured >= limits.reset
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Runtime-only capacity; never writes Claude's settings or its process environment. */
|
|
258
|
+
async function capCommand($: Engine, state: ResetState, args: string): Promise<{ text: string }> {
|
|
259
|
+
if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /notesoup again" }
|
|
260
|
+
const parts = args.trim().toLowerCase().split(/\s+/)
|
|
261
|
+
if (parts[0] !== "" && (parts[0] !== "cap" || parts.length > 2)) return { text: "Usage: /notesoup cap [100k|1m|tokens|off]" }
|
|
262
|
+
if (parts.length === 2) {
|
|
263
|
+
const generation = state.generation
|
|
264
|
+
const usage = await contextUsage($, state) ?? {}
|
|
265
|
+
const facts = await limitFacts($, state, usage)
|
|
266
|
+
const result = await run($, { op: "cap", value: parts[1], facts })
|
|
267
|
+
if (generation !== state.generation) return { text: "🥣 Different brain now · try /notesoup again" }
|
|
268
|
+
if (!result.ok) return { text: result.error }
|
|
269
|
+
const cap = typeof result.result === "object" && result.result !== null ? (result.result as { cap?: unknown }).cap : undefined
|
|
270
|
+
if (cap !== null && (typeof cap !== "number" || !Number.isSafeInteger(cap) || cap <= 0)) return { text: "🥣 Invalid cap from helper" }
|
|
271
|
+
state.capTokens = cap ?? undefined
|
|
272
|
+
}
|
|
273
|
+
return { text: `🥣 notesoup · cap ${state.capTokens === undefined ? "off" : state.capTokens.toLocaleString("en-US")} · current session only` }
|
|
274
|
+
}
|
|
275
|
+
|
|
239
276
|
/** The shared reset prose: one helper round trip per session, retried until it lands. */
|
|
240
277
|
async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | undefined> {
|
|
241
278
|
if (state.texts) return state.texts
|
|
@@ -304,6 +341,7 @@ function forgetSession(state: ResetState) {
|
|
|
304
341
|
state.commit?.resolve(false)
|
|
305
342
|
state.commit = undefined
|
|
306
343
|
state.retainedBoot = undefined
|
|
344
|
+
state.capTokens = undefined
|
|
307
345
|
state.texts = state.limits = undefined
|
|
308
346
|
state.continuation = undefined
|
|
309
347
|
state.limitsAttempts = 0
|
|
@@ -412,6 +450,7 @@ export function register(on: On) {
|
|
|
412
450
|
registered.clear()
|
|
413
451
|
await loadTexts($, state)
|
|
414
452
|
armReset($, state, resetSignal)
|
|
453
|
+
await $.command.register({ name: "notesoup", description: "Show or cap the notesoup context capacity: cap [100k|1m|tokens|off]", immediate: true })
|
|
415
454
|
await $.command.register({ name: "empty", description: "Reset context to a fresh notes-only window", immediate: true })
|
|
416
455
|
await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
|
|
417
456
|
const wipe = await $.tool.register({
|
|
@@ -460,6 +499,9 @@ export function register(on: On) {
|
|
|
460
499
|
})
|
|
461
500
|
on("turn.step", async function* ($, e, next) {
|
|
462
501
|
if (state.disabled || e.agentId !== undefined) return yield* next(e)
|
|
502
|
+
// Like the warning, the hard point consumes the same resolved limits. This boundary
|
|
503
|
+
// follows the whole previous tool batch; no sibling tool or in-flight request is aborted.
|
|
504
|
+
if (await hardResetDue($, state)) state.flow.requestAutomatic()
|
|
463
505
|
if (!state.flow.cutoff(e.turnId)) return yield* next(e)
|
|
464
506
|
// This boundary follows the entire tool batch. A synthetic streamed stop
|
|
465
507
|
// ends the main turn without aborting siblings or making an old-window request.
|
|
@@ -475,11 +517,15 @@ export function register(on: On) {
|
|
|
475
517
|
// A failed turn proves nothing about whether its notes were saved.
|
|
476
518
|
if (cancelled) log($, `Brain emptying cancelled · turn ended ${e.reason}; ask /fresh-window again`)
|
|
477
519
|
if (!await refreshIdentity($, state)) return result
|
|
478
|
-
if (e.reason === "answer"
|
|
520
|
+
if (e.reason === "answer") {
|
|
521
|
+
if (!state.flow.request && await hardResetDue($, state)) state.flow.requestAutomatic()
|
|
522
|
+
if (state.flow.request) resetSignal.wake?.({ kind: "reset", generation: state.generation })
|
|
523
|
+
}
|
|
479
524
|
return result
|
|
480
525
|
})
|
|
481
526
|
on("command.run", async ($, e, next) => {
|
|
482
527
|
if (state.disabled) return next(e)
|
|
528
|
+
if (e.command === "notesoup") return capCommand($, state, e.args)
|
|
483
529
|
if (e.command !== "empty" && e.command !== "fresh-window") return next(e)
|
|
484
530
|
if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
|
|
485
531
|
if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
|
|
@@ -13,6 +13,7 @@ import type { BootToolNames } from "../../../src/boot/text.js";
|
|
|
13
13
|
import { selectContinuation } from "../../../src/budget/text.js";
|
|
14
14
|
import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
|
|
15
15
|
import { resolveClaudeLimits } from "./thresholds.js";
|
|
16
|
+
import { parseContextCap } from "../../../src/budget/cap.js";
|
|
16
17
|
import { projectKey, snapshotNotesIdentity, type NotesIdentity } from "../../../src/notes/index.js";
|
|
17
18
|
import type { Operation } from "../../../src/tools/result.js";
|
|
18
19
|
import { notesToolContext, type NotesToolContext } from "../../../src/tools/notes-context.js";
|
|
@@ -70,6 +71,16 @@ function historySource(value: unknown, sessionId: string): ClaudeHistorySource {
|
|
|
70
71
|
export async function dispatch(request: unknown, historyOptions: Pick<LocalHistoryOptions, "roots" | "home" | "env"> = {}): Promise<unknown> {
|
|
71
72
|
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
|
|
72
73
|
const value = request as Record<string, unknown>;
|
|
74
|
+
if (value.op === "cap") {
|
|
75
|
+
const cap = typeof value.value === "string" ? parseContextCap(value.value) : undefined;
|
|
76
|
+
if (cap === undefined) throw new Error("Usage: /notesoup cap [100k|1m|tokens|off]");
|
|
77
|
+
if (cap !== null) {
|
|
78
|
+
const facts = value.facts && typeof value.facts === "object" ? value.facts as Record<string, unknown> : {};
|
|
79
|
+
const limits = resolveClaudeLimits({ ...facts, capTokens: undefined, usage: { window: cap }, breakdown: {} });
|
|
80
|
+
if (limits.reset <= 1) throw new Error("Cap is too small for Claude's output, compaction and reset reserves");
|
|
81
|
+
}
|
|
82
|
+
return { cap };
|
|
83
|
+
}
|
|
73
84
|
if (value.op === "schemas") return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
|
|
74
85
|
// The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
|
|
75
86
|
// cannot drift apart. The hooks module caches one copy per session.
|
|
@@ -81,6 +81,12 @@ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: nu
|
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
function windowPoint(window: number, autoCompact: boolean, pct: number | undefined): number {
|
|
85
|
+
const available = window - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
86
|
+
const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
|
|
87
|
+
return autoCompact ? pct === undefined ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold) : available;
|
|
88
|
+
}
|
|
89
|
+
|
|
84
90
|
/**
|
|
85
91
|
* Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
|
|
86
92
|
* so a missing or malformed one degrades to the next source and finally to the percent
|
|
@@ -103,6 +109,13 @@ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
|
|
|
103
109
|
&& !presenceFlag(env.disableAutoCompact)
|
|
104
110
|
&& breakdown.isAutoCompactEnabled !== false;
|
|
105
111
|
const pct = percent(env.pctOverride);
|
|
112
|
+
const window = positiveNumber(usage.window);
|
|
113
|
+
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
114
|
+
const configured = configuredWindow(settings, env, breakdown.model);
|
|
115
|
+
const effective = Math.min(configured ?? capacity, capacity);
|
|
116
|
+
const cap = positiveInteger(root.capTokens);
|
|
117
|
+
const capped = cap !== undefined && cap < effective;
|
|
118
|
+
const nativeFromWindow = windowPoint(Math.min(effective, cap ?? Infinity), autoCompact, pct);
|
|
106
119
|
|
|
107
120
|
// (a) Claude's own point. It already includes the window, model settings and CLI flag; only
|
|
108
121
|
// the percent override is applied separately, on the window-after-output-reserve it is
|
|
@@ -111,20 +124,14 @@ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
|
|
|
111
124
|
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
112
125
|
if (autoCompact && threshold !== undefined) {
|
|
113
126
|
const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
114
|
-
if (native > 0)
|
|
127
|
+
if (native > 0) {
|
|
128
|
+
const point = capped ? Math.min(native, nativeFromWindow) : native;
|
|
129
|
+
return tokenLimits(point < native ? "window" : "auto-compact", true, point, resetMargin, warningRunway);
|
|
130
|
+
}
|
|
115
131
|
}
|
|
116
132
|
|
|
117
133
|
// (b/c) Compute once, using the classic 200K capacity only when the host reports none.
|
|
118
|
-
const
|
|
119
|
-
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
120
|
-
const configured = configuredWindow(settings, env, breakdown.model);
|
|
121
|
-
const effective = Math.min(configured ?? capacity, capacity);
|
|
122
|
-
const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
123
|
-
const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
|
|
124
|
-
const native = autoCompact
|
|
125
|
-
? pct === undefined ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow)
|
|
126
|
-
: available;
|
|
127
|
-
const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
|
|
134
|
+
const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, nativeFromWindow, resetMargin, warningRunway);
|
|
128
135
|
if (window !== undefined) return limits;
|
|
129
136
|
return {
|
|
130
137
|
...limits, unit: "percent",
|
package/plugins/pi/budget.ts
CHANGED
|
@@ -17,9 +17,9 @@ export const ContextRemainingOutputSchema = Type.Object({
|
|
|
17
17
|
}, { additionalProperties: false });
|
|
18
18
|
|
|
19
19
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
20
|
-
function remainingTokens(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model"
|
|
20
|
+
function remainingTokens(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">, cap?: number): number | null {
|
|
21
21
|
const usage = windowUsage(ctx);
|
|
22
|
-
return !usage || usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
|
|
22
|
+
return !usage || usage.tokens === null ? null : Math.max(0, Math.min(usage.contextWindow, cap ?? Infinity) - usage.tokens);
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export function registerBudget(
|
|
@@ -27,6 +27,7 @@ export function registerBudget(
|
|
|
27
27
|
isEnabled: () => boolean,
|
|
28
28
|
settingsManager?: SettingsManager,
|
|
29
29
|
) {
|
|
30
|
+
let cap: number | undefined;
|
|
30
31
|
let cachedPolicy: { thresholds: ResolvedThresholds; automatic: boolean } | undefined;
|
|
31
32
|
const notifiedWarnings = new Set<string>();
|
|
32
33
|
const resolvePolicy = (ctx: ExtensionContext): ThresholdSettingsResolution => {
|
|
@@ -45,15 +46,16 @@ export function registerBudget(
|
|
|
45
46
|
const hardReserveDue = (ctx: ExtensionContext, preSendMessages?: AgentMessage[]): boolean => {
|
|
46
47
|
if (!automaticResetEnabled(ctx)) return false;
|
|
47
48
|
if (preSendMessages) {
|
|
48
|
-
const
|
|
49
|
-
if (!
|
|
49
|
+
const nativeWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
|
|
50
|
+
if (!nativeWindow || nativeWindow <= 0) return false;
|
|
51
|
+
const contextWindow = Math.min(nativeWindow, cap ?? Infinity);
|
|
50
52
|
const { reserve } = thresholdsFor(ctx);
|
|
51
53
|
const estimate = estimateContextTokens(convertToLlm(preSendMessages));
|
|
52
54
|
if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve) return false;
|
|
53
55
|
return contextWindow - estimate.tokens <= reserve;
|
|
54
56
|
}
|
|
55
|
-
const
|
|
56
|
-
return
|
|
57
|
+
const remaining = remainingTokens(ctx, cap);
|
|
58
|
+
return remaining !== null && remaining <= thresholdsFor(ctx).reserve;
|
|
57
59
|
};
|
|
58
60
|
let pendingGuidance: { windowId: string; content: string } | undefined;
|
|
59
61
|
let pendingWarning: { windowId: string; content: string } | undefined;
|
|
@@ -87,10 +89,10 @@ export function registerBudget(
|
|
|
87
89
|
}));
|
|
88
90
|
};
|
|
89
91
|
|
|
90
|
-
pi.on("session_start", (_event, ctx) => { resetForTransition(); thresholdsFor(ctx); });
|
|
92
|
+
pi.on("session_start", (_event, ctx) => { cap = undefined; resetForTransition(); thresholdsFor(ctx); });
|
|
91
93
|
pi.on("session_tree", resetForTransition);
|
|
92
94
|
pi.on("model_select", resetForTransition);
|
|
93
|
-
pi.on("session_shutdown", resetForTransition);
|
|
95
|
+
pi.on("session_shutdown", () => { cap = undefined; resetForTransition(); });
|
|
94
96
|
pi.on("agent_settled", clearStaged);
|
|
95
97
|
pi.on("context", (event, ctx) => {
|
|
96
98
|
if (!isEnabled()) return undefined;
|
|
@@ -104,7 +106,7 @@ export function registerBudget(
|
|
|
104
106
|
// measured for that request, and persists the same text at its successful turn_end.
|
|
105
107
|
// Without automatic reset nothing gets cleared, so there is nothing to remind about.
|
|
106
108
|
if (!automaticResetEnabled(ctx)) return result();
|
|
107
|
-
const remaining = remainingTokens(ctx);
|
|
109
|
+
const remaining = remainingTokens(ctx, cap);
|
|
108
110
|
if (remaining === null) return result();
|
|
109
111
|
const windowId = currentWindowId(ctx);
|
|
110
112
|
const { reminder, warning, reserve } = thresholdsFor(ctx);
|
|
@@ -139,7 +141,7 @@ export function registerBudget(
|
|
|
139
141
|
outputSchema: ContextRemainingOutputSchema,
|
|
140
142
|
async execute(_id, _params, _signal, _update, ctx) {
|
|
141
143
|
// Report room to the hard-reserve wipe, including the warning runway.
|
|
142
|
-
const remaining = remainingTokens(ctx);
|
|
144
|
+
const remaining = remainingTokens(ctx, cap);
|
|
143
145
|
const value = { remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx as ExtensionContext).reserve) };
|
|
144
146
|
return { ...output(value), structuredContent: value };
|
|
145
147
|
},
|
|
@@ -150,7 +152,15 @@ export function registerBudget(
|
|
|
150
152
|
hardReserveDue,
|
|
151
153
|
consumeTurnEnd,
|
|
152
154
|
/** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
|
|
153
|
-
statusFor: (ctx: ExtensionContext)
|
|
155
|
+
statusFor: (ctx: ExtensionContext) => ({ remaining: remainingBudget(remainingTokens(ctx, cap), thresholdsFor(ctx).reserve), cap }),
|
|
156
|
+
/** Runtime-only cap; reserve and all warning margins keep their existing meanings. */
|
|
157
|
+
setCap: (value: number | undefined, ctx: ExtensionContext): string | undefined => {
|
|
158
|
+
const reserve = thresholdsFor(ctx).reserve;
|
|
159
|
+
if (value !== undefined && value <= reserve) return `Cap must exceed the ${reserve.toLocaleString("en-US")}-token reset reserve`;
|
|
160
|
+
cap = value;
|
|
161
|
+
clearStaged();
|
|
162
|
+
return undefined;
|
|
163
|
+
},
|
|
154
164
|
clear: () => { clearStaged(); notifiedWindows.clear(); },
|
|
155
165
|
};
|
|
156
166
|
}
|
package/plugins/pi/runtime.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { buildBootMessage, sendBoot, type IncompleteNotesNotifier } from "./boot
|
|
|
17
17
|
import { maybeSendMarker } from "./marker.js";
|
|
18
18
|
import { nextHistorySeq } from "./history.js";
|
|
19
19
|
import { errorMessage } from "../../src/error-message.js";
|
|
20
|
+
import { parseContextCap } from "../../src/budget/cap.js";
|
|
20
21
|
|
|
21
22
|
function readPackageVersion(): string {
|
|
22
23
|
for (const up of ["../../package.json", "../../../package.json"]) {
|
|
@@ -152,12 +153,23 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
152
153
|
});
|
|
153
154
|
|
|
154
155
|
pi.registerCommand("notesoup", {
|
|
155
|
-
description: "Show
|
|
156
|
+
description: "Show notesoup status, toggle context windows, or cap their capacity",
|
|
156
157
|
getArgumentCompletions: (prefix) =>
|
|
157
|
-
["on", "off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
|
|
158
|
+
["on", "off", "cap", "cap off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
|
|
158
159
|
handler: async (args, cmdCtx) => {
|
|
159
160
|
const arg = args.trim().toLowerCase();
|
|
160
|
-
|
|
161
|
+
const parts = arg.split(/\s+/);
|
|
162
|
+
if (parts[0] === "cap") {
|
|
163
|
+
if (parts.length > 1) {
|
|
164
|
+
const value = parts.length === 2 ? parseContextCap(parts[1]!) : undefined;
|
|
165
|
+
if (value === undefined) {
|
|
166
|
+
cmdCtx.ui.notify("Usage: /notesoup cap [100k|1m|tokens|off]", "error");
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const error = budget.setCap(value ?? undefined, cmdCtx);
|
|
170
|
+
if (error) { cmdCtx.ui.notify(`🥣 ${error}`, "error"); return; }
|
|
171
|
+
}
|
|
172
|
+
} else if (arg === "on") {
|
|
161
173
|
enabled = true;
|
|
162
174
|
const generation = ++lifecycleGeneration;
|
|
163
175
|
await ensureBoot(pi, cmdCtx, notifyIncompleteNotes, () => generation === lifecycleGeneration && enabled);
|
|
@@ -170,11 +182,11 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
170
182
|
budget.clear();
|
|
171
183
|
resets.clear();
|
|
172
184
|
} else if (arg !== "") {
|
|
173
|
-
cmdCtx.ui.notify("Usage: /notesoup [on|off]", "error");
|
|
185
|
+
cmdCtx.ui.notify("Usage: /notesoup [on|off|cap [100k|1m|tokens|off]]", "error");
|
|
174
186
|
return;
|
|
175
187
|
}
|
|
176
|
-
const remaining = budget.statusFor(cmdCtx)
|
|
177
|
-
cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
|
|
188
|
+
const { remaining, cap } = budget.statusFor(cmdCtx);
|
|
189
|
+
cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION} · cap ${cap === undefined ? "off" : cap.toLocaleString("en-US")}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
|
|
178
190
|
},
|
|
179
191
|
});
|
|
180
192
|
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Parse a slash-command cap: decimal k/m suffixes, whole tokens, or off. */
|
|
2
|
+
export function parseContextCap(value: string): number | null | undefined {
|
|
3
|
+
const text = value.trim().toLowerCase();
|
|
4
|
+
if (text === "off") return null;
|
|
5
|
+
const match = /^(\d+(?:\.\d+)?)([km]?)$/.exec(text);
|
|
6
|
+
if (!match) return undefined;
|
|
7
|
+
const tokens = Number(match[1]) * (match[2] === "m" ? 1_000_000 : match[2] === "k" ? 1_000 : 1);
|
|
8
|
+
return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined;
|
|
9
|
+
}
|