@narumitw/pi-context-management 0.0.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/LICENSE +21 -0
- package/README.md +148 -0
- package/docs/context-management.md +257 -0
- package/package.json +57 -0
- package/src/context-management.ts +895 -0
- package/src/context-tools.ts +203 -0
- package/src/context-window.ts +393 -0
- package/src/fingerprint.ts +104 -0
- package/src/index.ts +1 -0
- package/src/notes-state.ts +144 -0
- package/src/pi-context-management.ts +105 -0
- package/src/recall-context.ts +524 -0
- package/src/settings-menu.ts +186 -0
- package/src/settings.ts +175 -0
- package/src/terminal.ts +6 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { MenuDefinition } from "@narumitw/pi-tui-kit";
|
|
3
|
+
import type { ContextManagementSettingsRuntime, ContextManagementSettingsState } from "./settings.js";
|
|
4
|
+
import { terminalText as safeText } from "./terminal.js";
|
|
5
|
+
|
|
6
|
+
type Screen = "main" | "settings" | "status" | "help" | "invalid";
|
|
7
|
+
type Action = "set-enabled";
|
|
8
|
+
|
|
9
|
+
export interface ContextManagementMenuOwner {
|
|
10
|
+
signal: AbortSignal;
|
|
11
|
+
isCurrent(): boolean;
|
|
12
|
+
isActive(): boolean;
|
|
13
|
+
onSettingsChanged(): void | Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const settingsChangeQueues = new WeakMap<ContextManagementSettingsRuntime, Promise<void>>();
|
|
17
|
+
|
|
18
|
+
function enqueueSettingsChange<T>(runtime: ContextManagementSettingsRuntime, operation: () => Promise<T>): Promise<T> {
|
|
19
|
+
const queued = settingsChangeQueues.get(runtime) ?? Promise.resolve();
|
|
20
|
+
const result = queued.then(operation, operation);
|
|
21
|
+
settingsChangeQueues.set(
|
|
22
|
+
runtime,
|
|
23
|
+
result.then(
|
|
24
|
+
() => undefined,
|
|
25
|
+
() => undefined,
|
|
26
|
+
),
|
|
27
|
+
);
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function updateEnabled(
|
|
32
|
+
runtime: ContextManagementSettingsRuntime,
|
|
33
|
+
ctx: ExtensionCommandContext,
|
|
34
|
+
enabled: boolean,
|
|
35
|
+
signal: AbortSignal,
|
|
36
|
+
onSettingsChanged: () => void | Promise<void>,
|
|
37
|
+
) {
|
|
38
|
+
return enqueueSettingsChange(runtime, async () => {
|
|
39
|
+
const previous = runtime.get().settings.enabled;
|
|
40
|
+
try {
|
|
41
|
+
await runtime.update({ enabled }, signal);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (signal.aborted) return { kind: "rejected" as const };
|
|
44
|
+
ctx.ui.notify(
|
|
45
|
+
`Could not save pi-context-management.json: ${safeText(error instanceof Error ? error.message : String(error))}`,
|
|
46
|
+
"error",
|
|
47
|
+
);
|
|
48
|
+
return { kind: "rejected" as const };
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
// A completed save remains committed even if menu cancellation races with reconciliation.
|
|
52
|
+
await onSettingsChanged();
|
|
53
|
+
} catch (error) {
|
|
54
|
+
let rollbackError: unknown;
|
|
55
|
+
try {
|
|
56
|
+
await runtime.update({ enabled: previous });
|
|
57
|
+
await onSettingsChanged();
|
|
58
|
+
} catch (recoveryError) {
|
|
59
|
+
rollbackError = recoveryError;
|
|
60
|
+
}
|
|
61
|
+
if (signal.aborted) return { kind: "rejected" as const };
|
|
62
|
+
const failure = safeText(error instanceof Error ? error.message : String(error));
|
|
63
|
+
const recovery = rollbackError
|
|
64
|
+
? ` The previous setting could not be fully restored: ${safeText(rollbackError instanceof Error ? rollbackError.message : String(rollbackError))}`
|
|
65
|
+
: " The previous setting was restored.";
|
|
66
|
+
ctx.ui.notify(`Could not apply experimental context management: ${failure}.${recovery}`, "error");
|
|
67
|
+
return { kind: "rejected" as const };
|
|
68
|
+
}
|
|
69
|
+
if (signal.aborted) return { kind: "rejected" as const };
|
|
70
|
+
ctx.ui.notify("Context management settings saved.", "info");
|
|
71
|
+
return { kind: "stay" as const };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createContextManagementMenu(
|
|
76
|
+
runtime: ContextManagementSettingsRuntime,
|
|
77
|
+
options: {
|
|
78
|
+
isActive?: () => boolean;
|
|
79
|
+
onSettingsChanged?: () => void | Promise<void>;
|
|
80
|
+
} = {},
|
|
81
|
+
): MenuDefinition<ContextManagementSettingsState, Screen, Action, ExtensionCommandContext> {
|
|
82
|
+
return {
|
|
83
|
+
start: "main",
|
|
84
|
+
screens: {
|
|
85
|
+
main: ({ state }) => ({
|
|
86
|
+
kind: "actions",
|
|
87
|
+
title: "Experimental Context Management",
|
|
88
|
+
lines: [
|
|
89
|
+
`Configured: ${state.settings.enabled ? "On" : "Off"}`,
|
|
90
|
+
`Runtime: ${options.isActive?.() ? "Active" : state.settings.enabled ? "Unavailable" : "Inactive"}`,
|
|
91
|
+
],
|
|
92
|
+
items: [
|
|
93
|
+
state.kind === "invalid"
|
|
94
|
+
? {
|
|
95
|
+
id: "settings",
|
|
96
|
+
label: "Settings",
|
|
97
|
+
description: "Read-only until the invalid settings file is repaired.",
|
|
98
|
+
to: "invalid" as const,
|
|
99
|
+
}
|
|
100
|
+
: { id: "settings", label: "Settings", to: "settings" as const },
|
|
101
|
+
{ id: "status", label: "Status", to: "status" as const },
|
|
102
|
+
{ id: "help", label: "Help", to: "help" as const },
|
|
103
|
+
{ id: "close", label: "Close", close: true },
|
|
104
|
+
],
|
|
105
|
+
hint: "close",
|
|
106
|
+
}),
|
|
107
|
+
settings: ({ state }) => ({
|
|
108
|
+
kind: "settings",
|
|
109
|
+
title: "Context Management Settings",
|
|
110
|
+
lines: [`User settings · ${safeText(state.path)}`],
|
|
111
|
+
items: [
|
|
112
|
+
{
|
|
113
|
+
id: "enabled",
|
|
114
|
+
label: "Experimental context management",
|
|
115
|
+
description: "Use summary-free local rollover and four branch-local context tools.",
|
|
116
|
+
currentValue: state.settings.enabled ? "On" : "Off",
|
|
117
|
+
values: ["On", "Off"],
|
|
118
|
+
action: "set-enabled",
|
|
119
|
+
},
|
|
120
|
+
],
|
|
121
|
+
}),
|
|
122
|
+
status: ({ state }) => ({
|
|
123
|
+
kind: "detail",
|
|
124
|
+
title: "Context Management Status",
|
|
125
|
+
lines: [
|
|
126
|
+
`Configured: ${state.settings.enabled ? "On" : "Off"}`,
|
|
127
|
+
`Runtime: ${options.isActive?.() ? "Active" : state.settings.enabled ? "Unavailable" : "Inactive"}`,
|
|
128
|
+
`Settings: ${safeText(state.path)}`,
|
|
129
|
+
],
|
|
130
|
+
hint: "back",
|
|
131
|
+
}),
|
|
132
|
+
help: () => ({
|
|
133
|
+
kind: "detail",
|
|
134
|
+
title: "Context Management Help",
|
|
135
|
+
lines: [
|
|
136
|
+
"This experimental extension starts summary-free context windows and exposes bounded history and note tools.",
|
|
137
|
+
"Save important information in notes before starting a new context.",
|
|
138
|
+
"Disabling the extension restores Pi-native compaction after the active run settles.",
|
|
139
|
+
],
|
|
140
|
+
hint: "back",
|
|
141
|
+
}),
|
|
142
|
+
invalid: ({ state }) => ({
|
|
143
|
+
kind: "detail",
|
|
144
|
+
title: "Context Management Settings · Read only",
|
|
145
|
+
lines: [
|
|
146
|
+
`Invalid settings file: ${safeText(state.path)}`,
|
|
147
|
+
`Issue: ${safeText(state.issue ?? "unknown validation error")}`,
|
|
148
|
+
"Built-in defaults are active. Repair the file and run /reload; it will not be overwritten.",
|
|
149
|
+
],
|
|
150
|
+
hint: "back",
|
|
151
|
+
}),
|
|
152
|
+
},
|
|
153
|
+
actions: {
|
|
154
|
+
"set-enabled": ({ ctx, value, signal }) =>
|
|
155
|
+
updateEnabled(runtime, ctx, value === "On", signal, options.onSettingsChanged ?? (() => undefined)),
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function showContextManagementMenu(
|
|
161
|
+
runtime: ContextManagementSettingsRuntime,
|
|
162
|
+
ctx: ExtensionCommandContext,
|
|
163
|
+
owner: ContextManagementMenuOwner,
|
|
164
|
+
): Promise<void> {
|
|
165
|
+
if (ctx.mode === "rpc" && ctx.hasUI) {
|
|
166
|
+
ctx.ui.notify(`Edit experimental context management settings at ${safeText(runtime.get().path)}.`, "info");
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (ctx.mode !== "tui") {
|
|
170
|
+
throw new Error("/context-management requires TUI or RPC UI support");
|
|
171
|
+
}
|
|
172
|
+
const { runMenu } = await import("@narumitw/pi-tui-kit");
|
|
173
|
+
if (owner.signal.aborted || !owner.isCurrent()) return;
|
|
174
|
+
await runMenu(
|
|
175
|
+
ctx,
|
|
176
|
+
createContextManagementMenu(runtime, {
|
|
177
|
+
isActive: owner.isActive,
|
|
178
|
+
onSettingsChanged: owner.onSettingsChanged,
|
|
179
|
+
}),
|
|
180
|
+
{
|
|
181
|
+
getState: () => runtime.get(),
|
|
182
|
+
signal: owner.signal,
|
|
183
|
+
isCurrent: owner.isCurrent,
|
|
184
|
+
},
|
|
185
|
+
);
|
|
186
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
|
|
7
|
+
export const CONTEXT_MANAGEMENT_SETTINGS_FILE = "pi-context-management.json";
|
|
8
|
+
export const MAX_SETTINGS_BYTES = 64 * 1024;
|
|
9
|
+
|
|
10
|
+
export interface ContextManagementSettings {
|
|
11
|
+
enabled: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_CONTEXT_MANAGEMENT_SETTINGS: Readonly<ContextManagementSettings> = Object.freeze({
|
|
15
|
+
enabled: false,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export interface ContextManagementSettingsState {
|
|
19
|
+
kind: "missing" | "loaded" | "invalid";
|
|
20
|
+
path: string;
|
|
21
|
+
settings: ContextManagementSettings;
|
|
22
|
+
document?: Record<string, unknown>;
|
|
23
|
+
issue?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ContextManagementSettingsRuntime {
|
|
27
|
+
get(): Readonly<ContextManagementSettingsState>;
|
|
28
|
+
reload(signal?: AbortSignal): Promise<Readonly<ContextManagementSettingsState>>;
|
|
29
|
+
update(
|
|
30
|
+
patch: Partial<ContextManagementSettings>,
|
|
31
|
+
signal?: AbortSignal,
|
|
32
|
+
): Promise<Readonly<ContextManagementSettingsState>>;
|
|
33
|
+
flush(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
37
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function normalizeContextManagementSettings(value: unknown): ContextManagementSettings | undefined {
|
|
41
|
+
if (!isRecord(value)) return undefined;
|
|
42
|
+
if (Object.hasOwn(value, "enabled") && typeof value.enabled !== "boolean") return undefined;
|
|
43
|
+
return {
|
|
44
|
+
enabled: typeof value.enabled === "boolean" ? value.enabled : DEFAULT_CONTEXT_MANAGEMENT_SETTINGS.enabled,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function contextManagementSettingsPath(): string {
|
|
49
|
+
return join(getAgentDir(), CONTEXT_MANAGEMENT_SETTINGS_FILE);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function aborted(signal?: AbortSignal): void {
|
|
53
|
+
if (signal?.aborted) throw new DOMException("Settings operation aborted", "AbortError");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function loadContextManagementSettings(
|
|
57
|
+
path = contextManagementSettingsPath(),
|
|
58
|
+
signal?: AbortSignal,
|
|
59
|
+
): Promise<ContextManagementSettingsState> {
|
|
60
|
+
aborted(signal);
|
|
61
|
+
try {
|
|
62
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
63
|
+
let text: string;
|
|
64
|
+
try {
|
|
65
|
+
const stats = await handle.stat();
|
|
66
|
+
aborted(signal);
|
|
67
|
+
if (!stats.isFile()) throw new Error("settings path is not a regular file");
|
|
68
|
+
if (stats.size > MAX_SETTINGS_BYTES) throw new Error("settings file exceeds 64 KiB");
|
|
69
|
+
text = await handle.readFile("utf8");
|
|
70
|
+
} finally {
|
|
71
|
+
await handle.close();
|
|
72
|
+
}
|
|
73
|
+
aborted(signal);
|
|
74
|
+
const document = JSON.parse(text) as unknown;
|
|
75
|
+
const settings = normalizeContextManagementSettings(document);
|
|
76
|
+
if (!settings || !isRecord(document)) throw new Error("invalid settings shape");
|
|
77
|
+
return { kind: "loaded", path, settings, document };
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (signal?.aborted) throw error;
|
|
80
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
81
|
+
return {
|
|
82
|
+
kind: "missing",
|
|
83
|
+
path,
|
|
84
|
+
settings: { ...DEFAULT_CONTEXT_MANAGEMENT_SETTINGS },
|
|
85
|
+
document: {},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
kind: "invalid",
|
|
90
|
+
path,
|
|
91
|
+
settings: { ...DEFAULT_CONTEXT_MANAGEMENT_SETTINGS },
|
|
92
|
+
issue:
|
|
93
|
+
isNodeError(error) && error.code === "ELOOP"
|
|
94
|
+
? "symbolic links are not accepted"
|
|
95
|
+
: error instanceof Error
|
|
96
|
+
? error.message
|
|
97
|
+
: String(error),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function savePatch(
|
|
103
|
+
path: string,
|
|
104
|
+
patch: Partial<ContextManagementSettings>,
|
|
105
|
+
signal?: AbortSignal,
|
|
106
|
+
): Promise<ContextManagementSettingsState> {
|
|
107
|
+
const latest = await loadContextManagementSettings(path, signal);
|
|
108
|
+
if (latest.kind === "invalid") {
|
|
109
|
+
throw new Error("Cannot overwrite an invalid pi-context-management.json; repair it and reload first");
|
|
110
|
+
}
|
|
111
|
+
const document = { ...latest.document, ...patch };
|
|
112
|
+
const settings = normalizeContextManagementSettings(document);
|
|
113
|
+
if (!settings) throw new Error("Refusing to save invalid context management settings");
|
|
114
|
+
const temporaryPath = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
115
|
+
await mkdir(dirname(path), { recursive: true });
|
|
116
|
+
aborted(signal);
|
|
117
|
+
try {
|
|
118
|
+
await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}\n`, {
|
|
119
|
+
encoding: "utf8",
|
|
120
|
+
flag: "wx",
|
|
121
|
+
mode: 0o600,
|
|
122
|
+
});
|
|
123
|
+
aborted(signal);
|
|
124
|
+
const current = await loadContextManagementSettings(path, signal);
|
|
125
|
+
if (
|
|
126
|
+
current.kind === "invalid" ||
|
|
127
|
+
current.kind !== latest.kind ||
|
|
128
|
+
JSON.stringify(current.document) !== JSON.stringify(latest.document)
|
|
129
|
+
) {
|
|
130
|
+
throw new Error("pi-context-management.json changed while saving; reopen settings and retry");
|
|
131
|
+
}
|
|
132
|
+
await rename(temporaryPath, path);
|
|
133
|
+
} finally {
|
|
134
|
+
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
return { kind: "loaded", path, settings, document };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function createContextManagementSettingsRuntime(
|
|
140
|
+
path = contextManagementSettingsPath(),
|
|
141
|
+
): ContextManagementSettingsRuntime {
|
|
142
|
+
let state: ContextManagementSettingsState = {
|
|
143
|
+
kind: "missing",
|
|
144
|
+
path,
|
|
145
|
+
settings: { ...DEFAULT_CONTEXT_MANAGEMENT_SETTINGS },
|
|
146
|
+
document: {},
|
|
147
|
+
};
|
|
148
|
+
let queue = Promise.resolve();
|
|
149
|
+
const enqueue = <T>(operation: () => Promise<T>): Promise<T> => {
|
|
150
|
+
const result = queue.then(operation, operation);
|
|
151
|
+
queue = result.then(
|
|
152
|
+
() => undefined,
|
|
153
|
+
() => undefined,
|
|
154
|
+
);
|
|
155
|
+
return result;
|
|
156
|
+
};
|
|
157
|
+
return {
|
|
158
|
+
get: () => structuredClone(state),
|
|
159
|
+
reload: (signal) =>
|
|
160
|
+
enqueue(async () => {
|
|
161
|
+
state = await loadContextManagementSettings(path, signal);
|
|
162
|
+
return structuredClone(state);
|
|
163
|
+
}),
|
|
164
|
+
update: (patch, signal) =>
|
|
165
|
+
enqueue(async () => {
|
|
166
|
+
state = await savePatch(path, patch, signal);
|
|
167
|
+
return structuredClone(state);
|
|
168
|
+
}),
|
|
169
|
+
flush: () => queue,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
174
|
+
return error instanceof Error && "code" in error;
|
|
175
|
+
}
|
package/src/terminal.ts
ADDED