notesoup 0.47.1 → 0.48.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 +2 -2
- package/dist/src/boot/render.d.ts +14 -7
- package/dist/src/boot/render.js +29 -16
- package/dist/src/boot/text.d.ts +25 -4
- package/dist/src/boot/text.js +60 -13
- package/dist/src/budget/constants.d.ts +2 -4
- package/dist/src/budget/constants.js +2 -4
- package/dist/src/budget/policy.d.ts +2 -2
- package/dist/src/budget/policy.js +3 -3
- package/dist/src/budget/text.d.ts +29 -9
- package/dist/src/budget/text.js +51 -10
- package/dist/src/claude/helper.d.ts +2 -3
- package/dist/src/claude/helper.js +45 -11
- package/dist/src/claude/history.d.ts +9 -0
- package/dist/src/claude/history.js +271 -0
- package/dist/src/dsh/budget.js +1 -1
- package/dist/src/dsh/engine.d.ts +2 -1
- package/dist/src/dsh/engine.js +18 -9
- package/dist/src/dsh/index.js +9 -4
- package/dist/src/dsh/tools.js +1 -1
- package/dist/src/dsh/window.d.ts +2 -1
- package/dist/src/dsh/window.js +14 -8
- package/dist/src/history/query.js +59 -81
- package/dist/src/notes/address.d.ts +5 -0
- package/dist/src/notes/address.js +20 -21
- package/dist/src/notes/store.js +12 -19
- package/dist/src/pi/boot.d.ts +1 -1
- package/dist/src/pi/boot.js +28 -5
- package/dist/src/pi/budget.d.ts +1 -3
- package/dist/src/pi/budget.js +20 -61
- package/dist/src/pi/entries.d.ts +0 -1
- package/dist/src/pi/entries.js +0 -1
- package/dist/src/pi/history.d.ts +3 -0
- package/dist/src/pi/history.js +4 -0
- package/dist/src/pi/reset/artifacts.d.ts +7 -2
- package/dist/src/pi/reset/artifacts.js +16 -14
- package/dist/src/pi/reset/lifecycle.d.ts +21 -25
- package/dist/src/pi/reset/lifecycle.js +48 -72
- package/dist/src/pi/runtime.js +9 -8
- package/dist/src/pi/window.d.ts +12 -6
- package/dist/src/pi/window.js +7 -0
- package/dist/test/agent-loop.test.js +53 -30
- package/dist/test/boot.integration.test.js +123 -12
- package/dist/test/budget-settings.integration.test.js +10 -6
- package/dist/test/claude-history.test.d.ts +1 -0
- package/dist/test/claude-history.test.js +184 -0
- package/dist/test/claude-mod.test.js +236 -42
- package/dist/test/dsh.test.js +80 -3
- package/dist/test/helpers/extension.d.ts +3 -0
- package/dist/test/helpers/extension.js +33 -5
- package/dist/test/history.integration.test.js +66 -0
- package/dist/test/host-neutral.test.js +1 -1
- package/dist/test/model-facing-text.test.d.ts +1 -0
- package/dist/test/model-facing-text.test.js +181 -0
- package/dist/test/notes.integration.test.js +16 -18
- package/dist/test/reset-lifecycle.test.js +201 -46
- package/docs/architecture.md +3 -3
- package/docs/claude-code-mod.md +15 -3
- package/docs/dsh.md +2 -2
- package/docs/reset-lifecycle.md +32 -20
- package/docs/skills.md +1 -1
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +836 -92
- package/mods/notesoup/hooks/register.ts +140 -38
- package/package.json +1 -1
- package/src/boot/render.ts +41 -23
- package/src/boot/text.ts +69 -13
- package/src/budget/constants.ts +2 -4
- package/src/budget/policy.ts +3 -3
- package/src/budget/text.ts +61 -10
- package/src/claude/helper.ts +53 -22
- package/src/claude/history.ts +228 -0
- package/src/dsh/budget.ts +1 -1
- package/src/dsh/engine.ts +16 -9
- package/src/dsh/index.ts +8 -3
- package/src/dsh/tools.ts +1 -1
- package/src/dsh/window.ts +15 -9
- package/src/history/query.ts +57 -82
- package/src/notes/address.ts +19 -16
- package/src/notes/store.ts +9 -14
- package/src/pi/boot.ts +27 -5
- package/src/pi/budget.ts +20 -58
- package/src/pi/entries.ts +0 -1
- package/src/pi/history.ts +7 -2
- package/src/pi/reset/artifacts.ts +17 -14
- package/src/pi/reset/lifecycle.ts +56 -79
- package/src/pi/runtime.ts +9 -8
- package/src/pi/window.ts +11 -1
|
@@ -4,7 +4,7 @@ import { failure, success } from "../tools/result.js";
|
|
|
4
4
|
import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
|
|
5
5
|
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
6
6
|
import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
7
|
-
import {
|
|
7
|
+
import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
|
|
8
8
|
/** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
|
|
9
9
|
const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
10
10
|
/** Epoch ms for one optional time param, or a refusal naming it. */
|
|
@@ -59,20 +59,12 @@ function truncateHistoryItem(item, fits) {
|
|
|
59
59
|
const { tool: _dropped, ...withoutName } = item;
|
|
60
60
|
return fits(withoutName) ? withoutName : shrinkContent(withoutName);
|
|
61
61
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
/** Only a call without roles or query folds tool/context runs. */
|
|
66
|
-
function foldsRuns(params) {
|
|
67
|
-
return !params.roles && params.query === undefined;
|
|
68
|
-
}
|
|
69
|
-
/** Folded counts stay exact even when some distinct tool names must be omitted. */
|
|
70
|
-
function foldedRuns(events) {
|
|
62
|
+
/** Summarize one already ordered gap; omitted tool names never change its exact count. */
|
|
63
|
+
function foldedRun(events) {
|
|
71
64
|
if (events.length === 0)
|
|
72
|
-
return
|
|
73
|
-
const sorted = [...events].sort((a, b) => a.seq - b.seq);
|
|
65
|
+
return undefined;
|
|
74
66
|
const counts = new Map();
|
|
75
|
-
for (const event of
|
|
67
|
+
for (const event of events) {
|
|
76
68
|
if (event.role !== "tool")
|
|
77
69
|
continue;
|
|
78
70
|
const name = event.execution?.name ?? "unknown";
|
|
@@ -81,64 +73,45 @@ function foldedRuns(events) {
|
|
|
81
73
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
82
74
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
83
75
|
const tools = Object.fromEntries(entries);
|
|
84
|
-
return
|
|
76
|
+
return { folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
|
|
85
77
|
}
|
|
86
|
-
/**
|
|
87
|
-
function
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
return foldedRuns(allItems(projection).filter((event) => inSelection(event, params) && isFoldableEvent(event)));
|
|
104
|
-
}
|
|
105
|
-
const windowEvents = allItems(projection).filter((event) => inSelection(event, params)).sort((a, b) => a.seq - b.seq);
|
|
106
|
-
const folded = [];
|
|
107
|
-
const firstSeq = selected[0].seq;
|
|
108
|
-
const lastSeq = selected.at(-1).seq;
|
|
109
|
-
if (cursors.page_older === null)
|
|
110
|
-
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
|
|
111
|
-
// pageData already ordered selected by seq.
|
|
112
|
-
for (let i = 0; i + 1 < selected.length; i++) {
|
|
113
|
-
const left = selected[i].seq;
|
|
114
|
-
const right = selected[i + 1].seq;
|
|
115
|
-
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
|
|
78
|
+
/** Filter and order once. Conversation candidates own the folded gap immediately before them. */
|
|
79
|
+
function prepareSelection(projection, params) {
|
|
80
|
+
const folds = !params.roles && params.query === undefined;
|
|
81
|
+
const candidates = [];
|
|
82
|
+
let run = [];
|
|
83
|
+
for (const event of filteredItems(projection, params, false)) {
|
|
84
|
+
if (folds && (event.role === "tool" || event.role === "context")) {
|
|
85
|
+
run.push(event);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (folds && eventDocument(event) === "")
|
|
89
|
+
continue;
|
|
90
|
+
const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query);
|
|
91
|
+
if (matchOffset !== undefined && matchOffset < 0)
|
|
92
|
+
continue;
|
|
93
|
+
candidates.push({ event, matchOffset, before: foldedRun(run) });
|
|
94
|
+
run = [];
|
|
116
95
|
}
|
|
117
|
-
|
|
118
|
-
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
|
|
119
|
-
return folded;
|
|
96
|
+
return { candidates, tail: foldedRun(run) };
|
|
120
97
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
98
|
+
/** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
|
|
99
|
+
function pageData(prepared, start, end, maxChars, preview) {
|
|
100
|
+
const { candidates, tail } = prepared;
|
|
101
|
+
const items = [];
|
|
102
|
+
for (let index = start; index < end; index++) {
|
|
103
|
+
const candidate = candidates[index];
|
|
104
|
+
if (candidate.before && (index > start || start === 0))
|
|
105
|
+
items.push(candidate.before);
|
|
106
|
+
items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
|
|
130
107
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const needles = params.query;
|
|
139
|
-
return events
|
|
140
|
-
.map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
|
|
141
|
-
.filter((candidate) => candidate.matchOffset >= 0);
|
|
108
|
+
if (end === candidates.length && tail)
|
|
109
|
+
items.push(tail);
|
|
110
|
+
return {
|
|
111
|
+
items,
|
|
112
|
+
page_older: start > 0 && start < end ? { before_seq: candidates[start].event.seq } : null,
|
|
113
|
+
page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1].event.seq, from: "oldest" } : null,
|
|
114
|
+
};
|
|
142
115
|
}
|
|
143
116
|
/**
|
|
144
117
|
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
@@ -158,25 +131,30 @@ export function selectPage(projection, params, fits, maxChars) {
|
|
|
158
131
|
throw error;
|
|
159
132
|
}
|
|
160
133
|
const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
//
|
|
134
|
+
const prepared = prepareSelection(projection, scoped);
|
|
135
|
+
const { candidates } = prepared;
|
|
136
|
+
// Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
|
|
137
|
+
const newest = scoped.from !== "oldest";
|
|
138
|
+
let start = newest ? candidates.length : 0;
|
|
139
|
+
let end = start;
|
|
164
140
|
const limit = Math.max(1, scoped.limit ?? 20);
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
|
|
172
|
-
kept.push(candidate);
|
|
141
|
+
for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
|
|
142
|
+
const nextStart = newest ? start - 1 : start;
|
|
143
|
+
const nextEnd = newest ? end : end + 1;
|
|
144
|
+
if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
|
|
145
|
+
start = nextStart;
|
|
146
|
+
end = nextEnd;
|
|
173
147
|
continue;
|
|
174
148
|
}
|
|
175
|
-
if (
|
|
176
|
-
|
|
149
|
+
if (start === end) {
|
|
150
|
+
start = nextStart;
|
|
151
|
+
end = nextEnd;
|
|
152
|
+
const candidate = candidates[start];
|
|
153
|
+
candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
|
|
154
|
+
}
|
|
177
155
|
break;
|
|
178
156
|
}
|
|
179
|
-
const page = pageData(
|
|
157
|
+
const page = pageData(prepared, start, end, maxChars);
|
|
180
158
|
if (!fits(page)) {
|
|
181
159
|
return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
|
|
182
160
|
}
|
|
@@ -6,6 +6,11 @@ export type NoteAddress = {
|
|
|
6
6
|
who?: string;
|
|
7
7
|
};
|
|
8
8
|
export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
|
|
9
|
+
/** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
|
|
10
|
+
export declare const HOME_HEADS: ReadonlyMap<string, {
|
|
11
|
+
readonly scope: Scope;
|
|
12
|
+
readonly home?: "project" | "agents" | "models";
|
|
13
|
+
}>;
|
|
9
14
|
/**
|
|
10
15
|
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
11
16
|
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { NoteError, shown } from "./errors.js";
|
|
2
2
|
import { assertVirtualPath, SLUG_PATTERN } from "./paths.js";
|
|
3
3
|
export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
|
|
4
|
+
/** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
|
|
5
|
+
export const HOME_HEADS = new Map([
|
|
6
|
+
["project", { scope: "project" }],
|
|
7
|
+
["human", { scope: "human" }],
|
|
8
|
+
["self", { scope: "agent" }],
|
|
9
|
+
["model", { scope: "model" }],
|
|
10
|
+
["projects", { scope: "project", home: "project" }],
|
|
11
|
+
["agents", { scope: "agent", home: "agents" }],
|
|
12
|
+
["models", { scope: "model", home: "models" }],
|
|
13
|
+
]);
|
|
4
14
|
/**
|
|
5
15
|
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
6
16
|
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
@@ -52,29 +62,18 @@ export function assertAddress(value) {
|
|
|
52
62
|
let path = value;
|
|
53
63
|
let who;
|
|
54
64
|
if (value.startsWith("@")) {
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (head ===
|
|
61
|
-
|
|
62
|
-
else
|
|
63
|
-
|
|
64
|
-
else if (head === "self")
|
|
65
|
-
scope = "agent";
|
|
66
|
-
else if (head === "model")
|
|
67
|
-
scope = "model";
|
|
68
|
-
else if (head === "projects" || head === "agents" || head === "models") {
|
|
69
|
-
const nameEnd = tail.indexOf("/");
|
|
70
|
-
who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
|
|
65
|
+
const [rawHead, ...tail] = value.slice(1).split("/");
|
|
66
|
+
const head = HOME_HEADS.get(rawHead);
|
|
67
|
+
if (head === undefined)
|
|
68
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
69
|
+
scope = head.scope;
|
|
70
|
+
if (head.home === undefined)
|
|
71
|
+
path = tail.join("/");
|
|
72
|
+
else {
|
|
73
|
+
who = tail[0] ?? "";
|
|
71
74
|
if (!SLUG_PATTERN.test(who))
|
|
72
75
|
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
73
|
-
|
|
74
|
-
path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
|
|
75
|
-
}
|
|
76
|
-
else {
|
|
77
|
-
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
76
|
+
path = tail.slice(1).join("/");
|
|
78
77
|
}
|
|
79
78
|
if (path === "" && scope !== "agent" && scope !== "model")
|
|
80
79
|
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
package/dist/src/notes/store.js
CHANGED
|
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
5
|
-
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp } from "./address.js";
|
|
5
|
+
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
|
|
6
6
|
import { isFilesystemError } from "./fs-error.js";
|
|
7
7
|
import { snapshotNotesIdentity } from "./identity.js";
|
|
8
8
|
import { NoteError } from "./errors.js";
|
|
@@ -79,24 +79,17 @@ async function walkMarkdown(dir, base = dir) {
|
|
|
79
79
|
async function homesForPattern(pattern, identity) {
|
|
80
80
|
if (!pattern || !pattern.startsWith("@"))
|
|
81
81
|
return undefined;
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if (
|
|
90
|
-
return [{ scope:
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
|
|
94
|
-
if (name.length > 0 && !/[*?]/.test(name))
|
|
95
|
-
return [{ scope, who: assertWho(name) }];
|
|
96
|
-
const names = head === "projects" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head, identity.home);
|
|
97
|
-
return names.map((who) => ({ scope, who }));
|
|
98
|
-
}
|
|
99
|
-
return [];
|
|
82
|
+
const [rawHead, ...tail] = pattern.split("/");
|
|
83
|
+
const head = tail.length === 0 ? undefined : HOME_HEADS.get(rawHead.slice(1)); // a bare "@projects" names no homes
|
|
84
|
+
if (head === undefined)
|
|
85
|
+
return [];
|
|
86
|
+
if (head.home === undefined)
|
|
87
|
+
return [{ scope: head.scope }];
|
|
88
|
+
const name = tail[0];
|
|
89
|
+
if (name !== undefined && name.length > 0 && !/[*?]/.test(name))
|
|
90
|
+
return [{ scope: head.scope, who: assertWho(name) }];
|
|
91
|
+
const names = head.home === "project" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head.home, identity.home);
|
|
92
|
+
return names.map((who) => ({ scope: head.scope, who }));
|
|
100
93
|
}
|
|
101
94
|
/** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
|
|
102
95
|
function normalizePattern(pattern, identity) {
|
package/dist/src/pi/boot.d.ts
CHANGED
|
@@ -14,6 +14,6 @@ export type BootMessage = {
|
|
|
14
14
|
* Acquire one notes snapshot and build the boot custom message for a window. All identity
|
|
15
15
|
* fields are captured synchronously before the first filesystem await.
|
|
16
16
|
*/
|
|
17
|
-
export declare function buildBootMessage(ctx: ExtensionContext, windowId: string,
|
|
17
|
+
export declare function buildBootMessage(ctx: ExtensionContext, windowId: string, firstSeq: number | undefined, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean): Promise<BootMessage>;
|
|
18
18
|
/** Persist one hidden boot message without triggering a model turn. */
|
|
19
19
|
export declare function sendBoot(pi: ExtensionAPI, boot: BootMessage): void;
|
package/dist/src/pi/boot.js
CHANGED
|
@@ -1,18 +1,41 @@
|
|
|
1
|
-
import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
|
|
1
|
+
import { DEFAULT_BOOT_TOOL_NAMES, PI_PRE_RESET_HINTS } from "../boot/text.js";
|
|
2
2
|
import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
|
|
3
3
|
import { loadNotesSnapshot, unavailableNotesSnapshot } from "../boot/snapshot.js";
|
|
4
4
|
import { isFilesystemError } from "../notes/index.js";
|
|
5
5
|
import { BOOT_TYPE } from "./entries.js";
|
|
6
6
|
import { renderBootBlock } from "../boot/render.js";
|
|
7
|
-
import {
|
|
7
|
+
import { historyFromSession, nextHistorySeq } from "./history.js";
|
|
8
8
|
/**
|
|
9
9
|
* Acquire one notes snapshot and build the boot custom message for a window. All identity
|
|
10
10
|
* fields are captured synchronously before the first filesystem await.
|
|
11
11
|
*/
|
|
12
|
-
export async function buildBootMessage(ctx, windowId,
|
|
12
|
+
export async function buildBootMessage(ctx, windowId, firstSeq, notifyIncompleteNotes, isCurrent = () => true) {
|
|
13
13
|
const agentName = agentSlug();
|
|
14
14
|
const modelName = modelSlug(ctx);
|
|
15
|
-
const
|
|
15
|
+
const windows = historyFromSession(ctx).windows.map((window) => {
|
|
16
|
+
const seqs = window.items.map((item) => item.seq);
|
|
17
|
+
return {
|
|
18
|
+
shortName: window.windowId.slice(window.windowId.lastIndexOf(":") + 1),
|
|
19
|
+
firstSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.min(...seqs),
|
|
20
|
+
lastSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.max(...seqs),
|
|
21
|
+
isCurrent: window.windowId === windowId,
|
|
22
|
+
};
|
|
23
|
+
});
|
|
24
|
+
if (firstSeq !== undefined) {
|
|
25
|
+
// An empty old window will consume the pending boundary before its marker is written.
|
|
26
|
+
const last = windows.at(-1);
|
|
27
|
+
last.firstSeq ??= last.isCurrent ? firstSeq : nextHistorySeq(ctx);
|
|
28
|
+
}
|
|
29
|
+
if (!windows.some((window) => window.isCurrent)) {
|
|
30
|
+
windows.push({ shortName: windowId.slice(windowId.lastIndexOf(":") + 1), firstSeq, lastSeq: undefined, isCurrent: true });
|
|
31
|
+
}
|
|
32
|
+
// A closing boundary includes folded result slots, pending warnings and the old checkpoint.
|
|
33
|
+
for (let index = 0; index < windows.length - 1; index++) {
|
|
34
|
+
const nextFirst = windows[index + 1].firstSeq;
|
|
35
|
+
if (nextFirst !== undefined)
|
|
36
|
+
windows[index].lastSeq = nextFirst - 1;
|
|
37
|
+
}
|
|
38
|
+
const tree = { trunk: windowId.slice(0, windowId.lastIndexOf(":")), windows };
|
|
16
39
|
const openedAt = Date.now();
|
|
17
40
|
let notes;
|
|
18
41
|
try {
|
|
@@ -27,7 +50,7 @@ export async function buildBootMessage(ctx, windowId, previousId, notifyIncomple
|
|
|
27
50
|
notifyIncompleteNotes?.(ctx, windowId, notes);
|
|
28
51
|
return {
|
|
29
52
|
customType: BOOT_TYPE,
|
|
30
|
-
content: renderBootBlock({ agentName, modelName,
|
|
53
|
+
content: renderBootBlock({ agentName, modelName, tree, notes, tools: { ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS } }),
|
|
31
54
|
display: false,
|
|
32
55
|
details: { windowId },
|
|
33
56
|
};
|
package/dist/src/pi/budget.d.ts
CHANGED
|
@@ -3,9 +3,7 @@ export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolea
|
|
|
3
3
|
automaticResetEnabled: (ctx: ExtensionContext) => boolean;
|
|
4
4
|
hardReserveDue: (ctx: ExtensionContext) => boolean;
|
|
5
5
|
consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
|
|
6
|
-
/** The
|
|
7
|
-
setCloseOut: (handler: (windowId: string) => void) => void;
|
|
8
|
-
/** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
|
|
6
|
+
/** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
|
|
9
7
|
statusFor: (ctx: ExtensionContext) => {
|
|
10
8
|
remaining: number | null;
|
|
11
9
|
};
|
package/dist/src/pi/budget.js
CHANGED
|
@@ -3,9 +3,9 @@ import { remainingBudget } from "../budget/policy.js";
|
|
|
3
3
|
import { Type } from "@earendil-works/pi-ai";
|
|
4
4
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
6
|
-
import {
|
|
6
|
+
import { warningContent } from "../budget/text.js";
|
|
7
7
|
import { readThresholdSettings } from "./thresholds.js";
|
|
8
|
-
import { currentWindowId, hasWindowMessage,
|
|
8
|
+
import { currentWindowId, hasWindowMessage, windowUsage } from "./window.js";
|
|
9
9
|
import { tokenBudgetGuidance } from "../budget/text.js";
|
|
10
10
|
import { arrangeAnchoredReminders } from "./anchored.js";
|
|
11
11
|
import { output } from "./tool-result.js";
|
|
@@ -17,9 +17,6 @@ function remainingTokens(ctx) {
|
|
|
17
17
|
export function registerBudget(pi, isEnabled, settingsManager) {
|
|
18
18
|
let cachedPolicy;
|
|
19
19
|
const notifiedWarnings = new Set();
|
|
20
|
-
// The reset owner is wired after both sides exist, so no handler can observe a
|
|
21
|
-
// half-constructed pair (a close-out request cannot arrive before registration ends).
|
|
22
|
-
let onCloseOut = () => { };
|
|
23
20
|
const resolvePolicy = (ctx) => {
|
|
24
21
|
if (!settingsManager && cachedPolicy)
|
|
25
22
|
return { ...cachedPolicy, warnings: [] };
|
|
@@ -44,41 +41,14 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
44
41
|
};
|
|
45
42
|
let pendingGuidance;
|
|
46
43
|
let pendingWarning;
|
|
47
|
-
|
|
48
|
-
const noticeKey = (sessionId, windowId) => `${sessionId}:${windowId}`;
|
|
49
|
-
const warningCommittedInWindow = (ctx, notice) => {
|
|
50
|
-
if (ctx.sessionManager.getSessionId() !== notice.sessionId)
|
|
51
|
-
return false;
|
|
52
|
-
let windowId = rootWindowId(notice.sessionId);
|
|
53
|
-
for (const entry of ctx.sessionManager.getBranch()) {
|
|
54
|
-
if (isWindowMarker(entry)) {
|
|
55
|
-
windowId = entry.data.windowId;
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
if (windowId === notice.windowId && entry.type === "custom_message" && entry.customType === WARNING_TYPE)
|
|
59
|
-
return true;
|
|
60
|
-
}
|
|
61
|
-
return false;
|
|
62
|
-
};
|
|
63
|
-
const notifyCommittedWarnings = (ctx, settled = false) => {
|
|
64
|
-
for (const [key, notice] of pendingNotices) {
|
|
65
|
-
if (warningCommittedInWindow(ctx, notice)) {
|
|
66
|
-
pendingNotices.delete(key);
|
|
67
|
-
ctx.ui.notify("🥣 Brain almost full · taking notes", "warning");
|
|
68
|
-
}
|
|
69
|
-
else if (settled) {
|
|
70
|
-
// An uncommitted draft must not be matched to a later manual warning.
|
|
71
|
-
pendingNotices.delete(key);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
};
|
|
44
|
+
const notifiedWindows = new Set();
|
|
75
45
|
const clearStaged = () => {
|
|
76
46
|
pendingGuidance = undefined;
|
|
77
47
|
pendingWarning = undefined;
|
|
78
48
|
};
|
|
79
49
|
const resetForTransition = () => {
|
|
80
50
|
clearStaged();
|
|
81
|
-
|
|
51
|
+
notifiedWindows.clear();
|
|
82
52
|
cachedPolicy = undefined;
|
|
83
53
|
notifiedWarnings.clear();
|
|
84
54
|
};
|
|
@@ -90,10 +60,6 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
90
60
|
clearStaged();
|
|
91
61
|
const windowId = currentWindowId(ctx);
|
|
92
62
|
const drafts = staged.filter((draft) => draft !== undefined && draft.windowId === windowId);
|
|
93
|
-
if (drafts.some((draft) => draft.customType === WARNING_TYPE)) {
|
|
94
|
-
const sessionId = ctx.sessionManager.getSessionId();
|
|
95
|
-
pendingNotices.set(noticeKey(sessionId, windowId), { sessionId, windowId });
|
|
96
|
-
}
|
|
97
63
|
return drafts.map((draft) => ({
|
|
98
64
|
type: "custom_message",
|
|
99
65
|
customType: draft.customType,
|
|
@@ -106,14 +72,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
106
72
|
pi.on("session_tree", resetForTransition);
|
|
107
73
|
pi.on("model_select", resetForTransition);
|
|
108
74
|
pi.on("session_shutdown", resetForTransition);
|
|
109
|
-
|
|
110
|
-
// active window. Observe the active branch at public lifecycle boundaries and match
|
|
111
|
-
// the candidate against its originating window segment, not only the current window.
|
|
112
|
-
pi.on("turn_start", (_event, ctx) => notifyCommittedWarnings(ctx));
|
|
113
|
-
pi.on("agent_settled", (_event, ctx) => {
|
|
114
|
-
notifyCommittedWarnings(ctx, true);
|
|
115
|
-
clearStaged();
|
|
116
|
-
});
|
|
75
|
+
pi.on("agent_settled", clearStaged);
|
|
117
76
|
pi.on("context", (event, ctx) => {
|
|
118
77
|
if (!isEnabled())
|
|
119
78
|
return undefined;
|
|
@@ -133,18 +92,21 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
133
92
|
if (remaining === null)
|
|
134
93
|
return result();
|
|
135
94
|
const windowId = currentWindowId(ctx);
|
|
136
|
-
const { reminder, warning } = thresholdsFor(ctx);
|
|
95
|
+
const { reminder, warning, reserve } = thresholdsFor(ctx);
|
|
137
96
|
if (remaining <= warning) {
|
|
138
|
-
// Re-arm close-out on each eligible request. A prior request may have aborted
|
|
139
|
-
// after persisting the warning, so warning deduplication must not own this state.
|
|
140
|
-
onCloseOut(windowId);
|
|
141
97
|
if (hasWindowMessage(ctx, WARNING_TYPE))
|
|
142
98
|
return result();
|
|
143
99
|
// The critical close-out starts at reserve + runway, not at the hard reserve.
|
|
144
100
|
// Another request in the same turn re-sends the staged text instead of re-measuring.
|
|
145
101
|
pendingGuidance = undefined;
|
|
146
102
|
if (pendingWarning?.windowId !== windowId)
|
|
147
|
-
pendingWarning = { windowId, content:
|
|
103
|
+
pendingWarning = { windowId, content: warningContent() };
|
|
104
|
+
// Notify when injected, not after tools finish or a reset has already committed.
|
|
105
|
+
// An aborted request does not undo the low-budget condition or repeat the toast.
|
|
106
|
+
if (!notifiedWindows.has(windowId)) {
|
|
107
|
+
notifiedWindows.add(windowId);
|
|
108
|
+
ctx.ui.notify("🥣 Brain almost full · taking notes", "warning");
|
|
109
|
+
}
|
|
148
110
|
return result({ customType: WARNING_TYPE, content: pendingWarning.content });
|
|
149
111
|
}
|
|
150
112
|
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId)
|
|
@@ -154,30 +116,27 @@ export function registerBudget(pi, isEnabled, settingsManager) {
|
|
|
154
116
|
if (pendingGuidance?.windowId !== windowId) {
|
|
155
117
|
if (remaining > reminder)
|
|
156
118
|
return result();
|
|
157
|
-
pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining,
|
|
119
|
+
pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, reserve) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
|
|
158
120
|
}
|
|
159
121
|
return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
|
|
160
122
|
});
|
|
161
123
|
pi.registerTool(defineTool({
|
|
162
124
|
name: "get_context_remaining",
|
|
163
125
|
label: "Get context remaining",
|
|
164
|
-
description: "
|
|
126
|
+
description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
|
|
165
127
|
parameters: Type.Object({}, { additionalProperties: false }),
|
|
166
128
|
async execute(_id, _params, _signal, _update, ctx) {
|
|
167
|
-
//
|
|
168
|
-
// the runway below it is overdraft the model never sees. See budget/constants.ts.
|
|
129
|
+
// Report room to the hard-reserve wipe, including the warning runway.
|
|
169
130
|
const remaining = remainingTokens(ctx);
|
|
170
|
-
return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).
|
|
131
|
+
return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).reserve) });
|
|
171
132
|
},
|
|
172
133
|
}));
|
|
173
134
|
return {
|
|
174
135
|
automaticResetEnabled,
|
|
175
136
|
hardReserveDue,
|
|
176
137
|
consumeTurnEnd,
|
|
177
|
-
/** The
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
|
|
181
|
-
clear: () => { clearStaged(); pendingNotices.clear(); },
|
|
138
|
+
/** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
|
|
139
|
+
statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).reserve) }),
|
|
140
|
+
clear: () => { clearStaged(); notifiedWindows.clear(); },
|
|
182
141
|
};
|
|
183
142
|
}
|
package/dist/src/pi/entries.d.ts
CHANGED
|
@@ -4,5 +4,4 @@ export declare const WARNING_TYPE = "notesoup/warning";
|
|
|
4
4
|
export declare const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
|
|
5
5
|
export declare const RESET_MARKER_TYPE = "notesoup/reset-marker";
|
|
6
6
|
export declare const CONTINUATION_TYPE = "notesoup/continuation";
|
|
7
|
-
export declare const RESET_PROMPT_TYPE = "notesoup/reset-prompt";
|
|
8
7
|
export declare const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
|
package/dist/src/pi/entries.js
CHANGED
|
@@ -4,5 +4,4 @@ export const WARNING_TYPE = "notesoup/warning";
|
|
|
4
4
|
export const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
|
|
5
5
|
export const RESET_MARKER_TYPE = "notesoup/reset-marker";
|
|
6
6
|
export const CONTINUATION_TYPE = "notesoup/continuation";
|
|
7
|
-
export const RESET_PROMPT_TYPE = "notesoup/reset-prompt";
|
|
8
7
|
export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
|
package/dist/src/pi/history.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import type { SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
|
|
1
2
|
import type { SessionReader } from "./session-reader.js";
|
|
2
3
|
import { type HistoryProjection } from "../history/history.js";
|
|
4
|
+
/** Pending boundary drafts use the same slots as persisted entries. */
|
|
5
|
+
export declare function nextHistorySeq(ctx: SessionReader, pending?: readonly SessionBoundaryDraft[]): number;
|
|
3
6
|
/** Build stable internal addresses, then project the active branch into public events. */
|
|
4
7
|
export declare function historyFromSession(ctx: SessionReader): HistoryProjection;
|
package/dist/src/pi/history.js
CHANGED
|
@@ -24,6 +24,10 @@ function sequenceCount(entry) {
|
|
|
24
24
|
return 1;
|
|
25
25
|
return 1 + entry.message.content.filter(isToolCall).length;
|
|
26
26
|
}
|
|
27
|
+
/** Pending boundary drafts use the same slots as persisted entries. */
|
|
28
|
+
export function nextHistorySeq(ctx, pending = []) {
|
|
29
|
+
return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + sequenceCount(entry), 0);
|
|
30
|
+
}
|
|
27
31
|
function messageContent(message) {
|
|
28
32
|
switch (message.role) {
|
|
29
33
|
case "bashExecution":
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type ResetOrigin } from "../../budget/text.js";
|
|
2
3
|
import { type WindowMarker } from "../window.js";
|
|
3
4
|
import { type IncompleteNotesNotifier } from "../boot.js";
|
|
4
5
|
export type ResetTailState = {
|
|
@@ -15,9 +16,13 @@ export declare function sanitizeLastWord(raw: string | undefined): string | unde
|
|
|
15
16
|
export declare function isWindowContinuationEntry(entry: SessionEntry): boolean;
|
|
16
17
|
/**
|
|
17
18
|
* The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
|
|
18
|
-
* continuation, then an optional parting line
|
|
19
|
+
* continuation, then an optional parting line. The prompt is not persisted here — it reached the
|
|
20
|
+
* closing window inside the warning. The boot snapshot is acquired asynchronously after capturing
|
|
21
|
+
* this identity. The continuation is drawn from the pool its origin names, here, once: the caller
|
|
22
|
+
* persists the returned text and no read, render, or repair draws it again. The origin defaults to
|
|
23
|
+
* `normal`, the same reading a legacy marker with no origin gets.
|
|
19
24
|
*/
|
|
20
|
-
export declare function buildResetDrafts(ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean,
|
|
25
|
+
export declare function buildResetDrafts(ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean, lastWord?: string, firstSeq?: number, origin?: ResetOrigin): Promise<SessionBoundaryDraft[]>;
|
|
21
26
|
/**
|
|
22
27
|
* Inspect the persisted tail of a reset marker. It reports which reset messages are present
|
|
23
28
|
* only while the tail stays repairable: metadata may follow the marker, but real conversation,
|