pi-tuck 1.6.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,16 @@
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
+
6
16
  ## [1.6.0]
7
17
 
8
18
  ### Added
package/README.md CHANGED
@@ -71,7 +71,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
71
71
 
72
72
  ## Output exhaustion and small windows
73
73
 
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.
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.
75
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.
76
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.
77
77
 
@@ -1 +1 @@
1
- export declare const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
1
+ export declare const BUILD_ID = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
@@ -1 +1 @@
1
- export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
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 &&
@@ -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 = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
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)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.6.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 = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
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 &&
@@ -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;