pi-tuck 1.5.0 → 1.7.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,25 @@
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.7.0]
7
+
8
+ ### Changed
9
+
10
+ - Reply room after a length stop: once a reply on the current branch stops at its length limit, pi-tuck trims so the next request leaves
11
+ twice that reply's output for the reply (at most the model's `maxTokens`, and at most half the window), by Pi's own clamp math. With no
12
+ length stop the trim point is unchanged. Admission is unchanged: the raise never refuses a request Pi would send.
13
+ - A reply that used the model's whole `maxTokens` while still thinking gets its own notice: it names the model, the cap and `models.json`,
14
+ and says a lower thinking level or a task that writes to files as it goes usually helps more than a bigger cap.
15
+
16
+ ## [1.6.0]
17
+
18
+ ### Added
19
+
20
+ - Model config check: once per Pi start, in the background, for a model whose provider is defined in `models.json`, pi-tuck compares the
21
+ context window and thinking levels with the server's `/models` reply. With a UI it asks before changing `models.json` (dated backup,
22
+ only the reported fields; a file with comments gets the exact edit instead) and remembers a "no" in `pi-tuck.json` for that server
23
+ value. Without a UI it prints nothing; `/tuck` lists the findings.
24
+
6
25
  ## [1.5.0]
7
26
 
8
27
  ### 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.
@@ -67,7 +71,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
67
71
 
68
72
  ## Output exhaustion and small windows
69
73
 
70
- - Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is.
74
+ - Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is. After any length stop on the branch, pi-tuck trims so the next reply gets twice that stop's output (at most `maxTokens` and half the window). A stop at the full `maxTokens` while still thinking names the setting and `models.json`; a lower thinking level usually helps more than a bigger cap.
71
75
  - Pi-tuck uses the context window declared in Pi's model configuration. A length stop alone does not establish a smaller window. If the server has a smaller effective limit, set that limit in Pi's model configuration.
72
76
  - Pi's compaction reserve sets the cut target. For larger requests, pi-tuck estimates reply needs from observed output on the current branch for the active model, bounded by the reserve and model output limit. A cut above the room aims to leave 3,584 reply tokens within those bounds; where no cut can, the request goes out as before. If cuts cannot leave enough room for the protected prompt and a reply, try a shorter prompt, fewer tools, or a larger window. Pi-tuck's checks use estimates. Pi handles recognized provider overflows, and silent truncation can go undetected.
73
77
 
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 = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
@@ -1 +1 @@
1
- export const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
1
+ export const BUILD_ID = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
@@ -8,6 +8,8 @@ export declare const refusalNotice: (message: string, factor: number) => string;
8
8
  /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
9
9
  export declare const overflowNotice: (contextWindow: number, bound: number, learned: boolean) => string;
10
10
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
11
+ /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
12
+ export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
11
13
  export declare const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
12
14
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
13
15
  export declare const CALIBRATION_CEILING = 1.5;
@@ -1,10 +1,12 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run } from "./run.js";
3
- import { CUT_REPLY_FLOOR, requestReplyFloor, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
8
10
  import { exportSource } from "./source-export.js";
9
11
  import { isDeepStrictEqual } from "node:util";
10
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
@@ -12,7 +14,7 @@ import { projectedMessages } from "./omissions.js";
12
14
  import { applyClips, clipBudgets, clipFor } from "./clip.js";
13
15
  import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
14
16
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext } from "@earendil-works/pi-ai";
15
- import { calculateContextTokens, convertToLlm, estimateTokens, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
17
+ import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
16
18
  import { Type } from "typebox";
17
19
  import { Check } from "typebox/value";
18
20
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
@@ -59,6 +61,20 @@ export const refusalNotice = (message, factor) => message + "; shorten the input
59
61
  export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
60
62
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
61
63
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
64
+ /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
65
+ export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
66
+ `The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
67
+ "The unfinished response is saved in the session.";
68
+ /** Pi's models.json, shown with ~ for the home folder. */
69
+ function modelsPath() {
70
+ try {
71
+ const path = join(getAgentDir(), "models.json"), home = homedir();
72
+ return path.startsWith(home + "/") ? "~" + path.slice(home.length) : path;
73
+ }
74
+ catch {
75
+ return "~/.pi/agent/models.json";
76
+ }
77
+ }
62
78
  export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
63
79
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
64
80
  export const CALIBRATION_CEILING = 1.5;
@@ -331,18 +347,22 @@ export async function installCompaction(pi, options = {}) {
331
347
  lengthStop = event.message.stopReason === "length" ? {
332
348
  kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
333
349
  cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
350
+ cap: ctx.model && ctx.model.maxTokens > 0 && event.message.usage?.output === ctx.model.maxTokens
351
+ ? { model: `${ctx.model.provider}/${ctx.model.id}`, maxTokens: ctx.model.maxTokens } : undefined,
334
352
  } : undefined;
335
353
  });
336
354
  pi.on("agent_settled", (_event, ctx) => {
337
355
  try {
338
356
  if (standDown(ctx) || !lengthStop || !active())
339
357
  return;
340
- const { kind, cacheMiss } = lengthStop;
341
- const message = kind === "thinking"
342
- ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
343
- : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
358
+ const { kind, cacheMiss, cap } = lengthStop;
359
+ // A thinking-only stop exactly at the configured cap: the cap itself, not the context, ended the reply.
360
+ const message = kind === "thinking" && cap ? capStopNotice(cap.model, cap.maxTokens, modelsPath())
361
+ : kind === "thinking"
362
+ ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
363
+ : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
344
364
  lengthStop = undefined;
345
- notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
365
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + (cap && kind === "thinking" ? "" : INCIDENT_HINT), "warning");
346
366
  }
347
367
  finally {
348
368
  resetRun();
@@ -370,9 +390,14 @@ export async function installCompaction(pi, options = {}) {
370
390
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
371
391
  let floorMinimum = 1;
372
392
  const limits = (ctx) => {
373
- const response = responseReserve(ctx), room = inputRoom(response, ctx);
374
- const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
375
- const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
393
+ const reserve = responseReserve(ctx);
394
+ const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
395
+ // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: Pi gives a request
396
+ // min(maxTokens, window - input - margin), so the room is window - margin - raised. Admission (floor, hard line) stays as without a
397
+ // stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
398
+ const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
399
+ const response = raised === undefined ? reserve : Math.max(reserve, raised + piMargin), room = inputRoom(response, ctx);
400
+ const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
376
401
  return { response, room, hardLine, replyFloor: floor };
377
402
  };
378
403
  const preservePrefix = (ctx) => ctx.model !== undefined &&
@@ -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 = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -29,6 +29,10 @@ export declare const CUT_REPLY_FLOOR = 3584;
29
29
  /** Ordinary reply demand is bounded by the reserve and model output limit.
30
30
  * Recovery compares its candidate against the interrupted attempt separately. */
31
31
  export declare function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, model: ReplyModel, minimum?: number): number;
32
+ /** Reply room after a length stop on this branch (1.7.0): twice the largest stopped output of this model, bounded by its maxTokens instead of
33
+ * the reserve, and by half of what Pi can give a request (so a small window keeps room for the conversation). Undefined with no length stop:
34
+ * then nothing changes. Read from the branch only; nothing carries across sessions. */
35
+ export declare function stoppedReplyRoom(branch: readonly SessionEntry[], model: ReplyModel, window: number, margin: number): number | undefined;
32
36
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
33
37
  export declare function carriesPrompt(messages: Messages, prompt: string, role?: 'user' | 'custom'): boolean;
34
38
  export {};
@@ -83,6 +83,26 @@ export function requestReplyFloor(branch, reserve, model, minimum = 1) {
83
83
  }
84
84
  return Math.min(limit, Math.ceil(largest));
85
85
  }
86
+ /** Reply room after a length stop on this branch (1.7.0): twice the largest stopped output of this model, bounded by its maxTokens instead of
87
+ * the reserve, and by half of what Pi can give a request (so a small window keeps room for the conversation). Undefined with no length stop:
88
+ * then nothing changes. Read from the branch only; nothing carries across sessions. */
89
+ export function stoppedReplyRoom(branch, model, window, margin) {
90
+ let largest = 0;
91
+ for (const entry of branch) {
92
+ if (entry.type !== 'message' || entry.message.role !== 'assistant')
93
+ continue;
94
+ const message = entry.message;
95
+ if (message.stopReason !== 'length' || message.model !== model.id || message.provider !== model.provider || message.api !== model.api)
96
+ continue;
97
+ const output = message.usage?.output;
98
+ if (typeof output === 'number' && Number.isFinite(output) && output > largest)
99
+ largest = output;
100
+ }
101
+ if (largest <= 0)
102
+ return undefined;
103
+ const raised = Math.ceil(2 * largest), cap = model.maxTokens > 0 ? model.maxTokens : raised;
104
+ return Math.max(1, Math.min(raised, cap, Math.floor((window - margin) / 2)));
105
+ }
86
106
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
87
107
  export function carriesPrompt(messages, prompt, role = 'user') {
88
108
  if (!prompt.length)
@@ -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.7.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 = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
package/src/compaction.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
3
- import { CUT_REPLY_FLOOR, requestReplyFloor, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
8
10
  import { exportSource } from "./source-export.js";
9
11
  import { isDeepStrictEqual } from "node:util";
10
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
@@ -13,7 +15,7 @@ import { applyClips, clipBudgets, clipFor, type Clip } from "./clip.js";
13
15
  import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
14
16
  type AgentMessage, type Decision, type Messages, type Plan, type Target } from "./budget.js";
15
17
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext, type ImageContent, type ToolResultMessage } from "@earendil-works/pi-ai";
16
- import { calculateContextTokens, convertToLlm, estimateTokens, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
18
+ import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
17
19
  import { Type } from "typebox";
18
20
  import { Check } from "typebox/value";
19
21
  import type { RecallPolicy } from "./recall.js";
@@ -62,6 +64,18 @@ export const overflowNotice = (contextWindow: number, bound: number, learned: bo
62
64
  `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
63
65
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
64
66
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
67
+ /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
68
+ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
69
+ `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
70
+ `The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
71
+ "The unfinished response is saved in the session.";
72
+ /** Pi's models.json, shown with ~ for the home folder. */
73
+ function modelsPath(): string {
74
+ try {
75
+ const path = join(getAgentDir(), "models.json"), home = homedir();
76
+ return path.startsWith(home + "/") ? "~" + path.slice(home.length) : path;
77
+ } catch { return "~/.pi/agent/models.json"; }
78
+ }
65
79
  export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
66
80
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
67
81
  export const CALIBRATION_CEILING = 1.5;
@@ -297,7 +311,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
297
311
  });
298
312
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
299
313
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
300
- let lengthStop: { kind: "thinking" | "output"; cacheMiss: boolean } | undefined;
314
+ let lengthStop: { kind: "thinking" | "output"; cacheMiss: boolean; cap?: { model: string; maxTokens: number } } | undefined;
301
315
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted"); lengthStop = undefined; calibration.pending = undefined; });
302
316
  // Pi's overflow-recovery rule: a new user message or a good reply grants another recovery.
303
317
  const rearmLengthRetry = (ctx: ExtensionContext) => {
@@ -310,17 +324,21 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
310
324
  lengthStop = event.message.stopReason === "length" ? {
311
325
  kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
312
326
  cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
327
+ cap: ctx.model && ctx.model.maxTokens > 0 && event.message.usage?.output === ctx.model.maxTokens
328
+ ? { model: `${ctx.model.provider}/${ctx.model.id}`, maxTokens: ctx.model.maxTokens } : undefined,
313
329
  } : undefined;
314
330
  });
315
331
  pi.on("agent_settled", (_event, ctx) => {
316
332
  try {
317
333
  if (standDown(ctx) || !lengthStop || !active()) return;
318
- const { kind, cacheMiss } = lengthStop;
319
- const message = kind === "thinking"
334
+ const { kind, cacheMiss, cap } = lengthStop;
335
+ // A thinking-only stop exactly at the configured cap: the cap itself, not the context, ended the reply.
336
+ const message = kind === "thinking" && cap ? capStopNotice(cap.model, cap.maxTokens, modelsPath())
337
+ : kind === "thinking"
320
338
  ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
321
339
  : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
322
340
  lengthStop = undefined;
323
- notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
341
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + (cap && kind === "thinking" ? "" : INCIDENT_HINT), "warning");
324
342
  } finally { resetRun(); }
325
343
  });
326
344
  const active = () => options.active?.() ?? true;
@@ -345,9 +363,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
345
363
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
346
364
  let floorMinimum = 1;
347
365
  const limits = (ctx: ExtensionContext) => {
348
- const response = responseReserve(ctx), room = inputRoom(response, ctx);
349
- const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
350
- const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
366
+ const reserve = responseReserve(ctx);
367
+ const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
368
+ // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: Pi gives a request
369
+ // min(maxTokens, window - input - margin), so the room is window - margin - raised. Admission (floor, hard line) stays as without a
370
+ // stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
371
+ const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
372
+ const response = raised === undefined ? reserve : Math.max(reserve, raised + piMargin), room = inputRoom(response, ctx);
373
+ const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
351
374
  return { response, room, hardLine, replyFloor: floor };
352
375
  };
353
376
  const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
@@ -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
+ }
@@ -79,6 +79,23 @@ export function requestReplyFloor(branch: readonly SessionEntry[], reserve: numb
79
79
  return Math.min(limit, Math.ceil(largest));
80
80
  }
81
81
 
82
+ /** Reply room after a length stop on this branch (1.7.0): twice the largest stopped output of this model, bounded by its maxTokens instead of
83
+ * the reserve, and by half of what Pi can give a request (so a small window keeps room for the conversation). Undefined with no length stop:
84
+ * then nothing changes. Read from the branch only; nothing carries across sessions. */
85
+ export function stoppedReplyRoom(branch: readonly SessionEntry[], model: ReplyModel, window: number, margin: number): number | undefined {
86
+ let largest = 0;
87
+ for (const entry of branch) {
88
+ if (entry.type !== 'message' || entry.message.role !== 'assistant') continue;
89
+ const message = entry.message;
90
+ if (message.stopReason !== 'length' || message.model !== model.id || message.provider !== model.provider || message.api !== model.api) continue;
91
+ const output = message.usage?.output;
92
+ if (typeof output === 'number' && Number.isFinite(output) && output > largest) largest = output;
93
+ }
94
+ if (largest <= 0) return undefined;
95
+ const raised = Math.ceil(2 * largest), cap = model.maxTokens > 0 ? model.maxTokens : raised;
96
+ return Math.max(1, Math.min(raised, cap, Math.floor((window - margin) / 2)));
97
+ }
98
+
82
99
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
83
100
  export function carriesPrompt(messages: Messages, prompt: string, role: 'user' | 'custom' = 'user'): boolean {
84
101
  if (!prompt.length) return true;
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
  }