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
package/src/history/query.ts
CHANGED
|
@@ -1,22 +1,74 @@
|
|
|
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, type Static } from "typebox";
|
|
3
3
|
import { failure, success, type Outcome } 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, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
|
|
6
7
|
|
|
7
8
|
type PageRow = HistoryPageItem | HistoryFoldedRow;
|
|
8
9
|
type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem };
|
|
9
|
-
|
|
10
|
+
|
|
11
|
+
/** Which end of one selection `limit` is taken from; page items always come back ascending. */
|
|
12
|
+
export type HistoryOrder = "newest" | "oldest";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What one list call selects. `before_seq`/`after_seq` choose a seq range and `since`/`until` a time
|
|
16
|
+
* range; `from` chooses the end `limit` counts from; a `query` keeps only matching events, across
|
|
17
|
+
* every role, with no folded rows.
|
|
18
|
+
*/
|
|
19
|
+
export type HistorySelection = HistoryFilter & {
|
|
20
|
+
from?: HistoryOrder;
|
|
21
|
+
limit?: number;
|
|
22
|
+
query?: string | string[];
|
|
23
|
+
since?: string;
|
|
24
|
+
until?: string;
|
|
25
|
+
max_chars_per_item?: number;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
|
|
29
|
+
const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
30
|
+
|
|
31
|
+
/** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
|
|
32
|
+
function isoUtcMs(value: string): number | undefined {
|
|
33
|
+
const match = ISO_8601.exec(value);
|
|
34
|
+
if (match === null) return undefined;
|
|
35
|
+
const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
|
|
36
|
+
return Number.isNaN(at) ? undefined : at;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Epoch ms for one optional time param, or a refusal naming it. */
|
|
40
|
+
function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
|
|
41
|
+
if (value === undefined) return success(undefined);
|
|
42
|
+
const at = isoUtcMs(value);
|
|
43
|
+
return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Parse `since`/`until`; a malformed or inverted pair refuses here. */
|
|
47
|
+
function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number; untilMs?: number }> {
|
|
48
|
+
const since = timeBound("since", params.since);
|
|
49
|
+
if (!since.ok) return since;
|
|
50
|
+
const until = timeBound("until", params.until);
|
|
51
|
+
if (!until.ok) return until;
|
|
52
|
+
if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
|
|
53
|
+
return failure("invalid_time", "since must be earlier than until");
|
|
54
|
+
}
|
|
55
|
+
return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The params to merge into the previous call to continue toward older events. */
|
|
59
|
+
export const HistoryOlderSchema = Type.Object({
|
|
60
|
+
before_seq: Type.Integer({ minimum: 1 }),
|
|
61
|
+
}, { additionalProperties: false });
|
|
62
|
+
/** The params to merge into the previous call to continue toward newer events. */
|
|
63
|
+
export const HistoryNewerSchema = Type.Object({
|
|
64
|
+
after_seq: Type.Integer({ minimum: 1 }),
|
|
65
|
+
from: Type.Literal("oldest"),
|
|
66
|
+
}, { additionalProperties: false });
|
|
10
67
|
|
|
11
68
|
export const HistoryPageSchema = Type.Object({
|
|
12
69
|
items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}, { additionalProperties: false });
|
|
16
|
-
/** Search never returns conversation folds. */
|
|
17
|
-
export const HistorySearchPageSchema = Type.Object({
|
|
18
|
-
...HistoryPageSchema.properties,
|
|
19
|
-
items: Type.Array(HistoryPageItemSchema),
|
|
70
|
+
page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
|
|
71
|
+
page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
|
|
20
72
|
}, { additionalProperties: false });
|
|
21
73
|
|
|
22
74
|
/** One whole page payload, before it becomes an outcome. */
|
|
@@ -34,17 +86,16 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
|
|
|
34
86
|
if (fits(withContent)) return withContent;
|
|
35
87
|
if (item.tool === undefined) return withContent;
|
|
36
88
|
const { tool: _dropped, ...withoutName } = item;
|
|
37
|
-
|
|
38
|
-
if (fits(named)) return named;
|
|
39
|
-
return shrinkContent(named);
|
|
89
|
+
return fits(withoutName) ? withoutName : shrinkContent(withoutName);
|
|
40
90
|
}
|
|
41
91
|
|
|
42
92
|
function isFoldableEvent(event: HistoryEvent): boolean {
|
|
43
93
|
return event.role === "tool" || event.role === "context";
|
|
44
94
|
}
|
|
45
95
|
|
|
46
|
-
|
|
47
|
-
|
|
96
|
+
/** Only a call without roles or query folds tool/context runs. */
|
|
97
|
+
function foldsRuns(params: HistorySelection): boolean {
|
|
98
|
+
return !params.roles && params.query === undefined;
|
|
48
99
|
}
|
|
49
100
|
|
|
50
101
|
/** Folded counts stay exact even when some distinct tool names must be omitted. */
|
|
@@ -60,88 +111,112 @@ function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
|
|
|
60
111
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
61
112
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
62
113
|
const tools = Object.fromEntries(entries);
|
|
63
|
-
|
|
64
|
-
return [{ folded: true, first_seq: sorted[0]!.seq, last_seq: sorted.at(-1)!.seq, count: sorted.length, tools, ...(omitted > 0 ? { omitted_tools: omitted } : {}) }];
|
|
114
|
+
return [{ folded: true, first_seq: sorted[0]!.seq, last_seq: sorted.at(-1)!.seq, count: sorted.length, tools }];
|
|
65
115
|
}
|
|
66
116
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
117
|
+
/** A cursor exists only when the same selection still has a visible event past that end. */
|
|
118
|
+
function pageCursors(vis: HistoryEvent[], selected: HistoryEvent[], beforeSeq: number | undefined, afterSeq: number | undefined): Pick<HistoryPage, "page_older" | "page_newer"> {
|
|
119
|
+
if (selected.length === 0) return { page_older: null, page_newer: null };
|
|
120
|
+
const lower = afterSeq ?? 0;
|
|
121
|
+
const upper = beforeSeq ?? Number.POSITIVE_INFINITY;
|
|
71
122
|
// Selected events are in seq order.
|
|
72
123
|
const first = selected[0]!.seq;
|
|
73
124
|
const last = selected.at(-1)!.seq;
|
|
74
125
|
return {
|
|
75
|
-
|
|
76
|
-
|
|
126
|
+
page_older: vis.some((event) => event.seq > lower && event.seq < first) ? { before_seq: first } : null,
|
|
127
|
+
page_newer: vis.some((event) => event.seq > last && event.seq < upper) ? { after_seq: last, from: "oldest" } : null,
|
|
77
128
|
};
|
|
78
129
|
}
|
|
79
130
|
|
|
80
|
-
function foldRows(projection: HistoryProjection, params:
|
|
81
|
-
const lower = params.after ?? 0;
|
|
82
|
-
const upper = params.before ?? Number.POSITIVE_INFINITY;
|
|
131
|
+
function foldRows(projection: HistoryProjection, params: HistorySelection, selected: HistoryEvent[], cursors: Pick<HistoryPage, "page_older" | "page_newer">): HistoryFoldedRow[] {
|
|
83
132
|
if (selected.length === 0) {
|
|
84
133
|
// Even a range with no conversation can contain tool/context events.
|
|
85
|
-
|
|
86
|
-
return foldedRuns(hidden);
|
|
134
|
+
return foldedRuns(allItems(projection).filter((event) => inSelection(event, params) && isFoldableEvent(event)));
|
|
87
135
|
}
|
|
88
|
-
const windowEvents = allItems(projection)
|
|
89
|
-
.filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper)
|
|
90
|
-
.sort((a, b) => a.seq - b.seq);
|
|
136
|
+
const windowEvents = allItems(projection).filter((event) => inSelection(event, params)).sort((a, b) => a.seq - b.seq);
|
|
91
137
|
const folded: HistoryFoldedRow[] = [];
|
|
92
138
|
const firstSeq = selected[0]!.seq;
|
|
93
139
|
const lastSeq = selected.at(-1)!.seq;
|
|
94
|
-
if (
|
|
140
|
+
if (cursors.page_older === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
|
|
95
141
|
// pageData already ordered selected by seq.
|
|
96
142
|
for (let i = 0; i + 1 < selected.length; i++) {
|
|
97
143
|
const left = selected[i]!.seq;
|
|
98
144
|
const right = selected[i + 1]!.seq;
|
|
99
145
|
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
|
|
100
146
|
}
|
|
101
|
-
if (
|
|
147
|
+
if (cursors.page_newer === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
|
|
102
148
|
return folded;
|
|
103
149
|
}
|
|
104
150
|
|
|
105
|
-
function pageData(projection: HistoryProjection, params:
|
|
151
|
+
function pageData(projection: HistoryProjection, params: HistorySelection, vis: HistoryEvent[], selected: Candidate[], maxChars: number, folds: boolean): HistoryPage {
|
|
106
152
|
const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
|
|
107
153
|
const selectedEvents = orderedSelected.map((candidate) => candidate.event);
|
|
108
|
-
const
|
|
154
|
+
const cursors = pageCursors(vis, selectedEvents, params.before_seq, params.after_seq);
|
|
109
155
|
const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
|
|
110
156
|
let rows: PageRow[] = visible;
|
|
111
157
|
if (folds) {
|
|
112
|
-
const folded = foldRows(projection, params, selectedEvents,
|
|
158
|
+
const folded = foldRows(projection, params, selectedEvents, cursors);
|
|
113
159
|
rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
|
|
114
160
|
}
|
|
115
|
-
return { items: rows, ...
|
|
161
|
+
return { items: rows, ...cursors };
|
|
116
162
|
}
|
|
117
163
|
|
|
118
|
-
|
|
164
|
+
/** Filter, then keep only literal matches when a query is present. Query shape errors refuse here. */
|
|
165
|
+
function selectionCandidates(projection: HistoryProjection, params: HistorySelection): Outcome<Candidate[]> {
|
|
166
|
+
let queries: string[] | undefined;
|
|
167
|
+
if (params.query !== undefined) {
|
|
168
|
+
try {
|
|
169
|
+
queries = searchQueries(params.query);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const events = filteredItems(projection, params, queries === undefined);
|
|
176
|
+
if (queries === undefined) return success(events.map((event) => ({ event })));
|
|
177
|
+
const needles = queries;
|
|
178
|
+
return success(events
|
|
179
|
+
.map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
|
|
180
|
+
.filter((candidate) => candidate.matchOffset >= 0));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Take the limit from the end `from` names, starting there so a budget for one row keeps the most
|
|
185
|
+
* important row. The selection is already filtered to its range; `from` never states a direction.
|
|
186
|
+
*/
|
|
187
|
+
function orderedCandidates(vis: Candidate[], params: HistorySelection, limit: number): Candidate[] {
|
|
119
188
|
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
if (before !== undefined) return ascending.filter((candidate) => candidate.event.seq < before).reverse().slice(0, limit);
|
|
123
|
-
return ascending.slice(-limit).reverse();
|
|
189
|
+
const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
|
|
190
|
+
return params.from === "oldest" ? selected : selected.reverse();
|
|
124
191
|
}
|
|
125
192
|
|
|
126
|
-
/**
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const
|
|
193
|
+
/**
|
|
194
|
+
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
195
|
+
* Grow the page in selection order; shorten the first preview only when no full row fits.
|
|
196
|
+
*/
|
|
197
|
+
export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
|
|
198
|
+
const bounds = resolveTimeBounds(params);
|
|
199
|
+
if (!bounds.ok) return bounds;
|
|
200
|
+
const scoped = { ...params, ...bounds.data };
|
|
201
|
+
const candidates = selectionCandidates(projection, scoped);
|
|
202
|
+
if (!candidates.ok) return candidates;
|
|
203
|
+
const vis = candidates.data;
|
|
204
|
+
const limit = scoped.limit ?? 20;
|
|
205
|
+
const folds = foldsRuns(scoped);
|
|
206
|
+
const ordered = orderedCandidates(vis, scoped, limit);
|
|
132
207
|
const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
|
|
133
208
|
const kept: Candidate[] = [];
|
|
134
|
-
for (const candidate of
|
|
135
|
-
if (fits(pageData(projection,
|
|
209
|
+
for (const candidate of ordered) {
|
|
210
|
+
if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
|
|
136
211
|
kept.push(candidate);
|
|
137
212
|
continue;
|
|
138
213
|
}
|
|
139
|
-
if (kept.length === 0) kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection,
|
|
214
|
+
if (kept.length === 0) kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, scoped, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
|
|
140
215
|
break;
|
|
141
216
|
}
|
|
142
|
-
const page = pageData(projection,
|
|
217
|
+
const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
|
|
143
218
|
if (!fits(page)) {
|
|
144
|
-
return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow
|
|
219
|
+
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`);
|
|
145
220
|
}
|
|
146
221
|
return success(page);
|
|
147
|
-
}
|
|
222
|
+
}
|
package/src/notes/store.ts
CHANGED
|
@@ -31,16 +31,16 @@ export type NotesQuery = (
|
|
|
31
31
|
| { scope?: undefined; who?: never }
|
|
32
32
|
| { scope: "session" | "project" | "human"; who?: never }
|
|
33
33
|
| { scope: "agent" | "model"; who?: string }
|
|
34
|
-
) & {
|
|
34
|
+
) & { glob?: string; crumpled?: boolean };
|
|
35
35
|
/** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
|
|
36
36
|
export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
|
|
37
37
|
export type NoteWriteResult = { meta: NoteMeta; outcome: "created" | "overwrote" | "uncrumpled" };
|
|
38
38
|
export type NoteChange =
|
|
39
39
|
| { kind: "none"; before: ""; after: "" }
|
|
40
|
-
| { kind: "body" | "metadata"
|
|
40
|
+
| { kind: "body" | "metadata"; before: string; after: string };
|
|
41
41
|
export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange };
|
|
42
42
|
export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
|
|
43
|
-
export type NoteQueryStatus = {
|
|
43
|
+
export type NoteQueryStatus = { homesUnavailable: string[] };
|
|
44
44
|
export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
|
|
45
45
|
|
|
46
46
|
/** Public identity resolved for an operation, never a filesystem path. */
|
|
@@ -174,7 +174,7 @@ async function homesFor(identity: NotesIdentity, opts: NotesQuery): Promise<Home
|
|
|
174
174
|
return [{ scope }];
|
|
175
175
|
}
|
|
176
176
|
if (opts.who !== undefined) throw new NoteError("invalid_scope", "who requires agent or model scope");
|
|
177
|
-
return await homesForPattern(normalizePattern(opts.
|
|
177
|
+
return await homesForPattern(normalizePattern(opts.glob, identity), identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
|
|
178
178
|
}
|
|
179
179
|
|
|
180
180
|
/**
|
|
@@ -358,7 +358,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
358
358
|
assertSerializedSize(serialized);
|
|
359
359
|
const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
360
360
|
let change: NoteChange;
|
|
361
|
-
|
|
361
|
+
// A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
|
|
362
|
+
// whole serialized file, so the frontmatter part stays visible in the diff.
|
|
363
|
+
if (bodyChanged && metadataChanged) change = { kind: "body", before: raw, after: serialized };
|
|
362
364
|
else if (bodyChanged) change = { kind: "body", before: body, after: next };
|
|
363
365
|
else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
|
|
364
366
|
else change = { kind: "none", before: "", after: "" };
|
|
@@ -406,20 +408,19 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
406
408
|
}
|
|
407
409
|
|
|
408
410
|
async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
|
|
409
|
-
const matcher = matcherFor(normalizePattern(options.
|
|
411
|
+
const matcher = matcherFor(normalizePattern(options.glob, identity));
|
|
410
412
|
let homes: HomeRef[];
|
|
411
413
|
try {
|
|
412
414
|
homes = await homesFor(identity, options);
|
|
413
415
|
} catch (error) {
|
|
414
|
-
if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.
|
|
415
|
-
status.homesUnavailable.push(options.
|
|
416
|
+
if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.glob ?? "")) throw error;
|
|
417
|
+
status.homesUnavailable.push(options.glob!.startsWith("@agents/") ? "@agents" : "@models");
|
|
416
418
|
return;
|
|
417
419
|
}
|
|
418
420
|
for (const home of homes) {
|
|
419
421
|
const scope = home.scope;
|
|
420
422
|
const root = scopeDir(scope, identity, home.who);
|
|
421
423
|
const homeRows: Array<Omit<NoteRow, "sizeBytes">> = [];
|
|
422
|
-
let excluded = 0;
|
|
423
424
|
try {
|
|
424
425
|
for (const path of await walkMarkdown(root)) {
|
|
425
426
|
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
|
|
@@ -428,10 +429,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
428
429
|
const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
|
|
429
430
|
const { meta, body } = parseNote(raw);
|
|
430
431
|
meta.scope = scope;
|
|
431
|
-
if ((meta.crumpledAt !== undefined) !== (options.
|
|
432
|
-
if (meta.crumpledAt !== undefined) excluded++;
|
|
433
|
-
continue;
|
|
434
|
-
}
|
|
432
|
+
if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
|
|
435
433
|
homeRows.push({ address, scope, path, meta, body });
|
|
436
434
|
}
|
|
437
435
|
} catch (error) {
|
|
@@ -439,7 +437,6 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
439
437
|
status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
|
|
440
438
|
continue;
|
|
441
439
|
}
|
|
442
|
-
if (status) status.crumpledExcluded += excluded;
|
|
443
440
|
for (const row of homeRows) yield row;
|
|
444
441
|
}
|
|
445
442
|
}
|
|
@@ -455,11 +452,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
455
452
|
rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
|
|
456
453
|
}
|
|
457
454
|
rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
|
|
458
|
-
return { rows, status: status ?? {
|
|
455
|
+
return { rows, status: status ?? { homesUnavailable: [] } };
|
|
459
456
|
}
|
|
460
457
|
|
|
461
458
|
function listWithStatus(options: NotesQuery = {}): Promise<NoteQueryResult<NoteRow>> {
|
|
462
|
-
return listRows(options, {
|
|
459
|
+
return listRows(options, { homesUnavailable: [] });
|
|
463
460
|
}
|
|
464
461
|
|
|
465
462
|
async function search(queries: string[], options: NotesQuery = {}): Promise<NoteSearchRow[]> {
|
|
@@ -486,11 +483,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
486
483
|
if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
|
|
487
484
|
}
|
|
488
485
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
489
|
-
return { rows, status: status ?? {
|
|
486
|
+
return { rows, status: status ?? { homesUnavailable: [] } };
|
|
490
487
|
}
|
|
491
488
|
|
|
492
489
|
function searchWithStatus(queries: string[], options: NotesQuery = {}): Promise<NoteQueryResult<NoteSearchRow>> {
|
|
493
|
-
return searchRows(queries, options, {
|
|
490
|
+
return searchRows(queries, options, { homesUnavailable: [] });
|
|
494
491
|
}
|
|
495
492
|
|
|
496
493
|
return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { SessionReader } from "./session-reader.js";
|
|
3
|
+
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Budget reminders reach the model inside the request that crosses a threshold, but
|
|
7
|
+
* Pi can only persist them at turn_end, after that request's assistant reply. Each
|
|
8
|
+
* durable copy records the reply it preceded; projections move it back before that
|
|
9
|
+
* reply so later requests see the same prefix the first one did, and only one copy.
|
|
10
|
+
*/
|
|
11
|
+
export type AnchorDetails = { anchorEntryId: string };
|
|
12
|
+
|
|
13
|
+
const ANCHORED_TYPES = new Set([GUIDANCE_TYPE, WARNING_TYPE]);
|
|
14
|
+
|
|
15
|
+
function anchorOf(message: AgentMessage): string | undefined {
|
|
16
|
+
if (message.role !== "custom" || !ANCHORED_TYPES.has(message.customType)) return undefined;
|
|
17
|
+
const details = message.details as { anchorEntryId?: unknown } | undefined;
|
|
18
|
+
return typeof details?.anchorEntryId === "string" ? details.anchorEntryId : undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Move each durable reminder directly before the reply it preceded. Only an anchor on
|
|
23
|
+
* the active branch and visible in `messages` counts; any other reminder stays put.
|
|
24
|
+
*/
|
|
25
|
+
export function arrangeAnchoredReminders(messages: AgentMessage[], ctx: SessionReader): AgentMessage[] {
|
|
26
|
+
if (!messages.some((message) => anchorOf(message) !== undefined)) return messages;
|
|
27
|
+
// Replies are cloned into `messages`, so match by timestamp. Fast turns can share a
|
|
28
|
+
// millisecond; rank equal timestamps from the newest, since projections only drop
|
|
29
|
+
// older messages.
|
|
30
|
+
const replies = new Map<string, string>();
|
|
31
|
+
const seen = new Map<number, number>();
|
|
32
|
+
for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
|
|
33
|
+
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
34
|
+
const rank = seen.get(entry.message.timestamp) ?? 0;
|
|
35
|
+
seen.set(entry.message.timestamp, rank + 1);
|
|
36
|
+
replies.set(entry.id, `${entry.message.timestamp}#${rank}`);
|
|
37
|
+
}
|
|
38
|
+
const keys = new Map<AgentMessage, string>();
|
|
39
|
+
seen.clear();
|
|
40
|
+
for (const message of [...messages].reverse()) {
|
|
41
|
+
if (message.role !== "assistant") continue;
|
|
42
|
+
const rank = seen.get(message.timestamp) ?? 0;
|
|
43
|
+
seen.set(message.timestamp, rank + 1);
|
|
44
|
+
keys.set(message, `${message.timestamp}#${rank}`);
|
|
45
|
+
}
|
|
46
|
+
const visible = new Set(keys.values());
|
|
47
|
+
const before = new Map<string, AgentMessage[]>();
|
|
48
|
+
const rest = messages.filter((message) => {
|
|
49
|
+
const anchorId = anchorOf(message);
|
|
50
|
+
const key = anchorId ? replies.get(anchorId) : undefined;
|
|
51
|
+
if (key === undefined || !visible.has(key)) return true;
|
|
52
|
+
before.set(key, [...(before.get(key) ?? []), message]);
|
|
53
|
+
return false;
|
|
54
|
+
});
|
|
55
|
+
return rest.flatMap((message) => {
|
|
56
|
+
const key = keys.get(message);
|
|
57
|
+
const moved = key ? before.get(key) : undefined;
|
|
58
|
+
if (!moved) return [message];
|
|
59
|
+
before.delete(key!);
|
|
60
|
+
return [...moved, message];
|
|
61
|
+
});
|
|
62
|
+
}
|
package/src/pi/budget.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { WARNING_CONTENT } from "./reset/text.js";
|
|
|
7
7
|
import { readThresholdSettings, type ThresholdSettingsResolution } 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, type AnchorDetails } from "./anchored.js";
|
|
10
11
|
import { output } from "../tools/output.js";
|
|
11
12
|
|
|
12
13
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
@@ -66,7 +67,7 @@ export function registerBudget(
|
|
|
66
67
|
for (const [key, notice] of pendingNotices) {
|
|
67
68
|
if (warningCommittedInWindow(ctx, notice)) {
|
|
68
69
|
pendingNotices.delete(key);
|
|
69
|
-
ctx.ui.notify("
|
|
70
|
+
ctx.ui.notify("🥣 Context almost full · saving notes before memory clears", "warning");
|
|
70
71
|
} else if (settled) {
|
|
71
72
|
// An uncommitted draft must not be matched to a later manual warning.
|
|
72
73
|
pendingNotices.delete(key);
|
|
@@ -85,7 +86,7 @@ export function registerBudget(
|
|
|
85
86
|
notifiedWarnings.clear();
|
|
86
87
|
};
|
|
87
88
|
|
|
88
|
-
const consumeTurnEnd = (ctx: ExtensionContext): SessionBoundaryDraft[] => {
|
|
89
|
+
const consumeTurnEnd = (ctx: ExtensionContext, anchorEntryId: string): SessionBoundaryDraft[] => {
|
|
89
90
|
const staged = [
|
|
90
91
|
pendingGuidance ? { ...pendingGuidance, customType: GUIDANCE_TYPE } : undefined,
|
|
91
92
|
pendingWarning ? { ...pendingWarning, customType: WARNING_TYPE } : undefined,
|
|
@@ -102,6 +103,7 @@ export function registerBudget(
|
|
|
102
103
|
customType: draft.customType,
|
|
103
104
|
content: draft.content,
|
|
104
105
|
display: false,
|
|
106
|
+
details: { anchorEntryId } satisfies AnchorDetails,
|
|
105
107
|
}));
|
|
106
108
|
};
|
|
107
109
|
|
|
@@ -117,41 +119,40 @@ export function registerBudget(
|
|
|
117
119
|
notifyCommittedWarnings(ctx, true);
|
|
118
120
|
clearStaged();
|
|
119
121
|
});
|
|
120
|
-
pi.on("context", (
|
|
122
|
+
pi.on("context", (event, ctx) => {
|
|
121
123
|
if (!isEnabled()) return undefined;
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
+
// Durable reminders return to the slot where the model first read them.
|
|
125
|
+
const messages = arrangeAnchoredReminders(event.messages, ctx);
|
|
126
|
+
const result = (extra?: { customType: string; content: string }) => {
|
|
127
|
+
if (!extra) return messages === event.messages ? undefined : { messages };
|
|
128
|
+
return { messages: [...messages, { role: "custom" as const, ...extra, display: false, timestamp: Date.now() }] };
|
|
129
|
+
};
|
|
130
|
+
// Each crossing reaches the model in the request that crosses it, with the count
|
|
131
|
+
// measured for that request, and persists the same text at its successful turn_end.
|
|
132
|
+
// Without automatic reset nothing gets cleared, so there is nothing to remind about.
|
|
133
|
+
if (!automaticResetEnabled(ctx)) return result();
|
|
124
134
|
const remaining = remainingTokens(ctx);
|
|
125
|
-
if (remaining === null) return
|
|
135
|
+
if (remaining === null) return result();
|
|
126
136
|
const windowId = currentWindowId(ctx);
|
|
127
137
|
const { reminder, warning } = thresholdsFor(ctx);
|
|
128
|
-
if (remaining <= warning
|
|
138
|
+
if (remaining <= warning) {
|
|
129
139
|
// Re-arm close-out on each eligible request. A prior request may have aborted
|
|
130
140
|
// after persisting the warning, so warning deduplication must not own this state.
|
|
131
141
|
onCloseOut(windowId);
|
|
132
|
-
if (hasWindowMessage(ctx, WARNING_TYPE)
|
|
142
|
+
if (hasWindowMessage(ctx, WARNING_TYPE)) return result();
|
|
133
143
|
// The critical close-out starts at reserve + runway, not at the hard reserve.
|
|
144
|
+
// Another request in the same turn re-sends the staged text instead of re-measuring.
|
|
134
145
|
pendingGuidance = undefined;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const warningMessage = {
|
|
138
|
-
role: "custom" as const,
|
|
139
|
-
customType: WARNING_TYPE,
|
|
140
|
-
content,
|
|
141
|
-
display: false,
|
|
142
|
-
timestamp: Date.now(),
|
|
143
|
-
};
|
|
144
|
-
return { messages: [..._event.messages, warningMessage] };
|
|
146
|
+
if (pendingWarning?.windowId !== windowId) pendingWarning = { windowId, content: WARNING_CONTENT };
|
|
147
|
+
return result({ customType: WARNING_TYPE, content: pendingWarning.content });
|
|
145
148
|
}
|
|
146
|
-
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return
|
|
147
|
-
if (hasWindowMessage(ctx, GUIDANCE_TYPE)
|
|
148
|
-
if (
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const left = Math.max(0, remaining - warning);
|
|
152
|
-
pendingGuidance = { windowId, content: tokenBudgetGuidance(left, PI_TOOL_NAMES.wipe) };
|
|
149
|
+
if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId) return result();
|
|
150
|
+
if (hasWindowMessage(ctx, GUIDANCE_TYPE)) return result();
|
|
151
|
+
if (pendingGuidance?.windowId !== windowId) {
|
|
152
|
+
if (remaining > reminder) return result();
|
|
153
|
+
pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
|
|
153
154
|
}
|
|
154
|
-
return
|
|
155
|
+
return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
|
|
155
156
|
});
|
|
156
157
|
|
|
157
158
|
pi.registerTool(defineTool({
|
package/src/pi/dream/cli.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { gitCommit } from "../../dream/git.js";
|
|
|
13
13
|
import { readDreamerSettings } from "./settings.js";
|
|
14
14
|
import { doctor } from "../../dream/doctor.js";
|
|
15
15
|
import { notesRoot } from "../notes/adapter.js";
|
|
16
|
+
import { errorMessage } from "../../error-message.js";
|
|
16
17
|
|
|
17
18
|
function args(argv: string[]) { const out: Record<string, string | boolean> = {}; for (let i=0;i<argv.length;i++) { const a=argv[i]!; if (a === "--force" || a === "--help") out[a.slice(2)] = true; else if (a.startsWith("--")) out[a.slice(2)] = argv[++i] ?? ""; } return out; }
|
|
18
19
|
function packageRoot(): string {
|
|
@@ -43,7 +44,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
43
44
|
const time = timeGate(stampPath, minHours); console.log(time.reason); if (!a.force && !time.ok) return 0;
|
|
44
45
|
const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
|
|
45
46
|
const material = materialGate(home, since, minSessions); console.log(material.reason); if (!a.force && !material.ok) return 0;
|
|
46
|
-
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${e
|
|
47
|
+
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${errorMessage(e)}`); return 0; } if (!lock.held) { console.log(lock.reason); return 0; }
|
|
47
48
|
const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-"); const reportPath = join(home, "dreams", `${stamp}.md`);
|
|
48
49
|
let succeeded = false;
|
|
49
50
|
try {
|
|
@@ -67,7 +68,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
67
68
|
const playbook = loadPlaybook(playbookPath);
|
|
68
69
|
result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
|
|
69
70
|
} catch (e) {
|
|
70
|
-
const message =
|
|
71
|
+
const message = errorMessage(e);
|
|
71
72
|
console.error(message);
|
|
72
73
|
return finishDream(home, stamp, reportPath, true, message, []);
|
|
73
74
|
}
|
package/src/pi/dream/runner.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { DreamResult, DreamWrite } from "../../dream/result.js";
|
|
|
3
3
|
import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager, type AgentSession, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { Type, type Api, type Model } from "@earendil-works/pi-ai";
|
|
5
5
|
import { contentText } from "../../history/history.js";
|
|
6
|
+
import { errorMessage } from "../../error-message.js";
|
|
6
7
|
|
|
7
8
|
export type DreamerSession = Pick<AgentSession, "prompt" | "subscribe" | "dispose">;
|
|
8
9
|
export type DreamerSessionFactory = (options: { cwd: string; modelPattern?: string; tools: string[] }) => Promise<DreamerSession>;
|
|
@@ -80,7 +81,7 @@ export async function runDreamer(playbook: string, cwd: string, options: { model
|
|
|
80
81
|
try {
|
|
81
82
|
await session.prompt(playbook);
|
|
82
83
|
} catch (error) {
|
|
83
|
-
return { report: answer, writes, error:
|
|
84
|
+
return { report: answer, writes, error: errorMessage(error) };
|
|
84
85
|
}
|
|
85
86
|
if (providerError) return { report: answer, writes, error: `dreamer failed: ${providerError}` };
|
|
86
87
|
return { report: answer, writes };
|
package/src/pi/history-tools.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { historyWindows, historyList, historyRead
|
|
2
|
+
import { historyWindows, historyList, historyRead } from "../tools/history.js";
|
|
3
3
|
import { historyFromSession } from "./history.js";
|
|
4
4
|
import { HISTORY_NAMESPACE, registerOperation } from "./tool-result.js";
|
|
5
5
|
|
|
6
|
-
/** Register the
|
|
6
|
+
/** Register the three shared history operations; the adapter allocates addresses and supplies them. */
|
|
7
7
|
export function registerHistoryTools(pi: ExtensionAPI) {
|
|
8
8
|
registerOperation(pi, historyWindows, (params, ctx) => historyWindows.execute(params, historyFromSession(ctx), ctx.sessionManager.getSessionId()), HISTORY_NAMESPACE);
|
|
9
9
|
registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
10
10
|
registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
11
|
-
registerOperation(pi, historySearch, (params, ctx) => historySearch.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
12
11
|
}
|