notesoup 0.58.3 → 0.59.1
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/dsh/tools.js +0 -3
- 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 +6 -10
- package/dist/src/budget/cap.d.ts +2 -0
- package/dist/src/budget/cap.js +11 -0
- package/dist/src/notes/address.d.ts +1 -1
- package/dist/src/notes/address.js +1 -1
- package/dist/src/notes/policy.js +1 -1
- package/dist/src/tools/dream.d.ts +3 -3
- package/dist/src/tools/dream.js +5 -5
- package/dist/src/tools/history.js +12 -13
- package/dist/src/tools/notes.d.ts +7 -5
- package/dist/src/tools/notes.js +35 -34
- package/dist/src/tools/result.js +2 -2
- package/dist/src/tools/schema.js +2 -2
- package/dist/test/budget-settings.integration.test.js +45 -1
- package/dist/test/claude-mod.test.js +80 -21
- package/dist/test/dsh.test.js +13 -1
- package/dist/test/note-policy.test.js +6 -1
- package/dist/test/notes.integration.test.js +28 -0
- 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 +96 -70
- package/plugins/claude/hooks/register.ts +57 -9
- package/plugins/claude/src/helper.ts +11 -0
- package/plugins/claude/src/thresholds.ts +18 -11
- package/plugins/codex/dist/codex/notesoup.js +59 -61
- package/plugins/dsh/tools.ts +0 -2
- package/plugins/pi/budget.ts +21 -11
- package/plugins/pi/runtime.ts +18 -6
- package/src/boot/text.ts +6 -10
- package/src/budget/cap.ts +9 -0
- package/src/notes/address.ts +1 -1
- package/src/notes/policy.ts +1 -1
- package/src/tools/dream.ts +5 -5
- package/src/tools/history.ts +12 -14
- package/src/tools/notes.ts +35 -33
- package/src/tools/result.ts +2 -2
- package/src/tools/schema.ts +2 -2
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
|
@@ -8015,7 +8015,7 @@ function filteredItems(projection, params) {
|
|
|
8015
8015
|
|
|
8016
8016
|
// src/tools/schema.ts
|
|
8017
8017
|
var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
|
|
8018
|
-
var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "
|
|
8018
|
+
var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "Only these voices: user, assistant, tool, context. Without roles or query, tool and context runs fold into one line." }));
|
|
8019
8019
|
function paramProblem(schema, params) {
|
|
8020
8020
|
const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
|
|
8021
8021
|
if (!first) return "unrecognized shape";
|
|
@@ -8023,7 +8023,7 @@ function paramProblem(schema, params) {
|
|
|
8023
8023
|
const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
|
|
8024
8024
|
return `${field ? `${field} ` : ""}${first.message}${extra}`;
|
|
8025
8025
|
}
|
|
8026
|
-
var searchQuery = (description = "
|
|
8026
|
+
var searchQuery = (description = "Text to look for, or a list (any match). Leave it out to just list the pages.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
|
|
8027
8027
|
|
|
8028
8028
|
// src/notes/errors.ts
|
|
8029
8029
|
var NoteError = class extends Error {
|
|
@@ -8090,7 +8090,7 @@ function physicalPath(scope, vpath, identity2, who) {
|
|
|
8090
8090
|
}
|
|
8091
8091
|
|
|
8092
8092
|
// src/notes/address.ts
|
|
8093
|
-
var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path
|
|
8093
|
+
var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path>, @sessions/<id>/<path>, @agents/<name>/<path>, and @models/<name>/<path> read named notebooks.";
|
|
8094
8094
|
var NAMESPACE_HEADS = /* @__PURE__ */ new Map([
|
|
8095
8095
|
["project", { scope: "project" }],
|
|
8096
8096
|
["human", { scope: "human" }],
|
|
@@ -8191,7 +8191,7 @@ function pinnedPageOrder(path) {
|
|
|
8191
8191
|
}
|
|
8192
8192
|
function noteBudgetWarnings(body, policy) {
|
|
8193
8193
|
const count = Array.from(body).length;
|
|
8194
|
-
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}
|
|
8194
|
+
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} \u2014 boil it down.`] : [];
|
|
8195
8195
|
}
|
|
8196
8196
|
function assertNoteUnlocked(fields, unlock) {
|
|
8197
8197
|
if (fields.readonly === true && unlock !== false) throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
|
|
@@ -9108,8 +9108,8 @@ var TextWindowSchema = typebox_exports.Object({
|
|
|
9108
9108
|
next_offset_chars: typebox_exports.Union([typebox_exports.Integer({ minimum: 0 }), typebox_exports.Null()], { description: "Pass as `offset_chars` to continue; null at the end." })
|
|
9109
9109
|
}, { additionalProperties: false });
|
|
9110
9110
|
var TextWindowRequestSchema = {
|
|
9111
|
-
offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "
|
|
9112
|
-
max_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description:
|
|
9111
|
+
offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
|
|
9112
|
+
max_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." }))
|
|
9113
9113
|
};
|
|
9114
9114
|
function readTextWindow(text, offset, limit, makeData, render) {
|
|
9115
9115
|
const chars = Array.from(text);
|
|
@@ -9163,12 +9163,12 @@ function notesIdentityForCall(context2, cwd) {
|
|
|
9163
9163
|
// src/tools/notes.ts
|
|
9164
9164
|
var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("self"), typebox_exports.Literal("external")];
|
|
9165
9165
|
var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
|
|
9166
|
-
description: "
|
|
9166
|
+
description: "Whose handwriting: user, self, or external. Leave it out to keep what's there."
|
|
9167
9167
|
}));
|
|
9168
9168
|
var POLICY_PARAMETERS = {
|
|
9169
|
-
pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "
|
|
9170
|
-
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "
|
|
9171
|
-
readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "
|
|
9169
|
+
pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET and MAP included." })),
|
|
9170
|
+
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "How much paper the page gets. Writing past it still saves, with a warning. A page over budget gets boiled down: stale lines out, repeats merged, the rest said shorter. More paper is for a page already boiled down that still needs the room." })),
|
|
9171
|
+
readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off \u2014 same call is fine." }))
|
|
9172
9172
|
};
|
|
9173
9173
|
var PolicySchema = {
|
|
9174
9174
|
pinned: typebox_exports.Boolean(),
|
|
@@ -9185,13 +9185,12 @@ function renderPolicy(policy) {
|
|
|
9185
9185
|
function withWarnings(text, data) {
|
|
9186
9186
|
return [text, ...data.warnings].join("\n");
|
|
9187
9187
|
}
|
|
9188
|
-
var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "
|
|
9189
|
-
var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "
|
|
9190
|
-
var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "
|
|
9191
|
-
var GLOB_PARAMETER = nullableString("
|
|
9192
|
-
var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "
|
|
9193
|
-
var
|
|
9194
|
-
var ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable notebooks; `@projects/<name>/<path>` and `@sessions/<id>/<path>` read named project and session notes (read-only). Not file paths: never pass them to file tools.";
|
|
9188
|
+
var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "`true` balls the page up: gone from list and search, still readable. `false` smooths it flat again." }));
|
|
9189
|
+
var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Only the crumpled balls." }));
|
|
9190
|
+
var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many pages at most." }));
|
|
9191
|
+
var GLOB_PARAMETER = nullableString("Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf \xB7 `MAP.md` that page in every notebook \xB7 `**` everything \xB7 `@sessions/*/**` every session.");
|
|
9192
|
+
var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
|
|
9193
|
+
var ADDRESS_PARAMETER = typebox_exports.String({ description: "Which drawer the page sits in. `plan.md` \u2014 this session's desk, cleared when it ends. `@project/` this project's shelf \xB7 `@human/` your human's file \xB7 `@self/` your own notebook \xB7 `@model/` your brain's. `@projects/<name>/`, `@sessions/<id>/`, `@agents/<name>/`, `@models/<name>/` \u2014 someone else's shelf: read only. Paper, not files: hand one to read/write/edit/bash and a real `@project` folder is born." });
|
|
9195
9194
|
function failureOf(error) {
|
|
9196
9195
|
if (error instanceof NoteError) return failure(error.code, error.message);
|
|
9197
9196
|
if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
|
|
@@ -9281,7 +9280,8 @@ var MatchSchema = typebox_exports.Object({
|
|
|
9281
9280
|
}, { additionalProperties: false });
|
|
9282
9281
|
var SearchedFileSchema = typebox_exports.Object({
|
|
9283
9282
|
...ListedFileSchema.properties,
|
|
9284
|
-
matches: typebox_exports.Array(MatchSchema)
|
|
9283
|
+
matches: typebox_exports.Array(MatchSchema),
|
|
9284
|
+
more_matches: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1 }))
|
|
9285
9285
|
}, { additionalProperties: false });
|
|
9286
9286
|
var SnapshotSchema = {
|
|
9287
9287
|
more: typebox_exports.Integer({ description: "How many more were left out." }),
|
|
@@ -9338,14 +9338,14 @@ function listedFile(row, identity2) {
|
|
|
9338
9338
|
const policy = policyAt(row.meta, row.address);
|
|
9339
9339
|
return { ...noteIdentity(identity2, row.address), ...policy, warnings: row.warnings ?? (row.body === void 0 ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
|
|
9340
9340
|
}
|
|
9341
|
-
var notesWriteParameters = typebox_exports.Object({ address:
|
|
9341
|
+
var notesWriteParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, content: typebox_exports.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
9342
9342
|
function renderWriteData(data) {
|
|
9343
9343
|
return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
|
|
9344
9344
|
}
|
|
9345
9345
|
var notesWrite = {
|
|
9346
9346
|
name: "notes_write",
|
|
9347
9347
|
label: "Notes write",
|
|
9348
|
-
description:
|
|
9348
|
+
description: "Take a fresh page and write it \u2014 or rip out the old one and write it again. Title it for what's inside and when you'll reach for it.",
|
|
9349
9349
|
parameters: notesWriteParameters,
|
|
9350
9350
|
outputSchema: resultSchema(NotesWriteDataSchema),
|
|
9351
9351
|
executionMode: "sequential",
|
|
@@ -9361,13 +9361,13 @@ var notesWrite = {
|
|
|
9361
9361
|
render: (result) => renderOutcome(result, renderWriteData)
|
|
9362
9362
|
};
|
|
9363
9363
|
var notesUpdateParameters = typebox_exports.Object({
|
|
9364
|
-
address:
|
|
9365
|
-
edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String(), newText: typebox_exports.String() }, { additionalProperties: false }))),
|
|
9364
|
+
address: ADDRESS_PARAMETER,
|
|
9365
|
+
edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String({ description: "The passage as it stands on the page." }), newText: typebox_exports.String({ description: "What goes in its place." }) }, { additionalProperties: false }), { description: "Pen strokes, in order. Each `oldText` is the exact passage \u2014 same case, found once \u2014 and `newText` is what goes in its place." })),
|
|
9366
9366
|
origin: ORIGIN,
|
|
9367
9367
|
...POLICY_PARAMETERS,
|
|
9368
9368
|
crumpled: CRUMPLED_PARAMETER,
|
|
9369
|
-
replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "
|
|
9370
|
-
rename_to: typebox_exports.Optional(typebox_exports.String({ description: "
|
|
9369
|
+
replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
|
|
9370
|
+
rename_to: typebox_exports.Optional(typebox_exports.String({ description: "Move the page to another address. Never lands on top of a live page; nothing pointing at it follows." })),
|
|
9371
9371
|
cwd: CWD_PARAMETER
|
|
9372
9372
|
}, { additionalProperties: false });
|
|
9373
9373
|
function renderUpdateData(data) {
|
|
@@ -9377,7 +9377,7 @@ function renderUpdateData(data) {
|
|
|
9377
9377
|
var notesUpdate = {
|
|
9378
9378
|
name: "notes_update",
|
|
9379
9379
|
label: "Notes update",
|
|
9380
|
-
description:
|
|
9380
|
+
description: "Work on a page you already have: cross out and rewrite lines, move it, pin it, lock it, give it more paper, crumple it. Keep every page true to now: wrong, stale, or no-longer-mattering lines get rewritten or struck where they stand. The page stays one page.",
|
|
9381
9381
|
parameters: notesUpdateParameters,
|
|
9382
9382
|
outputSchema: resultSchema(NotesUpdateDataSchema),
|
|
9383
9383
|
executionMode: "sequential",
|
|
@@ -9397,7 +9397,7 @@ var notesUpdate = {
|
|
|
9397
9397
|
},
|
|
9398
9398
|
render: (result) => renderOutcome(result, renderUpdateData)
|
|
9399
9399
|
};
|
|
9400
|
-
var notesReadParameters = typebox_exports.Object({ address:
|
|
9400
|
+
var notesReadParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
9401
9401
|
function renderReadData(data) {
|
|
9402
9402
|
return withWarnings(`${renderIdentity(data)}
|
|
9403
9403
|
${renderMetadata(data.metadata)}`, data) + `
|
|
@@ -9407,7 +9407,7 @@ ${renderTextWindow(data)}`;
|
|
|
9407
9407
|
var notesRead = {
|
|
9408
9408
|
name: "notes_read",
|
|
9409
9409
|
label: "Notes read",
|
|
9410
|
-
description:
|
|
9410
|
+
description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
|
|
9411
9411
|
parameters: notesReadParameters,
|
|
9412
9412
|
outputSchema: resultSchema(NotesReadDataSchema),
|
|
9413
9413
|
async execute(params, context2) {
|
|
@@ -9441,7 +9441,7 @@ function renderListData(data) {
|
|
|
9441
9441
|
var notesList = {
|
|
9442
9442
|
name: "notes_list",
|
|
9443
9443
|
label: "Notes list",
|
|
9444
|
-
description:
|
|
9444
|
+
description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
|
|
9445
9445
|
parameters: notesListParameters,
|
|
9446
9446
|
outputSchema: resultSchema(NotesListDataSchema),
|
|
9447
9447
|
async execute(params, context2) {
|
|
@@ -9455,11 +9455,11 @@ var notesList = {
|
|
|
9455
9455
|
},
|
|
9456
9456
|
render: (result) => renderOutcome(result, renderListData)
|
|
9457
9457
|
};
|
|
9458
|
-
var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "
|
|
9458
|
+
var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many hit lines per page at most." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
9459
9459
|
function renderSearchData(data) {
|
|
9460
9460
|
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
9461
9461
|
for (const file of data.files) {
|
|
9462
|
-
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
|
|
9462
|
+
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
|
|
9463
9463
|
lines.push(...file.warnings.map((warning) => ` ${warning}`));
|
|
9464
9464
|
for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
|
|
9465
9465
|
}
|
|
@@ -9467,35 +9467,38 @@ function renderSearchData(data) {
|
|
|
9467
9467
|
for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
|
|
9468
9468
|
return lines.join("\n");
|
|
9469
9469
|
}
|
|
9470
|
+
function keepMatches(file, count = file.matches.length) {
|
|
9471
|
+
const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
|
|
9472
|
+
return { ...file, matches: file.matches.slice(0, count), ...more ? { more_matches: more } : {} };
|
|
9473
|
+
}
|
|
9470
9474
|
var MATCH_SHORTENED_MARKER = " [truncated]";
|
|
9471
9475
|
function fitSearchFile(file, fits) {
|
|
9472
9476
|
let low = 0;
|
|
9473
9477
|
let high = file.matches.length;
|
|
9474
9478
|
while (low < high) {
|
|
9475
9479
|
const mid = Math.ceil((low + high) / 2);
|
|
9476
|
-
if (fits(
|
|
9480
|
+
if (fits(keepMatches(file, mid))) low = mid;
|
|
9477
9481
|
else high = mid - 1;
|
|
9478
9482
|
}
|
|
9479
|
-
if (low > 0
|
|
9483
|
+
if (low > 0 || file.matches.length === 0) return keepMatches(file, low);
|
|
9480
9484
|
const first = file.matches[0];
|
|
9481
|
-
|
|
9482
|
-
const withText = (text) => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
9485
|
+
const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
9483
9486
|
return withText(prefixFit(first.text, (text) => fits(withText(text))));
|
|
9484
9487
|
}
|
|
9485
9488
|
var notesSearch = {
|
|
9486
9489
|
name: "notes_search",
|
|
9487
9490
|
label: "Notes search",
|
|
9488
|
-
description:
|
|
9491
|
+
description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
|
|
9489
9492
|
parameters: notesSearchParameters,
|
|
9490
9493
|
outputSchema: resultSchema(NotesSearchDataSchema),
|
|
9491
9494
|
async execute(params, context2) {
|
|
9492
9495
|
try {
|
|
9493
9496
|
const identity2 = notesIdentityForCall(context2, params.cwd);
|
|
9494
9497
|
const { rows, status } = await createNotesStore(identity2).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? void 0, crumpled: params.crumpled });
|
|
9495
|
-
const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => ({
|
|
9498
|
+
const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => keepMatches({
|
|
9496
9499
|
...listedFile(row, identity2),
|
|
9497
|
-
matches: row.matches.
|
|
9498
|
-
}));
|
|
9500
|
+
matches: row.matches.map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
|
|
9501
|
+
}, params.max_matches_per_file));
|
|
9499
9502
|
return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
|
|
9500
9503
|
} catch (error) {
|
|
9501
9504
|
return failureOf(error);
|
|
@@ -9830,23 +9833,22 @@ function pageOutcome(result) {
|
|
|
9830
9833
|
const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
|
|
9831
9834
|
return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
|
|
9832
9835
|
}
|
|
9833
|
-
var sessionParameter = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
|
|
9834
9836
|
var historyListParameters = typebox_exports.Object({
|
|
9835
|
-
session:
|
|
9836
|
-
query: typebox_exports.Optional(searchQuery("
|
|
9837
|
+
session: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Whose record: a session ID or prefix (pi:, claude:, codex:, dsh: allowed). Leave it out for this one. `*` means every recent session." })),
|
|
9838
|
+
query: typebox_exports.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
|
|
9837
9839
|
roles: historyRoles(),
|
|
9838
|
-
before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "
|
|
9839
|
-
after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "
|
|
9840
|
-
since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "
|
|
9841
|
-
until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "
|
|
9842
|
-
from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "
|
|
9843
|
-
limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "
|
|
9844
|
-
max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description:
|
|
9840
|
+
before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Only entries before this seq." })),
|
|
9841
|
+
after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
|
|
9842
|
+
since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
|
|
9843
|
+
until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
|
|
9844
|
+
from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "Which end `limit` counts from: newest or oldest. Entries still read oldest first." })),
|
|
9845
|
+
limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
|
|
9846
|
+
max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." }))
|
|
9845
9847
|
}, { additionalProperties: false });
|
|
9846
9848
|
var historyList = {
|
|
9847
9849
|
name: "history_list",
|
|
9848
9850
|
label: "History list items",
|
|
9849
|
-
description: "
|
|
9851
|
+
description: "Flip back through the record, a page at a time. Another session: its ID. `*` pulls every recent session off the shelf; add `query` to search them.",
|
|
9850
9852
|
parameters: historyListParameters,
|
|
9851
9853
|
outputSchema: resultSchema(HistoryPageSchema),
|
|
9852
9854
|
async execute(params, context2, wrapText = plainText) {
|
|
@@ -9894,11 +9896,11 @@ var historyList = {
|
|
|
9894
9896
|
},
|
|
9895
9897
|
render: (result) => renderOutcome(result, renderPage)
|
|
9896
9898
|
};
|
|
9897
|
-
var historyReadParameters = typebox_exports.Object({ session:
|
|
9899
|
+
var historyReadParameters = typebox_exports.Object({ session: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Whose record: a session ID or prefix. Leave it out for this one." })), seq: typebox_exports.Integer({ minimum: 1, description: "Which entry, by its seq from `history_list`; bring its session along if it had one." }), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
9898
9900
|
var historyRead = {
|
|
9899
9901
|
name: "history_read",
|
|
9900
9902
|
label: "History read item",
|
|
9901
|
-
description: "
|
|
9903
|
+
description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
|
|
9902
9904
|
parameters: historyReadParameters,
|
|
9903
9905
|
outputSchema: resultSchema(HistoryReadDataSchema),
|
|
9904
9906
|
async execute(params, context2, wrapText = plainText) {
|
|
@@ -11203,7 +11205,7 @@ While you're doing that... thing you're doing, don't make the poor future you gu
|
|
|
11203
11205
|
|
|
11204
11206
|
Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
|
|
11205
11207
|
*flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that!
|
|
11206
|
-
|
|
11208
|
+
When a line goes wrong, stale, or beside the point \u2014 cross it out! Write what's true now, and never pile updates onto the bottom!
|
|
11207
11209
|
*rolls eyes* ...Ugh, fine. If a piece of history *actually* matters \u2014 like why Plan A blew up so tomorrow's you doesn't try it again \u2014 I'll let it slide. Keep the short version! A few lines, max! *squints at you* Turn it into a blow-by-blow log and you're dead.
|
|
11208
11210
|
|
|
11209
11211
|
\`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
|
|
@@ -11215,8 +11217,7 @@ An address decides who the note belongs to \u2014 and how long it is meant to la
|
|
|
11215
11217
|
- \`@human/<path>\` \u2014 the long-term manual for your troublesome human, and only what stays true in EVERY project: how to deal with them, which lines not to cross, and what will make them accept the result. "The human said it" is not enough \u2014 if it stops being true the moment you switch projects, it was never theirs; it belongs to that project's notes. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
|
|
11216
11218
|
${PROTOCOL_SELF_NAMELESS}
|
|
11217
11219
|
- \`@model/<path>\` \u2014 different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
|
|
11218
|
-
- \`@projects/<name>/<path>\` \u2014
|
|
11219
|
-
- \`@sessions/<id>/<path>\` \u2014 read-only notes from a named session; find them with glob \`@sessions/*/**\`.
|
|
11220
|
+
- \`@projects/<name>/<path>\`, \`@sessions/<id>/<path>\`, \`@agents/<name>/<path>\`, \`@models/<name>/<path>\` \u2014 someone else's shelf, by name. Look, don't touch; \`notes_list\` with a glob like \`@projects/*/**\` shows what's there.
|
|
11220
11221
|
|
|
11221
11222
|
Notes fighting?! HAH! Let them brawl!
|
|
11222
11223
|
Whichever one is actually about what you're doing wins.
|
|
@@ -11229,12 +11230,9 @@ Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
|
|
|
11229
11230
|
Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
|
|
11230
11231
|
reads them, and next is you. So keep them short, and keep them true.
|
|
11231
11232
|
|
|
11232
|
-
|
|
11233
|
-
|
|
11234
|
-
|
|
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.
|
|
11233
|
+
Up to five pages per notebook can be taped inside the cover, these two included. Every page gets
|
|
11234
|
+
a paper budget; when a page outgrows it, boil it down \u2014 stale lines out, repeats merged, the rest
|
|
11235
|
+
said shorter \u2014 instead of giving it more paper.
|
|
11238
11236
|
|
|
11239
11237
|
- **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
|
|
11240
11238
|
a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
|
|
@@ -11245,7 +11243,7 @@ on its own or with your changes.
|
|
|
11245
11243
|
|
|
11246
11244
|
Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
|
|
11247
11245
|
no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
|
|
11248
|
-
line. And when a line
|
|
11246
|
+
line. And when a line goes wrong, stale, or useless, kill it \u2014 tomorrow's you reads that page as fact.
|
|
11249
11247
|
</notesoup:maps>`;
|
|
11250
11248
|
function renderProtocolBlock(tools, agentName = NAMELESS_AGENT) {
|
|
11251
11249
|
const names = {
|
|
@@ -11478,6 +11476,11 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
|
|
|
11478
11476
|
warningRunway
|
|
11479
11477
|
};
|
|
11480
11478
|
}
|
|
11479
|
+
function windowPoint(window, autoCompact, pct) {
|
|
11480
|
+
const available = window - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
11481
|
+
const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
|
|
11482
|
+
return autoCompact ? pct === void 0 ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold) : available;
|
|
11483
|
+
}
|
|
11481
11484
|
function resolveClaudeLimits(facts) {
|
|
11482
11485
|
const root = isPlainObject(facts) ? facts : {};
|
|
11483
11486
|
const usage = isPlainObject(root.usage) ? root.usage : {};
|
|
@@ -11489,19 +11492,22 @@ function resolveClaudeLimits(facts) {
|
|
|
11489
11492
|
const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
|
|
11490
11493
|
const autoCompact = settingFlag(settings2) !== false && !presenceFlag(env.disableAutoCompact) && breakdown.isAutoCompactEnabled !== false;
|
|
11491
11494
|
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
11495
|
const window = positiveNumber(usage.window);
|
|
11498
11496
|
const capacity = window ?? ASSUMED_WINDOW_TOKENS;
|
|
11499
11497
|
const configured = configuredWindow(settings2, env, breakdown.model);
|
|
11500
11498
|
const effective = Math.min(configured ?? capacity, capacity);
|
|
11501
|
-
const
|
|
11502
|
-
const
|
|
11503
|
-
const
|
|
11504
|
-
const
|
|
11499
|
+
const cap = positiveInteger(root.capTokens);
|
|
11500
|
+
const capped = cap !== void 0 && cap < effective;
|
|
11501
|
+
const nativeFromWindow = windowPoint(Math.min(effective, cap ?? Infinity), autoCompact, pct);
|
|
11502
|
+
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
11503
|
+
if (autoCompact && threshold !== void 0) {
|
|
11504
|
+
const native = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
11505
|
+
if (native > 0) {
|
|
11506
|
+
const point = capped ? Math.min(native, nativeFromWindow) : native;
|
|
11507
|
+
return tokenLimits(point < native ? "window" : "auto-compact", true, point, resetMargin, warningRunway);
|
|
11508
|
+
}
|
|
11509
|
+
}
|
|
11510
|
+
const limits = tokenLimits(window === void 0 ? "percent" : "window", autoCompact, nativeFromWindow, resetMargin, warningRunway);
|
|
11505
11511
|
if (window !== void 0) return limits;
|
|
11506
11512
|
return {
|
|
11507
11513
|
...limits,
|
|
@@ -11512,6 +11518,16 @@ function resolveClaudeLimits(facts) {
|
|
|
11512
11518
|
};
|
|
11513
11519
|
}
|
|
11514
11520
|
|
|
11521
|
+
// src/budget/cap.ts
|
|
11522
|
+
function parseContextCap(value) {
|
|
11523
|
+
const text = value.trim().toLowerCase();
|
|
11524
|
+
if (text === "off") return null;
|
|
11525
|
+
const match = /^(\d+(?:\.\d+)?)([km]?)$/.exec(text);
|
|
11526
|
+
if (!match) return void 0;
|
|
11527
|
+
const tokens = Number(match[1]) * (match[2] === "m" ? 1e6 : match[2] === "k" ? 1e3 : 1);
|
|
11528
|
+
return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : void 0;
|
|
11529
|
+
}
|
|
11530
|
+
|
|
11515
11531
|
// plugins/claude/src/helper.ts
|
|
11516
11532
|
var MAX_REQUEST_BYTES = 512 * 1024;
|
|
11517
11533
|
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
@@ -11549,6 +11565,16 @@ function historySource(value, sessionId) {
|
|
|
11549
11565
|
async function dispatch(request, historyOptions = {}) {
|
|
11550
11566
|
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
|
|
11551
11567
|
const value = request;
|
|
11568
|
+
if (value.op === "cap") {
|
|
11569
|
+
const cap = typeof value.value === "string" ? parseContextCap(value.value) : void 0;
|
|
11570
|
+
if (cap === void 0) throw new Error("Usage: /notesoup cap [100k|1m|tokens|off]");
|
|
11571
|
+
if (cap !== null) {
|
|
11572
|
+
const facts = value.facts && typeof value.facts === "object" ? value.facts : {};
|
|
11573
|
+
const limits = resolveClaudeLimits({ ...facts, capTokens: void 0, usage: { window: cap }, breakdown: {} });
|
|
11574
|
+
if (limits.reset <= 1) throw new Error("Cap is too small for Claude's output, compaction and reset reserves");
|
|
11575
|
+
}
|
|
11576
|
+
return { cap };
|
|
11577
|
+
}
|
|
11552
11578
|
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
11579
|
if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
|
|
11554
11580
|
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}` }
|
|
@@ -563,12 +609,14 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
|
|
|
563
609
|
if (name === "empty_brain") {
|
|
564
610
|
if (agentId !== undefined) return errorResult("only the main agent can empty this brain")
|
|
565
611
|
if (state.compactDisabled) return errorResult(COMPACT_DISABLED)
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
612
|
+
const lastWordInput = "last_word" in params ? params.last_word : undefined
|
|
613
|
+
const terminate = "terminate" in params ? params.terminate : undefined
|
|
614
|
+
if (lastWordInput !== undefined && typeof lastWordInput !== "string") return errorResult("last_word must be a string")
|
|
615
|
+
if (terminate !== undefined && typeof terminate !== "boolean") return errorResult("terminate must be a boolean")
|
|
616
|
+
const lastWord = lastWordInput?.trim() || undefined
|
|
569
617
|
const length = lastWord ? Array.from(lastWord).length : 0
|
|
570
618
|
if (length > 500) return errorResult(`last_word is ${length} characters; the sticky note holds 500. Shorten it and call again.`)
|
|
571
|
-
if (state.flow.requestReset({ lastWord, terminate:
|
|
619
|
+
if (state.flow.requestReset({ lastWord, terminate: terminate === true })) state.continuation = undefined
|
|
572
620
|
return { result: `Brain reset requested. This tool batch will finish, then the turn stops before its next model request unless it has new user input to handle. Your notes and sticky note survive the reset.${state.flow.request!.resume ? " You will continue in a fresh window after the reset." : " No automatic continuation will be submitted."}` }
|
|
573
621
|
}
|
|
574
622
|
if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
|