proper-base 0.6.0 → 0.8.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.
@@ -0,0 +1,310 @@
1
+ import {
2
+ type Component,
3
+ sliceByColumn,
4
+ stripTerminalSequences,
5
+ type TUI,
6
+ visibleWidth,
7
+ wrapTextWithAnsi,
8
+ } from "@earendil-works/pi-tui";
9
+
10
+ const INSTALLED = Symbol.for("pi-proper-base.clipboard-selection");
11
+ type Point = {
12
+ row: number;
13
+ col: number;
14
+ scrollView?: Component;
15
+ boundary?: boolean;
16
+ };
17
+ type Bounds = { start: Point; end: Point };
18
+ type Row = {
19
+ source: string;
20
+ offset: number;
21
+ end: number;
22
+ column: number;
23
+ group: object;
24
+ skip: number;
25
+ };
26
+ type Token = { type: string };
27
+ type MarkdownHost = Component & {
28
+ text: string;
29
+ paddingX: number;
30
+ paddingY: number;
31
+ theme: { codeBlockIndent?: string };
32
+ cachedLines?: string[];
33
+ renderToken(token: Token, width: number, ...rest: unknown[]): string[];
34
+ };
35
+ type Layout = {
36
+ children: Layout[];
37
+ scrollView?: Component;
38
+ scrollContentLines?: readonly string[];
39
+ rect: { width: number };
40
+ };
41
+ type Host = TUI & {
42
+ currentLayout?: { root?: Layout };
43
+ getActiveSelectionText?(): string | undefined;
44
+ getSelectionBounds?(): Bounds | undefined;
45
+ getSelectionColumns?(
46
+ line: string,
47
+ row: number,
48
+ bounds: Bounds,
49
+ ): { start: number; end: number };
50
+ [INSTALLED]?: () => void;
51
+ };
52
+
53
+ function plain(line: string): string {
54
+ return stripTerminalSequences(line).trimEnd();
55
+ }
56
+
57
+ /** Map native wrapping back to the logical line, including spaces lost at wraps. */
58
+ function wrappedRows(
59
+ line: string,
60
+ width: number,
61
+ skip: number,
62
+ ): { lines: string[]; rows: Row[] } | undefined {
63
+ const source = stripTerminalSequences(line);
64
+ const lines = wrapTextWithAnsi(line, width).map(plain);
65
+ const group = {};
66
+ const rows: Row[] = [];
67
+ let offset = 0;
68
+ for (const fragment of lines) {
69
+ let start = offset;
70
+ while (!source.startsWith(fragment, start) && source[start] === " ")
71
+ start++;
72
+ if (!source.startsWith(fragment, start)) return undefined;
73
+ rows.push({
74
+ source,
75
+ offset: start,
76
+ end: start + fragment.length,
77
+ column: 0,
78
+ group,
79
+ skip,
80
+ });
81
+ offset = start + fragment.length;
82
+ }
83
+ return { lines, rows };
84
+ }
85
+
86
+ /**
87
+ * Replay only a Markdown clone. Its native token renderer supplies the logical
88
+ * lines and wrapping widths; the live component and terminal output stay intact.
89
+ */
90
+ function markdownRows(component: MarkdownHost, width: number) {
91
+ const clone = Object.assign(
92
+ Object.create(Object.getPrototypeOf(component)),
93
+ component,
94
+ ) as MarkdownHost;
95
+ delete clone.cachedLines;
96
+ const renderToken = component.renderToken;
97
+ const rows = new Map<number, Row>();
98
+ let depth = 0;
99
+ let blocked = 0;
100
+ let rowOffset = component.paddingY;
101
+ let groups: Array<{ lines: string[]; rows: Row[] }> = [];
102
+ clone.renderToken = function (token, tokenWidth, ...rest) {
103
+ const outer = depth++ === 0;
104
+ if (outer) groups = [];
105
+ const unsupported = ![
106
+ "blockquote",
107
+ "paragraph",
108
+ "text",
109
+ "code",
110
+ "space",
111
+ ].includes(token.type);
112
+ if (unsupported) blocked++;
113
+ const lines = renderToken.call(this, token, tokenWidth, ...rest);
114
+ if (!blocked && token.type !== "blockquote") {
115
+ const indent = stripTerminalSequences(
116
+ this.theme.codeBlockIndent ?? " ",
117
+ ).length;
118
+ for (const [index, line] of lines.entries()) {
119
+ // Code fences are display framing, not source code.
120
+ if (token.type === "code" && (index === 0 || plain(line) === "```"))
121
+ continue;
122
+ for (const logical of line.split(/\r\n|\r|\n/u)) {
123
+ const group = wrappedRows(
124
+ logical,
125
+ tokenWidth,
126
+ token.type === "code" ? indent : 0,
127
+ );
128
+ if (group) groups.push(group);
129
+ }
130
+ }
131
+ }
132
+ if (unsupported) blocked--;
133
+ depth--;
134
+ if (outer) {
135
+ const rendered = lines
136
+ .flatMap((line) => wrapTextWithAnsi(line, tokenWidth))
137
+ .map(plain);
138
+ let cursor = 0;
139
+ for (const group of groups) {
140
+ for (
141
+ let start = cursor;
142
+ start <= rendered.length - group.lines.length;
143
+ start++
144
+ ) {
145
+ const prefixes = group.lines.map((fragment, index) => {
146
+ const line = rendered[start + index] ?? "";
147
+ if (!line.endsWith(fragment)) return undefined;
148
+ const prefix = line.slice(0, line.length - fragment.length);
149
+ return /^[ │]*$/u.test(prefix) ? prefix : undefined;
150
+ });
151
+ if (prefixes.some((prefix) => prefix === undefined)) continue;
152
+ for (const [index, row] of group.rows.entries()) {
153
+ rows.set(rowOffset + start + index, {
154
+ ...row,
155
+ column: component.paddingX + visibleWidth(prefixes[index] ?? ""),
156
+ });
157
+ }
158
+ cursor = start + group.lines.length;
159
+ break;
160
+ }
161
+ }
162
+ rowOffset += rendered.length;
163
+ }
164
+ return lines;
165
+ };
166
+ return { lines: clone.render(width).map(plain), rows };
167
+ }
168
+
169
+ function findScrollBox(box: Layout, scrollView: Component): Layout | undefined {
170
+ if (box.scrollView === scrollView) return box;
171
+ for (const child of box.children ?? []) {
172
+ const found = findScrollBox(child, scrollView);
173
+ if (found) return found;
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ function selectionRows(
179
+ root: Component,
180
+ width: number,
181
+ source: readonly string[],
182
+ bounds: Bounds,
183
+ ): Map<number, Row> {
184
+ const result = new Map<number, Row>();
185
+ const ambiguous = new Set<number>();
186
+ const sourceLines = source.map(plain);
187
+ function visit(component: Component, available: number, padding: number) {
188
+ const candidate = component as Partial<MarkdownHost> & {
189
+ children?: Component[];
190
+ };
191
+ if (
192
+ typeof candidate.renderToken === "function" &&
193
+ typeof candidate.text === "string" &&
194
+ typeof candidate.paddingX === "number" &&
195
+ typeof candidate.paddingY === "number" &&
196
+ candidate.theme
197
+ ) {
198
+ const mapped = markdownRows(candidate as MarkdownHost, available);
199
+ if (!mapped.lines.some((line) => line.trim())) return;
200
+ const lines = mapped.lines.map((line) =>
201
+ (" ".repeat(padding) + line).trimEnd(),
202
+ );
203
+ for (
204
+ let start = Math.max(0, bounds.start.row - lines.length + 1);
205
+ start <= bounds.end.row;
206
+ start++
207
+ ) {
208
+ if (!lines.every((line, index) => sourceLines[start + index] === line))
209
+ continue;
210
+ for (const [index, row] of mapped.rows) {
211
+ const target = start + index;
212
+ if (result.has(target)) ambiguous.add(target);
213
+ result.set(target, { ...row, column: row.column + padding });
214
+ }
215
+ }
216
+ return;
217
+ }
218
+ const inset =
219
+ typeof candidate.paddingX === "number" ? candidate.paddingX : 0;
220
+ for (const child of candidate.children ?? [])
221
+ visit(child, Math.max(1, available - inset * 2), padding + inset);
222
+ }
223
+ // ponytail: scan Markdown on copy only; add a render-time source map if large transcripts make copying slow.
224
+ visit(root, width, 0);
225
+ for (const row of ambiguous) result.delete(row);
226
+ return result;
227
+ }
228
+
229
+ /** @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Clipboard selection cleanup]] */
230
+ export function installClipboardSelection(tui: TUI): (() => void) | undefined {
231
+ const host = tui as Host;
232
+ if (
233
+ typeof host.getActiveSelectionText !== "function" ||
234
+ typeof host.getSelectionBounds !== "function" ||
235
+ typeof host.getSelectionColumns !== "function"
236
+ )
237
+ return undefined;
238
+ host[INSTALLED]?.();
239
+ const original = host.getActiveSelectionText;
240
+ const own = Object.hasOwn(host, "getActiveSelectionText");
241
+ const wrapped = () => {
242
+ const native = original.call(host);
243
+ const bounds = host.getSelectionBounds?.();
244
+ if (!native || !bounds?.start.scrollView || !host.currentLayout?.root)
245
+ return native;
246
+ const scrollView = bounds.start.scrollView;
247
+ const box = findScrollBox(host.currentLayout.root, scrollView);
248
+ if (!box?.scrollContentLines) return native;
249
+ const getWidth = (
250
+ scrollView as Component & { getContentWidth?(width: number): number }
251
+ ).getContentWidth;
252
+ if (typeof getWidth !== "function") return native;
253
+ const rows = selectionRows(
254
+ scrollView,
255
+ getWidth.call(scrollView, box.rect.width),
256
+ box.scrollContentLines,
257
+ bounds,
258
+ );
259
+ if (rows.size === 0) return native;
260
+ let text = "";
261
+ let previous: { row: Row; end: number } | undefined;
262
+ for (let index = bounds.start.row; index <= bounds.end.row; index++) {
263
+ const line = box.scrollContentLines[index] ?? "";
264
+ const columns = host.getSelectionColumns?.(line, index, bounds);
265
+ if (!columns) return native;
266
+ const row = rows.get(index);
267
+ if (!row) {
268
+ text +=
269
+ (index === bounds.start.row ? "" : "\n") +
270
+ plain(
271
+ sliceByColumn(
272
+ line,
273
+ columns.start,
274
+ Math.max(0, columns.end - columns.start),
275
+ true,
276
+ ),
277
+ );
278
+ previous = undefined;
279
+ continue;
280
+ }
281
+ const fragment = row.source.slice(row.offset, row.end);
282
+ const at = (column: number) =>
283
+ Math.max(
284
+ row.skip,
285
+ row.offset +
286
+ sliceByColumn(fragment, 0, Math.max(0, column - row.column), true)
287
+ .length,
288
+ );
289
+ const start = at(columns.start);
290
+ const end = Math.max(start, at(columns.end));
291
+ if (previous?.row.group === row.group)
292
+ text += row.source.slice(previous.end, start);
293
+ else if (index !== bounds.start.row) text += "\n";
294
+ text += row.source.slice(start, end);
295
+ previous = { row, end };
296
+ }
297
+ return text || undefined;
298
+ };
299
+ host.getActiveSelectionText = wrapped;
300
+ const dispose = () => {
301
+ if (host[INSTALLED] !== dispose) return;
302
+ if (host.getActiveSelectionText === wrapped) {
303
+ if (own) host.getActiveSelectionText = original;
304
+ else delete host.getActiveSelectionText;
305
+ }
306
+ delete host[INSTALLED];
307
+ };
308
+ host[INSTALLED] = dispose;
309
+ return dispose;
310
+ }
@@ -0,0 +1,340 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { Component } from "@earendil-works/pi-tui";
5
+
6
+ const CONFIG_FILE_NAME = "proper-base.json";
7
+ const GLOBAL_KEY = "contextTokens";
8
+
9
+ /**
10
+ * The hard input cap of OpenAI's 1,050,000-token models: the window minus
11
+ * the 128,000 reserved output tokens. Probing the Codex backend through
12
+ * CLIProxyAPI on 2026-09-22 rejected every listed model one token past it
13
+ * (usage-counted 921,858 accepted, 921,859 refused; the rest is hidden
14
+ * request framing), just as gpt-5.5 there stops at Pi's registered 272,000.
15
+ * Codex's own catalog budgets 872,000, keeping 50,000 of headroom that Pi's
16
+ * `reserveTokens` provides instead.
17
+ */
18
+ const MAX_INPUT = 922_000;
19
+ const CODEX_MODELS = new Set([
20
+ "gpt-6-astra",
21
+ "gpt-6.1-sol",
22
+ "gpt-6-sol",
23
+ "gpt-6-luna",
24
+ "gpt-5.6-sol",
25
+ "gpt-5.6-terra",
26
+ "gpt-5.6-luna",
27
+ ]);
28
+ /** The API also serves GPT-5.5 and GPT-5.4 at 1,050,000 (Codex keeps GPT-5.5 at 272,000). */
29
+ const API_MODELS = new Set([...CODEX_MODELS, "gpt-5.5", "gpt-5.4"]);
30
+
31
+ export const CONTEXT_TOKENS_ENTRY = "proper-base-context-tokens";
32
+ export const TOKENS_USAGE = "Usage: /tokens [max|default] [global]";
33
+
34
+ export type ContextTokensMode = "max" | "default";
35
+ export type TokenLimits = { default: number; max: number };
36
+ export type TokensModel = {
37
+ provider: string;
38
+ id: string;
39
+ contextWindow: number;
40
+ };
41
+ type CompactionSettings = { enabled: boolean; reserveTokens: number };
42
+ type BranchEntry = { type: string; customType?: string; data?: unknown };
43
+
44
+ /** The live AgentSession fields this module reads and writes. */
45
+ export type TokensSession = {
46
+ agent: { state: { model: TokensModel | undefined } };
47
+ settingsManager: {
48
+ getCompactionSettings(model?: TokensModel): CompactionSettings;
49
+ };
50
+ sessionManager: { getBranch(): readonly BranchEntry[] };
51
+ };
52
+
53
+ /** The ModelRegistry call this module needs. */
54
+ export type TokensRegistry = {
55
+ find(provider: string, id: string): TokensModel | undefined;
56
+ };
57
+
58
+ type JsonObject = Record<string, unknown>;
59
+
60
+ function readJsonObject(path: string): JsonObject | undefined {
61
+ try {
62
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
63
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
64
+ ? (parsed as JsonObject)
65
+ : undefined;
66
+ } catch {
67
+ return undefined;
68
+ }
69
+ }
70
+
71
+ function isMode(value: unknown): value is ContextTokensMode {
72
+ return value === "max" || value === "default";
73
+ }
74
+
75
+ /** Feature-detect the private AgentSession shape; a renamed field disables the command. */
76
+ export function asTokensSession(value: unknown): TokensSession | undefined {
77
+ const session = value as Partial<TokensSession> | undefined;
78
+ return session?.agent?.state &&
79
+ typeof session.settingsManager?.getCompactionSettings === "function" &&
80
+ typeof session.sessionManager?.getBranch === "function"
81
+ ? (session as TokensSession)
82
+ : undefined;
83
+ }
84
+
85
+ /** `""` shows the state; otherwise `max|default` with an optional `global`. */
86
+ export function parseTokensArgs(
87
+ args: string,
88
+ ): { mode?: ContextTokensMode; global: boolean } | undefined {
89
+ const words = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
90
+ if (words.length === 0) return { global: false };
91
+ const [mode, scope, ...rest] = words;
92
+ if (!isMode(mode) || rest.length || (scope && scope !== "global")) {
93
+ return undefined;
94
+ }
95
+ return { mode, global: scope === "global" };
96
+ }
97
+
98
+ const COMPLETIONS = [
99
+ { value: "max", description: "Largest window for this session" },
100
+ { value: "default", description: "Standard window for this session" },
101
+ { value: "max global", description: "Largest window for every session" },
102
+ { value: "default global", description: "Standard window for every session" },
103
+ ];
104
+
105
+ export function tokensArgumentCompletions(prefix: string) {
106
+ const needle = prefix.trimStart().toLowerCase();
107
+ // After a completed mode, list its scopes. The session scope leads and its
108
+ // value equals the typed text, so Pi preselects it and Enter or Tab keeps
109
+ // the choice session-only instead of turning it global.
110
+ const mode = /^(max|default) $/.exec(needle)?.[1];
111
+ const items = mode
112
+ ? COMPLETIONS.filter(({ value }) => value.startsWith(mode)).map((item) => ({
113
+ ...item,
114
+ value: item.value === mode ? needle : item.value,
115
+ label: item.value,
116
+ }))
117
+ : COMPLETIONS.filter(({ value }) => value.startsWith(needle)).map(
118
+ (item) => ({ ...item, label: item.value }),
119
+ );
120
+ return items.length ? items : null;
121
+ }
122
+
123
+ const SCOPE_INSTALLED = Symbol.for("pi-proper-base.tokens-scope-completion");
124
+ const MODE_TEXT = /^\/tokens (?:max|default)$/;
125
+ const SCOPE_TEXT = /^\/tokens (?:max|default) $/;
126
+
127
+ type ScopeEditor = Component & {
128
+ getText?(): string;
129
+ handleInput?(data: string): void;
130
+ isShowingAutocomplete?(): boolean;
131
+ tryTriggerAutocomplete?(): void;
132
+ [SCOPE_INSTALLED]?: boolean;
133
+ };
134
+
135
+ /**
136
+ * Offer the `global` scope after a `/tokens` mode. Pi reopens suggestions
137
+ * only from typed letters and digits, and the separator is a space, so Tab
138
+ * on a mode stops there, adds the space, and opens the scope menu, and a
139
+ * typed space opens it too. Tab on a scope completes it and closes.
140
+ */
141
+ export function installTokensScopeCompletion(
142
+ editor: Component,
143
+ keybindings: { matches(data: string, action: string): boolean },
144
+ ): void {
145
+ const target = editor as ScopeEditor;
146
+ if (target[SCOPE_INSTALLED] || !target.handleInput || !target.getText) return;
147
+ const handleInput = target.handleInput.bind(target);
148
+ target.handleInput = (data: string) => {
149
+ handleInput(data);
150
+ if (target.isShowingAutocomplete?.()) return;
151
+ const tab = keybindings.matches(data, "tui.input.tab");
152
+ if (tab && MODE_TEXT.test(target.getText?.() ?? "")) handleInput(" ");
153
+ else if (data !== " ") return;
154
+ if (SCOPE_TEXT.test(target.getText?.() ?? ""))
155
+ target.tryTriggerAutocomplete?.();
156
+ };
157
+ target[SCOPE_INSTALLED] = true;
158
+ }
159
+
160
+ const format = (tokens: number) => tokens.toLocaleString("en-US");
161
+
162
+ /**
163
+ * Session and global context-window choices for OpenAI models.
164
+ *
165
+ * Pi registers these models at their standard window (272,000) although
166
+ * the backend accepts more, so the choice only changes Pi's budgeting: the
167
+ * session model is swapped for a copy carrying the chosen `contextWindow`,
168
+ * which every compaction, overflow, and footer check reads live. The
169
+ * provider/id identity is unchanged, so per-model compaction overrides keep
170
+ * applying. The session choice is a branch entry; the global choice is
171
+ * `contextTokens` in `proper-base.json`, re-read on every apply.
172
+ */
173
+ export class ContextTokens {
174
+ private readonly agentDir: string;
175
+ private readonly cliproxyProviderId: () => string;
176
+
177
+ constructor(agentDir: string, cliproxyProviderId: () => string) {
178
+ this.agentDir = agentDir;
179
+ this.cliproxyProviderId = cliproxyProviderId;
180
+ }
181
+
182
+ private configPath(): string {
183
+ return join(this.agentDir, CONFIG_FILE_NAME);
184
+ }
185
+
186
+ globalMode(): ContextTokensMode | undefined {
187
+ const value = readJsonObject(this.configPath())?.[GLOBAL_KEY];
188
+ return isMode(value) ? value : undefined;
189
+ }
190
+
191
+ /** Preserves every other key. Write failures propagate to the caller. */
192
+ setGlobalMode(mode: ContextTokensMode): void {
193
+ const existing = readJsonObject(this.configPath()) ?? {};
194
+ writeFileSync(
195
+ this.configPath(),
196
+ `${JSON.stringify({ ...existing, [GLOBAL_KEY]: mode }, null, "\t")}\n`,
197
+ );
198
+ }
199
+
200
+ /** The latest session choice on this branch; `null` data follows global. */
201
+ sessionMode(branch: readonly BranchEntry[]): ContextTokensMode | undefined {
202
+ for (let index = branch.length - 1; index >= 0; index--) {
203
+ const entry = branch[index];
204
+ if (entry?.type !== "custom" || entry.customType !== CONTEXT_TOKENS_ENTRY)
205
+ continue;
206
+ const mode = (entry.data as { mode?: unknown } | undefined)?.mode;
207
+ return isMode(mode) ? mode : undefined;
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ effectiveMode(branch: readonly BranchEntry[]): ContextTokensMode {
213
+ return this.sessionMode(branch) ?? this.globalMode() ?? "default";
214
+ }
215
+
216
+ /**
217
+ * Limits for a registry model, or `undefined` when it has no larger
218
+ * window. The default is the registry's own value, including any
219
+ * `models.json` override.
220
+ */
221
+ limitsFor(model: TokensModel): TokenLimits | undefined {
222
+ const models =
223
+ model.provider === "openai"
224
+ ? API_MODELS
225
+ : model.provider === "openai-codex" ||
226
+ model.provider === this.cliproxyProviderId()
227
+ ? CODEX_MODELS
228
+ : undefined;
229
+ return models?.has(model.id) && MAX_INPUT > model.contextWindow
230
+ ? { default: model.contextWindow, max: MAX_INPUT }
231
+ : undefined;
232
+ }
233
+
234
+ /** The model carrying the effective window, or the model unchanged. */
235
+ private windowed(
236
+ model: TokensModel | undefined,
237
+ session: TokensSession,
238
+ registry: TokensRegistry,
239
+ ): TokensModel | undefined {
240
+ if (!model) return model;
241
+ const base = registry.find(model.provider, model.id) ?? model;
242
+ const limits = this.limitsFor(base);
243
+ if (!limits) return model;
244
+ const mode = this.effectiveMode(session.sessionManager.getBranch());
245
+ const window = mode === "max" ? limits.max : limits.default;
246
+ if (model.contextWindow === window) return model;
247
+ return window === base.contextWindow
248
+ ? base
249
+ : { ...base, contextWindow: window };
250
+ }
251
+
252
+ /**
253
+ * Swap the session model for one carrying the effective window. Returns
254
+ * the applied window, or `undefined` when the model is ineligible.
255
+ */
256
+ apply(
257
+ session: TokensSession,
258
+ registry: TokensRegistry,
259
+ ): { window: number; limits: TokenLimits } | undefined {
260
+ const state = session.agent.state;
261
+ const next = this.windowed(state.model, session, registry);
262
+ if (next !== state.model) state.model = next;
263
+ if (!next) return undefined;
264
+ const limits = this.limitsFor(
265
+ registry.find(next.provider, next.id) ?? next,
266
+ );
267
+ return limits && { window: next.contextWindow, limits };
268
+ }
269
+
270
+ /**
271
+ * Keep the effective window across every write to the session model.
272
+ * Model switches, session restore, and any extension's provider
273
+ * (re)registration put the registry object back without an event, so the
274
+ * setter windows each model as it lands. Global changes made by another
275
+ * process still need `apply`. Returns the uninstaller.
276
+ */
277
+ guard(session: TokensSession, registry: TokensRegistry): () => void {
278
+ const state = session.agent.state;
279
+ let model = state.model;
280
+ const get = () => model;
281
+ Object.defineProperty(state, "model", {
282
+ configurable: true,
283
+ enumerable: true,
284
+ get,
285
+ set: (next: TokensModel | undefined) => {
286
+ model = this.windowed(next, session, registry);
287
+ },
288
+ });
289
+ return () => {
290
+ if (Object.getOwnPropertyDescriptor(state, "model")?.get !== get) return;
291
+ Object.defineProperty(state, "model", {
292
+ configurable: true,
293
+ enumerable: true,
294
+ writable: true,
295
+ value: model,
296
+ });
297
+ };
298
+ }
299
+ }
300
+
301
+ /** Feedback for `/tokens`, including where compaction will now trigger. */
302
+ export function tokensNotice(options: {
303
+ modelId: string;
304
+ /** The chosen mode, or for status its label and source. */
305
+ mode: string;
306
+ scope: "session" | "global" | "status";
307
+ window: number;
308
+ limits: TokenLimits;
309
+ compaction: CompactionSettings;
310
+ contextTokens: number | null | undefined;
311
+ }): { message: string; level: "info" | "warning" } {
312
+ const { modelId, mode, scope, window, limits, compaction, contextTokens } =
313
+ options;
314
+ const where =
315
+ scope === "global"
316
+ ? " for all sessions"
317
+ : scope === "session"
318
+ ? " for this session"
319
+ : "";
320
+ const lead =
321
+ scope === "status"
322
+ ? `${modelId}: ${format(window)}-token context window (${mode}; default ${format(limits.default)}, max ${format(limits.max)}).`
323
+ : `Context window ${mode}${where}: ${modelId} now uses ${format(window)} tokens.`;
324
+ if (!compaction.enabled) {
325
+ const over = contextTokens != null && contextTokens > window;
326
+ return {
327
+ message: `${lead} Auto-compaction is off${over ? `; the current ${format(contextTokens)}-token context already exceeds the window.` : "."}`,
328
+ level: over ? "warning" : "info",
329
+ };
330
+ }
331
+ const threshold = window - compaction.reserveTokens;
332
+ const trigger = `Compaction triggers above ${format(Math.max(0, threshold))} tokens (reserve ${format(compaction.reserveTokens)}).`;
333
+ if (contextTokens != null && contextTokens > threshold) {
334
+ return {
335
+ message: `${lead} ${trigger} The current ${format(contextTokens)}-token context is past it, so the next request compacts first.`,
336
+ level: "warning",
337
+ };
338
+ }
339
+ return { message: `${lead} ${trigger}`, level: "info" };
340
+ }