notesoup 0.58.2 → 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 +2 -1
- 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/boot/text.d.ts +1 -1
- package/dist/src/boot/text.js +5 -4
- package/dist/src/budget/cap.d.ts +2 -0
- package/dist/src/budget/cap.js +11 -0
- package/dist/src/notes/policy.d.ts +1 -1
- package/dist/src/notes/policy.js +4 -3
- package/dist/src/tools/notes.js +1 -1
- package/dist/test/agent-loop.test.js +13 -39
- package/dist/test/boot.integration.test.js +20 -18
- package/dist/test/budget-settings.integration.test.js +63 -14
- package/dist/test/claude-history.test.js +1 -2
- package/dist/test/claude-mod.test.js +96 -29
- package/dist/test/codex-history.test.js +9 -6
- package/dist/test/codex-plugin.test.js +4 -8
- package/dist/test/dream-skill.test.js +6 -10
- package/dist/test/dsh-cli.test.js +2 -3
- package/dist/test/dsh.test.js +1 -7
- package/dist/test/helpers/extension.js +3 -1
- package/dist/test/history-corpus.test.js +2 -3
- package/dist/test/history-prefilter.test.js +33 -40
- package/dist/test/history-summary-cache.test.js +1 -1
- package/dist/test/history.integration.test.js +11 -37
- package/dist/test/host-neutral.test.js +2 -2
- package/dist/test/marker.test.js +1 -2
- package/dist/test/model-facing-text.test.js +20 -187
- package/dist/test/note-policy.test.js +40 -22
- package/dist/test/notes-library.test.js +2 -2
- package/dist/test/notes.integration.test.js +36 -149
- package/dist/test/notes.test.js +13 -61
- package/dist/test/pi-render.test.js +23 -62
- package/dist/test/reset-lifecycle.test.js +4 -9
- package/docs/architecture.md +1 -1
- package/docs/claude-code-mod.md +5 -3
- package/docs/dsh.md +1 -1
- package/docs/notes-library.md +1 -1
- package/docs/reset-lifecycle.md +3 -1
- package/docs/tool-results.md +1 -1
- package/package.json +1 -1
- package/playbook.md +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +47 -17
- package/plugins/claude/hooks/register.ts +51 -5
- package/plugins/claude/playbook.md +1 -1
- package/plugins/claude/skills/dream/SKILL.md +1 -1
- package/plugins/claude/skills/memory/SKILL.md +1 -1
- package/plugins/claude/src/helper.ts +11 -0
- package/plugins/claude/src/thresholds.ts +18 -11
- package/plugins/codex/dist/codex/notesoup.js +10 -8
- package/plugins/pi/budget.ts +21 -11
- package/plugins/pi/runtime.ts +18 -6
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/text.ts +5 -4
- package/src/budget/cap.ts +9 -0
- package/src/notes/policy.ts +4 -3
- package/src/tools/notes.ts +1 -1
package/docs/dsh.md
CHANGED
|
@@ -47,7 +47,7 @@ The reminder and close-out warning go through `agent.steer`. Close-out remains a
|
|
|
47
47
|
| dsh versions | Tested against **0.2.1-alpha.2**. Capability checks do not establish wire or persistence compatibility with every newer preview. Run the scripted tests before upgrading. |
|
|
48
48
|
| Model calls per reset | **0** auxiliary model calls. The agent's note-writing turns and fresh-window continuation still make ordinary calls. |
|
|
49
49
|
| Retention | Surface node **0**, one boot/continuation checkpoint, and subsequent messages. An unfinished tool batch postpones reset; no partial tool pairs are discarded. |
|
|
50
|
-
| Boot bounds | Up to **5 live pins** and **3 recent notes per notebook**, from the shared policy/renderer. Root CHEATSHEET/MAP default pinned; explicit `pinned:false` overrides.
|
|
50
|
+
| Boot bounds | Up to **5 live pins** and **3 recent notes per notebook**, from the shared policy/renderer. Root CHEATSHEET/MAP default pinned; explicit `pinned:false` overrides. Ordinary pages default to a **4096-code-point advisory budget**; root CHEATSHEET/MAP default to **2048**, adjustable per note. Pinned bodies arrive **whole**, with over-budget warnings instead of truncation; manually over-cap pins are omitted with a visible address list. |
|
|
51
51
|
| Tool output | Shared **32 KiB** bounds; use `next_offset_chars`, history cursors, or narrower filters. There is no unbounded hidden result. |
|
|
52
52
|
| Warning timing | Steering enters the next step; a large current response/tool batch can spend the runway. The hard reserve protects the next balanced boundary, not an in-flight provider call. |
|
|
53
53
|
| Unknown capacity | Countdown is **null** and automatic reserve checks skip. Add `models[].contextWindow` to `llm-deepseek`; explicit resets still work. |
|
package/docs/notes-library.md
CHANGED
|
@@ -53,7 +53,7 @@ Addresses are a relative path (a current-session note), `@project/`, `@human/`,
|
|
|
53
53
|
|
|
54
54
|
`effectiveNotePolicy(meta, path)` returns `{ pinned, budget, readonly }` for a notebook-relative Markdown path (`MAP.md`, not an `@` address). This is the shared default resolver used by storage, tools and boot:
|
|
55
55
|
|
|
56
|
-
-
|
|
56
|
+
- Ordinary pages have a default budget of **4096 Unicode code points**; root `CHEATSHEET.md` and `MAP.md` default to **2048**, adjustable to any positive safe integer. `warnings` on write/update/rename results report body overflow but do not reject it. Astral characters count once. The separate serialized-file byte limit still applies.
|
|
57
57
|
- Only root `CHEATSHEET.md` and `MAP.md` default to pinned; all other paths, including nested files with those names, default false. Explicit false overrides the default. Raw `meta` keeps absent policy fields absent, so implicit defaults are re-evaluated at a move's destination; explicitly set values travel with the note.
|
|
58
58
|
- Every physical notebook allows **5 live pins**, including existing default pages. Crumpled pins don't count. New pinning, writes that restore notes, explicit restores, and moves/renames all check admission and refuse with `pin_limit` before mutation if they would add a sixth pin. Same-notebook moves of an already-live pin don't consume another slot. Existing over-cap notes can still be edited, unpinned or crumpled. Boot defensively selects at most five pins, default-page-first then path order, visibly naming omitted pins in a manually over-cap notebook. Pinned bodies are injected whole, with budget warnings rather than truncation.
|
|
59
59
|
- `readonly: true` is a **soft lock**, not an authorization/security boundary. Existing locked notes refuse changes, overwrite, crumple/restore, rename/move, and dream deletion with `readonly`. Explicit `readonly: false` permits a metadata-only unlock or unlock plus the requested mutation in one call. A new/unlocked note may be written and locked together. Replacing a locked crumpled move target also requires explicit false. Reads/access counters still write, and filesystem edits can bypass the lock.
|
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/docs/tool-results.md
CHANGED
|
@@ -69,7 +69,7 @@ One selection determines the structured result and its text. Both complete repre
|
|
|
69
69
|
|
|
70
70
|
`after_seq` is a strict lower bound; `after_seq: 0` starts from the beginning. History pages carry boolean `has_older` and `has_newer` flags. For single-session pages, use the first item’s `seq` as `before_seq` to page older, and the last item’s `seq` as `after_seq` to page newer; include its `session` when present. Wildcard pages instead report more results and suggest narrowing by time, query, roles or session pattern; an overview with unvisited sessions may have more. The single-session rendered newer footer gives `→ newer: {"after_seq":...}` with an optional session. `from` picks which end of a bounded range `limit` counts from: it defaults to `oldest` when `after_seq` is set, and `newest` otherwise. Explicit `from` wins. `since`/`until` narrow that range by event `created_at`, and only a single-session call without roles or a non-empty query folds tool/context runs. Omitted queries, empty strings and empty lists all disable search filtering; empty entries in a query list are ignored. Without a query, notes search returns scoped notes with empty `matches`, not every body line. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
|
|
71
71
|
|
|
72
|
-
`notes_write` and `notes_update` accept optional `pinned`, `budget`, and `readonly` policy fields. Their receipts, list/search rows, and read `metadata` expose the effective `pinned`, `budget`, and `readonly` values as structured fields **and visible text**. Successes also carry a `warnings` array (per file for list/search), rendered visibly when a body exceeds its budget: the default is
|
|
72
|
+
`notes_write` and `notes_update` accept optional `pinned`, `budget`, and `readonly` policy fields. Their receipts, list/search rows, and read `metadata` expose the effective `pinned`, `budget`, and `readonly` values as structured fields **and visible text**. Successes also carry a `warnings` array (per file for list/search), rendered visibly when a body exceeds its budget: the default is 4096 Unicode code points for ordinary pages and 2048 for root `CHEATSHEET.md` and `MAP.md`, adjustable per note. Overflow saves successfully; boot injects full pinned bodies instead of cutting them. Pi's custom write/update/read renderers show policy and warnings even when collapsed, outside the expandable body/diff and clipped summary. A readonly note refuses mutations with `readonly` until explicitly unlocked with `readonly:false`; this is a soft lock, not security. Pin admission refuses a sixth live pin per notebook with `pin_limit`, including restore/move/rename. Invalid policy fields refuse with `invalid_policy`.
|
|
73
73
|
|
|
74
74
|
A note read reports unrecognized frontmatter under `metadata.extra`; a value too large to carry, or past the verbatim budget, is named in place as `[omitted: too large]` under its key rather than delivered in part, and the value itself stays in the note file. A rename receipt uses `address` for the destination and `rename_from` for the source; it has no duplicate `rename_to` field.
|
|
75
75
|
|
package/package.json
CHANGED
package/playbook.md
CHANGED
|
@@ -27,7 +27,7 @@ Durable notes hold decisions, constraints, and lessons that stay true after the
|
|
|
27
27
|
5. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper notebook, move it there, preserving its metadata, and update both notebooks' maps. Do it, don't propose it. Propose only when the destination notebook itself is unclear.
|
|
28
28
|
6. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
|
|
29
29
|
7. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links.
|
|
30
|
-
8. **Keep wake-up pages useful.** Each writable notebook's `CHEATSHEET.md` holds standing reminders, kept to five lines. Its `MAP.md` holds only the note index: durable notes' addresses and short gists. Both default to pinned and load every window when live unless explicitly unpinned; do not create empty pages. Each notebook allows five live pins.
|
|
30
|
+
8. **Keep wake-up pages useful.** Each writable notebook's `CHEATSHEET.md` holds standing reminders, kept to five lines. Its `MAP.md` holds only the note index: durable notes' addresses and short gists. Both default to pinned and load every window when live unless explicitly unpinned; do not create empty pages. Each notebook allows five live pins. Ordinary pages default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note; overflow warns without truncating a pinned body. Preserve standing rules, add promoted notes to the map, and drop entries that no longer hold.
|
|
31
31
|
|
|
32
32
|
## Deleting
|
|
33
33
|
|
|
@@ -8165,7 +8165,7 @@ function addressFor(identity2, scope, path, who) {
|
|
|
8165
8165
|
}
|
|
8166
8166
|
|
|
8167
8167
|
// src/notes/policy.ts
|
|
8168
|
-
var DEFAULT_NOTE_BUDGET =
|
|
8168
|
+
var DEFAULT_NOTE_BUDGET = 4096;
|
|
8169
8169
|
var MAX_PINNED_NOTES = 5;
|
|
8170
8170
|
var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
|
|
8171
8171
|
function validateNotePolicy(fields) {
|
|
@@ -8178,9 +8178,10 @@ function validateNotePolicy(fields) {
|
|
|
8178
8178
|
}
|
|
8179
8179
|
function effectiveNotePolicy(fields, path) {
|
|
8180
8180
|
validateNotePolicy(fields);
|
|
8181
|
+
const defaultPage = DEFAULT_PINNED_PAGES.some((page) => page === path);
|
|
8181
8182
|
return {
|
|
8182
|
-
pinned: fields.pinned ??
|
|
8183
|
-
budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
|
|
8183
|
+
pinned: fields.pinned ?? defaultPage,
|
|
8184
|
+
budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
|
|
8184
8185
|
readonly: fields.readonly ?? false
|
|
8185
8186
|
};
|
|
8186
8187
|
}
|
|
@@ -9166,7 +9167,7 @@ var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES],
|
|
|
9166
9167
|
}));
|
|
9167
9168
|
var POLICY_PARAMETERS = {
|
|
9168
9169
|
pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
|
|
9169
|
-
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default
|
|
9170
|
+
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 4096; root CHEATSHEET.md and MAP.md default 2048). Over budget warns but saves; boot does not truncate." })),
|
|
9170
9171
|
readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." }))
|
|
9171
9172
|
};
|
|
9172
9173
|
var PolicySchema = {
|
|
@@ -11229,10 +11230,11 @@ Pinned pages get jammed straight into your brain the moment you wake up. Whoever
|
|
|
11229
11230
|
reads them, and next is you. So keep them short, and keep them true.
|
|
11230
11231
|
|
|
11231
11232
|
Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
|
|
11232
|
-
live pins, including the defaults; \`pinned:false\` unpins even a default page.
|
|
11233
|
-
|
|
11234
|
-
and pinned bodies arrive whole, not cut short.
|
|
11235
|
-
explicitly set \`readonly:false\` to unlock,
|
|
11233
|
+
live pins, including the defaults; \`pinned:false\` unpins even a default page. Budgets start at 4096
|
|
11234
|
+
Unicode code points, or 2048 for root \`CHEATSHEET.md\` and \`MAP.md\`; set a positive integer to
|
|
11235
|
+
change one. Going over warns but saves, and pinned bodies arrive whole, not cut short.
|
|
11236
|
+
\`readonly:true\` is a soft lock, not security; explicitly set \`readonly:false\` to unlock,
|
|
11237
|
+
on its own or with your changes.
|
|
11236
11238
|
|
|
11237
11239
|
- **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
|
|
11238
11240
|
a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
|
|
@@ -11476,6 +11478,11 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
|
|
|
11476
11478
|
warningRunway
|
|
11477
11479
|
};
|
|
11478
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
|
+
}
|
|
11479
11486
|
function resolveClaudeLimits(facts) {
|
|
11480
11487
|
const root = isPlainObject(facts) ? facts : {};
|
|
11481
11488
|
const usage = isPlainObject(root.usage) ? root.usage : {};
|
|
@@ -11487,19 +11494,22 @@ function resolveClaudeLimits(facts) {
|
|
|
11487
11494
|
const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
|
|
11488
11495
|
const autoCompact = settingFlag(settings2) !== false && !presenceFlag(env.disableAutoCompact) && breakdown.isAutoCompactEnabled !== false;
|
|
11489
11496
|
const pct = percent(env.pctOverride);
|
|
11490
|
-
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
11491
|
-
if (autoCompact && threshold !== void 0) {
|
|
11492
|
-
const native2 = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
11493
|
-
if (native2 > 0) return tokenLimits("auto-compact", true, native2, resetMargin, warningRunway);
|
|
11494
|
-
}
|
|
11495
11497
|
const window = positiveNumber(usage.window);
|
|
11496
11498
|
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
11497
11499
|
const configured = configuredWindow(settings2, env, breakdown.model);
|
|
11498
11500
|
const effective = Math.min(configured ?? capacity, capacity);
|
|
11499
|
-
const
|
|
11500
|
-
const
|
|
11501
|
-
const
|
|
11502
|
-
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);
|
|
11503
11513
|
if (window !== void 0) return limits;
|
|
11504
11514
|
return {
|
|
11505
11515
|
...limits,
|
|
@@ -11510,6 +11520,16 @@ function resolveClaudeLimits(facts) {
|
|
|
11510
11520
|
};
|
|
11511
11521
|
}
|
|
11512
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
|
+
|
|
11513
11533
|
// plugins/claude/src/helper.ts
|
|
11514
11534
|
var MAX_REQUEST_BYTES = 512 * 1024;
|
|
11515
11535
|
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
@@ -11547,6 +11567,16 @@ function historySource(value, sessionId) {
|
|
|
11547
11567
|
async function dispatch(request, historyOptions = {}) {
|
|
11548
11568
|
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
|
|
11549
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
|
+
}
|
|
11550
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)) }));
|
|
11551
11581
|
if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
|
|
11552
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}` }
|
|
@@ -27,7 +27,7 @@ Durable notes hold decisions, constraints, and lessons that stay true after the
|
|
|
27
27
|
5. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper notebook, move it there, preserving its metadata, and update both notebooks' maps. Do it, don't propose it. Propose only when the destination notebook itself is unclear.
|
|
28
28
|
6. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
|
|
29
29
|
7. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links.
|
|
30
|
-
8. **Keep wake-up pages useful.** Each writable notebook's `CHEATSHEET.md` holds standing reminders, kept to five lines. Its `MAP.md` holds only the note index: durable notes' addresses and short gists. Both default to pinned and load every window when live unless explicitly unpinned; do not create empty pages. Each notebook allows five live pins.
|
|
30
|
+
8. **Keep wake-up pages useful.** Each writable notebook's `CHEATSHEET.md` holds standing reminders, kept to five lines. Its `MAP.md` holds only the note index: durable notes' addresses and short gists. Both default to pinned and load every window when live unless explicitly unpinned; do not create empty pages. Each notebook allows five live pins. Ordinary pages default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note; overflow warns without truncating a pinned body. Preserve standing rules, add promoted notes to the map, and drop entries that no longer hold.
|
|
31
31
|
|
|
32
32
|
## Deleting
|
|
33
33
|
|
|
@@ -5,7 +5,7 @@ description: Review and consolidate durable notes using notesoup's shared dream
|
|
|
5
5
|
|
|
6
6
|
# Dream
|
|
7
7
|
|
|
8
|
-
Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. Standing reminders belong in a separate `CHEATSHEET.md` (five lines); `MAP.md` holds only the note index. Both default to pinned and load every window when live unless explicitly unpinned.
|
|
8
|
+
Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. Standing reminders belong in a separate `CHEATSHEET.md` (five lines); `MAP.md` holds only the note index. Both default to pinned and load every window when live unless explicitly unpinned. Ordinary notes default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note; pinned bodies load whole with overflow warnings. Respect soft readonly locks; explicitly unlock with `readonly:false` before changing a locked note.
|
|
9
9
|
|
|
10
10
|
Dream in this agent's current session. Do not start another agent or model unless the human asks.
|
|
11
11
|
|
|
@@ -32,7 +32,7 @@ Any other `@` prefix is refused. A path is relative and `/`-separated, with no e
|
|
|
32
32
|
|
|
33
33
|
`@` addresses are not file paths: never pass them to file tools like `read`, `write`, `edit`, or `bash`. That creates a stray directory instead of a note.
|
|
34
34
|
|
|
35
|
-
`CHEATSHEET.md` and `MAP.md` at each notebook's root are separate default-pinned pages you wake up with; absent or crumpled pages are skipped. Set `pinned`, `budget`, and `readonly` through `notes_write`/`notes_update` or frontmatter. Explicit `pinned:false` unpins even a default page. Each notebook allows five live pins;
|
|
35
|
+
`CHEATSHEET.md` and `MAP.md` at each notebook's root are separate default-pinned pages you wake up with; absent or crumpled pages are skipped. Set `pinned`, `budget`, and `readonly` through `notes_write`/`notes_update` or frontmatter. Explicit `pinned:false` unpins even a default page. Each notebook allows five live pins; ordinary pages default to a 4096-code-point advisory budget (2048 for root `CHEATSHEET.md` and `MAP.md`), adjustable per note. Overflow warns but saves, and pinned bodies load whole. `readonly:true` is a soft lock, not security; explicitly set `readonly:false` to unlock, alone or alongside your changes. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
|
|
36
36
|
|
|
37
37
|
Keep notes focused on what is true now; if a piece of past context still matters (such as why an approach was ruled out), keep only a brief summary rather than a blow-by-blow log. Crumple notes that are no longer true; a stale note is worse than none.
|
|
38
38
|
|
|
@@ -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",
|
|
@@ -25140,7 +25140,7 @@ function addressFor(identity, scope, path, who) {
|
|
|
25140
25140
|
}
|
|
25141
25141
|
|
|
25142
25142
|
// src/notes/policy.ts
|
|
25143
|
-
var DEFAULT_NOTE_BUDGET =
|
|
25143
|
+
var DEFAULT_NOTE_BUDGET = 4096;
|
|
25144
25144
|
var MAX_PINNED_NOTES = 5;
|
|
25145
25145
|
var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
|
|
25146
25146
|
function validateNotePolicy(fields) {
|
|
@@ -25153,9 +25153,10 @@ function validateNotePolicy(fields) {
|
|
|
25153
25153
|
}
|
|
25154
25154
|
function effectiveNotePolicy(fields, path) {
|
|
25155
25155
|
validateNotePolicy(fields);
|
|
25156
|
+
const defaultPage = DEFAULT_PINNED_PAGES.some((page) => page === path);
|
|
25156
25157
|
return {
|
|
25157
|
-
pinned: fields.pinned ??
|
|
25158
|
-
budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
|
|
25158
|
+
pinned: fields.pinned ?? defaultPage,
|
|
25159
|
+
budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
|
|
25159
25160
|
readonly: fields.readonly ?? false
|
|
25160
25161
|
};
|
|
25161
25162
|
}
|
|
@@ -26141,7 +26142,7 @@ var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES],
|
|
|
26141
26142
|
}));
|
|
26142
26143
|
var POLICY_PARAMETERS = {
|
|
26143
26144
|
pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
|
|
26144
|
-
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default
|
|
26145
|
+
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 4096; root CHEATSHEET.md and MAP.md default 2048). Over budget warns but saves; boot does not truncate." })),
|
|
26145
26146
|
readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." }))
|
|
26146
26147
|
};
|
|
26147
26148
|
var PolicySchema = {
|
|
@@ -28284,10 +28285,11 @@ Pinned pages get jammed straight into your brain the moment you wake up. Whoever
|
|
|
28284
28285
|
reads them, and next is you. So keep them short, and keep them true.
|
|
28285
28286
|
|
|
28286
28287
|
Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
|
|
28287
|
-
live pins, including the defaults; \`pinned:false\` unpins even a default page.
|
|
28288
|
-
|
|
28289
|
-
and pinned bodies arrive whole, not cut short.
|
|
28290
|
-
explicitly set \`readonly:false\` to unlock,
|
|
28288
|
+
live pins, including the defaults; \`pinned:false\` unpins even a default page. Budgets start at 4096
|
|
28289
|
+
Unicode code points, or 2048 for root \`CHEATSHEET.md\` and \`MAP.md\`; set a positive integer to
|
|
28290
|
+
change one. Going over warns but saves, and pinned bodies arrive whole, not cut short.
|
|
28291
|
+
\`readonly:true\` is a soft lock, not security; explicitly set \`readonly:false\` to unlock,
|
|
28292
|
+
on its own or with your changes.
|
|
28291
28293
|
|
|
28292
28294
|
- **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
|
|
28293
28295
|
a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
|
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
|
}
|