notesoup 0.47.0 → 0.48.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 +1 -1
- 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 +59 -11
- 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/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/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 +0 -2
- package/dist/src/pi/budget.js +13 -53
- 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 +49 -73
- package/dist/src/pi/runtime.js +19 -18
- package/dist/src/pi/window.d.ts +12 -6
- package/dist/src/pi/window.js +7 -0
- package/dist/test/agent-loop.test.js +65 -42
- package/dist/test/boot.integration.test.js +119 -16
- package/dist/test/budget-settings.integration.test.js +4 -2
- 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 +243 -49
- package/dist/test/dsh.test.js +79 -2
- 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 +202 -47
- package/docs/architecture.md +3 -3
- package/docs/claude-code-mod.md +15 -3
- package/docs/dsh.md +1 -1
- 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 +154 -52
- package/package.json +1 -1
- package/src/boot/render.ts +41 -23
- package/src/boot/text.ts +68 -11
- package/src/budget/text.ts +61 -10
- package/src/claude/helper.ts +53 -22
- package/src/claude/history.ts +228 -0
- package/src/dsh/engine.ts +16 -9
- package/src/dsh/index.ts +8 -3
- 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 +13 -50
- 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 +57 -80
- package/src/pi/runtime.ts +19 -18
- package/src/pi/window.ts +11 -1
package/src/dsh/engine.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { CompactionEngine, CompactionId, ManualCompactionError, compactCheckpoin
|
|
|
6
6
|
import { createUserMessage, type ContentBlock } from "@deepseek-ai/dsh-llm";
|
|
7
7
|
import { appendPluginRecord, type Session, type SessionSeq } from "@deepseek-ai/dsh-session";
|
|
8
8
|
import { measureBudget, type BudgetConfig } from "./budget.js";
|
|
9
|
+
import { selectContinuation, type ResetOrigin } from "../budget/text.js";
|
|
9
10
|
import { checkpointText, Windows, WINDOW_RECORD, type NotesConfig } from "./window.js";
|
|
10
11
|
|
|
11
12
|
export type EngineConfig = NotesConfig & Partial<BudgetConfig>;
|
|
@@ -69,8 +70,10 @@ export class NotesoupCompactionEngine extends CompactionEngine {
|
|
|
69
70
|
async compactIfNeeded(agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null> {
|
|
70
71
|
signal.throwIfAborted();
|
|
71
72
|
const state = this.windows.get(agent.session);
|
|
72
|
-
|
|
73
|
-
|
|
73
|
+
// `pendingReset` is the model's own `empty_brain` call. A budget cutoff happens without one,
|
|
74
|
+
// and that difference is the reset's actual origin.
|
|
75
|
+
const modelRequested = state.pendingReset;
|
|
76
|
+
if (!modelRequested) {
|
|
74
77
|
if (!this.config.auto) return null;
|
|
75
78
|
// Context overflow is deliberately left to the host. This adapter owns reserve resets.
|
|
76
79
|
if (trigger === "context-overflow") return null;
|
|
@@ -79,11 +82,11 @@ export class NotesoupCompactionEngine extends CompactionEngine {
|
|
|
79
82
|
}
|
|
80
83
|
const selected = range(agent.session);
|
|
81
84
|
if (!selected) return null;
|
|
82
|
-
return this.compactRegion(selected.start, selected.end, agent, signal);
|
|
85
|
+
return this.compactRegion(selected.start, selected.end, agent, signal, modelRequested ? "normal" : "forced");
|
|
83
86
|
}
|
|
84
|
-
async compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal): Promise<CompactionResult> {
|
|
87
|
+
async compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal, origin: ResetOrigin = "forced"): Promise<CompactionResult> {
|
|
85
88
|
if (entryState(agent.session).turn === null) throw new ManualCompactionError("busy", "notesoup: compactRegion needs an open turn; use compactNow while idle.");
|
|
86
|
-
return this.transaction(start, end, agent, signal);
|
|
89
|
+
return this.transaction(start, end, agent, signal, origin);
|
|
87
90
|
}
|
|
88
91
|
compactNow(agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId): Promise<CompactionResult | null> {
|
|
89
92
|
signal.throwIfAborted();
|
|
@@ -94,13 +97,13 @@ export class NotesoupCompactionEngine extends CompactionEngine {
|
|
|
94
97
|
if (entryState(agent.session).turn !== null) throw new ManualCompactionError("busy", "notesoup: an open turn remains; wait for the agent to stop, then retry.");
|
|
95
98
|
const selected = range(agent.session);
|
|
96
99
|
if (!selected) return null;
|
|
97
|
-
return this.transaction(selected.start, selected.end, agent, combined, sourceCommandId, true);
|
|
100
|
+
return this.transaction(selected.start, selected.end, agent, combined, "forced", sourceCommandId, true);
|
|
98
101
|
});
|
|
99
102
|
} catch (error) { throw new ManualCompactionError("busy", "notesoup: wait for the agent to become idle, then retry compactNow.", { cause: error }); }
|
|
100
103
|
}
|
|
101
104
|
|
|
102
105
|
/** No model call, no shrink requirement: even a one-message window can be cleared. */
|
|
103
|
-
private async transaction(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal
|
|
106
|
+
private async transaction(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal: AbortSignal | undefined, origin: ResetOrigin, sourceCommandId?: CommandId, flush = false): Promise<CompactionResult> {
|
|
104
107
|
const session = agent.session;
|
|
105
108
|
signal?.throwIfAborted();
|
|
106
109
|
const selected = range(session);
|
|
@@ -109,6 +112,7 @@ export class NotesoupCompactionEngine extends CompactionEngine {
|
|
|
109
112
|
if (entry.busy) throw new ManualCompactionError("busy", "notesoup: a compaction/start has no matching end; reload this session before retrying.");
|
|
110
113
|
const state = this.windows.get(session);
|
|
111
114
|
const previous = state.snapshot;
|
|
115
|
+
const previousContinuation = state.continuation;
|
|
112
116
|
const shadowedSeqs = [...session.surface.nodes.slice(1)];
|
|
113
117
|
const generation = session.surface.contentGeneration;
|
|
114
118
|
const measured = this.ctx.tokenMeter.measure(session);
|
|
@@ -127,8 +131,11 @@ export class NotesoupCompactionEngine extends CompactionEngine {
|
|
|
127
131
|
signal?.throwIfAborted();
|
|
128
132
|
if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1) throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next notebook; retry after current work finishes.");
|
|
129
133
|
// Mint BEFORE writing the checkpoint. A rejected append restores the previous notebook.
|
|
134
|
+
// One draw per reset artifact: the checkpoint text and the steered copy share it.
|
|
135
|
+
const continuation = selectContinuation(origin);
|
|
130
136
|
state.snapshot = next;
|
|
131
|
-
|
|
137
|
+
state.continuation = continuation;
|
|
138
|
+
const summary: ContentBlock[] = [{ type: "text", text: checkpointText(next, continuation) }];
|
|
132
139
|
const summarized = session.append("compaction/summary", { compactionId, ...(sourceCommandId === undefined ? {} : { sourceCommandId }), summary, shadowedRange: { start, end }, shadowedSeqs, shadowedTokenCount, provider: "notesoup", model: "notes" });
|
|
133
140
|
session.append("user/message", createUserMessage({ content: summary, source: compactCheckpointSource(compactionId, sourceCommandId) }), { surfaceOp: { op: "replace", startSeq: start, endSeq: end }, sourceEventSeqs: [opened.seq, summarized.seq, ...shadowedSeqs] });
|
|
134
141
|
landed = true;
|
|
@@ -142,7 +149,7 @@ export class NotesoupCompactionEngine extends CompactionEngine {
|
|
|
142
149
|
try { appendPluginRecord(session, WINDOW_RECORD, next); }
|
|
143
150
|
catch (error) { this.ctx.logger.warn(`notesoup: window record could not be written; the checkpoint holds ${next.windowId}. ${String(error)}`); }
|
|
144
151
|
} catch (error) {
|
|
145
|
-
if (!landed) state.snapshot = previous;
|
|
152
|
+
if (!landed) { state.snapshot = previous; state.continuation = previousContinuation; }
|
|
146
153
|
failure = error;
|
|
147
154
|
if (!closing) {
|
|
148
155
|
try { session.append("compaction/end", { ...lifecycle, error: String(error) }); closed = true; }
|
package/src/dsh/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Context } from "@deepseek-ai/cordis";
|
|
2
2
|
import type {} from "@deepseek-ai/dsh-agent";
|
|
3
3
|
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
4
|
-
import {
|
|
4
|
+
import { COUNTDOWN_LINE, warningPrompt, tokenBudgetGuidance } from "../budget/text.js";
|
|
5
5
|
import { measureBudget } from "./budget.js";
|
|
6
6
|
import { BOOT_SECTION, restoreWarnings } from "./window.js";
|
|
7
7
|
import { preflight } from "./engine.js";
|
|
@@ -43,7 +43,7 @@ export function apply(ctx: Context): void {
|
|
|
43
43
|
const state = engine.windows.get(agent.session);
|
|
44
44
|
const phase = budget.remaining <= budget.warning ? "warning" : budget.remaining <= budget.reminder ? "reminder" : undefined;
|
|
45
45
|
if (phase && !(phase === "warning" ? state.warned : state.reminded || state.warned)) {
|
|
46
|
-
const text = phase === "warning" ?
|
|
46
|
+
const text = phase === "warning" ? `${warningPrompt()}\n${COUNTDOWN_LINE}` : tokenBudgetGuidance(budget.countdown, "empty_brain");
|
|
47
47
|
agent.steer(createUserMessage({ content: [{ type: "text", text }], source: { kind: "notesoup-budget", windowId: state.snapshot.windowId, phase } }));
|
|
48
48
|
if (phase === "warning") state.warned = true;
|
|
49
49
|
else state.reminded = true;
|
|
@@ -55,7 +55,12 @@ export function apply(ctx: Context): void {
|
|
|
55
55
|
ctx.on("agent/turn-stopping", async ({ agent, signal }) => {
|
|
56
56
|
if (signal.aborted) return;
|
|
57
57
|
const result = await engine.compactIfNeeded(agent, "pressure", signal);
|
|
58
|
-
if (result)
|
|
58
|
+
if (result) {
|
|
59
|
+
// The checkpoint already carries this exact paragraph; the steer is the same artifact's
|
|
60
|
+
// second representation, never a second draw.
|
|
61
|
+
const { continuation } = engine.windows.get(agent.session);
|
|
62
|
+
if (continuation !== undefined) agent.steer(createUserMessage({ content: [{ type: "text", text: continuation }], source: { kind: "notesoup-continuation" } }));
|
|
63
|
+
}
|
|
59
64
|
});
|
|
60
65
|
ctx.on("session/event", (session, event) => {
|
|
61
66
|
if (event.type === "turn/end" && event.data.reason.kind !== "completed") {
|
package/src/dsh/window.ts
CHANGED
|
@@ -7,7 +7,6 @@ import { createHash } from "node:crypto";
|
|
|
7
7
|
import { loadNotesSnapshot } from "../boot/snapshot.js";
|
|
8
8
|
import { renderBootBlock } from "../boot/render.js";
|
|
9
9
|
import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
|
|
10
|
-
import { CONTINUATION } from "../budget/text.js";
|
|
11
10
|
import { contentText } from "../history/history.js";
|
|
12
11
|
import { projectKey, slugify, snapshotNotesIdentity, type NotesIdentity } from "../notes/index.js";
|
|
13
12
|
|
|
@@ -17,7 +16,7 @@ const BOOT_OPEN = "<notesoup-boot>\n";
|
|
|
17
16
|
const BOOT_CLOSE = "\n</notesoup-boot>";
|
|
18
17
|
const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
|
|
19
18
|
export type WindowSnapshot = Readonly<{ version: 1; window: number; windowId: string; openedAt: number; boot: string; notesDigest: string }>;
|
|
20
|
-
export type WindowState = { snapshot: WindowSnapshot; pendingReset: boolean; warned: boolean; reminded: boolean };
|
|
19
|
+
export type WindowState = { snapshot: WindowSnapshot; pendingReset: boolean; warned: boolean; reminded: boolean; continuation?: string };
|
|
21
20
|
export type NotesConfig = { notesHome?: string; agentName?: string };
|
|
22
21
|
|
|
23
22
|
export function restoreWarnings(state: WindowState, events: readonly SessionEvent[]): void {
|
|
@@ -37,7 +36,7 @@ declare module "@deepseek-ai/dsh-session/types" {
|
|
|
37
36
|
|
|
38
37
|
export function windowId(sessionId: string, window: number): string { return `dsh:${sessionId}:${window}`; }
|
|
39
38
|
function digest(boot: string): string { return createHash("sha256").update(boot).digest("hex"); }
|
|
40
|
-
export function checkpointText(snapshot: WindowSnapshot): string { return snapshot.boot + CHECKPOINT_END +
|
|
39
|
+
export function checkpointText(snapshot: WindowSnapshot, continuation: string): string { return snapshot.boot + CHECKPOINT_END + continuation + "\n</notesoup-continuation>"; }
|
|
41
40
|
|
|
42
41
|
export function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined {
|
|
43
42
|
const record = pluginRecordOf(event);
|
|
@@ -65,10 +64,17 @@ function systemSnapshot(event: SessionEvent): WindowSnapshot | undefined {
|
|
|
65
64
|
return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
|
|
66
65
|
}
|
|
67
66
|
|
|
67
|
+
/**
|
|
68
|
+
* Read the window identity out of a persisted boot. The `context_window` spelling is what boots
|
|
69
|
+
* written before the rename carry, so both spellings still yield their ordinal and window id.
|
|
70
|
+
*/
|
|
68
71
|
function snapshotFromBoot(boot: string, openedAt: number): WindowSnapshot | undefined {
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
+
const identity = /<(?:context_window|notesoup:window_identity)>\n[\s\S]*?\n(dsh:[^\n]+)\n[\s\S]*?└─ (\d+)(?: +[^\n]*)?\n<\/(?:context_window|notesoup:window_identity)>/.exec(boot);
|
|
73
|
+
const legacy = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
|
|
74
|
+
const shortName = identity?.[2] ?? legacy?.[2];
|
|
75
|
+
const id = identity ? `${identity[1]}:${shortName}` : legacy?.[1];
|
|
76
|
+
if (!id || shortName === undefined || !Number.isSafeInteger(Number(shortName))) return undefined;
|
|
77
|
+
return Object.freeze({ version: 1, window: Number(shortName), windowId: id, openedAt, boot, notesDigest: digest(boot) });
|
|
72
78
|
}
|
|
73
79
|
|
|
74
80
|
export function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined {
|
|
@@ -116,9 +122,9 @@ export class Windows {
|
|
|
116
122
|
async mint(agent: Pick<Agent, "session" | "options">, window: number, openedAt: number): Promise<WindowSnapshot> {
|
|
117
123
|
const identity = notesIdentity(agent, this.config);
|
|
118
124
|
const notes = await loadNotesSnapshot(identity, openedAt);
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model,
|
|
125
|
+
const trunk = `dsh:${agent.session.id}`;
|
|
126
|
+
const tree = { trunk, windows: Array.from({ length: window + 1 }, (_, index) => ({ shortName: String(index), isCurrent: index === window })) };
|
|
127
|
+
const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, tree, notes, tools: DEFAULT_BOOT_TOOL_NAMES }) + BOOT_CLOSE;
|
|
122
128
|
return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
|
|
123
129
|
}
|
|
124
130
|
}
|
package/src/history/query.ts
CHANGED
|
@@ -4,10 +4,10 @@ import { failure, success, type Outcome } 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, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
|
|
8
8
|
|
|
9
|
-
type
|
|
10
|
-
type
|
|
9
|
+
type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
|
|
10
|
+
type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow };
|
|
11
11
|
|
|
12
12
|
/** Which end of one selection `limit` is taken from; page items always come back ascending. */
|
|
13
13
|
export type HistoryOrder = "newest" | "oldest";
|
|
@@ -83,21 +83,11 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
|
|
|
83
83
|
return fits(withoutName) ? withoutName : shrinkContent(withoutName);
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
/** Only a call without roles or query folds tool/context runs. */
|
|
91
|
-
function foldsRuns(params: HistorySelection): boolean {
|
|
92
|
-
return !params.roles && params.query === undefined;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Folded counts stay exact even when some distinct tool names must be omitted. */
|
|
96
|
-
function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
|
|
97
|
-
if (events.length === 0) return [];
|
|
98
|
-
const sorted = [...events].sort((a, b) => a.seq - b.seq);
|
|
86
|
+
/** Summarize one already ordered gap; omitted tool names never change its exact count. */
|
|
87
|
+
function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
|
|
88
|
+
if (events.length === 0) return undefined;
|
|
99
89
|
const counts = new Map<string, number>();
|
|
100
|
-
for (const event of
|
|
90
|
+
for (const event of events) {
|
|
101
91
|
if (event.role !== "tool") continue;
|
|
102
92
|
const name = event.execution?.name ?? "unknown";
|
|
103
93
|
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
@@ -105,64 +95,43 @@ function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
|
|
|
105
95
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
106
96
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
107
97
|
const tools = Object.fromEntries(entries);
|
|
108
|
-
return
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** A cursor exists only when the same selection still has a visible event past that end. */
|
|
112
|
-
function pageCursors(vis: HistoryEvent[], selected: HistoryEvent[], beforeSeq: number | undefined, afterSeq: number | undefined): Pick<HistoryPage, "page_older" | "page_newer"> {
|
|
113
|
-
if (selected.length === 0) return { page_older: null, page_newer: null };
|
|
114
|
-
const lower = afterSeq ?? 0;
|
|
115
|
-
const upper = beforeSeq ?? Number.POSITIVE_INFINITY;
|
|
116
|
-
// Selected events are in seq order.
|
|
117
|
-
const first = selected[0]!.seq;
|
|
118
|
-
const last = selected.at(-1)!.seq;
|
|
119
|
-
return {
|
|
120
|
-
page_older: vis.some((event) => event.seq > lower && event.seq < first) ? { before_seq: first } : null,
|
|
121
|
-
page_newer: vis.some((event) => event.seq > last && event.seq < upper) ? { after_seq: last, from: "oldest" } : null,
|
|
122
|
-
};
|
|
98
|
+
return { folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
|
|
123
99
|
}
|
|
124
100
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
101
|
+
/** Filter and order once. Conversation candidates own the folded gap immediately before them. */
|
|
102
|
+
function prepareSelection(projection: HistoryProjection, params: HistorySelection): PreparedSelection {
|
|
103
|
+
const folds = !params.roles && params.query === undefined;
|
|
104
|
+
const candidates: Candidate[] = [];
|
|
105
|
+
let run: HistoryEvent[] = [];
|
|
106
|
+
for (const event of filteredItems(projection, params, false)) {
|
|
107
|
+
if (folds && (event.role === "tool" || event.role === "context")) {
|
|
108
|
+
run.push(event);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (folds && eventDocument(event) === "") continue;
|
|
112
|
+
const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query as string[]);
|
|
113
|
+
if (matchOffset !== undefined && matchOffset < 0) continue;
|
|
114
|
+
candidates.push({ event, matchOffset, before: foldedRun(run) });
|
|
115
|
+
run = [];
|
|
140
116
|
}
|
|
141
|
-
|
|
142
|
-
return folded;
|
|
117
|
+
return { candidates, tail: foldedRun(run) };
|
|
143
118
|
}
|
|
144
119
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
|
|
120
|
+
/** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
|
|
121
|
+
function pageData(prepared: PreparedSelection, start: number, end: number, maxChars: number, preview?: HistoryPageItem): HistoryPage {
|
|
122
|
+
const { candidates, tail } = prepared;
|
|
123
|
+
const items: HistoryPage["items"] = [];
|
|
124
|
+
for (let index = start; index < end; index++) {
|
|
125
|
+
const candidate = candidates[index]!;
|
|
126
|
+
if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
|
|
127
|
+
items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
|
|
154
128
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
if (params.query === undefined) return events.map((event) => ({ event }));
|
|
162
|
-
const needles = params.query as string[];
|
|
163
|
-
return events
|
|
164
|
-
.map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
|
|
165
|
-
.filter((candidate) => candidate.matchOffset >= 0);
|
|
129
|
+
if (end === candidates.length && tail) items.push(tail);
|
|
130
|
+
return {
|
|
131
|
+
items,
|
|
132
|
+
page_older: start > 0 && start < end ? { before_seq: candidates[start]!.event.seq } : null,
|
|
133
|
+
page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
|
|
134
|
+
};
|
|
166
135
|
}
|
|
167
136
|
|
|
168
137
|
/**
|
|
@@ -180,24 +149,30 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
|
|
|
180
149
|
throw error;
|
|
181
150
|
}
|
|
182
151
|
const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
//
|
|
152
|
+
const prepared = prepareSelection(projection, scoped);
|
|
153
|
+
const { candidates } = prepared;
|
|
154
|
+
// Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
|
|
155
|
+
const newest = scoped.from !== "oldest";
|
|
156
|
+
let start = newest ? candidates.length : 0;
|
|
157
|
+
let end = start;
|
|
186
158
|
const limit = Math.max(1, scoped.limit ?? 20);
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
|
|
194
|
-
kept.push(candidate);
|
|
159
|
+
for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
|
|
160
|
+
const nextStart = newest ? start - 1 : start;
|
|
161
|
+
const nextEnd = newest ? end : end + 1;
|
|
162
|
+
if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
|
|
163
|
+
start = nextStart;
|
|
164
|
+
end = nextEnd;
|
|
195
165
|
continue;
|
|
196
166
|
}
|
|
197
|
-
if (
|
|
167
|
+
if (start === end) {
|
|
168
|
+
start = nextStart;
|
|
169
|
+
end = nextEnd;
|
|
170
|
+
const candidate = candidates[start]!;
|
|
171
|
+
candidate.preview = truncateHistoryItem(candidate.preview!, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
|
|
172
|
+
}
|
|
198
173
|
break;
|
|
199
174
|
}
|
|
200
|
-
const page = pageData(
|
|
175
|
+
const page = pageData(prepared, start, end, maxChars);
|
|
201
176
|
if (!fits(page)) {
|
|
202
177
|
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.`);
|
|
203
178
|
}
|
package/src/notes/address.ts
CHANGED
|
@@ -6,6 +6,17 @@ export type NoteAddress = { scope: Scope; path: string; who?: string };
|
|
|
6
6
|
|
|
7
7
|
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.";
|
|
8
8
|
|
|
9
|
+
/** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
|
|
10
|
+
export const HOME_HEADS: ReadonlyMap<string, { readonly scope: Scope; readonly home?: "project" | "agents" | "models" }> = new Map([
|
|
11
|
+
["project", { scope: "project" }],
|
|
12
|
+
["human", { scope: "human" }],
|
|
13
|
+
["self", { scope: "agent" }],
|
|
14
|
+
["model", { scope: "model" }],
|
|
15
|
+
["projects", { scope: "project", home: "project" }],
|
|
16
|
+
["agents", { scope: "agent", home: "agents" }],
|
|
17
|
+
["models", { scope: "model", home: "models" }],
|
|
18
|
+
]);
|
|
19
|
+
|
|
9
20
|
/**
|
|
10
21
|
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
11
22
|
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
@@ -52,23 +63,15 @@ export function assertAddress(value: unknown): NoteAddress {
|
|
|
52
63
|
let path = value;
|
|
53
64
|
let who: string | undefined;
|
|
54
65
|
if (value.startsWith("@")) {
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
path = tail;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
else if (head === "self") scope = "agent";
|
|
63
|
-
else if (head === "model") scope = "model";
|
|
64
|
-
else if (head === "projects" || head === "agents" || head === "models") {
|
|
65
|
-
const nameEnd = tail.indexOf("/");
|
|
66
|
-
who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
|
|
66
|
+
const [rawHead, ...tail] = value.slice(1).split("/");
|
|
67
|
+
const head = HOME_HEADS.get(rawHead!);
|
|
68
|
+
if (head === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
69
|
+
scope = head.scope;
|
|
70
|
+
if (head.home === undefined) path = tail.join("/");
|
|
71
|
+
else {
|
|
72
|
+
who = tail[0] ?? "";
|
|
67
73
|
if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
68
|
-
|
|
69
|
-
path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
|
|
70
|
-
} else {
|
|
71
|
-
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
74
|
+
path = tail.slice(1).join("/");
|
|
72
75
|
}
|
|
73
76
|
if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
74
77
|
if (path === "" && who === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
package/src/notes/store.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { Dirent } from "node:fs";
|
|
|
3
3
|
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
5
|
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
6
|
-
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp } from "./address.js";
|
|
6
|
+
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
|
|
7
7
|
import { isFilesystemError } from "./fs-error.js";
|
|
8
8
|
import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
|
|
9
9
|
import { NoteError } from "./errors.js";
|
|
@@ -121,19 +121,14 @@ type HomeRef = { scope: Scope; who?: string };
|
|
|
121
121
|
|
|
122
122
|
async function homesForPattern(pattern: string | undefined, identity: NotesIdentity): Promise<HomeRef[] | undefined> {
|
|
123
123
|
if (!pattern || !pattern.startsWith("@")) return undefined;
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
if (head ===
|
|
127
|
-
if (head ===
|
|
128
|
-
|
|
129
|
-
if (
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (name.length > 0 && !/[*?]/.test(name)) return [{ scope, who: assertWho(name) }];
|
|
133
|
-
const names = head === "projects" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head, identity.home);
|
|
134
|
-
return names.map((who) => ({ scope, who }));
|
|
135
|
-
}
|
|
136
|
-
return [];
|
|
124
|
+
const [rawHead, ...tail] = pattern.split("/");
|
|
125
|
+
const head = tail.length === 0 ? undefined : HOME_HEADS.get(rawHead!.slice(1)); // a bare "@projects" names no homes
|
|
126
|
+
if (head === undefined) return [];
|
|
127
|
+
if (head.home === undefined) return [{ scope: head.scope }];
|
|
128
|
+
const name = tail[0];
|
|
129
|
+
if (name !== undefined && name.length > 0 && !/[*?]/.test(name)) return [{ scope: head.scope, who: assertWho(name) }];
|
|
130
|
+
const names = head.home === "project" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head.home, identity.home);
|
|
131
|
+
return names.map((who) => ({ scope: head.scope, who }));
|
|
137
132
|
}
|
|
138
133
|
|
|
139
134
|
/** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
|
package/src/pi/boot.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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 type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
|
|
4
4
|
import { loadNotesSnapshot, unavailableNotesSnapshot, type NotesSnapshot } from "../boot/snapshot.js";
|
|
5
5
|
import { isFilesystemError } from "../notes/index.js";
|
|
6
6
|
import { BOOT_TYPE } from "./entries.js";
|
|
7
7
|
import { renderBootBlock } from "../boot/render.js";
|
|
8
|
-
import {
|
|
8
|
+
import { historyFromSession, nextHistorySeq } from "./history.js";
|
|
9
9
|
|
|
10
10
|
export type IncompleteNotesNotifier = (ctx: ExtensionContext, windowId: string, snapshot: NotesSnapshot) => void;
|
|
11
11
|
|
|
@@ -24,13 +24,35 @@ export type BootMessage = {
|
|
|
24
24
|
export async function buildBootMessage(
|
|
25
25
|
ctx: ExtensionContext,
|
|
26
26
|
windowId: string,
|
|
27
|
-
|
|
27
|
+
firstSeq: number | undefined,
|
|
28
28
|
notifyIncompleteNotes?: IncompleteNotesNotifier,
|
|
29
29
|
isCurrent: () => boolean = () => true,
|
|
30
30
|
): Promise<BootMessage> {
|
|
31
31
|
const agentName = agentSlug();
|
|
32
32
|
const modelName = modelSlug(ctx);
|
|
33
|
-
const
|
|
33
|
+
const windows = historyFromSession(ctx).windows.map((window) => {
|
|
34
|
+
const seqs = window.items.map((item) => item.seq);
|
|
35
|
+
return {
|
|
36
|
+
shortName: window.windowId.slice(window.windowId.lastIndexOf(":") + 1),
|
|
37
|
+
firstSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.min(...seqs),
|
|
38
|
+
lastSeq: firstSeq === undefined || seqs.length === 0 ? undefined : Math.max(...seqs),
|
|
39
|
+
isCurrent: window.windowId === windowId,
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
if (firstSeq !== undefined) {
|
|
43
|
+
// An empty old window will consume the pending boundary before its marker is written.
|
|
44
|
+
const last = windows.at(-1)!;
|
|
45
|
+
last.firstSeq ??= last.isCurrent ? firstSeq : nextHistorySeq(ctx);
|
|
46
|
+
}
|
|
47
|
+
if (!windows.some((window) => window.isCurrent)) {
|
|
48
|
+
windows.push({ shortName: windowId.slice(windowId.lastIndexOf(":") + 1), firstSeq, lastSeq: undefined, isCurrent: true });
|
|
49
|
+
}
|
|
50
|
+
// A closing boundary includes folded result slots, pending warnings and the old checkpoint.
|
|
51
|
+
for (let index = 0; index < windows.length - 1; index++) {
|
|
52
|
+
const nextFirst = windows[index + 1]!.firstSeq;
|
|
53
|
+
if (nextFirst !== undefined) windows[index]!.lastSeq = nextFirst - 1;
|
|
54
|
+
}
|
|
55
|
+
const tree = { trunk: windowId.slice(0, windowId.lastIndexOf(":")), windows };
|
|
34
56
|
const openedAt = Date.now();
|
|
35
57
|
let notes: NotesSnapshot;
|
|
36
58
|
try {
|
|
@@ -42,7 +64,7 @@ export async function buildBootMessage(
|
|
|
42
64
|
if (isCurrent()) notifyIncompleteNotes?.(ctx, windowId, notes);
|
|
43
65
|
return {
|
|
44
66
|
customType: BOOT_TYPE,
|
|
45
|
-
content: renderBootBlock({ agentName, modelName,
|
|
67
|
+
content: renderBootBlock({ agentName, modelName, tree, notes, tools: { ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS } }),
|
|
46
68
|
display: false,
|
|
47
69
|
details: { windowId },
|
|
48
70
|
};
|