pi-tuck 1.5.0 → 1.6.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/CHANGELOG.md CHANGED
@@ -3,6 +3,15 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.6.0]
7
+
8
+ ### Added
9
+
10
+ - Model config check: once per Pi start, in the background, for a model whose provider is defined in `models.json`, pi-tuck compares the
11
+ context window and thinking levels with the server's `/models` reply. With a UI it asks before changing `models.json` (dated backup,
12
+ only the reported fields; a file with comments gets the exact edit instead) and remembers a "no" in `pi-tuck.json` for that server
13
+ value. Without a UI it prints nothing; `/tuck` lists the findings.
14
+
6
15
  ## [1.5.0]
7
16
 
8
17
  ### Added
package/README.md CHANGED
@@ -12,7 +12,7 @@ pi install npm:pi-tuck
12
12
 
13
13
  Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
14
14
 
15
- This README describes pi-tuck 1.5.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.5.0` or `pi install git:github.com/galyavin/pi-tuck@v1.5.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.6.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.6.0` or `pi install git:github.com/galyavin/pi-tuck@v1.6.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -45,6 +45,10 @@ context ████████░░ 19k of 24k · 2 trims
45
45
 
46
46
  When pi-tuck stops a request or a reply ends at its length limit, the notice suggests `/tuck-incident next` to record the next trim for a bug report.
47
47
 
48
+ ## Model config check
49
+
50
+ Once per Pi start, in the background, pi-tuck reads the server's own model list (`{baseUrl}/models`, with Pi's auth for that provider) for the session's model, when that model's provider is defined in Pi's `models.json`. It compares the context window (`max_model_len`, `context_length`, `context_window` or `n_ctx`; never the training length `n_ctx_train`) and the thinking levels (`reasoning.efforts`, matched only by identical names) with `models.json`. In the terminal UI each difference is a yes/no question; yes backs up `models.json` next to it with the date in the name and changes only those fields (restart Pi to use them), and no is remembered in `pi-tuck.json` until the server reports a different value. A `models.json` with comments is not rewritten; pi-tuck shows the exact edit instead. Without a UI, nothing is printed: the findings go to the session and to `/tuck`. Tested with a server whose `/v1/models` entry reports `max_model_len` and `reasoning.efforts`; other servers, including llama.cpp's, are not verified yet.
51
+
48
52
  ## Settings
49
53
 
50
54
  Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by default, or `PI_CODING_AGENT_DIR`). Restart Pi to apply changes. The input room starts at the model's context window minus Pi's `compaction.reserveTokens`. Invalid JSON uses defaults. An invalid field uses its own default, with a notice when compaction is active.
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { validCutAt } from "./src/budget.js";
6
6
  import { notify } from "./src/notify.js";
7
7
  import { cleanupLegacyFiles } from "./src/legacy-cleanup.js";
8
8
  import { installFooter } from "./src/footer.js";
9
+ import { installConfigCheck } from "./src/config-check.js";
9
10
  export { installCompaction } from "./src/compaction.js";
10
11
  export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
11
12
  /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
@@ -39,6 +40,7 @@ export default async function (pi) {
39
40
  const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
40
41
  if (settings.footer !== false)
41
42
  installFooter(pi, ctx => handle.cutPoint(ctx));
43
+ installConfigCheck(pi, { agentDir: getAgentDir() });
42
44
  const continuation = settings.llamaContinuation;
43
45
  let continuationError;
44
46
  if (continuation) {
@@ -1 +1 @@
1
- export declare const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
1
+ export declare const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
@@ -1 +1 @@
1
- export const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
1
+ export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
@@ -0,0 +1,54 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /**
3
+ * The models.json check: once per Pi process, in the background at session start, for a model of a provider defined in models.json,
4
+ * read the server's own model list and compare the context window and the thinking levels with the config. With a UI each difference
5
+ * is a yes/no question; yes edits only the reported fields (after a dated backup), no is remembered in pi-tuck.json for that server
6
+ * value. Without a UI nothing is printed: the findings go to the session and to /tuck. It changes nothing the model sees.
7
+ */
8
+ export declare const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
9
+ type Map = Partial<Record<string, string | null>>;
10
+ /** What the server says about one model. Window from the first of these it reports; never n_ctx_train (the training length). */
11
+ export interface ServerModel {
12
+ window?: number;
13
+ efforts?: string[];
14
+ }
15
+ export declare function serverModel(body: unknown, id: string): ServerModel | undefined;
16
+ export interface Finding {
17
+ kind: "window" | "thinking";
18
+ /** The server value a "no" is remembered against. */
19
+ server: string;
20
+ question: string;
21
+ /** The fields to set on the model in models.json. */
22
+ patch: {
23
+ contextWindow?: number;
24
+ thinkingLevelMap?: Map;
25
+ };
26
+ }
27
+ /** The differences between the config and the server; the thinking levels only for a reasoning model whose server lists efforts. */
28
+ export declare function findings(model: {
29
+ contextWindow: number;
30
+ reasoning?: boolean;
31
+ thinkingLevelMap?: Map;
32
+ }, server: ServerModel): Finding[];
33
+ /** JSON with // and /* comments removed outside strings (Pi accepts comments in models.json). */
34
+ export declare function stripComments(text: string): string;
35
+ /** The exact edit, for a models.json Pi accepts but pi-tuck will not rewrite (it has comments). */
36
+ export declare const editText: (path: string, provider: string, id: string, patch: Finding["patch"]) => string;
37
+ /** Apply the accepted fields: back up models.json next to it, then write only those fields. Says what to tell the operator. */
38
+ export declare function applyPatch(path: string, provider: string, id: string, patch: Finding["patch"], now?: Date): {
39
+ outcome: "updated" | "edit shown" | "unchanged";
40
+ text: string;
41
+ };
42
+ /** Remembered "no" answers in pi-tuck.json: {"configCheck": {"provider/model": {"window": "272000", "thinking": "high,xhigh"}}}. */
43
+ export declare function declined(settingsPath: string): Record<string, Partial<Record<Finding["kind"], string>>>;
44
+ export declare function rememberNo(settingsPath: string, ref: string, finding: Finding): void;
45
+ export interface CheckDeps {
46
+ agentDir: string;
47
+ fetch?: typeof fetch;
48
+ now?: () => Date;
49
+ }
50
+ /** One check of the session's model. Resolves when done; never throws. */
51
+ export declare function checkModel(pi: Pick<ExtensionAPI, "appendEntry">, ctx: ExtensionContext, deps: CheckDeps): Promise<void>;
52
+ /** Run the check once per Pi process, in the background: session start never waits for it. */
53
+ export declare function installConfigCheck(pi: ExtensionAPI, deps: CheckDeps): void;
54
+ export {};
@@ -0,0 +1,196 @@
1
+ import { copyFileSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /**
4
+ * The models.json check: once per Pi process, in the background at session start, for a model of a provider defined in models.json,
5
+ * read the server's own model list and compare the context window and the thinking levels with the config. With a UI each difference
6
+ * is a yes/no question; yes edits only the reported fields (after a dated backup), no is remembered in pi-tuck.json for that server
7
+ * value. Without a UI nothing is printed: the findings go to the session and to /tuck. It changes nothing the model sees.
8
+ */
9
+ export const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
10
+ /** Pi's thinking levels that a server can list; "off" is never a server effort. */
11
+ const LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
12
+ export function serverModel(body, id) {
13
+ const data = body?.data;
14
+ const entry = Array.isArray(data) ? data.find(m => m?.id === id) : undefined;
15
+ if (!entry)
16
+ return undefined;
17
+ const window = ["max_model_len", "context_length", "context_window", "n_ctx"].map(k => entry[k]).find(v => Number.isSafeInteger(v) && v > 0);
18
+ const raw = entry.reasoning?.efforts;
19
+ const efforts = Array.isArray(raw) && raw.every(e => typeof e === "string") ? raw : undefined;
20
+ return { window, efforts };
21
+ }
22
+ const k = (n) => n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`;
23
+ /** The differences between the config and the server; the thinking levels only for a reasoning model whose server lists efforts. */
24
+ export function findings(model, server) {
25
+ const out = [];
26
+ const w = server.window, c = model.contextWindow;
27
+ if (w !== undefined && w !== c)
28
+ out.push({ kind: "window", server: String(w), patch: { contextWindow: w }, question: w > c
29
+ ? `Server allows ${k(w)}, config says ${k(c)}. Use ${k(w)}?`
30
+ : `Config says ${k(c)}, but the server allows only ${k(w)}: requests past ${k(w)} will fail. Use ${k(w)}?` });
31
+ if (model.reasoning && server.efforts) {
32
+ const map = {};
33
+ for (const level of LEVELS) {
34
+ const want = server.efforts.includes(level) ? level : null;
35
+ if (model.thinkingLevelMap?.[level] !== want)
36
+ map[level] = want;
37
+ }
38
+ const on = LEVELS.filter(l => typeof model.thinkingLevelMap?.[l] === "string").join(", ") || "none";
39
+ if (Object.keys(map).length)
40
+ out.push({ kind: "thinking", server: server.efforts.join(","), patch: { thinkingLevelMap: map },
41
+ question: `Server thinking levels: ${server.efforts.join(", ") || "none"}; config enables: ${on}. Match the server?` });
42
+ }
43
+ return out;
44
+ }
45
+ /** JSON with // and /* comments removed outside strings (Pi accepts comments in models.json). */
46
+ export function stripComments(text) {
47
+ let out = "", i = 0, str = false;
48
+ while (i < text.length) {
49
+ const ch = text[i], next = text[i + 1];
50
+ if (str) {
51
+ out += ch;
52
+ if (ch === "\\") {
53
+ out += next ?? "";
54
+ i += 2;
55
+ continue;
56
+ }
57
+ if (ch === '"')
58
+ str = false;
59
+ i++;
60
+ continue;
61
+ }
62
+ if (ch === '"') {
63
+ str = true;
64
+ out += ch;
65
+ i++;
66
+ continue;
67
+ }
68
+ if (ch === "/" && next === "/") {
69
+ while (i < text.length && text[i] !== "\n")
70
+ i++;
71
+ continue;
72
+ }
73
+ if (ch === "/" && next === "*") {
74
+ const end = text.indexOf("*/", i + 2);
75
+ i = end < 0 ? text.length : end + 2;
76
+ continue;
77
+ }
78
+ out += ch;
79
+ i++;
80
+ }
81
+ return out;
82
+ }
83
+ const stamp = (d) => d.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
84
+ /** The exact edit, for a models.json Pi accepts but pi-tuck will not rewrite (it has comments). */
85
+ export const editText = (path, provider, id, patch) => `In ${path}, provider "${provider}", model "${id}": ` + Object.entries(patch.thinkingLevelMap ?? {}).map(([l, v]) => `set thinkingLevelMap.${l} to ${JSON.stringify(v)}`)
86
+ .concat(patch.contextWindow === undefined ? [] : [`set contextWindow to ${patch.contextWindow}`]).join("; ") + ".";
87
+ /** Apply the accepted fields: back up models.json next to it, then write only those fields. Says what to tell the operator. */
88
+ export function applyPatch(path, provider, id, patch, now = new Date()) {
89
+ const text = readFileSync(path, "utf8");
90
+ let file;
91
+ try {
92
+ file = JSON.parse(text);
93
+ }
94
+ catch {
95
+ return { outcome: "edit shown", text: `pi-tuck: ${path} has comments, so pi-tuck did not change it. ${editText(path, provider, id, patch)} Then restart Pi.` };
96
+ }
97
+ const model = file.providers?.[provider]?.models?.find(m => m.id === id);
98
+ if (!model)
99
+ return { outcome: "unchanged", text: `pi-tuck: ${provider}/${id} is no longer in ${path}; nothing changed.` };
100
+ if (patch.contextWindow !== undefined)
101
+ model.contextWindow = patch.contextWindow;
102
+ if (patch.thinkingLevelMap)
103
+ model.thinkingLevelMap = { ...model.thinkingLevelMap, ...patch.thinkingLevelMap };
104
+ const backup = `${path}.before-pi-tuck-${stamp(now)}`;
105
+ copyFileSync(path, backup);
106
+ writeFileSync(path, JSON.stringify(file, null, 2) + "\n");
107
+ return { outcome: "updated", text: `pi-tuck: updated ${path} (backup ${backup}). Restart Pi to use it.` };
108
+ }
109
+ /** Remembered "no" answers in pi-tuck.json: {"configCheck": {"provider/model": {"window": "272000", "thinking": "high,xhigh"}}}. */
110
+ export function declined(settingsPath) {
111
+ try {
112
+ const value = JSON.parse(readFileSync(settingsPath, "utf8"));
113
+ return value.configCheck && typeof value.configCheck === "object" ? value.configCheck : {};
114
+ }
115
+ catch {
116
+ return {};
117
+ }
118
+ }
119
+ export function rememberNo(settingsPath, ref, finding) {
120
+ let value = {};
121
+ try {
122
+ value = JSON.parse(readFileSync(settingsPath, "utf8"));
123
+ }
124
+ catch (error) {
125
+ if (error.code !== "ENOENT")
126
+ return; // an unreadable pi-tuck.json is left alone
127
+ }
128
+ const all = { ...declined(settingsPath) };
129
+ all[ref] = { ...all[ref], [finding.kind]: finding.server };
130
+ writeFileSync(settingsPath, JSON.stringify({ ...value, configCheck: all }, null, 2) + "\n");
131
+ }
132
+ /** One check of the session's model. Resolves when done; never throws. */
133
+ export async function checkModel(pi, ctx, deps) {
134
+ try {
135
+ const model = ctx.model, registry = ctx.modelRegistry;
136
+ if (!model || typeof registry?.getApiKeyAndHeaders !== "function")
137
+ return;
138
+ const modelsPath = join(deps.agentDir, "models.json"), settingsPath = join(deps.agentDir, "pi-tuck.json");
139
+ let file;
140
+ try {
141
+ file = JSON.parse(stripComments(readFileSync(modelsPath, "utf8")));
142
+ }
143
+ catch {
144
+ return;
145
+ }
146
+ const provider = file.providers?.[model.provider];
147
+ if (typeof provider?.baseUrl !== "string" || !provider.models?.some(m => m.id === model.id))
148
+ return;
149
+ const auth = await registry.getApiKeyAndHeaders(model);
150
+ if (!auth.ok)
151
+ return;
152
+ const base = (auth.baseUrl ?? model.baseUrl ?? provider.baseUrl).replace(/\/+$/, "");
153
+ const headers = { ...(auth.apiKey ? { Authorization: `Bearer ${auth.apiKey}` } : {}), ...auth.headers };
154
+ const response = await (deps.fetch ?? fetch)(`${base}/models`, { headers, signal: AbortSignal.timeout(10_000) });
155
+ if (!response.ok)
156
+ return;
157
+ const server = serverModel(await response.json(), model.id);
158
+ if (!server)
159
+ return;
160
+ const ref = `${model.provider}/${model.id}`, no = declined(settingsPath)[ref] ?? {};
161
+ const open = findings(model, server).filter(f => no[f.kind] !== f.server);
162
+ if (!open.length)
163
+ return;
164
+ const lines = open.map(f => f.question.replace(/\?$/, "."));
165
+ if (!ctx.hasUI) {
166
+ pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome: "not asked (no UI)" });
167
+ return;
168
+ }
169
+ const accepted = [];
170
+ for (const f of open) {
171
+ if (await ctx.ui.confirm(`pi-tuck: ${ref} in models.json`, f.question))
172
+ accepted.push(f);
173
+ else
174
+ rememberNo(settingsPath, ref, f);
175
+ }
176
+ let outcome = "declined";
177
+ if (accepted.length) {
178
+ const patch = Object.assign({}, ...accepted.map(f => f.patch));
179
+ const told = applyPatch(modelsPath, model.provider, model.id, patch, deps.now?.());
180
+ ctx.ui.notify(told.text, told.outcome === "updated" ? "info" : "warning");
181
+ outcome = told.outcome;
182
+ }
183
+ pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome });
184
+ }
185
+ catch { /* a server that does not answer, or an ended session: no check */ }
186
+ }
187
+ /** Run the check once per Pi process, in the background: session start never waits for it. */
188
+ export function installConfigCheck(pi, deps) {
189
+ let done = false;
190
+ pi.on("session_start", (_event, ctx) => {
191
+ if (done)
192
+ return;
193
+ done = true;
194
+ void checkModel(pi, ctx, deps);
195
+ });
196
+ }
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
3
+ export declare const DIAGNOSTIC_BUILD = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -27,6 +27,8 @@ export function statusText(input) {
27
27
  : `Trims: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
28
28
  const native = cuts.length - ours.length;
29
29
  const now = input.cutPoint === undefined ? "" : ` (about ${count(input.cutPoint)} tokens with this model)`;
30
+ const check = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-config-check").at(-1)?.data;
31
+ const checkLines = Array.isArray(check?.lines) ? [`models.json check for ${String(check.model)} (${String(check.outcome)}):`, ...check.lines.map(line => ` ${String(line)}`)] : [];
30
32
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
31
33
  entry.data?.kind === "retry").length;
32
34
  return [
@@ -38,5 +40,6 @@ export function statusText(input) {
38
40
  input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
39
41
  ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
40
42
  "Search: by keyword.",
43
+ ...checkLines,
41
44
  ].join("\n");
42
45
  }
package/index.ts CHANGED
@@ -7,6 +7,7 @@ import { notify } from "./src/notify";
7
7
  import type { LlamaContinuation } from "./src/llama-continuation";
8
8
  import { cleanupLegacyFiles } from "./src/legacy-cleanup";
9
9
  import { installFooter } from "./src/footer";
10
+ import { installConfigCheck } from "./src/config-check";
10
11
 
11
12
  export type { CompactionOptions } from "./src/compaction";
12
13
  export { installCompaction } from "./src/compaction";
@@ -36,6 +37,7 @@ export default async function (pi: ExtensionAPI) {
36
37
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
37
38
  const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
38
39
  if (settings.footer !== false) installFooter(pi, ctx => handle.cutPoint(ctx));
40
+ installConfigCheck(pi, { agentDir: getAgentDir() });
39
41
  const continuation = settings.llamaContinuation;
40
42
  let continuationError: string | undefined;
41
43
  if (continuation) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
1
+ export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
@@ -0,0 +1,162 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { copyFileSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * The models.json check: once per Pi process, in the background at session start, for a model of a provider defined in models.json,
7
+ * read the server's own model list and compare the context window and the thinking levels with the config. With a UI each difference
8
+ * is a yes/no question; yes edits only the reported fields (after a dated backup), no is remembered in pi-tuck.json for that server
9
+ * value. Without a UI nothing is printed: the findings go to the session and to /tuck. It changes nothing the model sees.
10
+ */
11
+ export const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
12
+ /** Pi's thinking levels that a server can list; "off" is never a server effort. */
13
+ const LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
14
+ type Map = Partial<Record<string, string | null>>;
15
+
16
+ /** What the server says about one model. Window from the first of these it reports; never n_ctx_train (the training length). */
17
+ export interface ServerModel { window?: number; efforts?: string[] }
18
+ export function serverModel(body: unknown, id: string): ServerModel | undefined {
19
+ const data = (body as { data?: unknown } | null)?.data;
20
+ const entry = Array.isArray(data) ? data.find(m => (m as { id?: unknown } | null)?.id === id) as Record<string, unknown> | undefined : undefined;
21
+ if (!entry) return undefined;
22
+ const window = ["max_model_len", "context_length", "context_window", "n_ctx"].map(k => entry[k]).find(v => Number.isSafeInteger(v) && (v as number) > 0) as number | undefined;
23
+ const raw = (entry.reasoning as { efforts?: unknown } | null | undefined)?.efforts;
24
+ const efforts = Array.isArray(raw) && raw.every(e => typeof e === "string") ? raw as string[] : undefined;
25
+ return { window, efforts };
26
+ }
27
+
28
+ export interface Finding {
29
+ kind: "window" | "thinking";
30
+ /** The server value a "no" is remembered against. */
31
+ server: string;
32
+ question: string;
33
+ /** The fields to set on the model in models.json. */
34
+ patch: { contextWindow?: number; thinkingLevelMap?: Map };
35
+ }
36
+ const k = (n: number) => n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`;
37
+
38
+ /** The differences between the config and the server; the thinking levels only for a reasoning model whose server lists efforts. */
39
+ export function findings(model: { contextWindow: number; reasoning?: boolean; thinkingLevelMap?: Map }, server: ServerModel): Finding[] {
40
+ const out: Finding[] = [];
41
+ const w = server.window, c = model.contextWindow;
42
+ if (w !== undefined && w !== c) out.push({ kind: "window", server: String(w), patch: { contextWindow: w }, question: w > c
43
+ ? `Server allows ${k(w)}, config says ${k(c)}. Use ${k(w)}?`
44
+ : `Config says ${k(c)}, but the server allows only ${k(w)}: requests past ${k(w)} will fail. Use ${k(w)}?` });
45
+ if (model.reasoning && server.efforts) {
46
+ const map: Map = {};
47
+ for (const level of LEVELS) {
48
+ const want = server.efforts.includes(level) ? level : null;
49
+ if (model.thinkingLevelMap?.[level] !== want) map[level] = want;
50
+ }
51
+ const on = LEVELS.filter(l => typeof model.thinkingLevelMap?.[l] === "string").join(", ") || "none";
52
+ if (Object.keys(map).length) out.push({ kind: "thinking", server: server.efforts.join(","), patch: { thinkingLevelMap: map },
53
+ question: `Server thinking levels: ${server.efforts.join(", ") || "none"}; config enables: ${on}. Match the server?` });
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /** JSON with // and /* comments removed outside strings (Pi accepts comments in models.json). */
59
+ export function stripComments(text: string): string {
60
+ let out = "", i = 0, str = false;
61
+ while (i < text.length) {
62
+ const ch = text[i]!, next = text[i + 1];
63
+ if (str) { out += ch; if (ch === "\\") { out += next ?? ""; i += 2; continue; } if (ch === '"') str = false; i++; continue; }
64
+ if (ch === '"') { str = true; out += ch; i++; continue; }
65
+ if (ch === "/" && next === "/") { while (i < text.length && text[i] !== "\n") i++; continue; }
66
+ if (ch === "/" && next === "*") { const end = text.indexOf("*/", i + 2); i = end < 0 ? text.length : end + 2; continue; }
67
+ out += ch; i++;
68
+ }
69
+ return out;
70
+ }
71
+
72
+ type ModelsFile = { providers?: Record<string, { baseUrl?: unknown; models?: { id?: unknown }[] }> };
73
+ const stamp = (d: Date) => d.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
74
+ /** The exact edit, for a models.json Pi accepts but pi-tuck will not rewrite (it has comments). */
75
+ export const editText = (path: string, provider: string, id: string, patch: Finding["patch"]) =>
76
+ `In ${path}, provider "${provider}", model "${id}": ` + Object.entries(patch.thinkingLevelMap ?? {}).map(([l, v]) => `set thinkingLevelMap.${l} to ${JSON.stringify(v)}`)
77
+ .concat(patch.contextWindow === undefined ? [] : [`set contextWindow to ${patch.contextWindow}`]).join("; ") + ".";
78
+
79
+ /** Apply the accepted fields: back up models.json next to it, then write only those fields. Says what to tell the operator. */
80
+ export function applyPatch(path: string, provider: string, id: string, patch: Finding["patch"], now = new Date()): { outcome: "updated" | "edit shown" | "unchanged"; text: string } {
81
+ const text = readFileSync(path, "utf8");
82
+ let file: ModelsFile;
83
+ try { file = JSON.parse(text) as ModelsFile; } catch {
84
+ return { outcome: "edit shown", text: `pi-tuck: ${path} has comments, so pi-tuck did not change it. ${editText(path, provider, id, patch)} Then restart Pi.` };
85
+ }
86
+ const model = file.providers?.[provider]?.models?.find(m => m.id === id) as Record<string, unknown> | undefined;
87
+ if (!model) return { outcome: "unchanged", text: `pi-tuck: ${provider}/${id} is no longer in ${path}; nothing changed.` };
88
+ if (patch.contextWindow !== undefined) model.contextWindow = patch.contextWindow;
89
+ if (patch.thinkingLevelMap) model.thinkingLevelMap = { ...(model.thinkingLevelMap as Map | undefined), ...patch.thinkingLevelMap };
90
+ const backup = `${path}.before-pi-tuck-${stamp(now)}`;
91
+ copyFileSync(path, backup);
92
+ writeFileSync(path, JSON.stringify(file, null, 2) + "\n");
93
+ return { outcome: "updated", text: `pi-tuck: updated ${path} (backup ${backup}). Restart Pi to use it.` };
94
+ }
95
+
96
+ /** Remembered "no" answers in pi-tuck.json: {"configCheck": {"provider/model": {"window": "272000", "thinking": "high,xhigh"}}}. */
97
+ export function declined(settingsPath: string): Record<string, Partial<Record<Finding["kind"], string>>> {
98
+ try {
99
+ const value = JSON.parse(readFileSync(settingsPath, "utf8")) as { configCheck?: unknown };
100
+ return value.configCheck && typeof value.configCheck === "object" ? value.configCheck as Record<string, Partial<Record<Finding["kind"], string>>> : {};
101
+ } catch { return {}; }
102
+ }
103
+ export function rememberNo(settingsPath: string, ref: string, finding: Finding): void {
104
+ let value: Record<string, unknown> = {};
105
+ try { value = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>; } catch (error) {
106
+ if ((error as { code?: unknown }).code !== "ENOENT") return; // an unreadable pi-tuck.json is left alone
107
+ }
108
+ const all = { ...declined(settingsPath) };
109
+ all[ref] = { ...all[ref], [finding.kind]: finding.server };
110
+ writeFileSync(settingsPath, JSON.stringify({ ...value, configCheck: all }, null, 2) + "\n");
111
+ }
112
+
113
+ export interface CheckDeps { agentDir: string; fetch?: typeof fetch; now?: () => Date }
114
+
115
+ /** One check of the session's model. Resolves when done; never throws. */
116
+ export async function checkModel(pi: Pick<ExtensionAPI, "appendEntry">, ctx: ExtensionContext, deps: CheckDeps): Promise<void> {
117
+ try {
118
+ const model = ctx.model, registry = ctx.modelRegistry as { getApiKeyAndHeaders?: (m: unknown) => Promise<{ ok: boolean; apiKey?: string; headers?: Record<string, string>; baseUrl?: string }> } | undefined;
119
+ if (!model || typeof registry?.getApiKeyAndHeaders !== "function") return;
120
+ const modelsPath = join(deps.agentDir, "models.json"), settingsPath = join(deps.agentDir, "pi-tuck.json");
121
+ let file: ModelsFile;
122
+ try { file = JSON.parse(stripComments(readFileSync(modelsPath, "utf8"))) as ModelsFile; } catch { return; }
123
+ const provider = file.providers?.[model.provider];
124
+ if (typeof provider?.baseUrl !== "string" || !provider.models?.some(m => m.id === model.id)) return;
125
+ const auth = await registry.getApiKeyAndHeaders(model);
126
+ if (!auth.ok) return;
127
+ const base = (auth.baseUrl ?? model.baseUrl ?? provider.baseUrl).replace(/\/+$/, "");
128
+ const headers: Record<string, string> = { ...(auth.apiKey ? { Authorization: `Bearer ${auth.apiKey}` } : {}), ...auth.headers };
129
+ const response = await (deps.fetch ?? fetch)(`${base}/models`, { headers, signal: AbortSignal.timeout(10_000) });
130
+ if (!response.ok) return;
131
+ const server = serverModel(await response.json(), model.id);
132
+ if (!server) return;
133
+ const ref = `${model.provider}/${model.id}`, no = declined(settingsPath)[ref] ?? {};
134
+ const open = findings(model as never, server).filter(f => no[f.kind] !== f.server);
135
+ if (!open.length) return;
136
+ const lines = open.map(f => f.question.replace(/\?$/, "."));
137
+ if (!ctx.hasUI) { pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome: "not asked (no UI)" }); return; }
138
+ const accepted: Finding[] = [];
139
+ for (const f of open) {
140
+ if (await ctx.ui.confirm(`pi-tuck: ${ref} in models.json`, f.question)) accepted.push(f);
141
+ else rememberNo(settingsPath, ref, f);
142
+ }
143
+ let outcome = "declined";
144
+ if (accepted.length) {
145
+ const patch = Object.assign({}, ...accepted.map(f => f.patch)) as Finding["patch"];
146
+ const told = applyPatch(modelsPath, model.provider, model.id, patch, deps.now?.());
147
+ ctx.ui.notify(told.text, told.outcome === "updated" ? "info" : "warning");
148
+ outcome = told.outcome;
149
+ }
150
+ pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome });
151
+ } catch { /* a server that does not answer, or an ended session: no check */ }
152
+ }
153
+
154
+ /** Run the check once per Pi process, in the background: session start never waits for it. */
155
+ export function installConfigCheck(pi: ExtensionAPI, deps: CheckDeps): void {
156
+ let done = false;
157
+ pi.on("session_start", (_event, ctx) => {
158
+ if (done) return;
159
+ done = true;
160
+ void checkModel(pi, ctx, deps);
161
+ });
162
+ }
package/src/status.ts CHANGED
@@ -37,6 +37,8 @@ export function statusText(input: {
37
37
  : `Trims: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
38
38
  const native = cuts.length - ours.length;
39
39
  const now = input.cutPoint === undefined ? "" : ` (about ${count(input.cutPoint)} tokens with this model)`;
40
+ const check = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-config-check").at(-1)?.data as { model?: unknown; lines?: unknown; outcome?: unknown } | undefined;
41
+ const checkLines = Array.isArray(check?.lines) ? [`models.json check for ${String(check!.model)} (${String(check!.outcome)}):`, ...check!.lines.map(line => ` ${String(line)}`)] : [];
40
42
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
41
43
  (entry.data as { kind?: unknown } | null | undefined)?.kind === "retry").length;
42
44
  return [
@@ -48,5 +50,6 @@ export function statusText(input: {
48
50
  input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
49
51
  ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
50
52
  "Search: by keyword.",
53
+ ...checkLines,
51
54
  ].join("\n");
52
55
  }