pi-tuck 1.10.3 → 1.11.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 +26 -0
- package/README.md +2 -2
- package/dist/src/budget.d.ts +0 -2
- package/dist/src/budget.js +1 -3
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +10 -4
- package/dist/src/compaction.js +91 -19
- package/dist/src/config-check.d.ts +6 -0
- package/dist/src/config-check.js +13 -2
- package/dist/src/content-observations.d.ts +0 -6
- package/dist/src/content-observations.js +5 -5
- package/dist/src/diagnostic-replay.js +6 -6
- package/dist/src/diagnostics.d.ts +0 -1
- package/dist/src/diagnostics.js +2 -3
- package/dist/src/history-image.d.ts +0 -2
- package/dist/src/history-image.js +1 -1
- package/dist/src/kept-reads.d.ts +0 -2
- package/dist/src/kept-reads.js +1 -1
- package/dist/src/omissions.d.ts +3 -6
- package/dist/src/omissions.js +3 -10
- package/dist/src/recall.js +2 -2
- package/dist/src/thrash.d.ts +0 -6
- package/dist/src/thrash.js +1 -1
- package/dist/src/tuck/core/format.d.ts +2 -0
- package/dist/src/tuck/core/format.js +3 -0
- package/dist/src/tuck/core/token-estimate.d.ts +2 -8
- package/dist/src/tuck/core/token-estimate.js +3 -9
- package/dist/src/tuck/core/tool-args.d.ts +0 -1
- package/dist/src/tuck/core/tool-args.js +1 -1
- package/dist/src/tuck/core/transcript.d.ts +3 -2
- package/dist/src/tuck/cut.d.ts +0 -1
- package/dist/src/tuck/cut.js +0 -3
- package/dist/src/tuck.d.ts +2 -2
- package/dist/src/tuck.js +11 -8
- package/package.json +1 -1
- package/src/budget.ts +1 -4
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +80 -18
- package/src/config-check.ts +12 -2
- package/src/content-observations.ts +5 -5
- package/src/diagnostic-replay.ts +7 -6
- package/src/diagnostics.ts +2 -3
- package/src/history-image.ts +1 -1
- package/src/kept-reads.ts +1 -1
- package/src/omissions.ts +3 -10
- package/src/recall.ts +3 -3
- package/src/thrash.ts +1 -7
- package/src/tuck/core/format.ts +3 -0
- package/src/tuck/core/token-estimate.ts +4 -20
- package/src/tuck/core/tool-args.ts +1 -1
- package/src/tuck/core/transcript.ts +2 -2
- package/src/tuck/cut.ts +0 -4
- package/src/tuck.ts +11 -8
- package/dist/src/tuck/core/render-entries.d.ts +0 -6
- package/dist/src/tuck/core/render-entries.js +0 -1
- package/src/tuck/core/render-entries.ts +0 -6
package/dist/src/thrash.d.ts
CHANGED
|
@@ -3,12 +3,6 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
|
3
3
|
export declare const THRASH_WINDOW_REPLIES = 3;
|
|
4
4
|
/** Re-reads per cut at which a session is thrashing. */
|
|
5
5
|
export declare const THRASH_BAR = 0.5;
|
|
6
|
-
/**
|
|
7
|
-
* Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
|
|
8
|
-
* limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
|
|
9
|
-
* within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
|
|
10
|
-
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
11
|
-
*/
|
|
12
6
|
export interface Rereads {
|
|
13
7
|
cuts: number;
|
|
14
8
|
rereads: number;
|
package/dist/src/thrash.js
CHANGED
|
@@ -32,7 +32,7 @@ export function rereadsAfterCuts(branch) {
|
|
|
32
32
|
const args = block.arguments, path = extractPath(args);
|
|
33
33
|
if (!path)
|
|
34
34
|
continue;
|
|
35
|
-
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut:
|
|
35
|
+
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: current, soon: current > 0 && replies <= THRASH_WINDOW_REPLIES });
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
else if (message.role === "toolResult") {
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export declare const CLOSING_INSTRUCTION: string;
|
|
3
3
|
/** Parsing never depends on this wording (transcript.ts splitSummary). */
|
|
4
4
|
export declare const DIALOGUE_SUFFIX: string;
|
|
5
|
+
/** The deepest floor's last words: it lists no actions or files, so it does not claim to. */
|
|
6
|
+
export declare const DEEPEST_SUFFIX: string;
|
|
5
7
|
/** The closing words when working files follow: the re-read rule stays for every other file. */
|
|
6
8
|
export declare const WORKING_FILES_INSTRUCTION: string;
|
|
7
9
|
/** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
|
|
@@ -4,6 +4,9 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
|
|
|
4
4
|
"Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
|
|
5
5
|
/** Parsing never depends on this wording (transcript.ts splitSummary). */
|
|
6
6
|
export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
|
|
7
|
+
/** The deepest floor's last words: it lists no actions or files, so it does not claim to. */
|
|
8
|
+
export const DEEPEST_SUFFIX = CLOSING_SEPARATOR + "Only the dialogue and the outputs shown above carry over; no list of actions or files was kept. " +
|
|
9
|
+
"Before re-running a command, read its earlier output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
|
|
7
10
|
const REREAD = "Re-read a file before editing it or importing from it.";
|
|
8
11
|
/** The closing words when working files follow: the re-read rule stays for every other file. */
|
|
9
12
|
export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD, "Re-read a file before editing it or importing from it, unless it is one of the working files below.");
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
export declare const DEFAULT_CHARS_PER_TOKEN = 4;
|
|
2
2
|
export declare const MIN_CHARS_PER_TOKEN = 2;
|
|
3
3
|
export declare const MAX_CHARS_PER_TOKEN = 6;
|
|
4
|
-
export
|
|
5
|
-
export interface TokenEstimateCalibration {
|
|
6
|
-
mode: TokenEstimateMode;
|
|
4
|
+
export declare const calibrateCharsPerToken: (sourceChars: number, sourceTokens: number | undefined) => {
|
|
7
5
|
charsPerToken: number;
|
|
8
|
-
|
|
9
|
-
sourceTokens?: number;
|
|
10
|
-
rawCharsPerToken?: number;
|
|
11
|
-
}
|
|
12
|
-
export declare const calibrateCharsPerToken: (sourceChars: number, sourceTokens: number | undefined) => TokenEstimateCalibration;
|
|
6
|
+
};
|
|
13
7
|
export declare const estimateTokensFromChars: (chars: number, charsPerToken?: number) => number;
|
|
14
8
|
/**
|
|
15
9
|
* Chars attributed to one image part, mirroring pi-agent-core's own
|
|
@@ -4,19 +4,13 @@ export const MAX_CHARS_PER_TOKEN = 6;
|
|
|
4
4
|
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
|
5
5
|
export const calibrateCharsPerToken = (sourceChars, sourceTokens) => {
|
|
6
6
|
if (!sourceTokens || sourceTokens <= 0 || sourceChars <= 0) {
|
|
7
|
-
return {
|
|
7
|
+
return { charsPerToken: DEFAULT_CHARS_PER_TOKEN };
|
|
8
8
|
}
|
|
9
9
|
const rawCharsPerToken = sourceChars / sourceTokens;
|
|
10
10
|
if (!Number.isFinite(rawCharsPerToken) || rawCharsPerToken <= 0) {
|
|
11
|
-
return {
|
|
11
|
+
return { charsPerToken: DEFAULT_CHARS_PER_TOKEN };
|
|
12
12
|
}
|
|
13
|
-
return {
|
|
14
|
-
mode: "calibrated",
|
|
15
|
-
charsPerToken: clamp(rawCharsPerToken, MIN_CHARS_PER_TOKEN, MAX_CHARS_PER_TOKEN),
|
|
16
|
-
sourceChars,
|
|
17
|
-
sourceTokens,
|
|
18
|
-
rawCharsPerToken,
|
|
19
|
-
};
|
|
13
|
+
return { charsPerToken: clamp(rawCharsPerToken, MIN_CHARS_PER_TOKEN, MAX_CHARS_PER_TOKEN) };
|
|
20
14
|
};
|
|
21
15
|
export const estimateTokensFromChars = (chars, charsPerToken = DEFAULT_CHARS_PER_TOKEN) => Math.ceil(chars / charsPerToken);
|
|
22
16
|
/**
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type SourceTime } from "./source-time.js";
|
|
1
2
|
import type { HistoricalReceipt } from "../types.js";
|
|
2
3
|
export declare const MAX_RECEIPT_CHARACTERS = 8000;
|
|
3
4
|
export declare const MAX_PRODUCER_ARGUMENT_CHARACTERS = 1000;
|
|
@@ -5,10 +6,10 @@ export declare const RECEIPT_RANGE_NOTICE = "Incomplete original readable text a
|
|
|
5
6
|
/** Only complete JSON arguments; serialization must not coerce or omit values. */
|
|
6
7
|
export declare const smallOriginalArguments: (value: unknown, maxCharacters?: number) => value is Record<string, unknown>;
|
|
7
8
|
interface RecordFields {
|
|
8
|
-
sourceTime?:
|
|
9
|
+
sourceTime?: SourceTime;
|
|
9
10
|
sourceTimes?: ({
|
|
10
11
|
sourceIndex: number;
|
|
11
|
-
} &
|
|
12
|
+
} & SourceTime)[];
|
|
12
13
|
sourceEntryId?: string;
|
|
13
14
|
role?: "user" | "assistant" | "custom" | "bashExecution" | "toolResult";
|
|
14
15
|
sourceIndex?: number;
|
package/dist/src/tuck/cut.d.ts
CHANGED
package/dist/src/tuck/cut.js
CHANGED
|
@@ -67,7 +67,6 @@ export function buildOwnCut(branchEntries, keepUserTurns = 1) {
|
|
|
67
67
|
selectedIds: liveMessages.map((e) => e.entry.id),
|
|
68
68
|
firstKeptEntryId: "",
|
|
69
69
|
compactAll: true,
|
|
70
|
-
keptUserTurns: 0,
|
|
71
70
|
keepFallbackToCompactAll,
|
|
72
71
|
});
|
|
73
72
|
if (normalizedKeepUserTurns <= 0)
|
|
@@ -88,7 +87,6 @@ export function buildOwnCut(branchEntries, keepUserTurns = 1) {
|
|
|
88
87
|
selectedIds: liveMessages.slice(0, cutIdx).map((e) => e.entry.id),
|
|
89
88
|
firstKeptEntryId: liveMessages[cutIdx].entry.id,
|
|
90
89
|
compactAll: false,
|
|
91
|
-
keptUserTurns: userIndices.length - targetUserIdx,
|
|
92
90
|
keepFallbackToCompactAll: false,
|
|
93
91
|
};
|
|
94
92
|
}
|
|
@@ -138,7 +136,6 @@ export const applyTailBudget = (branchEntries, cut, opts = {}) => {
|
|
|
138
136
|
selectedIds: live.slice(0, idx).map((m) => m.entry.id),
|
|
139
137
|
firstKeptEntryId: live[idx].entry.id,
|
|
140
138
|
compactAll: false,
|
|
141
|
-
keptUserTurns: live.slice(idx).filter((m) => m.message.role === "user").length,
|
|
142
139
|
keepFallbackToCompactAll: false,
|
|
143
140
|
budgetCut,
|
|
144
141
|
});
|
package/dist/src/tuck.d.ts
CHANGED
|
@@ -72,8 +72,8 @@ export declare const tuck: Tuck;
|
|
|
72
72
|
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
73
73
|
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
74
74
|
export declare function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean, _operatorManual?: boolean, newPrompt?: boolean, protectedPromptEntryId?: string, keepRecentTokens?: number): Draft;
|
|
75
|
-
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
|
|
76
|
-
|
|
75
|
+
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
|
|
76
|
+
* `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
|
|
77
77
|
* a run a custom message starts); the session has moved on from an ended run.
|
|
78
78
|
* `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
|
|
79
79
|
export declare function tuckObservedDraft(tuck: Tuck, input: {
|
package/dist/src/tuck.js
CHANGED
|
@@ -2,7 +2,7 @@ import { resolveSourceTime } from "./tuck/core/source-time.js";
|
|
|
2
2
|
import { orderByOriginalSource } from "./tuck/core/source-order.js";
|
|
3
3
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
4
4
|
import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER } from "./tuck/core/transcript.js";
|
|
5
|
-
import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format.js";
|
|
5
|
+
import { closingSuffix, DEEPEST_SUFFIX, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format.js";
|
|
6
6
|
import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.js";
|
|
7
7
|
import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
@@ -33,8 +33,8 @@ export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {},
|
|
|
33
33
|
return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId,
|
|
34
34
|
keepRecentTokens: event.preparation.settings?.keepRecentTokens ?? keepRecentTokens }, ctx, reserveTokens, measure, policy, retainCurrentInput);
|
|
35
35
|
}
|
|
36
|
-
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
|
|
37
|
-
|
|
36
|
+
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
|
|
37
|
+
* `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
|
|
38
38
|
* a run a custom message starts); the session has moved on from an ended run.
|
|
39
39
|
* `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
|
|
40
40
|
export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true) {
|
|
@@ -74,13 +74,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
74
74
|
// made smaller. Inside the band a cut is opportunistic, and re-rendering there shrinks the summary and costs history for nothing (replays
|
|
75
75
|
// s04-B task 13, s08-B task 23: a 13,008-token first request became 3,336), so an opportunistic cut refuses as it did before.
|
|
76
76
|
else if (input.reRenderSummary && cut.reason === "no_live_messages" && entries.some(entry => entry.type === "compaction"))
|
|
77
|
-
cut = { ok: true, messages: [], selectedIds: [], firstKeptEntryId: "", compactAll: true,
|
|
77
|
+
cut = { ok: true, messages: [], selectedIds: [], firstKeptEntryId: "", compactAll: true, keepFallbackToCompactAll: false };
|
|
78
78
|
if (!cut.ok)
|
|
79
79
|
return { unavailable: `pi-tuck cannot select a cut: ${cut.reason}` };
|
|
80
80
|
const cutBefore = (cut, boundary, prefix) => ({
|
|
81
81
|
...cut, messages: prefix.messages, selectedIds: prefix.selectedIds,
|
|
82
82
|
firstKeptEntryId: entries[boundary]?.id ?? "", compactAll: boundary === entries.length, keepFallbackToCompactAll: false,
|
|
83
|
-
keptUserTurns: entries.slice(boundary).filter(entry => entry.type === "message" && entry.message.role === "user").length,
|
|
84
83
|
});
|
|
85
84
|
// The latest call's trailing receipts have not reached a subsequent response.
|
|
86
85
|
// A preferred tail size must not erase this first exposure when the whole
|
|
@@ -327,9 +326,13 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
327
326
|
// The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
|
|
328
327
|
// existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
|
|
329
328
|
if (input.deepest) {
|
|
330
|
-
|
|
331
|
-
const
|
|
332
|
-
|
|
329
|
+
// The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
|
|
330
|
+
const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, entry => readable(entry) !== undefined);
|
|
331
|
+
const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
|
|
332
|
+
const projection = preview(summary, floorBoundary);
|
|
333
|
+
assertNativeToolRounds(projection);
|
|
334
|
+
const after = measure(projection);
|
|
335
|
+
return { compaction: { summary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
|
|
333
336
|
details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
|
|
334
337
|
}
|
|
335
338
|
const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
|
package/package.json
CHANGED
package/src/budget.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getCurrentSystemMessage, type ImageContent } from "@earendil-works/pi-ai";
|
|
2
2
|
import { convertToLlm, estimateTokens, type BeforeAgentStartEvent, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import {
|
|
3
|
+
import { projectedMessages } from "./omissions.js";
|
|
4
4
|
import type { RecallPolicy } from "./recall.js";
|
|
5
5
|
import { isDiscardedResponse } from "./protocol.js";
|
|
6
6
|
import { MAX_TAIL_TOKENS } from "./tuck/cut.js";
|
|
@@ -92,9 +92,6 @@ export const requestTokens = (messages: Messages, systemPrompt: string): number
|
|
|
92
92
|
/** The saved conversation as the model receives it from this compactor, counted after Pi's conversion. This is the planner's measure too. */
|
|
93
93
|
export const projectedConversationTokens = (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy): number =>
|
|
94
94
|
conversationTokens(projectedMessages(messages, ctx, policy));
|
|
95
|
-
/** As `projectedConversationTokens`, but a summary that is not in this compactor's format is counted as it is instead of failing: what the planner measures with, so that a cut can replace one. */
|
|
96
|
-
export const measurableConversationTokens = (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy): number =>
|
|
97
|
-
conversationTokens(measurableMessages(messages, ctx, policy));
|
|
98
95
|
/** Raw reserve for the cut planner: the window less the raw tokens that fit the target room, plus the input no cut can remove. */
|
|
99
96
|
export const planningReserve = (window: number, targetRoom: number, factor: number, mandatory: number): number =>
|
|
100
97
|
window - Math.floor(targetRoom / factor) + mandatory;
|
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "e11927281c0dc22058687647b4d0658d8a588470b4fae558169cc0532bb02d4e";
|
package/src/compaction.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { textOf } from "./tuck/core/content.js";
|
|
|
2
2
|
import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
|
|
3
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
|
-
import {
|
|
5
|
+
import { lowestEffort, pendingCheck, serverEfforts } from "./config-check.js";
|
|
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";
|
|
8
9
|
import { homedir } from "node:os";
|
|
@@ -12,14 +13,13 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
12
13
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
13
14
|
import { projectedMessages } from "./omissions.js";
|
|
14
15
|
import { applyClips, clipBudgets, clipFor, type Clip } from "./clip.js";
|
|
15
|
-
import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens,
|
|
16
|
+
import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
|
|
16
17
|
type AgentMessage, type Decision, type Messages, type Plan, type Target } from "./budget.js";
|
|
17
18
|
import { getCurrentSystemMessage, isContextOverflow, normalizeContext, type ImageContent, type ToolResultMessage } from "@earendil-works/pi-ai";
|
|
18
19
|
import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
|
|
19
20
|
import { Type } from "typebox";
|
|
20
21
|
import { Check } from "typebox/value";
|
|
21
|
-
import type
|
|
22
|
-
import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
|
|
22
|
+
import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS, type RecallPolicy } from "./recall.js";
|
|
23
23
|
|
|
24
24
|
import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
|
|
25
25
|
import { thrashing } from "./thrash.js";
|
|
@@ -65,7 +65,6 @@ export const refusalNotice = (message: string, factor: number): string =>
|
|
|
65
65
|
export const overflowNotice = (contextWindow: number, bound: number, learned: boolean): string =>
|
|
66
66
|
`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.` +
|
|
67
67
|
(learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
|
|
68
|
-
/** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
|
|
69
68
|
/** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
|
|
70
69
|
export const capStopNotice = (model: string, maxTokens: number, file: string) =>
|
|
71
70
|
`pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
|
|
@@ -73,8 +72,33 @@ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
|
|
|
73
72
|
"The unfinished response is saved in the session.";
|
|
74
73
|
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
75
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
|
+
}
|
|
76
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). */
|
|
77
|
-
|
|
101
|
+
const ACT_NOW_LIMIT = 2;
|
|
78
102
|
/** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
|
|
79
103
|
* 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. */
|
|
80
104
|
export function actNowsInARow(branch: readonly SessionEntry[]): number {
|
|
@@ -204,10 +228,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
204
228
|
const piClamp = piMath?.clampMaxTokensToContext;
|
|
205
229
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
206
230
|
if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
207
|
-
const hostAccess = () => {
|
|
208
|
-
if (!active()) throw new Error("Compaction host is inactive");
|
|
209
|
-
options.assertAccess?.();
|
|
210
|
-
};
|
|
211
231
|
const view = (ctx: ExtensionContext, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
|
|
212
232
|
const liveCut = new PendingCut();
|
|
213
233
|
const recorder = new IncidentRecorder(options.diagnostics);
|
|
@@ -223,7 +243,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
223
243
|
proposalId = receiptId(attached);
|
|
224
244
|
if (recorder.enabled) { try {
|
|
225
245
|
const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
|
|
226
|
-
recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build:
|
|
246
|
+
recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build: BUILD_ID, receiptId: proposalId, entries: filtered.entries, branchEntryIds: ctx.sessionManager.getBranch().map(e => e.id), header: ctx.sessionManager.getHeader(), contextWindow: ctx.model?.contextWindow, reserve, tokensBefore, retainCurrentInput, operatorManual, previousSummary }, filtered.partial || Boolean(options.recallPolicy?.readAttemptMarker));
|
|
227
247
|
recorder.capture("proposal", "selected-draft-not-saved", attached);
|
|
228
248
|
} catch { recorder.stop("capture-failed-gap"); } }
|
|
229
249
|
return attached;
|
|
@@ -336,6 +356,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
336
356
|
const rearmLengthRetry = (ctx: ExtensionContext) => {
|
|
337
357
|
if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
|
|
338
358
|
};
|
|
359
|
+
// 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
|
|
360
|
+
// at it is a full-cap stop, not a squeezed one.
|
|
361
|
+
let actNowCap: number | undefined;
|
|
362
|
+
pi.on("before_provider_request", async (event, ctx) => {
|
|
363
|
+
const model = ctx.model;
|
|
364
|
+
if (model?.api !== "openai-completions" || !actNowPayload(event.payload, undefined)) { actNowCap = undefined; return undefined; }
|
|
365
|
+
await pendingCheck;
|
|
366
|
+
const rewritten = actNowPayload(event.payload, lowestEffort(serverEfforts.get(`${model.provider}/${model.id}`)))!;
|
|
367
|
+
actNowCap = rewritten.cap;
|
|
368
|
+
return rewritten.payload;
|
|
369
|
+
});
|
|
339
370
|
// The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
|
|
340
371
|
pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW) rearmLengthRetry(ctx); });
|
|
341
372
|
pi.on("message_end", (event, ctx) => {
|
|
@@ -442,7 +473,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
442
473
|
// The planner counts with the same function, except that it does not fail on a summary in another format: a cut can replace one
|
|
443
474
|
// (an operator's /compact repairs a session whose saved summary is foreign). Identical to the strict one for this compactor's summaries.
|
|
444
475
|
const plannerMeasureFor = (ctx: ExtensionContext) => Object.assign(
|
|
445
|
-
(messages: Messages) =>
|
|
476
|
+
(messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy),
|
|
446
477
|
{ messageTokens: (message: Messages[number]) => conversationTokens(applyClips([message], clips())) });
|
|
447
478
|
const hostMessages = (ctx: ExtensionContext) => options.hostMessages?.(ctx) ?? [];
|
|
448
479
|
const toolShapes = (names: Iterable<string>) => {
|
|
@@ -553,7 +584,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
553
584
|
|
|
554
585
|
const access = () => {
|
|
555
586
|
if (failure()) throw failure();
|
|
556
|
-
|
|
587
|
+
if (!active()) throw new Error("Compaction host is inactive");
|
|
588
|
+
options.assertAccess?.();
|
|
557
589
|
};
|
|
558
590
|
pi.on("input", async (event, ctx) => {
|
|
559
591
|
if (!ctx.isIdle() || run?.phase === "starting") return; // steering joins the existing run
|
|
@@ -1060,13 +1092,43 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1060
1092
|
markBoundary(entries);
|
|
1061
1093
|
return { entries, continue: false };
|
|
1062
1094
|
};
|
|
1095
|
+
// A retry's cut is an ordinary planned cut (summary with the action and file lists and kept results), shrunk until Pi's own clamp gives
|
|
1096
|
+
// the raised reply room, at most three times. Only when no such plan exists does the retry fall back to the deepest floor.
|
|
1097
|
+
const retryDecision = (ctx: ExtensionContext, asIs: Messages, host: Messages, pending: Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
|
|
1098
|
+
const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
|
|
1099
|
+
const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
|
|
1100
|
+
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1101
|
+
const { response, room } = limits(ctx), want = response - piMargin, band = decisionBand(ctx, room);
|
|
1102
|
+
let target = room;
|
|
1103
|
+
for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
|
|
1104
|
+
const targetBand = target === room ? band : target;
|
|
1105
|
+
const decision = chooseCut<CutPlan>({ before, mandatory, room: target, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), opportunistic: false,
|
|
1106
|
+
unreduced: "Length-retry compaction did not reduce context within the estimated request budget",
|
|
1107
|
+
plan: (kind): Plan<CutPlan> => {
|
|
1108
|
+
const reserve = planReserve(kind, target, targetBand, mandatory, ctx);
|
|
1109
|
+
const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
1110
|
+
protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
1111
|
+
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1112
|
+
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
1113
|
+
assertNativeToolRounds(kept);
|
|
1114
|
+
return { draft: true, after: measureFor(ctx)(kept), compaction: draft.compaction, reserve, messages: kept };
|
|
1115
|
+
},
|
|
1116
|
+
});
|
|
1117
|
+
if (decision.kind !== "cut") return undefined;
|
|
1118
|
+
const check = requestClamp(projectedRequest(decision.plan.messages, ctx, host, pending, ctx.getSystemPrompt(), pi.getActiveTools(), true), ctx);
|
|
1119
|
+
if (check.cap === undefined) return undefined;
|
|
1120
|
+
if (check.leavesFloor && check.cap >= want) return decision;
|
|
1121
|
+
target = Math.floor(target * (check.estimate - (want - check.cap)) / check.estimate);
|
|
1122
|
+
}
|
|
1123
|
+
return undefined;
|
|
1124
|
+
};
|
|
1063
1125
|
const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
|
|
1064
1126
|
// Exhausting the full per-request allowance is not evidence that input is too large.
|
|
1065
1127
|
// Preserve the unfinished response; provider-native continuation owns this case.
|
|
1066
1128
|
// Native Pi does not compact-and-retry output that reached the catalogue cap.
|
|
1067
1129
|
if (event.message.role !== "assistant" || !ctx.model) return;
|
|
1068
1130
|
const stoppedOutput = event.message.usage?.output;
|
|
1069
|
-
if (stoppedOutput >= ctx.model.maxTokens) {
|
|
1131
|
+
if (stoppedOutput >= (actNowCap ?? ctx.model.maxTokens)) {
|
|
1070
1132
|
return { entries: event.entries, continue: false };
|
|
1071
1133
|
}
|
|
1072
1134
|
// Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
|
|
@@ -1080,7 +1142,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1080
1142
|
const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
|
|
1081
1143
|
const asIsCheck = requestClamp(asIs, view);
|
|
1082
1144
|
const previousClips = new Map(clips());
|
|
1083
|
-
const decision = deepestDecision(view, false, true);
|
|
1145
|
+
const decision = retryDecision(view, asIs, hostInput, event.context.pendingMessages) ?? deepestDecision(view, false, true);
|
|
1084
1146
|
const cut = decision.kind === "cut" ? {
|
|
1085
1147
|
...decision,
|
|
1086
1148
|
messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
|
|
@@ -1171,7 +1233,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1171
1233
|
};
|
|
1172
1234
|
// A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
|
|
1173
1235
|
// atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
|
|
1174
|
-
const guardCut = (messages: Messages, tokens: number,
|
|
1236
|
+
const guardCut = (messages: Messages, tokens: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
|
|
1175
1237
|
const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
|
|
1176
1238
|
const before = conversationTokens(source), mandatory = tokens - before;
|
|
1177
1239
|
const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
|
|
@@ -1257,7 +1319,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1257
1319
|
try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
|
|
1258
1320
|
catch { return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx); }
|
|
1259
1321
|
}
|
|
1260
|
-
|
|
1322
|
+
run.pendingBoundaryReceipts = [];
|
|
1261
1323
|
}
|
|
1262
1324
|
// Pi commits these entries before the run settles.
|
|
1263
1325
|
try {
|
|
@@ -1292,7 +1354,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1292
1354
|
const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
|
|
1293
1355
|
piClamp && !requestClamp(messages, ctx).leavesFloor;
|
|
1294
1356
|
if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1295
|
-
const cut = guardCut(messages, tokens,
|
|
1357
|
+
const cut = guardCut(messages, tokens, ctx);
|
|
1296
1358
|
messages = cut.messages;
|
|
1297
1359
|
native = Boolean(cut.native);
|
|
1298
1360
|
system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
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
|
}
|
|
@@ -6,13 +6,13 @@ import { readableContentParts } from "./tuck/core/readable-content";
|
|
|
6
6
|
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
7
7
|
import { MAX_RECALL_CHARACTERS } from "./recall";
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
const MAX_OUTPUT_TAIL_LINES = 3;
|
|
10
|
+
const MAX_OUTPUT_TAIL_CHARACTERS = 200;
|
|
11
|
+
const MAX_DEFINITION_LINES = 40;
|
|
12
|
+
const MAX_DEFINITION_CHARACTERS = 800;
|
|
13
13
|
|
|
14
14
|
/** Mechanical line matches only; no language detection or inferred symbols. */
|
|
15
|
-
|
|
15
|
+
const DEFINITION_PATTERNS: readonly RegExp[] = [
|
|
16
16
|
/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:func|def|function)\b/u,
|
|
17
17
|
/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:type|struct|interface|class)\b/u,
|
|
18
18
|
/^\s*export\s+(?:const|let)\b/u,
|
package/src/diagnostic-replay.ts
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
import { SessionManager, type ExtensionContext, type SessionEntry, type SessionHeader } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { tuck, tuckObservedDraft } from './tuck.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { projectedConversationTokens } from './budget.js';
|
|
4
|
+
import { BUILD_ID } from './build-id.js';
|
|
5
|
+
import { type IncidentRecord } from './diagnostics.js';
|
|
5
6
|
export function inspectIncident(records: IncidentRecord[]) {
|
|
6
7
|
const inputs = records.filter(r => r.kind === 'replay-input');
|
|
7
8
|
const results = inputs.map(record => {
|
|
8
9
|
const i = record.data as { build?: string; receiptId?: string; entries?: SessionEntry[]; branchEntryIds?: string[]; header?: SessionHeader; contextWindow?: number; reserve?: number; tokensBefore?: number; retainCurrentInput?: boolean; operatorManual?: boolean; previousSummary?: string };
|
|
9
|
-
if (record.partial || i.build !==
|
|
10
|
+
if (record.partial || i.build !== BUILD_ID || !i.entries || !i.header || !Array.isArray(i.branchEntryIds) || i.branchEntryIds.some(id => typeof id !== 'string') || !Number.isSafeInteger(i.contextWindow) || !Number.isSafeInteger(i.reserve) || !Number.isSafeInteger(i.tokensBefore)) return { mode: 'partial-inspection', notice: 'Missing/redacted inputs or nonmatching build; no deterministic replay claim.' };
|
|
10
11
|
const manager = SessionManager.inMemory('/offline-compaction-replay', undefined, [i.header, ...i.entries]);
|
|
11
|
-
if (i.branchEntryIds
|
|
12
|
+
if (i.branchEntryIds.length) manager.branch(i.branchEntryIds.at(-1)!);
|
|
12
13
|
const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } } as unknown as ExtensionContext;
|
|
13
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary }, ctx, i.reserve!, messages =>
|
|
14
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary }, ctx, i.reserve!, messages => projectedConversationTokens(messages, ctx), {}, i.retainCurrentInput);
|
|
14
15
|
const proposal = records.find(r => r.kind === 'proposal' && (r.data as { details?: { diagnosticReceipt?: { id?: string } } })?.details?.diagnosticReceipt?.id === i.receiptId)?.data as { summary?: string; firstKeptEntryId?: string } | undefined;
|
|
15
16
|
const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
|
|
16
17
|
return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
|
|
17
18
|
});
|
|
18
|
-
return { build:
|
|
19
|
+
return { build: BUILD_ID, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
|
|
19
20
|
}
|
|
20
21
|
export function readableIncident(records: IncidentRecord[]): string {
|
|
21
22
|
return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
|
package/src/diagnostics.ts
CHANGED
|
@@ -7,11 +7,10 @@ import { homedir } from 'node:os';
|
|
|
7
7
|
import { createRecall, type RecallPolicy } from './recall.js';
|
|
8
8
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
9
9
|
import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
|
|
10
|
-
export const DIAGNOSTIC_BUILD = BUILD_ID;
|
|
11
10
|
export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
|
|
12
11
|
export function attachReceipt<T extends { details?: unknown; firstKeptEntryId: string; tokensBefore: number }>(draft: T, reason: string, reserveTokens: number, contextWindow: number, resolved: Partial<Receipt['settings']> = {}): T & { details: Record<string, unknown> & { diagnosticReceipt: Receipt } } {
|
|
13
12
|
const details = draft.details && typeof draft.details === 'object' ? draft.details as Record<string, unknown> : {};
|
|
14
|
-
const receipt: Receipt = { id: randomUUID(), build:
|
|
13
|
+
const receipt: Receipt = { id: randomUUID(), build: BUILD_ID, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
|
|
15
14
|
return { ...draft, details: { ...details, diagnosticReceipt: receipt } };
|
|
16
15
|
}
|
|
17
16
|
export function receiptId(entry: { details?: unknown }): string | undefined {
|
|
@@ -82,7 +81,7 @@ export class IncidentRecorder {
|
|
|
82
81
|
if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) { notify('Recorder directory must be outside project'); return; }
|
|
83
82
|
this.projectDirectory = resolve(project); this.notify = notify; this.state = 'recording'; this.nextCut = nextCut; this.sawCut = false; this.requests = 0; this.response = false; this.total = 0; this.captureCalls = 0; this.inlineMs = 0; this.hookMs = 0; this.id = randomUUID(); this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
|
|
84
83
|
this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs); this.timer.unref();
|
|
85
|
-
this.capture('start', 'operator-session-control', { id: this.id, build:
|
|
84
|
+
this.capture('start', 'operator-session-control', { id: this.id, build: BUILD_ID, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
|
|
86
85
|
}
|
|
87
86
|
measureInline<T>(operation: () => T): T { if (!this.enabled) return operation(); const started = performance.now(); try { return operation(); } finally { this.hookMs += performance.now() - started; } }
|
|
88
87
|
capture(kind: string, scope: string, value: unknown, inheritedPartial = false) {
|
package/src/history-image.ts
CHANGED
|
@@ -30,7 +30,7 @@ function images(entry: SessionEntry): ImageContent[] {
|
|
|
30
30
|
return entry.message.content.filter((block): block is ImageContent => block.type === "image");
|
|
31
31
|
}
|
|
32
32
|
/** Factual locators only; no interpretation of pixels or claim of current truth. */
|
|
33
|
-
|
|
33
|
+
function imageSource(entry: SessionEntry): ImageSource | undefined {
|
|
34
34
|
const imageCount = images(entry).length;
|
|
35
35
|
if (!imageCount || entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "toolResult")) return;
|
|
36
36
|
if (!entry.id || entry.id.length > MAX_RECALL_ENTRY_ID_CHARACTERS) throw new Error("Recall image source has an invalid or oversized ID");
|
package/src/kept-reads.ts
CHANGED
|
@@ -54,7 +54,7 @@ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHead
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
/** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
|
|
57
|
-
|
|
57
|
+
const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
|
|
58
58
|
const words = (text: string) => text.replace(/\s+/gu, " ").trim();
|
|
59
59
|
/** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
|
|
60
60
|
* first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
|