pi-tuck 1.10.5 → 1.11.1
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 +20 -0
- package/README.md +2 -2
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +9 -0
- package/dist/src/compaction.js +67 -11
- package/dist/src/config-check.d.ts +6 -0
- package/dist/src/config-check.js +13 -2
- package/dist/src/request-capacity.d.ts +6 -0
- package/dist/src/request-capacity.js +30 -0
- package/package.json +1 -1
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +59 -11
- package/src/config-check.ts +12 -2
- package/src/request-capacity.ts +21 -0
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,26 @@
|
|
|
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.11.1]
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- Reply room under Pi 1.7: Pi 1.7 keeps a safety margin of 15% of the input (at least 4,096 tokens) while that still leaves 32,768 output
|
|
11
|
+
tokens. pi-tuck assumed a fixed 4,096, so at long context with a model allowing more than 32,768 output tokens it planned more reply
|
|
12
|
+
room than Pi gives (for example 128,000 instead of 80,000 at 800,000 input in a 1M window). pi-tuck now asks Pi's own limit, at the
|
|
13
|
+
input size in question, how much input still leaves a given reply, wherever it planned with the fixed margin. Under earlier Pi
|
|
14
|
+
versions, and for any model allowing at most 32,768 output tokens, nothing changes.
|
|
15
|
+
|
|
16
|
+
## [1.11.0]
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Act-now turn: on a Chat Completions model, the request that asks the model to act after a thinking-only stop now goes out at the lowest
|
|
21
|
+
thinking effort the server lists (read from its model list at session start; sent top level and in the chat template arguments if Pi sends
|
|
22
|
+
one there) and with at most 20,480 output tokens, above the largest real reply seen on the founder's server. Before, it ran at the
|
|
23
|
+
session's effort and often thought itself into the same stall again. Other requests and other APIs are unchanged. A stop at that
|
|
24
|
+
smaller cap counts as a full-cap stop, so it gets the next act-now turn rather than a length retry.
|
|
25
|
+
|
|
6
26
|
## [1.10.5]
|
|
7
27
|
|
|
8
28
|
### Fixed
|
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.
|
|
15
|
+
This README describes pi-tuck 1.11.1. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.11.1` or `pi install git:github.com/galyavin/pi-tuck@v1.11.1`. To uninstall, run `pi remove` with the source you installed.
|
|
16
16
|
|
|
17
17
|
## Compaction and recall
|
|
18
18
|
|
|
@@ -75,7 +75,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
|
|
|
75
75
|
|
|
76
76
|
## Output exhaustion and small windows
|
|
77
77
|
|
|
78
|
-
- 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). When such a stop is not retried, pi-tuck queues one more user turn asking the model to act: "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning." The stopped reply stays saved but leaves that request's context. At most two such turns go out in a row until a reply finishes, and only when the request fits and no message is already queued; if the second also stops, the notice below stands. 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.
|
|
78
|
+
- 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). When such a stop is not retried, pi-tuck queues one more user turn asking the model to act: "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning." The stopped reply stays saved but leaves that request's context. On a Chat Completions model, that request alone goes out at the lowest thinking effort the server lists (pi-tuck reads the list at session start) and with at most 20,480 output tokens; a stop at that cap counts as a full-cap stop. At most two such turns go out in a row until a reply finishes, and only when the request fits and no message is already queued; if the second also stops, the notice below stands. 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.
|
|
79
79
|
- 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.
|
|
80
80
|
- 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.
|
|
81
81
|
|
package/dist/src/build-id.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const BUILD_ID = "
|
|
1
|
+
export declare const BUILD_ID = "952cfaf4cfce60b5ffa289b3838d6aa5e2649ba9997c52a144a2b91130c2dae6";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "952cfaf4cfce60b5ffa289b3838d6aa5e2649ba9997c52a144a2b91130c2dae6";
|
package/dist/src/compaction.d.ts
CHANGED
|
@@ -11,6 +11,15 @@ export declare const overflowNotice: (contextWindow: number, bound: number, lear
|
|
|
11
11
|
export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
|
|
12
12
|
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
13
13
|
export declare const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
14
|
+
/** The act-now request's reply cap: above the largest real reply seen on mac-studio (18.6k tokens in 476 replies), well under the 32k-65k caps
|
|
15
|
+
* a thinking runaway fills. */
|
|
16
|
+
export declare const ACT_NOW_MAX_TOKENS = 20480;
|
|
17
|
+
/** The act-now request, rewritten (Chat Completions payloads only): the lowest effort the server lists, top level (where vLLM-style servers
|
|
18
|
+
* read it) and in chat_template_kwargs if Pi sent one there, and an output cap of at most ACT_NOW_MAX_TOKENS. Undefined for any other request. */
|
|
19
|
+
export declare function actNowPayload(payload: unknown, effort: string | undefined): {
|
|
20
|
+
payload: Record<string, unknown>;
|
|
21
|
+
cap?: number;
|
|
22
|
+
} | undefined;
|
|
14
23
|
/** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
|
|
15
24
|
* or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
|
|
16
25
|
export declare function actNowsInARow(branch: readonly SessionEntry[]): number;
|
package/dist/src/compaction.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { textOf } from "./tuck/core/content.js";
|
|
2
2
|
import { PendingCut, StartingPrompt, Run } from "./run.js";
|
|
3
|
-
import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
|
|
3
|
+
import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, piInputFor, loadPiRequestMath } from "./request-capacity.js";
|
|
4
4
|
import { BUILD_ID } from "./build-id.js";
|
|
5
|
+
import { lowestEffort, pendingCheck, serverEfforts } from "./config-check.js";
|
|
5
6
|
import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
|
|
6
7
|
import { createHash } from "node:crypto";
|
|
7
8
|
import { readFileSync } from "node:fs";
|
|
@@ -68,6 +69,35 @@ export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used
|
|
|
68
69
|
"The unfinished response is saved in the session.";
|
|
69
70
|
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
70
71
|
export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
72
|
+
/** The act-now request's reply cap: above the largest real reply seen on mac-studio (18.6k tokens in 476 replies), well under the 32k-65k caps
|
|
73
|
+
* a thinking runaway fills. */
|
|
74
|
+
export const ACT_NOW_MAX_TOKENS = 20_480;
|
|
75
|
+
/** The act-now request, rewritten (Chat Completions payloads only): the lowest effort the server lists, top level (where vLLM-style servers
|
|
76
|
+
* read it) and in chat_template_kwargs if Pi sent one there, and an output cap of at most ACT_NOW_MAX_TOKENS. Undefined for any other request. */
|
|
77
|
+
export function actNowPayload(payload, effort) {
|
|
78
|
+
const body = payload;
|
|
79
|
+
const messages = body?.messages;
|
|
80
|
+
if (!Array.isArray(messages))
|
|
81
|
+
return undefined;
|
|
82
|
+
const last = messages.at(-1);
|
|
83
|
+
const text = typeof last?.content === "string" ? last.content
|
|
84
|
+
: Array.isArray(last?.content) ? last.content.map(part => part?.type === "text" ? String(part.text) : "").join("") : undefined;
|
|
85
|
+
if (last?.role !== "user" || text !== ACT_NOW)
|
|
86
|
+
return undefined;
|
|
87
|
+
const out = { ...body };
|
|
88
|
+
let cap;
|
|
89
|
+
for (const field of ["max_tokens", "max_completion_tokens"]) {
|
|
90
|
+
if (typeof out[field] === "number")
|
|
91
|
+
cap = out[field] = Math.min(out[field], ACT_NOW_MAX_TOKENS);
|
|
92
|
+
}
|
|
93
|
+
if (effort) {
|
|
94
|
+
out.reasoning_effort = effort;
|
|
95
|
+
const kwargs = out.chat_template_kwargs;
|
|
96
|
+
if (kwargs && typeof kwargs === "object" && "reasoning_effort" in kwargs)
|
|
97
|
+
out.chat_template_kwargs = { ...kwargs, reasoning_effort: effort };
|
|
98
|
+
}
|
|
99
|
+
return { payload: out, cap };
|
|
100
|
+
}
|
|
71
101
|
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
|
|
72
102
|
const ACT_NOW_LIMIT = 2;
|
|
73
103
|
/** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
|
|
@@ -179,6 +209,18 @@ export async function installCompaction(pi, options = {}) {
|
|
|
179
209
|
const piMath = await loadPiRequestMath();
|
|
180
210
|
const piMargin = options.requestReserve ? 0 : await piContextSafetyMargin(piMath);
|
|
181
211
|
const piClamp = piMath?.clampMaxTokensToContext;
|
|
212
|
+
// The largest input Pi still gives `reply` tokens (Pi 1.7's margin grows with the input). A host reserve keeps the fixed arithmetic.
|
|
213
|
+
const inputCache = new Map();
|
|
214
|
+
const inputFor = (ctx, reply) => {
|
|
215
|
+
const window = contextWindow(ctx), key = `${window}:${reply}`;
|
|
216
|
+
let input = inputCache.get(key);
|
|
217
|
+
if (input === undefined) {
|
|
218
|
+
if (inputCache.size > 256)
|
|
219
|
+
inputCache.clear();
|
|
220
|
+
inputCache.set(key, input = piInputFor(options.requestReserve ? undefined : piMath, window, reply, piMargin));
|
|
221
|
+
}
|
|
222
|
+
return input;
|
|
223
|
+
};
|
|
182
224
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
183
225
|
if (!validCutAt(cutAt))
|
|
184
226
|
throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
@@ -353,6 +395,20 @@ export async function installCompaction(pi, options = {}) {
|
|
|
353
395
|
if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
|
|
354
396
|
run?.rearmLengthRetry();
|
|
355
397
|
};
|
|
398
|
+
// The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. The cap sent is kept: a stop
|
|
399
|
+
// at it is a full-cap stop, not a squeezed one.
|
|
400
|
+
let actNowCap;
|
|
401
|
+
pi.on("before_provider_request", async (event, ctx) => {
|
|
402
|
+
const model = ctx.model;
|
|
403
|
+
if (model?.api !== "openai-completions" || !actNowPayload(event.payload, undefined)) {
|
|
404
|
+
actNowCap = undefined;
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
await pendingCheck;
|
|
408
|
+
const rewritten = actNowPayload(event.payload, lowestEffort(serverEfforts.get(`${model.provider}/${model.id}`)));
|
|
409
|
+
actNowCap = rewritten.cap;
|
|
410
|
+
return rewritten.payload;
|
|
411
|
+
});
|
|
356
412
|
// The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
|
|
357
413
|
pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW)
|
|
358
414
|
rearmLengthRetry(ctx); });
|
|
@@ -409,13 +465,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
409
465
|
const limits = (ctx) => {
|
|
410
466
|
const reserve = responseReserve(ctx);
|
|
411
467
|
const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
|
|
412
|
-
// After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math:
|
|
413
|
-
//
|
|
468
|
+
// After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: the room is the largest input
|
|
469
|
+
// Pi still gives the raised reply (window - margin - raised under a fixed margin). Admission (floor, hard line) stays as without a
|
|
414
470
|
// stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
|
|
415
471
|
const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
|
|
416
|
-
const response = raised === undefined ? reserve : Math.max(reserve,
|
|
417
|
-
const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve,
|
|
418
|
-
return { response, room, hardLine, replyFloor: floor };
|
|
472
|
+
const response = raised === undefined ? reserve : Math.max(reserve, contextWindow(ctx) - inputFor(ctx, raised)), room = inputRoom(response, ctx);
|
|
473
|
+
const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, inputFor(ctx, floor)), calibration.lastCeiling ?? Infinity);
|
|
474
|
+
return { response, room, hardLine, replyFloor: floor, want: Math.max(reserve - piMargin, raised ?? -Infinity) };
|
|
419
475
|
};
|
|
420
476
|
const preservePrefix = (ctx) => ctx.model !== undefined &&
|
|
421
477
|
options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
|
|
@@ -423,7 +479,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
423
479
|
// Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
|
|
424
480
|
// to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
|
|
425
481
|
// Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
|
|
426
|
-
// room:
|
|
482
|
+
// room: the largest input Pi still gives the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
|
|
427
483
|
// sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
|
|
428
484
|
const triggerLine = (ctx, room) => {
|
|
429
485
|
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
|
|
@@ -433,7 +489,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
433
489
|
return undefined;
|
|
434
490
|
const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
|
|
435
491
|
const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
|
|
436
|
-
const cap = Math.min(hardLine,
|
|
492
|
+
const cap = Math.min(hardLine, inputFor(ctx, reply)) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
437
493
|
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
438
494
|
};
|
|
439
495
|
// Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
|
|
@@ -554,7 +610,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
554
610
|
return lastAttempt();
|
|
555
611
|
// Shrink in the planner's units by Pi's measured shortfall, at most three times. Once we reach the original room,
|
|
556
612
|
// use its existing band/room policy; admission below the room is deliberately unchanged.
|
|
557
|
-
target = Math.max(room, Math.floor(target * (
|
|
613
|
+
target = Math.max(room, Math.floor(target * inputFor(ctx, limits(ctx).replyFloor) / check.estimate));
|
|
558
614
|
decision = replan(target);
|
|
559
615
|
if (decision.kind === "defer" || decision.kind === "fault")
|
|
560
616
|
return lastAttempt();
|
|
@@ -1197,7 +1253,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1197
1253
|
const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
|
|
1198
1254
|
const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
|
|
1199
1255
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1200
|
-
const {
|
|
1256
|
+
const { want, room } = limits(ctx), band = decisionBand(ctx, room);
|
|
1201
1257
|
let target = room;
|
|
1202
1258
|
for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
|
|
1203
1259
|
const targetBand = target === room ? band : target;
|
|
@@ -1232,7 +1288,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1232
1288
|
if (event.message.role !== "assistant" || !ctx.model)
|
|
1233
1289
|
return;
|
|
1234
1290
|
const stoppedOutput = event.message.usage?.output;
|
|
1235
|
-
if (stoppedOutput >= ctx.model.maxTokens) {
|
|
1291
|
+
if (stoppedOutput >= (actNowCap ?? ctx.model.maxTokens)) {
|
|
1236
1292
|
return { entries: event.entries, continue: false };
|
|
1237
1293
|
}
|
|
1238
1294
|
// Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
|
|
@@ -12,6 +12,12 @@ export interface ServerModel {
|
|
|
12
12
|
window?: number;
|
|
13
13
|
efforts?: string[];
|
|
14
14
|
}
|
|
15
|
+
/** The lowest ranked effort a server lists, or undefined. */
|
|
16
|
+
export declare const lowestEffort: (efforts: readonly string[] | undefined) => string | undefined;
|
|
17
|
+
/** The efforts each provider/model's server listed at this process's check; the act-now request reads them. */
|
|
18
|
+
export declare const serverEfforts: globalThis.Map<string, string[]>;
|
|
19
|
+
/** This process's check while it runs; the act-now request waits for it rather than go out without the efforts. */
|
|
20
|
+
export declare let pendingCheck: Promise<void> | undefined;
|
|
15
21
|
export declare function serverModel(body: unknown, id: string): ServerModel | undefined;
|
|
16
22
|
export interface Finding {
|
|
17
23
|
kind: "window" | "thinking";
|
package/dist/src/config-check.js
CHANGED
|
@@ -9,6 +9,14 @@ import { join } from "node:path";
|
|
|
9
9
|
export const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
|
|
10
10
|
/** Pi's thinking levels that a server can list; "off" is never a server effort. */
|
|
11
11
|
const LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
|
|
12
|
+
/** Server efforts from low to high, for the names pi-tuck can rank; "none" and "off" turn thinking off and are never picked. */
|
|
13
|
+
const EFFORT_RANK = ["xlow", "minimal", "low", "medium", "xmedium", "high", "xhigh", "max"];
|
|
14
|
+
/** The lowest ranked effort a server lists, or undefined. */
|
|
15
|
+
export const lowestEffort = (efforts) => EFFORT_RANK.find(e => efforts?.includes(e));
|
|
16
|
+
/** The efforts each provider/model's server listed at this process's check; the act-now request reads them. */
|
|
17
|
+
export const serverEfforts = new Map();
|
|
18
|
+
/** This process's check while it runs; the act-now request waits for it rather than go out without the efforts. */
|
|
19
|
+
export let pendingCheck;
|
|
12
20
|
export function serverModel(body, id) {
|
|
13
21
|
const data = body?.data;
|
|
14
22
|
const entry = Array.isArray(data) ? data.find(m => m?.id === id) : undefined;
|
|
@@ -157,7 +165,10 @@ export async function checkModel(pi, ctx, deps) {
|
|
|
157
165
|
const server = serverModel(await response.json(), model.id);
|
|
158
166
|
if (!server)
|
|
159
167
|
return;
|
|
160
|
-
const ref = `${model.provider}/${model.id}
|
|
168
|
+
const ref = `${model.provider}/${model.id}`;
|
|
169
|
+
if (server.efforts)
|
|
170
|
+
serverEfforts.set(ref, server.efforts);
|
|
171
|
+
const no = declined(settingsPath)[ref] ?? {};
|
|
161
172
|
const open = findings(model, server).filter(f => no[f.kind] !== f.server);
|
|
162
173
|
if (!open.length)
|
|
163
174
|
return;
|
|
@@ -191,6 +202,6 @@ export function installConfigCheck(pi, deps) {
|
|
|
191
202
|
if (done)
|
|
192
203
|
return;
|
|
193
204
|
done = true;
|
|
194
|
-
|
|
205
|
+
pendingCheck = checkModel(pi, ctx, deps).finally(() => { pendingCheck = undefined; });
|
|
195
206
|
});
|
|
196
207
|
}
|
|
@@ -16,6 +16,12 @@ export declare function loadPiRequestMath(): Promise<PiRequestMath | undefined>;
|
|
|
16
16
|
* Without Pi's request arithmetic, fall back to Pi 1.2–1.5's documented 4,096-token allowance.
|
|
17
17
|
*/
|
|
18
18
|
export declare function piContextSafetyMargin(math?: PiRequestMath): Promise<number>;
|
|
19
|
+
/** The largest input Pi still gives a reply of `reply` tokens, read from Pi's own clamp rather than a copied formula. Pi 1.2-1.6 keep a fixed
|
|
20
|
+
* margin, so this is window - margin - reply. Pi 1.7 keeps 15% of the input while that leaves 32,768 output, so at long context with a large
|
|
21
|
+
* maxTokens it is lower. The clamp only reads the window and the estimate, and an estimate is a reply's usage plus what follows it, so a
|
|
22
|
+
* context of one assistant reply whose usage is `input` asks Pi about any input size. Pi's cap never grows with the input, so search.
|
|
23
|
+
* Without Pi's request arithmetic: window - margin - reply. */
|
|
24
|
+
export declare function piInputFor(math: PiRequestMath | undefined, window: number, reply: number, margin: number): number;
|
|
19
25
|
/** A length stop with visible reasoning but no visible answer or work. */
|
|
20
26
|
export declare const thinkingOnlyLength: (message: AgentMessage) => boolean;
|
|
21
27
|
type ReplyModel = {
|
|
@@ -56,6 +56,36 @@ export async function piContextSafetyMargin(math) {
|
|
|
56
56
|
return 4_096;
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
+
/** The largest input Pi still gives a reply of `reply` tokens, read from Pi's own clamp rather than a copied formula. Pi 1.2-1.6 keep a fixed
|
|
60
|
+
* margin, so this is window - margin - reply. Pi 1.7 keeps 15% of the input while that leaves 32,768 output, so at long context with a large
|
|
61
|
+
* maxTokens it is lower. The clamp only reads the window and the estimate, and an estimate is a reply's usage plus what follows it, so a
|
|
62
|
+
* context of one assistant reply whose usage is `input` asks Pi about any input size. Pi's cap never grows with the input, so search.
|
|
63
|
+
* Without Pi's request arithmetic: window - margin - reply. */
|
|
64
|
+
export function piInputFor(math, window, reply, margin) {
|
|
65
|
+
const fixed = window - margin - reply;
|
|
66
|
+
if (!math || !(window > 0) || !Number.isSafeInteger(window))
|
|
67
|
+
return fixed;
|
|
68
|
+
const cap = (input) => math.clampMaxTokensToContext({ contextWindow: window, maxTokens: window }, { messages: [{ role: 'assistant', content: [], api: 'openai-completions', provider: 'pi-tuck', model: 'probe', stopReason: 'stop', timestamp: 0,
|
|
69
|
+
usage: { input, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: input, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }] }, window);
|
|
70
|
+
// Pi's cap bottoms out at one token even past the window; a cap counts only while it fits beside the fixed margin.
|
|
71
|
+
const gives = (input) => { const c = cap(input); return c >= reply && input + margin + c <= window; };
|
|
72
|
+
try {
|
|
73
|
+
if (!gives(0))
|
|
74
|
+
return fixed;
|
|
75
|
+
let low = 0, high = window;
|
|
76
|
+
while (low < high) {
|
|
77
|
+
const mid = Math.ceil((low + high) / 2);
|
|
78
|
+
if (gives(mid))
|
|
79
|
+
low = mid;
|
|
80
|
+
else
|
|
81
|
+
high = mid - 1;
|
|
82
|
+
}
|
|
83
|
+
return low;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return fixed;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
59
89
|
/** A length stop with visible reasoning but no visible answer or work. */
|
|
60
90
|
export const thinkingOnlyLength = (message) => message.role === 'assistant' && message.stopReason === 'length' &&
|
|
61
91
|
message.content.length > 0 && message.content.every(block => block.type === 'thinking');
|
package/package.json
CHANGED
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "952cfaf4cfce60b5ffa289b3838d6aa5e2649ba9997c52a144a2b91130c2dae6";
|
package/src/compaction.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
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, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
|
|
3
|
+
import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, piInputFor, loadPiRequestMath } from "./request-capacity.js";
|
|
4
4
|
import { BUILD_ID } from "./build-id.js";
|
|
5
|
+
import { lowestEffort, pendingCheck, serverEfforts } from "./config-check.js";
|
|
5
6
|
import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
|
|
6
7
|
import { createHash } from "node:crypto";
|
|
7
8
|
import { readFileSync } from "node:fs";
|
|
@@ -71,6 +72,31 @@ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
|
|
|
71
72
|
"The unfinished response is saved in the session.";
|
|
72
73
|
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
73
74
|
export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
75
|
+
/** The act-now request's reply cap: above the largest real reply seen on mac-studio (18.6k tokens in 476 replies), well under the 32k-65k caps
|
|
76
|
+
* a thinking runaway fills. */
|
|
77
|
+
export const ACT_NOW_MAX_TOKENS = 20_480;
|
|
78
|
+
/** The act-now request, rewritten (Chat Completions payloads only): the lowest effort the server lists, top level (where vLLM-style servers
|
|
79
|
+
* read it) and in chat_template_kwargs if Pi sent one there, and an output cap of at most ACT_NOW_MAX_TOKENS. Undefined for any other request. */
|
|
80
|
+
export function actNowPayload(payload: unknown, effort: string | undefined): { payload: Record<string, unknown>; cap?: number } | undefined {
|
|
81
|
+
const body = payload as Record<string, unknown> | null;
|
|
82
|
+
const messages = body?.messages;
|
|
83
|
+
if (!Array.isArray(messages)) return undefined;
|
|
84
|
+
const last = messages.at(-1) as { role?: unknown; content?: unknown } | undefined;
|
|
85
|
+
const text = typeof last?.content === "string" ? last.content
|
|
86
|
+
: Array.isArray(last?.content) ? last.content.map(part => (part as { type?: unknown; text?: unknown })?.type === "text" ? String((part as { text: unknown }).text) : "").join("") : undefined;
|
|
87
|
+
if (last?.role !== "user" || text !== ACT_NOW) return undefined;
|
|
88
|
+
const out: Record<string, unknown> = { ...body };
|
|
89
|
+
let cap: number | undefined;
|
|
90
|
+
for (const field of ["max_tokens", "max_completion_tokens"]) {
|
|
91
|
+
if (typeof out[field] === "number") cap = out[field] = Math.min(out[field] as number, ACT_NOW_MAX_TOKENS);
|
|
92
|
+
}
|
|
93
|
+
if (effort) {
|
|
94
|
+
out.reasoning_effort = effort;
|
|
95
|
+
const kwargs = out.chat_template_kwargs as Record<string, unknown> | undefined;
|
|
96
|
+
if (kwargs && typeof kwargs === "object" && "reasoning_effort" in kwargs) out.chat_template_kwargs = { ...kwargs, reasoning_effort: effort };
|
|
97
|
+
}
|
|
98
|
+
return { payload: out, cap };
|
|
99
|
+
}
|
|
74
100
|
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
|
|
75
101
|
const ACT_NOW_LIMIT = 2;
|
|
76
102
|
/** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
|
|
@@ -200,6 +226,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
200
226
|
const piMath = await loadPiRequestMath();
|
|
201
227
|
const piMargin = options.requestReserve ? 0 : await piContextSafetyMargin(piMath);
|
|
202
228
|
const piClamp = piMath?.clampMaxTokensToContext;
|
|
229
|
+
// The largest input Pi still gives `reply` tokens (Pi 1.7's margin grows with the input). A host reserve keeps the fixed arithmetic.
|
|
230
|
+
const inputCache = new Map<string, number>();
|
|
231
|
+
const inputFor = (ctx: ExtensionContext, reply: number) => {
|
|
232
|
+
const window = contextWindow(ctx), key = `${window}:${reply}`;
|
|
233
|
+
let input = inputCache.get(key);
|
|
234
|
+
if (input === undefined) {
|
|
235
|
+
if (inputCache.size > 256) inputCache.clear();
|
|
236
|
+
inputCache.set(key, input = piInputFor(options.requestReserve ? undefined : piMath, window, reply, piMargin));
|
|
237
|
+
}
|
|
238
|
+
return input;
|
|
239
|
+
};
|
|
203
240
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
204
241
|
if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
205
242
|
const view = (ctx: ExtensionContext, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
|
|
@@ -330,6 +367,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
330
367
|
const rearmLengthRetry = (ctx: ExtensionContext) => {
|
|
331
368
|
if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
|
|
332
369
|
};
|
|
370
|
+
// The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. The cap sent is kept: a stop
|
|
371
|
+
// at it is a full-cap stop, not a squeezed one.
|
|
372
|
+
let actNowCap: number | undefined;
|
|
373
|
+
pi.on("before_provider_request", async (event, ctx) => {
|
|
374
|
+
const model = ctx.model;
|
|
375
|
+
if (model?.api !== "openai-completions" || !actNowPayload(event.payload, undefined)) { actNowCap = undefined; return undefined; }
|
|
376
|
+
await pendingCheck;
|
|
377
|
+
const rewritten = actNowPayload(event.payload, lowestEffort(serverEfforts.get(`${model.provider}/${model.id}`)))!;
|
|
378
|
+
actNowCap = rewritten.cap;
|
|
379
|
+
return rewritten.payload;
|
|
380
|
+
});
|
|
333
381
|
// The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
|
|
334
382
|
pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW) rearmLengthRetry(ctx); });
|
|
335
383
|
pi.on("message_end", (event, ctx) => {
|
|
@@ -379,13 +427,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
379
427
|
const limits = (ctx: ExtensionContext) => {
|
|
380
428
|
const reserve = responseReserve(ctx);
|
|
381
429
|
const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
|
|
382
|
-
// After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math:
|
|
383
|
-
//
|
|
430
|
+
// After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: the room is the largest input
|
|
431
|
+
// Pi still gives the raised reply (window - margin - raised under a fixed margin). Admission (floor, hard line) stays as without a
|
|
384
432
|
// stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
|
|
385
433
|
const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
|
|
386
|
-
const response = raised === undefined ? reserve : Math.max(reserve,
|
|
387
|
-
const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve,
|
|
388
|
-
return { response, room, hardLine, replyFloor: floor };
|
|
434
|
+
const response = raised === undefined ? reserve : Math.max(reserve, contextWindow(ctx) - inputFor(ctx, raised)), room = inputRoom(response, ctx);
|
|
435
|
+
const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, inputFor(ctx, floor)), calibration.lastCeiling ?? Infinity);
|
|
436
|
+
return { response, room, hardLine, replyFloor: floor, want: Math.max(reserve - piMargin, raised ?? -Infinity) };
|
|
389
437
|
};
|
|
390
438
|
const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
|
|
391
439
|
options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
|
|
@@ -393,7 +441,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
393
441
|
// Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
|
|
394
442
|
// to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
|
|
395
443
|
// Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
|
|
396
|
-
// room:
|
|
444
|
+
// room: the largest input Pi still gives the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
|
|
397
445
|
// sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
|
|
398
446
|
const triggerLine = (ctx: ExtensionContext, room: number): number | undefined => {
|
|
399
447
|
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
|
|
@@ -401,7 +449,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
401
449
|
if (!thrashing(branch)) return undefined;
|
|
402
450
|
const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
|
|
403
451
|
const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
|
|
404
|
-
const cap = Math.min(hardLine,
|
|
452
|
+
const cap = Math.min(hardLine, inputFor(ctx, reply)) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
405
453
|
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
406
454
|
};
|
|
407
455
|
// Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
|
|
@@ -506,7 +554,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
506
554
|
if (retry === 3) return lastAttempt();
|
|
507
555
|
// Shrink in the planner's units by Pi's measured shortfall, at most three times. Once we reach the original room,
|
|
508
556
|
// use its existing band/room policy; admission below the room is deliberately unchanged.
|
|
509
|
-
target = Math.max(room, Math.floor(target * (
|
|
557
|
+
target = Math.max(room, Math.floor(target * inputFor(ctx, limits(ctx).replyFloor) / check.estimate));
|
|
510
558
|
decision = replan(target);
|
|
511
559
|
if (decision.kind === "defer" || decision.kind === "fault") return lastAttempt();
|
|
512
560
|
}
|
|
@@ -1061,7 +1109,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1061
1109
|
const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
|
|
1062
1110
|
const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
|
|
1063
1111
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1064
|
-
const {
|
|
1112
|
+
const { want, room } = limits(ctx), band = decisionBand(ctx, room);
|
|
1065
1113
|
let target = room;
|
|
1066
1114
|
for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
|
|
1067
1115
|
const targetBand = target === room ? band : target;
|
|
@@ -1091,7 +1139,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1091
1139
|
// Native Pi does not compact-and-retry output that reached the catalogue cap.
|
|
1092
1140
|
if (event.message.role !== "assistant" || !ctx.model) return;
|
|
1093
1141
|
const stoppedOutput = event.message.usage?.output;
|
|
1094
|
-
if (stoppedOutput >= ctx.model.maxTokens) {
|
|
1142
|
+
if (stoppedOutput >= (actNowCap ?? ctx.model.maxTokens)) {
|
|
1095
1143
|
return { entries: event.entries, continue: false };
|
|
1096
1144
|
}
|
|
1097
1145
|
// Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
|
package/src/config-check.ts
CHANGED
|
@@ -15,6 +15,14 @@ type Map = Partial<Record<string, string | null>>;
|
|
|
15
15
|
|
|
16
16
|
/** What the server says about one model. Window from the first of these it reports; never n_ctx_train (the training length). */
|
|
17
17
|
export interface ServerModel { window?: number; efforts?: string[] }
|
|
18
|
+
/** Server efforts from low to high, for the names pi-tuck can rank; "none" and "off" turn thinking off and are never picked. */
|
|
19
|
+
const EFFORT_RANK = ["xlow", "minimal", "low", "medium", "xmedium", "high", "xhigh", "max"];
|
|
20
|
+
/** The lowest ranked effort a server lists, or undefined. */
|
|
21
|
+
export const lowestEffort = (efforts: readonly string[] | undefined) => EFFORT_RANK.find(e => efforts?.includes(e));
|
|
22
|
+
/** The efforts each provider/model's server listed at this process's check; the act-now request reads them. */
|
|
23
|
+
export const serverEfforts = new Map<string, string[]>();
|
|
24
|
+
/** This process's check while it runs; the act-now request waits for it rather than go out without the efforts. */
|
|
25
|
+
export let pendingCheck: Promise<void> | undefined;
|
|
18
26
|
export function serverModel(body: unknown, id: string): ServerModel | undefined {
|
|
19
27
|
const data = (body as { data?: unknown } | null)?.data;
|
|
20
28
|
const entry = Array.isArray(data) ? data.find(m => (m as { id?: unknown } | null)?.id === id) as Record<string, unknown> | undefined : undefined;
|
|
@@ -130,7 +138,9 @@ export async function checkModel(pi: Pick<ExtensionAPI, "appendEntry">, ctx: Ext
|
|
|
130
138
|
if (!response.ok) return;
|
|
131
139
|
const server = serverModel(await response.json(), model.id);
|
|
132
140
|
if (!server) return;
|
|
133
|
-
const ref = `${model.provider}/${model.id}
|
|
141
|
+
const ref = `${model.provider}/${model.id}`;
|
|
142
|
+
if (server.efforts) serverEfforts.set(ref, server.efforts);
|
|
143
|
+
const no = declined(settingsPath)[ref] ?? {};
|
|
134
144
|
const open = findings(model as never, server).filter(f => no[f.kind] !== f.server);
|
|
135
145
|
if (!open.length) return;
|
|
136
146
|
const lines = open.map(f => f.question.replace(/\?$/, "."));
|
|
@@ -157,6 +167,6 @@ export function installConfigCheck(pi: ExtensionAPI, deps: CheckDeps): void {
|
|
|
157
167
|
pi.on("session_start", (_event, ctx) => {
|
|
158
168
|
if (done) return;
|
|
159
169
|
done = true;
|
|
160
|
-
|
|
170
|
+
pendingCheck = checkModel(pi, ctx, deps).finally(() => { pendingCheck = undefined; });
|
|
161
171
|
});
|
|
162
172
|
}
|
package/src/request-capacity.ts
CHANGED
|
@@ -51,6 +51,27 @@ export async function piContextSafetyMargin(math?: PiRequestMath): Promise<numbe
|
|
|
51
51
|
} catch { return 4_096; }
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
/** The largest input Pi still gives a reply of `reply` tokens, read from Pi's own clamp rather than a copied formula. Pi 1.2-1.6 keep a fixed
|
|
55
|
+
* margin, so this is window - margin - reply. Pi 1.7 keeps 15% of the input while that leaves 32,768 output, so at long context with a large
|
|
56
|
+
* maxTokens it is lower. The clamp only reads the window and the estimate, and an estimate is a reply's usage plus what follows it, so a
|
|
57
|
+
* context of one assistant reply whose usage is `input` asks Pi about any input size. Pi's cap never grows with the input, so search.
|
|
58
|
+
* Without Pi's request arithmetic: window - margin - reply. */
|
|
59
|
+
export function piInputFor(math: PiRequestMath | undefined, window: number, reply: number, margin: number): number {
|
|
60
|
+
const fixed = window - margin - reply;
|
|
61
|
+
if (!math || !(window > 0) || !Number.isSafeInteger(window)) return fixed;
|
|
62
|
+
const cap = (input: number) => math.clampMaxTokensToContext({ contextWindow: window, maxTokens: window } as never,
|
|
63
|
+
{ messages: [{ role: 'assistant', content: [], api: 'openai-completions', provider: 'pi-tuck', model: 'probe', stopReason: 'stop', timestamp: 0,
|
|
64
|
+
usage: { input, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: input, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }] } as never, window);
|
|
65
|
+
// Pi's cap bottoms out at one token even past the window; a cap counts only while it fits beside the fixed margin.
|
|
66
|
+
const gives = (input: number) => { const c = cap(input); return c >= reply && input + margin + c <= window; };
|
|
67
|
+
try {
|
|
68
|
+
if (!gives(0)) return fixed;
|
|
69
|
+
let low = 0, high = window;
|
|
70
|
+
while (low < high) { const mid = Math.ceil((low + high) / 2); if (gives(mid)) low = mid; else high = mid - 1; }
|
|
71
|
+
return low;
|
|
72
|
+
} catch { return fixed; }
|
|
73
|
+
}
|
|
74
|
+
|
|
54
75
|
/** A length stop with visible reasoning but no visible answer or work. */
|
|
55
76
|
export const thinkingOnlyLength = (message: AgentMessage): boolean => message.role === 'assistant' && message.stopReason === 'length' &&
|
|
56
77
|
message.content.length > 0 && message.content.every(block => block.type === 'thinking');
|