notesoup 0.39.0 → 0.41.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 +5 -2
- package/dist/src/boot/render.js +2 -2
- package/dist/src/boot/text.d.ts +0 -4
- package/dist/src/boot/text.js +18 -14
- package/dist/src/budget/policy.js +1 -1
- package/dist/src/budget/text.js +1 -1
- package/dist/src/dream/doctor.js +2 -1
- package/dist/src/dream/git.js +2 -1
- package/dist/src/dream/report.js +3 -2
- package/dist/src/error-message.d.ts +2 -0
- package/dist/src/error-message.js +4 -0
- package/dist/src/history/history.d.ts +23 -18
- package/dist/src/history/history.js +37 -20
- package/dist/src/history/query.d.ts +37 -49
- package/dist/src/history/query.js +114 -56
- package/dist/src/notes/store.d.ts +3 -4
- package/dist/src/notes/store.js +12 -16
- package/dist/src/pi/anchored.d.ts +16 -0
- package/dist/src/pi/anchored.js +55 -0
- package/dist/src/pi/budget.d.ts +1 -1
- package/dist/src/pi/budget.js +33 -28
- package/dist/src/pi/dream/cli.js +3 -2
- package/dist/src/pi/dream/runner.js +2 -1
- package/dist/src/pi/history-tools.d.ts +1 -1
- package/dist/src/pi/history-tools.js +2 -3
- package/dist/src/pi/reset/lifecycle.d.ts +1 -1
- package/dist/src/pi/reset/lifecycle.js +4 -3
- package/dist/src/pi/reset/text.d.ts +3 -3
- package/dist/src/pi/reset/text.js +2 -2
- package/dist/src/pi/runtime.js +12 -15
- package/dist/src/pi/thresholds.js +2 -1
- package/dist/src/pi/tool-names.d.ts +0 -4
- package/dist/src/pi/tool-names.js +0 -4
- package/dist/src/tools/history.d.ts +24 -33
- package/dist/src/tools/history.js +57 -98
- package/dist/src/tools/notes.d.ts +26 -58
- package/dist/src/tools/notes.js +85 -103
- package/dist/src/tools/result.d.ts +16 -13
- package/dist/src/tools/result.js +24 -50
- package/dist/src/tools/schema.d.ts +2 -2
- package/dist/src/tools/schema.js +3 -3
- package/dist/test/agent-loop.test.js +79 -29
- package/dist/test/boot.integration.test.js +6 -6
- package/dist/test/budget-settings.integration.test.js +9 -8
- package/dist/test/claude-mod.test.js +11 -11
- package/dist/test/dependencies.test.js +1 -1
- package/dist/test/helpers/extension.js +2 -3
- package/dist/test/history.integration.test.js +200 -123
- package/dist/test/host-neutral.test.js +32 -58
- package/dist/test/notes-library.test.js +8 -8
- package/dist/test/notes.integration.test.js +75 -57
- package/dist/test/notes.test.js +44 -42
- package/dist/test/reset-lifecycle.test.js +2 -2
- package/docs/architecture.md +3 -3
- package/docs/notes-library.md +6 -6
- package/docs/tool-results.md +15 -25
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +128 -179
- package/mods/notesoup/hooks/register.ts +19 -25
- package/mods/notesoup/playbook.md +10 -10
- package/mods/notesoup/skills/dream/SKILL.md +1 -1
- package/package.json +1 -1
- package/playbook.md +10 -10
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +11 -9
- package/src/boot/render.ts +2 -2
- package/src/boot/text.ts +18 -18
- package/src/budget/policy.ts +1 -1
- package/src/budget/text.ts +1 -1
- package/src/dream/doctor.ts +2 -1
- package/src/dream/git.ts +2 -1
- package/src/dream/report.ts +3 -2
- package/src/error-message.ts +4 -0
- package/src/history/history.ts +36 -20
- package/src/history/query.ts +130 -55
- package/src/notes/store.ts +15 -18
- package/src/pi/anchored.ts +62 -0
- package/src/pi/budget.ts +27 -26
- package/src/pi/dream/cli.ts +3 -2
- package/src/pi/dream/runner.ts +2 -1
- package/src/pi/history-tools.ts +2 -3
- package/src/pi/reset/lifecycle.ts +5 -4
- package/src/pi/reset/text.ts +2 -2
- package/src/pi/runtime.ts +12 -15
- package/src/pi/thresholds.ts +2 -1
- package/src/pi/tool-names.ts +0 -4
- package/src/tools/history.ts +61 -100
- package/src/tools/notes.ts +84 -97
- package/src/tools/result.ts +24 -49
- package/src/tools/schema.ts +3 -3
- package/mods/pi-context/dist/claude/helper.js +0 -9324
|
@@ -1,17 +1,52 @@
|
|
|
1
|
-
/** Stable-anchor paging and
|
|
1
|
+
/** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { failure, success } from "../tools/result.js";
|
|
4
|
-
import { prefixFit } from "../tools/output.js";
|
|
5
|
-
import {
|
|
4
|
+
import { earliestMatchOffsetChars, prefixFit } from "../tools/output.js";
|
|
5
|
+
import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
6
|
+
import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
|
|
7
|
+
/** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
|
|
8
|
+
const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
9
|
+
/** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
|
|
10
|
+
function isoUtcMs(value) {
|
|
11
|
+
const match = ISO_8601.exec(value);
|
|
12
|
+
if (match === null)
|
|
13
|
+
return undefined;
|
|
14
|
+
const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
|
|
15
|
+
return Number.isNaN(at) ? undefined : at;
|
|
16
|
+
}
|
|
17
|
+
/** Epoch ms for one optional time param, or a refusal naming it. */
|
|
18
|
+
function timeBound(name, value) {
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
return success(undefined);
|
|
21
|
+
const at = isoUtcMs(value);
|
|
22
|
+
return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
|
|
23
|
+
}
|
|
24
|
+
/** Parse `since`/`until`; a malformed or inverted pair refuses here. */
|
|
25
|
+
function resolveTimeBounds(params) {
|
|
26
|
+
const since = timeBound("since", params.since);
|
|
27
|
+
if (!since.ok)
|
|
28
|
+
return since;
|
|
29
|
+
const until = timeBound("until", params.until);
|
|
30
|
+
if (!until.ok)
|
|
31
|
+
return until;
|
|
32
|
+
if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
|
|
33
|
+
return failure("invalid_time", "since must be earlier than until");
|
|
34
|
+
}
|
|
35
|
+
return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
|
|
36
|
+
}
|
|
37
|
+
/** The params to merge into the previous call to continue toward older events. */
|
|
38
|
+
export const HistoryOlderSchema = Type.Object({
|
|
39
|
+
before_seq: Type.Integer({ minimum: 1 }),
|
|
40
|
+
}, { additionalProperties: false });
|
|
41
|
+
/** The params to merge into the previous call to continue toward newer events. */
|
|
42
|
+
export const HistoryNewerSchema = Type.Object({
|
|
43
|
+
after_seq: Type.Integer({ minimum: 1 }),
|
|
44
|
+
from: Type.Literal("oldest"),
|
|
45
|
+
}, { additionalProperties: false });
|
|
6
46
|
export const HistoryPageSchema = Type.Object({
|
|
7
47
|
items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}, { additionalProperties: false });
|
|
11
|
-
/** Search never returns conversation folds. */
|
|
12
|
-
export const HistorySearchPageSchema = Type.Object({
|
|
13
|
-
...HistoryPageSchema.properties,
|
|
14
|
-
items: Type.Array(HistoryPageItemSchema),
|
|
48
|
+
page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
|
|
49
|
+
page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
|
|
15
50
|
}, { additionalProperties: false });
|
|
16
51
|
/** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
|
|
17
52
|
function truncateHistoryItem(item, fits) {
|
|
@@ -28,16 +63,14 @@ function truncateHistoryItem(item, fits) {
|
|
|
28
63
|
if (item.tool === undefined)
|
|
29
64
|
return withContent;
|
|
30
65
|
const { tool: _dropped, ...withoutName } = item;
|
|
31
|
-
|
|
32
|
-
if (fits(named))
|
|
33
|
-
return named;
|
|
34
|
-
return shrinkContent(named);
|
|
66
|
+
return fits(withoutName) ? withoutName : shrinkContent(withoutName);
|
|
35
67
|
}
|
|
36
68
|
function isFoldableEvent(event) {
|
|
37
69
|
return event.role === "tool" || event.role === "context";
|
|
38
70
|
}
|
|
39
|
-
|
|
40
|
-
|
|
71
|
+
/** Only a call without roles or query folds tool/context runs. */
|
|
72
|
+
function foldsRuns(params) {
|
|
73
|
+
return !params.roles && params.query === undefined;
|
|
41
74
|
}
|
|
42
75
|
/** Folded counts stay exact even when some distinct tool names must be omitted. */
|
|
43
76
|
function foldedRuns(events) {
|
|
@@ -54,37 +87,32 @@ function foldedRuns(events) {
|
|
|
54
87
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
55
88
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
56
89
|
const tools = Object.fromEntries(entries);
|
|
57
|
-
|
|
58
|
-
return [{ folded: true, first_seq: sorted[0].seq, last_seq: sorted.at(-1).seq, count: sorted.length, tools, ...(omitted > 0 ? { omitted_tools: omitted } : {}) }];
|
|
90
|
+
return [{ folded: true, first_seq: sorted[0].seq, last_seq: sorted.at(-1).seq, count: sorted.length, tools }];
|
|
59
91
|
}
|
|
60
|
-
|
|
92
|
+
/** A cursor exists only when the same selection still has a visible event past that end. */
|
|
93
|
+
function pageCursors(vis, selected, beforeSeq, afterSeq) {
|
|
61
94
|
if (selected.length === 0)
|
|
62
|
-
return {
|
|
63
|
-
const lower =
|
|
64
|
-
const upper =
|
|
95
|
+
return { page_older: null, page_newer: null };
|
|
96
|
+
const lower = afterSeq ?? 0;
|
|
97
|
+
const upper = beforeSeq ?? Number.POSITIVE_INFINITY;
|
|
65
98
|
// Selected events are in seq order.
|
|
66
99
|
const first = selected[0].seq;
|
|
67
100
|
const last = selected.at(-1).seq;
|
|
68
101
|
return {
|
|
69
|
-
|
|
70
|
-
|
|
102
|
+
page_older: vis.some((event) => event.seq > lower && event.seq < first) ? { before_seq: first } : null,
|
|
103
|
+
page_newer: vis.some((event) => event.seq > last && event.seq < upper) ? { after_seq: last, from: "oldest" } : null,
|
|
71
104
|
};
|
|
72
105
|
}
|
|
73
|
-
function foldRows(projection, params, selected,
|
|
74
|
-
const lower = params.after ?? 0;
|
|
75
|
-
const upper = params.before ?? Number.POSITIVE_INFINITY;
|
|
106
|
+
function foldRows(projection, params, selected, cursors) {
|
|
76
107
|
if (selected.length === 0) {
|
|
77
108
|
// Even a range with no conversation can contain tool/context events.
|
|
78
|
-
|
|
79
|
-
return foldedRuns(hidden);
|
|
109
|
+
return foldedRuns(allItems(projection).filter((event) => inSelection(event, params) && isFoldableEvent(event)));
|
|
80
110
|
}
|
|
81
|
-
const windowEvents = allItems(projection)
|
|
82
|
-
.filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper)
|
|
83
|
-
.sort((a, b) => a.seq - b.seq);
|
|
111
|
+
const windowEvents = allItems(projection).filter((event) => inSelection(event, params)).sort((a, b) => a.seq - b.seq);
|
|
84
112
|
const folded = [];
|
|
85
113
|
const firstSeq = selected[0].seq;
|
|
86
114
|
const lastSeq = selected.at(-1).seq;
|
|
87
|
-
if (
|
|
115
|
+
if (cursors.page_older === null)
|
|
88
116
|
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
|
|
89
117
|
// pageData already ordered selected by seq.
|
|
90
118
|
for (let i = 0; i + 1 < selected.length; i++) {
|
|
@@ -92,52 +120,82 @@ function foldRows(projection, params, selected, anchors) {
|
|
|
92
120
|
const right = selected[i + 1].seq;
|
|
93
121
|
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
|
|
94
122
|
}
|
|
95
|
-
if (
|
|
123
|
+
if (cursors.page_newer === null)
|
|
96
124
|
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
|
|
97
125
|
return folded;
|
|
98
126
|
}
|
|
99
127
|
function pageData(projection, params, vis, selected, maxChars, folds) {
|
|
100
128
|
const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
|
|
101
129
|
const selectedEvents = orderedSelected.map((candidate) => candidate.event);
|
|
102
|
-
const
|
|
130
|
+
const cursors = pageCursors(vis, selectedEvents, params.before_seq, params.after_seq);
|
|
103
131
|
const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
|
|
104
132
|
let rows = visible;
|
|
105
133
|
if (folds) {
|
|
106
|
-
const folded = foldRows(projection, params, selectedEvents,
|
|
134
|
+
const folded = foldRows(projection, params, selectedEvents, cursors);
|
|
107
135
|
rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
|
|
108
136
|
}
|
|
109
|
-
return { items: rows, ...
|
|
137
|
+
return { items: rows, ...cursors };
|
|
138
|
+
}
|
|
139
|
+
/** Filter, then keep only literal matches when a query is present. Query shape errors refuse here. */
|
|
140
|
+
function selectionCandidates(projection, params) {
|
|
141
|
+
let queries;
|
|
142
|
+
if (params.query !== undefined) {
|
|
143
|
+
try {
|
|
144
|
+
queries = searchQueries(params.query);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error instanceof InvalidQueryError)
|
|
148
|
+
return failure("invalid_query", error.message);
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const events = filteredItems(projection, params, queries === undefined);
|
|
153
|
+
if (queries === undefined)
|
|
154
|
+
return success(events.map((event) => ({ event })));
|
|
155
|
+
const needles = queries;
|
|
156
|
+
return success(events
|
|
157
|
+
.map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
|
|
158
|
+
.filter((candidate) => candidate.matchOffset >= 0));
|
|
110
159
|
}
|
|
111
|
-
|
|
160
|
+
/**
|
|
161
|
+
* Take the limit from the end `from` names, starting there so a budget for one row keeps the most
|
|
162
|
+
* important row. The selection is already filtered to its range; `from` never states a direction.
|
|
163
|
+
*/
|
|
164
|
+
function orderedCandidates(vis, params, limit) {
|
|
112
165
|
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
if (after !== undefined)
|
|
116
|
-
return ascending.filter((candidate) => candidate.event.seq > after).slice(0, limit);
|
|
117
|
-
if (before !== undefined)
|
|
118
|
-
return ascending.filter((candidate) => candidate.event.seq < before).reverse().slice(0, limit);
|
|
119
|
-
return ascending.slice(-limit).reverse();
|
|
166
|
+
const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
|
|
167
|
+
return params.from === "oldest" ? selected : selected.reverse();
|
|
120
168
|
}
|
|
121
|
-
/**
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const
|
|
169
|
+
/**
|
|
170
|
+
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
171
|
+
* Grow the page in selection order; shorten the first preview only when no full row fits.
|
|
172
|
+
*/
|
|
173
|
+
export function selectPage(projection, params, fits, maxChars) {
|
|
174
|
+
const bounds = resolveTimeBounds(params);
|
|
175
|
+
if (!bounds.ok)
|
|
176
|
+
return bounds;
|
|
177
|
+
const scoped = { ...params, ...bounds.data };
|
|
178
|
+
const candidates = selectionCandidates(projection, scoped);
|
|
179
|
+
if (!candidates.ok)
|
|
180
|
+
return candidates;
|
|
181
|
+
const vis = candidates.data;
|
|
182
|
+
const limit = scoped.limit ?? 20;
|
|
183
|
+
const folds = foldsRuns(scoped);
|
|
184
|
+
const ordered = orderedCandidates(vis, scoped, limit);
|
|
127
185
|
const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
|
|
128
186
|
const kept = [];
|
|
129
|
-
for (const candidate of
|
|
130
|
-
if (fits(pageData(projection,
|
|
187
|
+
for (const candidate of ordered) {
|
|
188
|
+
if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
|
|
131
189
|
kept.push(candidate);
|
|
132
190
|
continue;
|
|
133
191
|
}
|
|
134
192
|
if (kept.length === 0)
|
|
135
|
-
kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection,
|
|
193
|
+
kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, scoped, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
|
|
136
194
|
break;
|
|
137
195
|
}
|
|
138
|
-
const page = pageData(projection,
|
|
196
|
+
const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
|
|
139
197
|
if (!fits(page)) {
|
|
140
|
-
return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow
|
|
198
|
+
return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow with before_seq/after_seq or since/until, or read one seq`);
|
|
141
199
|
}
|
|
142
200
|
return success(page);
|
|
143
201
|
}
|
|
@@ -44,8 +44,8 @@ export type NotesQuery = ({
|
|
|
44
44
|
scope: "agent" | "model";
|
|
45
45
|
who?: string;
|
|
46
46
|
}) & {
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
glob?: string;
|
|
48
|
+
crumpled?: boolean;
|
|
49
49
|
};
|
|
50
50
|
/** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
|
|
51
51
|
export type NoteReadResult = {
|
|
@@ -62,7 +62,7 @@ export type NoteChange = {
|
|
|
62
62
|
before: "";
|
|
63
63
|
after: "";
|
|
64
64
|
} | {
|
|
65
|
-
kind: "body" | "metadata"
|
|
65
|
+
kind: "body" | "metadata";
|
|
66
66
|
before: string;
|
|
67
67
|
after: string;
|
|
68
68
|
};
|
|
@@ -77,7 +77,6 @@ export type NoteRenameResult = {
|
|
|
77
77
|
replacedCrumpledTarget: boolean;
|
|
78
78
|
};
|
|
79
79
|
export type NoteQueryStatus = {
|
|
80
|
-
crumpledExcluded: number;
|
|
81
80
|
homesUnavailable: string[];
|
|
82
81
|
};
|
|
83
82
|
export type NoteQueryResult<T> = {
|
package/dist/src/notes/store.js
CHANGED
|
@@ -139,7 +139,7 @@ async function homesFor(identity, opts) {
|
|
|
139
139
|
}
|
|
140
140
|
if (opts.who !== undefined)
|
|
141
141
|
throw new NoteError("invalid_scope", "who requires agent or model scope");
|
|
142
|
-
return await homesForPattern(normalizePattern(opts.
|
|
142
|
+
return await homesForPattern(normalizePattern(opts.glob, identity), identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
|
|
143
143
|
}
|
|
144
144
|
/**
|
|
145
145
|
* Line numbers (1-based) of every occurrence of `needle` in `body`. The scan walks forward
|
|
@@ -331,8 +331,10 @@ export function createNotesStore(input) {
|
|
|
331
331
|
assertSerializedSize(serialized);
|
|
332
332
|
const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
333
333
|
let change;
|
|
334
|
+
// A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
|
|
335
|
+
// whole serialized file, so the frontmatter part stays visible in the diff.
|
|
334
336
|
if (bodyChanged && metadataChanged)
|
|
335
|
-
change = { kind: "
|
|
337
|
+
change = { kind: "body", before: raw, after: serialized };
|
|
336
338
|
else if (bodyChanged)
|
|
337
339
|
change = { kind: "body", before: body, after: next };
|
|
338
340
|
else if (metadataChanged)
|
|
@@ -385,22 +387,21 @@ export function createNotesStore(input) {
|
|
|
385
387
|
}));
|
|
386
388
|
}
|
|
387
389
|
async function* scan(options, status) {
|
|
388
|
-
const matcher = matcherFor(normalizePattern(options.
|
|
390
|
+
const matcher = matcherFor(normalizePattern(options.glob, identity));
|
|
389
391
|
let homes;
|
|
390
392
|
try {
|
|
391
393
|
homes = await homesFor(identity, options);
|
|
392
394
|
}
|
|
393
395
|
catch (error) {
|
|
394
|
-
if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.
|
|
396
|
+
if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.glob ?? ""))
|
|
395
397
|
throw error;
|
|
396
|
-
status.homesUnavailable.push(options.
|
|
398
|
+
status.homesUnavailable.push(options.glob.startsWith("@agents/") ? "@agents" : "@models");
|
|
397
399
|
return;
|
|
398
400
|
}
|
|
399
401
|
for (const home of homes) {
|
|
400
402
|
const scope = home.scope;
|
|
401
403
|
const root = scopeDir(scope, identity, home.who);
|
|
402
404
|
const homeRows = [];
|
|
403
|
-
let excluded = 0;
|
|
404
405
|
try {
|
|
405
406
|
for (const path of await walkMarkdown(root)) {
|
|
406
407
|
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who)))
|
|
@@ -410,11 +411,8 @@ export function createNotesStore(input) {
|
|
|
410
411
|
const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
|
|
411
412
|
const { meta, body } = parseNote(raw);
|
|
412
413
|
meta.scope = scope;
|
|
413
|
-
if ((meta.crumpledAt !== undefined) !== (options.
|
|
414
|
-
if (meta.crumpledAt !== undefined)
|
|
415
|
-
excluded++;
|
|
414
|
+
if ((meta.crumpledAt !== undefined) !== (options.crumpled === true))
|
|
416
415
|
continue;
|
|
417
|
-
}
|
|
418
416
|
homeRows.push({ address, scope, path, meta, body });
|
|
419
417
|
}
|
|
420
418
|
}
|
|
@@ -424,8 +422,6 @@ export function createNotesStore(input) {
|
|
|
424
422
|
status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
|
|
425
423
|
continue;
|
|
426
424
|
}
|
|
427
|
-
if (status)
|
|
428
|
-
status.crumpledExcluded += excluded;
|
|
429
425
|
for (const row of homeRows)
|
|
430
426
|
yield row;
|
|
431
427
|
}
|
|
@@ -440,10 +436,10 @@ export function createNotesStore(input) {
|
|
|
440
436
|
rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
|
|
441
437
|
}
|
|
442
438
|
rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
|
|
443
|
-
return { rows, status: status ?? {
|
|
439
|
+
return { rows, status: status ?? { homesUnavailable: [] } };
|
|
444
440
|
}
|
|
445
441
|
function listWithStatus(options = {}) {
|
|
446
|
-
return listRows(options, {
|
|
442
|
+
return listRows(options, { homesUnavailable: [] });
|
|
447
443
|
}
|
|
448
444
|
async function search(queries, options = {}) {
|
|
449
445
|
return (await searchRows(queries, options)).rows;
|
|
@@ -469,10 +465,10 @@ export function createNotesStore(input) {
|
|
|
469
465
|
rows.push({ address, path, scope, meta, matches });
|
|
470
466
|
}
|
|
471
467
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
472
|
-
return { rows, status: status ?? {
|
|
468
|
+
return { rows, status: status ?? { homesUnavailable: [] } };
|
|
473
469
|
}
|
|
474
470
|
function searchWithStatus(queries, options = {}) {
|
|
475
|
-
return searchRows(queries, options, {
|
|
471
|
+
return searchRows(queries, options, { homesUnavailable: [] });
|
|
476
472
|
}
|
|
477
473
|
return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
|
|
478
474
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { SessionReader } from "./session-reader.js";
|
|
3
|
+
/**
|
|
4
|
+
* Budget reminders reach the model inside the request that crosses a threshold, but
|
|
5
|
+
* Pi can only persist them at turn_end, after that request's assistant reply. Each
|
|
6
|
+
* durable copy records the reply it preceded; projections move it back before that
|
|
7
|
+
* reply so later requests see the same prefix the first one did, and only one copy.
|
|
8
|
+
*/
|
|
9
|
+
export type AnchorDetails = {
|
|
10
|
+
anchorEntryId: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Move each durable reminder directly before the reply it preceded. Only an anchor on
|
|
14
|
+
* the active branch and visible in `messages` counts; any other reminder stays put.
|
|
15
|
+
*/
|
|
16
|
+
export declare function arrangeAnchoredReminders(messages: AgentMessage[], ctx: SessionReader): AgentMessage[];
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
2
|
+
const ANCHORED_TYPES = new Set([GUIDANCE_TYPE, WARNING_TYPE]);
|
|
3
|
+
function anchorOf(message) {
|
|
4
|
+
if (message.role !== "custom" || !ANCHORED_TYPES.has(message.customType))
|
|
5
|
+
return undefined;
|
|
6
|
+
const details = message.details;
|
|
7
|
+
return typeof details?.anchorEntryId === "string" ? details.anchorEntryId : undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Move each durable reminder directly before the reply it preceded. Only an anchor on
|
|
11
|
+
* the active branch and visible in `messages` counts; any other reminder stays put.
|
|
12
|
+
*/
|
|
13
|
+
export function arrangeAnchoredReminders(messages, ctx) {
|
|
14
|
+
if (!messages.some((message) => anchorOf(message) !== undefined))
|
|
15
|
+
return messages;
|
|
16
|
+
// Replies are cloned into `messages`, so match by timestamp. Fast turns can share a
|
|
17
|
+
// millisecond; rank equal timestamps from the newest, since projections only drop
|
|
18
|
+
// older messages.
|
|
19
|
+
const replies = new Map();
|
|
20
|
+
const seen = new Map();
|
|
21
|
+
for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
|
|
22
|
+
if (entry.type !== "message" || entry.message.role !== "assistant")
|
|
23
|
+
continue;
|
|
24
|
+
const rank = seen.get(entry.message.timestamp) ?? 0;
|
|
25
|
+
seen.set(entry.message.timestamp, rank + 1);
|
|
26
|
+
replies.set(entry.id, `${entry.message.timestamp}#${rank}`);
|
|
27
|
+
}
|
|
28
|
+
const keys = new Map();
|
|
29
|
+
seen.clear();
|
|
30
|
+
for (const message of [...messages].reverse()) {
|
|
31
|
+
if (message.role !== "assistant")
|
|
32
|
+
continue;
|
|
33
|
+
const rank = seen.get(message.timestamp) ?? 0;
|
|
34
|
+
seen.set(message.timestamp, rank + 1);
|
|
35
|
+
keys.set(message, `${message.timestamp}#${rank}`);
|
|
36
|
+
}
|
|
37
|
+
const visible = new Set(keys.values());
|
|
38
|
+
const before = new Map();
|
|
39
|
+
const rest = messages.filter((message) => {
|
|
40
|
+
const anchorId = anchorOf(message);
|
|
41
|
+
const key = anchorId ? replies.get(anchorId) : undefined;
|
|
42
|
+
if (key === undefined || !visible.has(key))
|
|
43
|
+
return true;
|
|
44
|
+
before.set(key, [...(before.get(key) ?? []), message]);
|
|
45
|
+
return false;
|
|
46
|
+
});
|
|
47
|
+
return rest.flatMap((message) => {
|
|
48
|
+
const key = keys.get(message);
|
|
49
|
+
const moved = key ? before.get(key) : undefined;
|
|
50
|
+
if (!moved)
|
|
51
|
+
return [message];
|
|
52
|
+
before.delete(key);
|
|
53
|
+
return [...moved, message];
|
|
54
|
+
});
|
|
55
|
+
}
|
package/dist/src/pi/budget.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export declare function remainingTokens(ctx: Pick<ExtensionContext, "sessionMana
|
|
|
4
4
|
export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolean, settingsManager?: SettingsManager, onCloseOut?: (windowId: string) => void): {
|
|
5
5
|
automaticResetEnabled: (ctx: ExtensionContext) => boolean;
|
|
6
6
|
hardReserveDue: (ctx: ExtensionContext) => boolean;
|
|
7
|
-
consumeTurnEnd: (ctx: ExtensionContext) => SessionBoundaryDraft[];
|
|
7
|
+
consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
|
|
8
8
|
/** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
|
|
9
9
|
statusFor: (ctx: ExtensionContext) => {
|
|
10
10
|
remaining: number | null;
|
package/dist/src/pi/budget.js
CHANGED
|
@@ -7,6 +7,7 @@ import { WARNING_CONTENT } from "./reset/text.js";
|
|
|
7
7
|
import { readThresholdSettings } from "./thresholds.js";
|
|
8
8
|
import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
|
|
9
9
|
import { tokenBudgetGuidance } from "../budget/text.js";
|
|
10
|
+
import { arrangeAnchoredReminders } from "./anchored.js";
|
|
10
11
|
import { output } from "../tools/output.js";
|
|
11
12
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
12
13
|
export function remainingTokens(ctx) {
|
|
@@ -65,7 +66,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
|
|
|
65
66
|
for (const [key, notice] of pendingNotices) {
|
|
66
67
|
if (warningCommittedInWindow(ctx, notice)) {
|
|
67
68
|
pendingNotices.delete(key);
|
|
68
|
-
ctx.ui.notify("
|
|
69
|
+
ctx.ui.notify("🥣 Context almost full · saving notes before memory clears", "warning");
|
|
69
70
|
}
|
|
70
71
|
else if (settled) {
|
|
71
72
|
// An uncommitted draft must not be matched to a later manual warning.
|
|
@@ -83,7 +84,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
|
|
|
83
84
|
invalidateThresholds();
|
|
84
85
|
notifiedWarnings.clear();
|
|
85
86
|
};
|
|
86
|
-
const consumeTurnEnd = (ctx) => {
|
|
87
|
+
const consumeTurnEnd = (ctx, anchorEntryId) => {
|
|
87
88
|
const staged = [
|
|
88
89
|
pendingGuidance ? { ...pendingGuidance, customType: GUIDANCE_TYPE } : undefined,
|
|
89
90
|
pendingWarning ? { ...pendingWarning, customType: WARNING_TYPE } : undefined,
|
|
@@ -100,6 +101,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
|
|
|
100
101
|
customType: draft.customType,
|
|
101
102
|
content: draft.content,
|
|
102
103
|
display: false,
|
|
104
|
+
details: { anchorEntryId },
|
|
103
105
|
}));
|
|
104
106
|
};
|
|
105
107
|
pi.on("session_start", (_event, ctx) => { resetForTransition(); thresholdsFor(ctx); });
|
|
@@ -114,46 +116,49 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
|
|
|
114
116
|
notifyCommittedWarnings(ctx, true);
|
|
115
117
|
clearStaged();
|
|
116
118
|
});
|
|
117
|
-
pi.on("context", (
|
|
119
|
+
pi.on("context", (event, ctx) => {
|
|
118
120
|
if (!isEnabled())
|
|
119
121
|
return undefined;
|
|
120
|
-
//
|
|
121
|
-
|
|
122
|
+
// Durable reminders return to the slot where the model first read them.
|
|
123
|
+
const messages = arrangeAnchoredReminders(event.messages, ctx);
|
|
124
|
+
const result = (extra) => {
|
|
125
|
+
if (!extra)
|
|
126
|
+
return messages === event.messages ? undefined : { messages };
|
|
127
|
+
return { messages: [...messages, { role: "custom", ...extra, display: false, timestamp: Date.now() }] };
|
|
128
|
+
};
|
|
129
|
+
// Each crossing reaches the model in the request that crosses it, with the count
|
|
130
|
+
// measured for that request, and persists the same text at its successful turn_end.
|
|
131
|
+
// Without automatic reset nothing gets cleared, so there is nothing to remind about.
|
|
132
|
+
if (!automaticResetEnabled(ctx))
|
|
133
|
+
return result();
|
|
122
134
|
const remaining = remainingTokens(ctx);
|
|
123
135
|
if (remaining === null)
|
|
124
|
-
return
|
|
136
|
+
return result();
|
|
125
137
|
const windowId = currentWindowId(ctx);
|
|
126
138
|
const { reminder, warning } = thresholdsFor(ctx);
|
|
127
|
-
if (remaining <= warning
|
|
139
|
+
if (remaining <= warning) {
|
|
128
140
|
// Re-arm close-out on each eligible request. A prior request may have aborted
|
|
129
141
|
// after persisting the warning, so warning deduplication must not own this state.
|
|
130
142
|
onCloseOut(windowId);
|
|
131
|
-
if (hasWindowMessage(ctx, WARNING_TYPE)
|
|
132
|
-
return
|
|
143
|
+
if (hasWindowMessage(ctx, WARNING_TYPE))
|
|
144
|
+
return result();
|
|
133
145
|
// The critical close-out starts at reserve + runway, not at the hard reserve.
|
|
146
|
+
// Another request in the same turn re-sends the staged text instead of re-measuring.
|
|
134
147
|
pendingGuidance = undefined;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
role: "custom",
|
|
139
|
-
customType: WARNING_TYPE,
|
|
140
|
-
content,
|
|
141
|
-
display: false,
|
|
142
|
-
timestamp: Date.now(),
|
|
143
|
-
};
|
|
144
|
-
return { messages: [..._event.messages, warningMessage] };
|
|
148
|
+
if (pendingWarning?.windowId !== windowId)
|
|
149
|
+
pendingWarning = { windowId, content: WARNING_CONTENT };
|
|
150
|
+
return result({ customType: WARNING_TYPE, content: pendingWarning.content });
|
|
145
151
|
}
|
|
146
152
|
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId)
|
|
147
|
-
return
|
|
148
|
-
if (hasWindowMessage(ctx, GUIDANCE_TYPE)
|
|
149
|
-
return
|
|
150
|
-
if (
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
pendingGuidance = { windowId, content: tokenBudgetGuidance(left, PI_TOOL_NAMES.wipe) };
|
|
153
|
+
return result();
|
|
154
|
+
if (hasWindowMessage(ctx, GUIDANCE_TYPE))
|
|
155
|
+
return result();
|
|
156
|
+
if (pendingGuidance?.windowId !== windowId) {
|
|
157
|
+
if (remaining > reminder)
|
|
158
|
+
return result();
|
|
159
|
+
pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
|
|
155
160
|
}
|
|
156
|
-
return
|
|
161
|
+
return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
|
|
157
162
|
});
|
|
158
163
|
pi.registerTool(defineTool({
|
|
159
164
|
name: "get_context_remaining",
|
package/dist/src/pi/dream/cli.js
CHANGED
|
@@ -11,6 +11,7 @@ import { gitCommit } from "../../dream/git.js";
|
|
|
11
11
|
import { readDreamerSettings } from "./settings.js";
|
|
12
12
|
import { doctor } from "../../dream/doctor.js";
|
|
13
13
|
import { notesRoot } from "../notes/adapter.js";
|
|
14
|
+
import { errorMessage } from "../../error-message.js";
|
|
14
15
|
function args(argv) { const out = {}; for (let i = 0; i < argv.length; i++) {
|
|
15
16
|
const a = argv[i];
|
|
16
17
|
if (a === "--force" || a === "--help")
|
|
@@ -67,7 +68,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
|
|
|
67
68
|
lock = acquireLock(lockPath);
|
|
68
69
|
}
|
|
69
70
|
catch (e) {
|
|
70
|
-
console.log(`lock gate: ${e
|
|
71
|
+
console.log(`lock gate: ${errorMessage(e)}`);
|
|
71
72
|
return 0;
|
|
72
73
|
}
|
|
73
74
|
if (!lock.held) {
|
|
@@ -102,7 +103,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
|
|
|
102
103
|
result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
|
|
103
104
|
}
|
|
104
105
|
catch (e) {
|
|
105
|
-
const message =
|
|
106
|
+
const message = errorMessage(e);
|
|
106
107
|
console.error(message);
|
|
107
108
|
return finishDream(home, stamp, reportPath, true, message, []);
|
|
108
109
|
}
|
|
@@ -2,6 +2,7 @@ import { jailWritePath, deleteCrumpledNote } from "../../dream/jail.js";
|
|
|
2
2
|
import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { Type } from "@earendil-works/pi-ai";
|
|
4
4
|
import { contentText } from "../../history/history.js";
|
|
5
|
+
import { errorMessage } from "../../error-message.js";
|
|
5
6
|
export const DREAMER_TOOLS = ["read", "grep", "find", "ls", "write", "edit"];
|
|
6
7
|
function jailToolDefinition(definition, notesHome) {
|
|
7
8
|
const execute = definition.execute;
|
|
@@ -77,7 +78,7 @@ export async function runDreamer(playbook, cwd, options = {}) {
|
|
|
77
78
|
await session.prompt(playbook);
|
|
78
79
|
}
|
|
79
80
|
catch (error) {
|
|
80
|
-
return { report: answer, writes, error:
|
|
81
|
+
return { report: answer, writes, error: errorMessage(error) };
|
|
81
82
|
}
|
|
82
83
|
if (providerError)
|
|
83
84
|
return { report: answer, writes, error: `dreamer failed: ${providerError}` };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
/** Register the
|
|
2
|
+
/** Register the three shared history operations; the adapter allocates addresses and supplies them. */
|
|
3
3
|
export declare function registerHistoryTools(pi: ExtensionAPI): void;
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { historyWindows, historyList, historyRead
|
|
1
|
+
import { historyWindows, historyList, historyRead } from "../tools/history.js";
|
|
2
2
|
import { historyFromSession } from "./history.js";
|
|
3
3
|
import { HISTORY_NAMESPACE, registerOperation } from "./tool-result.js";
|
|
4
|
-
/** Register the
|
|
4
|
+
/** Register the three shared history operations; the adapter allocates addresses and supplies them. */
|
|
5
5
|
export function registerHistoryTools(pi) {
|
|
6
6
|
registerOperation(pi, historyWindows, (params, ctx) => historyWindows.execute(params, historyFromSession(ctx), ctx.sessionManager.getSessionId()), HISTORY_NAMESPACE);
|
|
7
7
|
registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
8
8
|
registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
9
|
-
registerOperation(pi, historySearch, (params, ctx) => historySearch.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
10
9
|
}
|
|
@@ -2,7 +2,7 @@ import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@eare
|
|
|
2
2
|
type BudgetOwner = {
|
|
3
3
|
automaticResetEnabled: (ctx: ExtensionContext) => boolean;
|
|
4
4
|
hardReserveDue: (ctx: ExtensionContext) => boolean;
|
|
5
|
-
consumeTurnEnd: (ctx: ExtensionContext) => SessionBoundaryDraft[];
|
|
5
|
+
consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
|
|
6
6
|
clear: () => void;
|
|
7
7
|
};
|
|
8
8
|
type ResetOptions = {
|