@sekobus/tacet 0.0.0-stage → 0.2.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/tacet.ts ADDED
@@ -0,0 +1,681 @@
1
+ // Tacet keeps a long Pi session light without summarizing it.
2
+ //
3
+ // Everything said stays in the model's context, word for word. Old tool output gives way to a
4
+ // short marking, and the model can get any of it back with the `unfold` tool. The session file
5
+ // keeps the originals: the score keeps everything, the part holds only what sounds now.
6
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, statSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { isAbsolute, join, resolve } from "node:path";
9
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext, type SessionEntry, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
10
+ import { SelectList, wrapTextWithAnsi } from "@earendil-works/pi-tui";
11
+ import { Type } from "typebox";
12
+
13
+ /** Candidate selection, independent of the profile. A wrapper extension can pass other values: `tacet(pi, { keep: 40_000 })`. */
14
+ export const defaults = {
15
+ /** Tokens of the latest context that are never folded. Pi's own compaction keeps as many by default. */
16
+ keep: 20_000,
17
+ /** Tools whose results are observations of the world and may be folded; what `unfold` returns is one too.
18
+ * Results of other tools stay. */
19
+ observations: ["read", "bash", "powershell", "grep", "find", "ls", "unfold"],
20
+ /** Files that are read as instructions, not observed. Their content stays. */
21
+ instructions: /(^|[/\\])(SKILL|AGENTS|CLAUDE)\.md$/,
22
+ };
23
+
24
+ const profiles = ["standard", "earlier", "later", "custom"] as const;
25
+ type Profile = typeof profiles[number];
26
+ const timing = { defaultProfile: "standard" as Profile, earlierFactor: 0.5, laterFactor: 2, customPercent: 30 };
27
+ type Language = "ru" | "en";
28
+ type Settings = typeof defaults & typeof timing & { language: Language };
29
+ const translate = (lang: Language) => (ru: string, en: string) => lang === "ru" ? ru : en;
30
+ const isProfile = (p: unknown): p is Profile => profiles.some(name => name === p);
31
+ const isPercent = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 99;
32
+ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
33
+
34
+ /** Validate the whole file before merging anything (especially the instruction guard). */
35
+ function parseSettings(text: string, t: ReturnType<typeof translate>): Partial<Settings> {
36
+ const json = JSON.parse(text);
37
+ if (!record(json)) throw new Error(t("Ожидается объект JSON", "Expected a JSON object"));
38
+ for (const [key, v] of Object.entries(json)) {
39
+ switch (key) {
40
+ case "language": if (v === "ru" || v === "en") continue; break;
41
+ case "defaultProfile": if (isProfile(v)) continue; break;
42
+ case "earlierFactor": if (typeof v === "number" && v > 0 && v < 1) continue; break;
43
+ case "laterFactor": if (typeof v === "number" && Number.isFinite(v) && v > 1) continue; break;
44
+ case "customPercent": if (isPercent(v)) continue; break;
45
+ case "keep": if (typeof v === "number" && Number.isInteger(v) && v >= 0) continue; break;
46
+ case "observations": if (Array.isArray(v) && v.every(n => typeof n === "string" && n.trim())) continue; break;
47
+ case "instructions":
48
+ if (record(v) && Object.keys(v).every(k => k === "source" || k === "flags") && typeof v.source === "string" &&
49
+ (v.flags === undefined || (typeof v.flags === "string" && !/[gy]/.test(v.flags)))) {
50
+ json[key] = new RegExp(v.source, v.flags as string | undefined);
51
+ continue;
52
+ }
53
+ break;
54
+ default: throw new Error(`${t("Неизвестная настройка", "Unknown setting")}: ${key}`);
55
+ }
56
+ throw new Error(`${t("Неверное значение", "Invalid value")}: ${key}`);
57
+ }
58
+ return json;
59
+ }
60
+
61
+ function configuration(options: Partial<typeof defaults>) {
62
+ const locale = [process.env.LC_ALL, process.env.LC_MESSAGES, process.env.LANG].find(v => v?.trim());
63
+ const language: Language = /^ru(?:$|[-_.@])/i.test(locale?.trim() ?? "") ? "ru" : "en";
64
+ const t = translate(language); // A rejected file cannot choose the language of its warning.
65
+ const path = join(getAgentDir(), "tacet.json");
66
+ let file: Partial<Settings> = {}, problem: string | undefined;
67
+ try {
68
+ if (lstatSync(path, { throwIfNoEntry: false })) {
69
+ if (!statSync(path).isFile()) throw new Error(t("Ожидается обычный файл", "Expected a regular file"));
70
+ file = parseSettings(readFileSync(path, "utf8"), t);
71
+ }
72
+ } catch (error) {
73
+ problem = `${path}: ${(error as Error).message}. ${t("Исправьте файл и вызовите", "Fix the file and run")} /reload.`;
74
+ }
75
+ const values = { ...defaults, ...timing, language, ...file };
76
+ const sources = Object.fromEntries(Object.keys(values).map(k => [k, Object.hasOwn(file, k) ? "file" : "built-in"]));
77
+ if (!file.language) sources.language = "environment";
78
+ for (const key of ["keep", "instructions", "observations"] as const) {
79
+ if (options[key] === undefined) continue;
80
+ Object.assign(values, { [key]: options[key] });
81
+ sources[key] = "wrapper";
82
+ }
83
+ return { path, values, sources, problem };
84
+ }
85
+
86
+ type ProjectList = { root: string; paths: Set<string> };
87
+ const listLimit = 64 * 1024;
88
+
89
+ /** Read one bounded snapshot. Don't follow a link or block on a FIFO swapped in after lstat. */
90
+ function projectSnapshot(ctx: ExtensionContext, t: ReturnType<typeof translate>): { list?: ProjectList; problem?: string } {
91
+ let root: string;
92
+ try {
93
+ if (ctx.isProjectTrusted?.() !== true || typeof ctx.cwd !== "string" || !isAbsolute(ctx.cwd)) return {};
94
+ root = ctx.cwd;
95
+ } catch { return {}; } // no trustworthy project context
96
+ const file = join(root, ".tacetprotect");
97
+ const invalid = (reason: string) => ({ problem: `.tacetprotect: ${reason}. ${t("Исправьте файл и вызовите", "Fix the file and run")} /reload.` });
98
+ const regular = t("нужен обычный файл без симлинка", "expected a regular file, not a symlink");
99
+ const tooLarge = t("больше 64 КиБ", "larger than 64 KiB");
100
+ const unsupportedOpen = () => ({ problem: t(
101
+ ".tacetprotect: нет безопасного открытия файла. Чтобы возобновить свёртки без списка, уберите .tacetprotect и вызовите /reload.",
102
+ ".tacetprotect: safe open unavailable. To resume folding without the list, remove .tacetprotect and run /reload.",
103
+ ) });
104
+ let bytes: Buffer;
105
+ try {
106
+ const stat = lstatSync(file, { throwIfNoEntry: false });
107
+ if (!stat) return {};
108
+ if (!stat.isFile()) return invalid(regular);
109
+ if (stat.size > listLimit) return invalid(tooLarge);
110
+ if (!constants.O_NOFOLLOW || !constants.O_NONBLOCK) return unsupportedOpen();
111
+ let fd: number;
112
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
113
+ catch (error) {
114
+ const code = (error as NodeJS.ErrnoException).code;
115
+ if (code === "EOPNOTSUPP" || code === "ENOTSUP") return unsupportedOpen();
116
+ throw error;
117
+ }
118
+ try {
119
+ if (!fstatSync(fd).isFile()) return invalid(regular);
120
+ bytes = Buffer.alloc(listLimit + 1);
121
+ let size = 0;
122
+ while (size < bytes.length) {
123
+ const n = readSync(fd, bytes, size, bytes.length - size, null);
124
+ if (!n) break;
125
+ size += n;
126
+ }
127
+ if (size > listLimit) return invalid(tooLarge);
128
+ bytes = bytes.subarray(0, size);
129
+ } finally { closeSync(fd); }
130
+ } catch { return invalid(t("не удалось безопасно прочитать файл", "could not safely read the file")); }
131
+
132
+ let text: string;
133
+ try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
134
+ catch { return invalid(t("ожидается текст UTF-8", "expected UTF-8 text")); }
135
+ const paths = new Set<string>();
136
+ for (const [i, line] of text.split("\n").entries()) {
137
+ const path = line.trim();
138
+ if (!path || path.startsWith("#")) continue;
139
+ if (path.startsWith("~/") || path.endsWith("/") || /^[A-Za-z]:\//.test(path) || isAbsolute(path) ||
140
+ /[\\\0\r]/.test(path) || path.split("/").includes(".."))
141
+ return invalid(t(`недопустимый путь в строке ${i + 1}`, `invalid path on line ${i + 1}`));
142
+ paths.add(join(root, path));
143
+ }
144
+ return { list: { root, paths } };
145
+ }
146
+
147
+ function projectProtects(list: ProjectList, argument: string) {
148
+ const path = argument.startsWith("@") ? argument.slice(1) : argument;
149
+ const listed = (p: string) => list.paths.has(p.startsWith("~/") ? join(homedir(), p.slice(2)) : resolve(list.root, p));
150
+ if (listed(path)) return true;
151
+ // Pi's built-in read maps these spaces in its argument to ASCII. Keep list entries and the session cwd literal.
152
+ const readPath = path.replace(/[\u00a0\u2000-\u200a\u202f\u205f\u3000]/g, " ");
153
+ return readPath !== path && listed(readPath);
154
+ }
155
+
156
+ const profileEntry = "tacet-profile";
157
+ function branchProfile(branch: readonly SessionEntry[]): { profile: Profile; customPercent?: number } | undefined {
158
+ for (let i = branch.length - 1; i >= 0; i--) {
159
+ const e = branch[i];
160
+ if (e.type !== "custom" || e.customType !== profileEntry || !record(e.data)) continue;
161
+ const { profile, customPercent } = e.data;
162
+ if (Object.hasOwn(e.data, "customPercent")) {
163
+ if (profile === "custom" && isPercent(customPercent)) return { profile, customPercent };
164
+ continue; // malformed choice: ignore the whole record
165
+ }
166
+ if (profile === "default") return undefined;
167
+ if (isProfile(profile)) return { profile }; // old records still take their percent from settings
168
+ }
169
+ }
170
+
171
+ const foldingEntry = "tacet-folding";
172
+ function foldingEnabled(branch: readonly any[]): boolean {
173
+ const entry = branch.findLast(e => e.type === "custom" && e.customType === foldingEntry && typeof e.data?.enabled === "boolean");
174
+ return entry?.data.enabled ?? true;
175
+ }
176
+
177
+ /** A fold costs once and saves on every request after it: the provider reads anew what the fold leaves, and every
178
+ * later request is smaller by what it removed. A fold is due when it pays back within this many requests. */
179
+ const PAYBACK_REQUESTS = 10;
180
+ /** The least a fold may remove, as a share of what it leaves, however weak the cache discount the model declares.
181
+ * It guards against a price list that does not know the model caches. */
182
+ const MIN_RATIO = 1 / 4;
183
+
184
+ /**
185
+ * How much a fold must remove, as a share of what it leaves, to pay back within PAYBACK_REQUESTS. With c the price
186
+ * of a cached input token against an uncached one, that is (1 − c) / (N · c), kept between MIN_RATIO and 1.
187
+ * Only declared prices count, and a zero price is an undeclared one. A model without prices gets 1.
188
+ */
189
+ export function foldRatio(model: any): number {
190
+ const { input = 0, cacheRead = 0, cacheWrite = 0 } = model?.cost ?? {};
191
+ const uncached = cacheWrite > 0 ? cacheWrite : input;
192
+ if (!(uncached > 0)) return 1;
193
+ const c = cacheRead > 0 ? cacheRead / uncached : 1; // no price for cached tokens: no cache
194
+ return Math.min(1, Math.max(MIN_RATIO, (1 - c) / (PAYBACK_REQUESTS * c)));
195
+ }
196
+
197
+ const textOf = (content: any): string =>
198
+ typeof content === "string" ? content : (content ?? []).map((part: any) => part.text ?? "").join("");
199
+
200
+ function onlyText(content: any): boolean {
201
+ return typeof content === "string" || (Array.isArray(content) &&
202
+ content.every(part => part?.type === "text" && typeof part.text === "string"));
203
+ }
204
+
205
+ // Pi projects both ! and !! commands, but omits !! when converting to model messages.
206
+ function shellChars(message: any): number {
207
+ return message.excludeFromContext === true ? 0 : (message.command?.length ?? 0) + (message.output?.length ?? 0);
208
+ }
209
+
210
+ /** Rough tokens a message adds to the context: a quarter of the characters of its text, thinking and tool-call arguments.
211
+ * Thinking counts because providers send it back to the model, and Pi counts it too. */
212
+ export function sizeOf(message: any): number {
213
+ if (message.role === "bashExecution") return Math.ceil(shellChars(message) / 4);
214
+ let chars = message.summary?.length ?? 0; // compaction and branch summaries
215
+ if (typeof message.content === "string") chars += message.content.length;
216
+ else for (const part of message.content ?? [])
217
+ chars += part.text?.length ?? part.thinking?.length ?? (part.arguments ? JSON.stringify(part.arguments).length : 0);
218
+ return Math.ceil(chars / 4);
219
+ }
220
+
221
+ /** What the model sees in place of a folded result. The tool call right before it already says what was run. */
222
+ function marking(entry: any): string {
223
+ const text = textOf(entry.message.content);
224
+ const name = entry.message.toolName;
225
+ const ending = name === "bash" || name === "powershell" ? `\n…\n${text.trimEnd().split("\n").slice(-3).join("\n").slice(-300)}` : "";
226
+ return `[tacet: ${text.length} chars folded; unfold("${entry.id}") returns them]${ending}`;
227
+ }
228
+
229
+ const isMarking = (edit: any): boolean => textOf(edit?.replacement?.content).startsWith("[tacet: ");
230
+
231
+ /**
232
+ * What `unfold` returns with `match`: the lines of a folded output that contain any of the texts separated by `|`,
233
+ * ignoring case, numbered as `grep -n -C 2` numbers them, with two lines around each. Plain text, not a regular
234
+ * expression: a pattern the model writes could hang Pi, a plain text cannot. Undefined when there is nothing to look for.
235
+ */
236
+ function linesMatching(text: string, match: string): string | undefined {
237
+ const texts = match.toLowerCase().split("|").filter((t) => t !== "");
238
+ if (texts.length === 0) return undefined;
239
+ const lines = text.split(/\r?\n/);
240
+ if (text.endsWith("\n")) lines.pop();
241
+ const hits = new Set(lines.flatMap((line, i) => (texts.some((t) => line.toLowerCase().includes(t)) ? [i] : [])));
242
+ if (hits.size === 0)
243
+ return `No line of the folded output (${lines.length} lines) contains "${match}". ` +
244
+ "match is plain text, not a regular expression, and ignores case; separate alternatives with |. " +
245
+ "Without match, unfold returns the whole output.";
246
+ const shown = lines.map(() => false);
247
+ for (const hit of hits) for (let i = Math.max(0, hit - 2); i <= Math.min(lines.length - 1, hit + 2); i++) shown[i] = true;
248
+ const answer = [`${hits.size} of ${lines.length} lines of the folded output contain "${match}", each shown with two lines around it. ` +
249
+ "The numbers count lines of the folded output, not lines of any file as it is now."];
250
+ lines.forEach((line, i) => {
251
+ if (!shown[i]) return;
252
+ if (i > 0 && !shown[i - 1] && answer.length > 1) answer.push("--");
253
+ answer.push(`${i + 1}${hits.has(i) ? ":" : "-"}${line}`);
254
+ });
255
+ return answer.join("\n");
256
+ }
257
+
258
+ function isInstructionPath(pattern: RegExp, path: string): boolean {
259
+ // A wrapper may pass g or y: match from zero for each path without moving its lastIndex.
260
+ const re = pattern.global || pattern.sticky ? new RegExp(pattern) : pattern;
261
+ // Preserve raw-path matches; Pi also resolves a path with one leading @ removed.
262
+ return re.test(path) || (path.startsWith("@") && re.test(path.slice(1)));
263
+ }
264
+
265
+ // IDs belong to a single assistant's group of calls. A duplicate cannot identify a path.
266
+ function callsById(content?: unknown) {
267
+ const calls = new Map<string, { name: string; path?: string } | undefined>();
268
+ if (Array.isArray(content)) for (const part of content) {
269
+ if (part?.type !== "toolCall" || typeof part.id !== "string" || !part.id) continue;
270
+ const path = part.arguments?.path;
271
+ calls.set(part.id, calls.has(part.id) ? undefined : { name: part.name, path: typeof path === "string" ? path : undefined });
272
+ }
273
+ return calls;
274
+ }
275
+
276
+ /**
277
+ * The context edits that would fold every answered observation older than the latest `keep` tokens,
278
+ * with the tokens they save and the tokens they leave.
279
+ *
280
+ * `projected` is Pi's session projection: what the model sees, entry by entry.
281
+ * `answeredBy` is the assistant message that ended the turn; results after it are still unanswered.
282
+ * `edited` holds the ids of entries that already carry a context edit.
283
+ */
284
+ export function foldable(projected: any[], answeredBy: string, edited: Set<string>, policy = defaults, project?: ProjectList) {
285
+ const sizes = projected.map((p) => p.messages.reduce((sum: number, message: any) => sum + sizeOf(message), 0));
286
+
287
+ let end = projected.length; // fold only what lies before `end`:
288
+ for (let recent = 0; end > 0 && recent < policy.keep; ) recent += sizes[--end]; // not the latest `keep` tokens,
289
+ end = Math.min(end, projected.findIndex((p) => p.sourceEntry.id === answeredBy)); // not results still unanswered
290
+
291
+ const edits = [];
292
+ let saved = 0;
293
+ let raw = callsById(), visible = raw;
294
+ for (let i = 0; i < end; i++) {
295
+ const { sourceEntry: entry, messages } = projected[i];
296
+ const message = entry.message;
297
+ if (message?.role === "assistant") {
298
+ raw = callsById(message.content);
299
+ const shown = messages.length === 1 && messages[0].role === "assistant" ? messages[0].content : undefined;
300
+ visible = shown === message.content ? raw : callsById(shown);
301
+ continue;
302
+ }
303
+ if (message?.role !== "toolResult") {
304
+ // Metadata alone doesn't separate parallel replies; another message ends the group.
305
+ if (message || messages.length) { raw.clear(); visible.clear(); }
306
+ continue;
307
+ }
308
+ const id = message.toolCallId, original = raw.get(id), call = visible.get(id);
309
+ raw.delete(id); visible.delete(id); // consume even a result already edited or too small to fold
310
+ if (edited.has(entry.id)) continue;
311
+ if (!policy.observations.includes(message.toolName) || !onlyText(message.content)) continue;
312
+ if (message.toolName === "read") {
313
+ if (original?.name !== "read" || call?.name !== "read" || !call.path || call.path !== original.path) continue;
314
+ if (project && projectProtects(project, call.path)) continue;
315
+ }
316
+ if (isInstructionPath(policy.instructions, call?.path ?? "")) continue;
317
+ const content = marking(entry);
318
+ const gain = sizes[i] - Math.ceil(content.length / 4);
319
+ if (gain <= 0) continue;
320
+ edits.push({ type: "context_edit" as const, targetId: entry.id, replacement: { content } });
321
+ saved += gain;
322
+ }
323
+ return { edits, saved, left: sizes.reduce((a, b) => a + b, 0) - saved };
324
+ }
325
+
326
+ function threshold(profile: Profile, settings: Settings, model: any, customPercent: number) {
327
+ if (profile === "custom") return {
328
+ percent: customPercent, source: "manual",
329
+ margin: (saved: number, left: number) => 100 * saved - customPercent * (saved + left),
330
+ };
331
+ const factor = profile === "earlier" ? settings.earlierFactor : profile === "later" ? settings.laterFactor : 1;
332
+ const k = foldRatio(model) * factor;
333
+ return {
334
+ percent: (k / (1 + k)) * 100, source: model?.cost?.input > 0 || model?.cost?.cacheWrite > 0 ? "prices" : "unpriced",
335
+ margin: (saved: number, left: number) => saved - k * left,
336
+ };
337
+ }
338
+
339
+ /** Count replacements still visible now, not historical edits or quotes of their text. */
340
+ function markingBalance(projected: any[], branch: readonly SessionEntry[], window?: number) {
341
+ const edited = new Set<string>();
342
+ for (const e of branch) if (e.type === "context_edit") edited.add(e.targetId);
343
+ let originals = 0, markings = 0;
344
+ for (const { sourceEntry, messages } of projected) {
345
+ if (!edited.delete(sourceEntry.id)) continue;
346
+ const [m] = messages;
347
+ if (m?.role !== "toolResult" || m.content.length !== 1 || m.content[0].type !== "text") continue;
348
+ const text = m.content[0].text;
349
+ // Compare with the original, not just a marking-like prefix.
350
+ if (!text.startsWith("[tacet: ")) continue;
351
+ const exact = marking(sourceEntry);
352
+ // Old PowerShell markings stopped at the header, with no tail.
353
+ if (text !== exact && !(m.toolName === "powershell" && text === exact.split("\n", 1)[0])) continue;
354
+ const original = sizeOf(sourceEntry.message), visible = sizeOf(m);
355
+ if (original <= visible) continue; // Tacet never folds a result without a gain.
356
+ originals += original;
357
+ markings += visible;
358
+ }
359
+ const gain = originals - markings;
360
+ const points = window != null && Number.isFinite(window) && window > 0 ? 100 * gain / window : undefined;
361
+ return { originals, markings, gain, points };
362
+ }
363
+
364
+ /** Only for the human report: group the same characters counted by sizeOf (rounding per group). */
365
+ function composition(projected: any[], observations: string[]) {
366
+ const chars = { messages: 0, thinking: 0, arguments: 0, observations: 0, other: 0 };
367
+ for (const p of projected) for (const m of p.messages) {
368
+ if (m.role === "bashExecution") { chars.messages += shellChars(m); continue; }
369
+ const group = m.role !== "toolResult" ? "messages" : observations.includes(m.toolName) ? "observations" : "other";
370
+ chars[group] += m.summary?.length ?? 0;
371
+ if (typeof m.content === "string") chars[group] += m.content.length;
372
+ else for (const part of m.content ?? []) {
373
+ if (part.text != null) chars[group] += part.text.length;
374
+ else if (part.thinking != null) chars.thinking += part.thinking.length;
375
+ else if (part.arguments) chars.arguments += JSON.stringify(part.arguments).length;
376
+ }
377
+ }
378
+ return Object.entries(chars).map(([k, v]) => [k, Math.ceil(v / 4)] as const);
379
+ }
380
+
381
+ function answerBoundary(projected: any[], event?: TurnEndEvent) {
382
+ const entry = event ? projected.find(p => p.sourceEntry.id === event.messageEntryId)
383
+ : projected.findLast(p => p.messages.some((m: any) => m.role === "assistant"));
384
+ const answer = entry?.messages.findLast((m: any) => m.role === "assistant");
385
+ // Even a completed turn can end at the length limit. Never fall back to an earlier answer.
386
+ return ["stop", "toolUse"].includes(answer?.stopReason) ? entry.sourceEntry.id : undefined;
387
+ }
388
+
389
+ const syntax = "/tacet standard|earlier|later|custom [1–99]|default|off|on";
390
+ // Small read-only screens share Pi's selection and keybindings; details use the same
391
+ // wrapped text outside TUI, but page through it in a bounded viewport here.
392
+ async function screen(ctx: ExtensionContext, title: string, body: string, choices: string[], t: ReturnType<typeof translate>) {
393
+ return ctx.ui.custom<string | undefined>((tui, theme, kb, done) => {
394
+ const list = new SelectList(choices.map(label => ({ label, value: label })), choices.length, {
395
+ selectedPrefix: s => theme.fg("accent", s), selectedText: s => theme.fg("accent", s),
396
+ description: s => theme.fg("muted", s), scrollInfo: s => theme.fg("dim", s), noMatch: s => s,
397
+ });
398
+ list.onSelect = item => done(item.value);
399
+ list.onCancel = () => done(undefined);
400
+ // One active shortcut per action keeps the legend short. Omit unbound actions.
401
+ const key = (action: "up" | "down" | "confirm" | "cancel") => {
402
+ const first = kb.getKeys(`tui.select.${action}`)[0];
403
+ if (!first) return "";
404
+ const names: Record<string, string> = { up: "↑", down: "↓", enter: "Enter", escape: "Esc" };
405
+ return names[first] ?? first.toUpperCase();
406
+ };
407
+ const details = choices.length === 1;
408
+ const nav = [key("up"), key("down")].filter(Boolean).join("/");
409
+ const confirm = key("confirm"), cancel = key("cancel");
410
+ const actions = details
411
+ ? [[nav, t("прокрутка", "scroll")], [[confirm, cancel].filter(Boolean).join("/"), t("назад", "back")]]
412
+ : [[nav, t("выбор", "move")], [confirm, t("выбрать", "select")], [cancel, t("назад", "back")]];
413
+ const hint = actions.filter(([keys]) => keys).map(pair => pair.join(" ")).join(" · ");
414
+ let offset = 0, last = 0;
415
+ return {
416
+ invalidate: () => list.invalidate(),
417
+ render(width) {
418
+ const lines = body ? wrapTextWithAnsi(body, width) : [];
419
+ const hints = hint ? wrapTextWithAnsi(hint, width).map(line => theme.fg("dim", line)) : [];
420
+ const heading = wrapTextWithAnsi(title, width).map(line => theme.bold(line));
421
+ const height = Math.max(2, Math.min(10, tui.terminal.rows - choices.length - hints.length - 8 - (heading.length - 1)));
422
+ last = Math.max(0, lines.length - height);
423
+ offset = Math.min(offset, last);
424
+ return [...heading, ...lines.slice(offset, offset + height), "", ...list.render(width), ...hints];
425
+ },
426
+ handleInput(data) {
427
+ if (choices.length === 1 && last && kb.matches(data, "tui.select.down")) offset = Math.min(last, offset + 1);
428
+ else if (choices.length === 1 && last && kb.matches(data, "tui.select.up")) offset = Math.max(0, offset - 1);
429
+ else list.handleInput(data);
430
+ tui.requestRender();
431
+ },
432
+ };
433
+ });
434
+ }
435
+ function tell(ctx: ExtensionContext, text: string, level: "info" | "warning" = "info") {
436
+ if (ctx.mode === "print" || ctx.mode === "json") process.stderr.write(`tacet: ${text}\n`);
437
+ else ctx.ui.notify(text, level);
438
+ }
439
+
440
+ export default function tacet(pi: ExtensionAPI, options: Partial<typeof defaults> = {}) {
441
+ const config = configuration(options);
442
+ const policy = config.values;
443
+ const t = translate(policy.language);
444
+ const labels: Record<string, string> = {
445
+ standard: t("Стандартный профиль", "Standard profile"), earlier: t("Раньше", "Earlier"), later: t("Позже", "Later"),
446
+ custom: t("Свой порог", "Custom threshold"), default: t("Использовать профиль из настроек", "Use settings profile"),
447
+ branch: t("ветка", "branch"), file: t("файл", "file"), "built-in": t("встроено", "built-in"),
448
+ wrapper: t("обёртка", "wrapper"), environment: t("окружение", "environment"),
449
+ manual: t("ручной порог", "manual"), prices: t("цены модели", "model prices"), unpriced: t("без цен", "no prices"),
450
+ messages: t("сообщения", "messages"), thinking: t("рассуждения", "thinking"), arguments: t("аргументы", "arguments"),
451
+ observations: t("наблюдения", "observations"), other: t("прочие результаты", "other results"),
452
+ };
453
+ const noData = t("нет данных", "unknown");
454
+ const fmt = new Intl.NumberFormat(policy.language, { maximumFractionDigits: 2, useGrouping: false });
455
+ const num = (v?: number | null) => v == null || !Number.isFinite(v) ? noData : fmt.format(v);
456
+ const pct = (v?: number | null) => v == null || !Number.isFinite(v) ? noData : `${num(v)}%`;
457
+ const paused = t("Новые свёртки на этой ветке выключены. Возобновить: /tacet on.", "New folds are paused on this branch. Resume: /tacet on.");
458
+ let warned = false;
459
+ let project: ReturnType<typeof projectSnapshot> = {};
460
+
461
+ // setStatus stores a string. Pi has no theme-change event: recheck only the colour
462
+ // of a visible TUI counter, without rescanning history or repainting if unchanged.
463
+ let statusTimer: ReturnType<typeof setInterval> | undefined;
464
+ function stopStatusTimer() {
465
+ clearInterval(statusTimer);
466
+ statusTimer = undefined;
467
+ }
468
+ pi.on("session_shutdown", stopStatusTimer);
469
+ const showStatus = (ctx: ExtensionContext, adding = 0) => {
470
+ stopStatusTimer();
471
+ if (!ctx.hasUI) return;
472
+ const folded = ctx.sessionManager.getBranch().filter(isMarking).length + adding;
473
+ const text = `tacet: ${t(`свёрнуто ${num(folded)}`, `${num(folded)} folded`)}`;
474
+ const ui = ctx.ui;
475
+ if (!folded || ctx.mode !== "tui") { ui.setStatus("tacet", folded ? text : undefined); return; }
476
+ let painted = ui.theme.fg("dim", text);
477
+ ui.setStatus("tacet", painted);
478
+ statusTimer = setInterval(() => {
479
+ const next = ui.theme.fg("dim", text);
480
+ if (next === painted) return;
481
+ painted = next;
482
+ ui.setStatus("tacet", next);
483
+ }, 500);
484
+ statusTimer.unref();
485
+ };
486
+ pi.on("session_start", (_event, ctx) => {
487
+ project = projectSnapshot(ctx, t);
488
+ showStatus(ctx);
489
+ if (ctx.hasUI && config.problem && !warned) {
490
+ warned = true;
491
+ ctx.ui.notify(`tacet: ${t("Свёртки на паузе.", "Folding paused.")} ${config.problem}`, "warning");
492
+ }
493
+ });
494
+ pi.on("session_tree", (_event, ctx) => showStatus(ctx)); // another branch has other folds
495
+
496
+ function decide(ctx: ExtensionContext, branch: readonly SessionEntry[], event?: TurnEndEvent) {
497
+ const choice = branchProfile(branch), profile = choice?.profile ?? policy.defaultProfile;
498
+ const limit = threshold(profile, policy, ctx.model, choice?.customPercent ?? policy.customPercent);
499
+ const keep = Math.min(policy.keep, (ctx.model?.contextWindow || Infinity) / 8);
500
+ let unfold: boolean | undefined;
501
+ try { unfold = pi.getActiveTools().includes("unfold"); } catch { /* fail open */ }
502
+ // A disabled tool needs no scan at turn end. A human may still ask about the current projection.
503
+ const projected = event && !unfold ? [] : event?.context?.contextEntries ?? ctx.sessionManager.buildSessionProjection().entries;
504
+ const boundary = answerBoundary(projected, event);
505
+ const edited = new Set([...branch, ...(event?.entries ?? [])].flatMap(e => e.type === "context_edit" ? [e.targetId] : []));
506
+ let batch: ReturnType<typeof foldable> | undefined;
507
+ if (!config.problem && !project.problem && (unfold || !event) && boundary)
508
+ batch = foldable(projected, boundary, edited, { ...policy, keep }, project.list);
509
+ // The sign explains the same comparison that gates a fold. Percentages are display only.
510
+ const margin = batch?.edits.length ? limit.margin(batch.saved, batch.left) : undefined;
511
+ const due = margin !== undefined && margin >= 0 && unfold === true;
512
+ return { profile, pinnedPercent: choice?.customPercent, source: choice ? "branch" : config.sources.defaultProfile, limit, keep, unfold, projected, batch, margin, due };
513
+ }
514
+
515
+ pi.on("turn_end", (event, ctx) => {
516
+ if (event.outcome !== "completed" || config.problem || project.problem) return;
517
+ const branch = ctx.sessionManager.getBranch();
518
+ if (!foldingEnabled(branch)) return; // no candidate scan and no change to earlier proposals
519
+ const d = decide(ctx, branch, event);
520
+ if (!d.due || !d.batch) return;
521
+ showStatus(ctx, d.batch.edits.length);
522
+ return { entries: [...event.entries, ...d.batch.edits] };
523
+ });
524
+
525
+ function summary(ctx: ExtensionContext) {
526
+ const branch = ctx.sessionManager.getBranch();
527
+ const enabled = foldingEnabled(branch);
528
+ const { profile, pinnedPercent, source, limit, keep, unfold, projected, batch, margin, due } = decide(ctx, branch);
529
+ const access = unfold === undefined ? noData : unfold ? t("доступен", "available") : t("недоступен", "unavailable");
530
+ const usage = ctx.getContextUsage();
531
+ const window = usage?.contextWindow ?? ctx.model?.contextWindow;
532
+ const share = batch && batch.saved + batch.left > 0 ? 100 * batch.saved / (batch.saved + batch.left) : undefined;
533
+ const balance = markingBalance(projected, branch, window);
534
+ const growth = t(`ещё ≈${num(balance.gain)} токенов`, `≈${num(balance.gain)} more tokens`);
535
+ const zero = t("Видимых пометок нет; прибавка — 0.", "No visible markings; increase: 0.");
536
+ const points = balance.points == null ? "" : ` (≈${num(balance.points)} ${t("п. п. окна", "window pp")})`;
537
+ const state = enabled ? t("Автоматика включена", "Automatic folding on") : t("Автоматика выключена", "Automatic folding off");
538
+ const blockers = [
539
+ !enabled && paused,
540
+ config.problem && t("Свёртки на паузе: ошибка tacet.json.", "Folding paused: invalid tacet.json."),
541
+ project.problem && `${t("Свёртки на паузе.", "Folding paused.")} ${project.problem}`,
542
+ !unfold && `${t("Нет доступа к unfold", "Cannot use unfold")} (${access}).`,
543
+ ].filter(Boolean);
544
+ const target = pct(limit.percent);
545
+ const indistinguishable = margin !== undefined && margin !== 0 && pct(share) === target;
546
+ const relative = margin !== undefined && margin < 0
547
+ ? t(`чуть ниже порога ${target}`, `just below the ${target} threshold`)
548
+ : t(`чуть выше порога ${target}`, `just above the ${target} threshold`);
549
+ const comparison = indistinguishable ? `${relative}.` : t(`можно убрать ${pct(share)}, требуется ${target}.`, `can remove ${pct(share)}, need ${target}.`);
550
+ const reason = blockers.length ? blockers.join("\n") : !batch ? t("Нет надёжной границы ответа.", "No reliable answer boundary.")
551
+ : !batch.edits.length ? t("Нет кандидатов для свёртки.", "No candidates to fold.")
552
+ : `${due ? t("Порог достигнут — была бы свёртка", "Would fold") : t("Выигрыш ниже порога — свёртки не было бы", "Would not fold")}: ${comparison}`;
553
+ const profileName = profile === "custom" ? `${labels.custom} · ${target}` : labels[profile];
554
+ const percentSource = pinnedPercent === undefined ? config.sources.customPercent : "branch";
555
+ const brief = [`${state} · ${profileName}`, reason, balance.markings ? `${t("Если развернуть пометки", "Restoring visible markings")}: ${growth}.` : zero].join("\n");
556
+ const compositionText = composition(projected, policy.observations).map(([k,v]) => `${labels[k]}: ${num(v)}`).join(", ");
557
+ const details = [
558
+ `${t("Профиль", "Profile")}: ${labels[profile]} (${labels[source]}) · ${state}`,
559
+ profile === "custom" ? `${t("Свой порог", "Custom threshold")}: ${target} (${labels[percentSource]})` : undefined,
560
+ `unfold: ${access} · ${t("пометок на ветке", "branch markings")}: ${num(branch.filter(isMarking).length)}`,
561
+ `Pi: ${ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : noData}; ${t("окно", "window")}: ${num(window)}; ${t("использование", "usage")}: ${num(usage?.tokens)} (${pct(usage?.percent)})`,
562
+ balance.markings ? `${t("Разворот видимых пометок", "Expanding visible markings")}: ${growth}${points}; ${t("пометки", "markings")} ≈${num(balance.markings)}, ${t("оригиналы", "originals")} ≈${num(balance.originals)}.` : zero,
563
+ "", t("Следующая свёртка (при включённой автоматике)", "Next fold (with automatic folding on)"),
564
+ `${t("кандидатов", "candidates")}: ${num(batch?.edits.length)}; ${t("убрать S", "remove S")}: ${num(batch?.saved)}; ${t("останется L", "leave L")}: ${num(batch?.left)}`,
565
+ `${t("Доля", "Share")}: ${indistinguishable ? relative : pct(share)}; ${t("порог", "threshold")}: ${pct(limit.percent)} (${labels[limit.source]}); ${t("хвост", "tail")}: ${num(policy.keep)} → ${num(keep)}`,
566
+ `${t("Состав", "Composition")} ≈ ${t("токены", "tokens")}: ${projected.some(p => p.messages.length) ? compositionText : noData}`,
567
+ "", t("Настройки", "Settings"),
568
+ ...Object.entries(policy).map(([k,v]) => `${k}=${typeof v === "number" ? v.toLocaleString(policy.language, { useGrouping: false, maximumSignificantDigits: 21 }) : String(v)} (${labels[config.sources[k]]})`),
569
+ `${config.path} · ${t("изменения", "apply changes")}: /reload`, config.problem, project.problem, syntax,
570
+ ].filter(line => line !== undefined).join("\n");
571
+ return { brief, details, enabled, pinnedPercent, current: source === "branch" ? profile : "default" };
572
+ }
573
+
574
+ async function chooseProfile(ctx: ExtensionContext, current: string, pinnedPercent?: number) {
575
+ const names = ["standard", "earlier", "later", "pin", "custom", "default"] as const;
576
+ const active = pinnedPercent === undefined ? current : "pin";
577
+ const items = names.map(p => {
578
+ const mark = p === active ? "✓ " : "";
579
+ if (p === "pin") return `${mark}${labels.custom}…${pinnedPercent === undefined ? "" : ` ${pct(pinnedPercent)}`}`;
580
+ const label = p === "custom" ? t("Свой порог из настроек", "Custom threshold from settings") : labels[p];
581
+ return `${mark}${label} (${p})`;
582
+ });
583
+ const selected = await screen(ctx, t("Сменить профиль…", "Change profile…"), "", [t("Назад", "Back"), ...items], t);
584
+ if (!selected || !items.includes(selected)) return ""; // back to the main screen
585
+ const name = names[items.indexOf(selected)];
586
+ if (name !== "pin") return name;
587
+ const now = pinnedPercent ?? policy.customPercent;
588
+ const prompt = t(`Какую долю контекста освободить? 1–99%, сейчас ${pct(now)}`, `What share of context should a fold free? 1–99%, currently ${pct(now)}`);
589
+ const input = (await ctx.ui.input(prompt, String(now)))?.trim();
590
+ return input ? `custom ${input}` : undefined; // cancel without issuing even a bare custom
591
+ }
592
+
593
+ pi.registerCommand("tacet", {
594
+ description: t("Прогноз, профиль и пауза свёртки на ветке", "Folding forecast, profile and pause on this branch"),
595
+ handler: async (args, ctx) => {
596
+ let name = args.trim();
597
+ if (!name) {
598
+ const { brief, details, enabled, pinnedPercent, current } = summary(ctx);
599
+ if (ctx.mode !== "tui") { tell(ctx, `${brief}\n\n${details}`); return; }
600
+ const done = t("Готово", "Done"), back = t("Назад", "Back");
601
+ const change = t("Сменить профиль…", "Change profile…"), more = t("Подробнее…", "Details…");
602
+ const action = enabled ? t("Приостановить свёртку", "Pause folding") : t("Возобновить свёртку", "Resume folding");
603
+ while (!name) {
604
+ const pick = await screen(ctx, "Tacet", brief, [done, change, action, more], t);
605
+ if (!pick || pick === done) return;
606
+ if (pick === action) name = enabled ? "off" : "on";
607
+ if (pick === more) await screen(ctx, more, details, [back], t);
608
+ if (pick === change) {
609
+ const selected = await chooseProfile(ctx, current, pinnedPercent);
610
+ if (selected === undefined) return;
611
+ name = selected;
612
+ }
613
+ }
614
+ }
615
+ const problem = config.problem ?? project.problem;
616
+ const pause = problem ? ` ${t("Свёртки на паузе.", "Folding paused.")} ${problem}` : "";
617
+ const failed = `${t("Не удалось записать выбор на ветке.", "Could not record the branch choice.")} ${syntax}.${pause}`;
618
+ if (name === "off" || name === "on") {
619
+ const enable = name === "on";
620
+ const changed = enable !== foldingEnabled(ctx.sessionManager.getBranch());
621
+ if (changed) {
622
+ try { pi.appendEntry(foldingEntry, { enabled: enable }); }
623
+ catch { tell(ctx, failed, "warning"); return; }
624
+ }
625
+ const message = enable ? (changed ? t("Ручная пауза снята.", "Manual pause lifted.") : t("Ручной паузы нет.", "Not manually paused.")) : paused;
626
+ tell(ctx, `${changed ? "" : t("Без изменений. ", "No change. ")}${message}${pause}`);
627
+ return;
628
+ }
629
+ let pinnedPercent: number | undefined;
630
+ if (/^custom\s/.test(name)) {
631
+ const value = name.slice("custom".length).trim();
632
+ if (!/^[1-9][0-9]?$/.test(value)) {
633
+ tell(ctx, `${t("Введите целое число от 1 до 99 без знака, ведущего нуля и %.", "Enter a whole number from 1 to 99 without a sign, leading zero or %.")} /tacet custom N.${pause}`, "warning");
634
+ return;
635
+ }
636
+ name = "custom";
637
+ pinnedPercent = Number(value);
638
+ }
639
+ if (!isProfile(name) && name !== "default") {
640
+ tell(ctx, `${t("Неизвестный аргумент.", "Unknown argument.")} ${syntax}.${pause}`, "warning");
641
+ return;
642
+ }
643
+ const effective = name === "default" ? policy.defaultProfile : name;
644
+ const value = labels[effective] + (effective === "custom" ? ` · ${pct(pinnedPercent ?? policy.customPercent)}` : "");
645
+ if (pinnedPercent !== undefined && branchProfile(ctx.sessionManager.getBranch())?.customPercent === pinnedPercent) {
646
+ tell(ctx, `${t("Без изменений", "No change")}: ${value}.${pause}`);
647
+ return;
648
+ }
649
+ try { pi.appendEntry(profileEntry, pinnedPercent === undefined ? { profile: name } : { profile: name, customPercent: pinnedPercent }); }
650
+ catch { tell(ctx, failed, "warning"); return; }
651
+ const hint = ctx.mode === "print" || ctx.mode === "json" ? t(" Для продолжения: --session с уже сохранённой сессией; постоянное умолчание: tacet.json.", " To continue, use --session with a saved session; set the permanent default in tacet.json.") : "";
652
+ tell(ctx, `${t("Выбрано на ветке", "Branch choice")}: ${name === "default" ? `${labels.default} → ` : ""}${value}.${hint}${pause}`);
653
+ },
654
+ });
655
+
656
+ pi.registerTool({
657
+ name: "unfold",
658
+ label: "Unfold",
659
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
660
+ description:
661
+ "Old tool results are folded into [tacet: ...] markings to keep the context small. " +
662
+ "unfold returns the original output of one of them, by the id in its marking. " +
663
+ "With match, it returns only the lines that contain the given text, numbered, with two lines around each; " +
664
+ "match is plain text, not a regular expression, and ignores case; separate alternatives with |.",
665
+ parameters: Type.Object({
666
+ id: Type.String({ description: "The id in the marking" }),
667
+ match: Type.Optional(Type.String({ description: "Only the lines that contain this plain text, ignoring case; alternatives separated by |" })),
668
+ }),
669
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
670
+ const branch = ctx.sessionManager.getBranch();
671
+ const lastEdit = branch.findLast((entry: any) => entry.type === "context_edit" && entry.targetId === params.id);
672
+ const original: any = isMarking(lastEdit) && branch.find((entry) => entry.id === params.id);
673
+ if (original?.type !== "message" || original.message?.role !== "toolResult") throw new Error(`Nothing is folded under the id ${params.id}`);
674
+ const text = textOf(original.message.content);
675
+ const answer = params.match ? linesMatching(text, params.match) : undefined;
676
+ // An answer that is not shorter than the original is not worth it: the original comes back instead.
677
+ if (answer !== undefined && answer.length < text.length) return { content: [{ type: "text" as const, text: answer }], details: undefined };
678
+ return { content: structuredClone(original.message.content), details: undefined }; // a copy: the score is never touched
679
+ },
680
+ });
681
+ }