pi-tuck 1.3.3 → 1.4.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 +43 -0
- package/LICENSE +0 -59
- package/NOTICE +63 -0
- package/README.md +59 -189
- package/dist/index.d.ts +1 -4
- package/dist/index.js +49 -10
- package/dist/src/budget.d.ts +6 -15
- package/dist/src/budget.js +6 -11
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +12 -20
- package/dist/src/compaction.js +220 -202
- package/dist/src/content-observations.d.ts +24 -0
- package/dist/src/content-observations.js +122 -0
- package/dist/src/diagnostics.d.ts +1 -3
- package/dist/src/ledger.d.ts +6 -3
- package/dist/src/ledger.js +14 -7
- package/dist/src/llama-continuation.d.ts +8 -0
- package/dist/src/llama-continuation.js +179 -0
- package/dist/src/omissions.d.ts +1 -5
- package/dist/src/omissions.js +8 -10
- package/dist/src/recall.js +8 -25
- package/dist/src/request-capacity.d.ts +11 -26
- package/dist/src/request-capacity.js +20 -57
- package/dist/src/run.d.ts +16 -7
- package/dist/src/run.js +53 -25
- package/dist/src/status.d.ts +2 -0
- package/dist/src/status.js +6 -5
- package/dist/src/tuck/core/format.js +1 -1
- package/dist/src/tuck/core/readable-content.d.ts +14 -0
- package/dist/src/tuck/core/readable-content.js +43 -0
- package/dist/src/tuck.d.ts +2 -1
- package/dist/src/tuck.js +92 -30
- package/index.ts +42 -10
- package/package.json +3 -2
- package/src/budget.ts +7 -12
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +220 -193
- package/src/content-observations.ts +115 -0
- package/src/diagnostics.ts +1 -1
- package/src/ledger.ts +17 -10
- package/src/llama-continuation.ts +176 -0
- package/src/omissions.ts +8 -10
- package/src/recall.ts +8 -20
- package/src/request-capacity.ts +18 -57
- package/src/run.ts +48 -22
- package/src/status.ts +8 -5
- package/src/tuck/core/format.ts +1 -1
- package/src/tuck/core/readable-content.ts +44 -0
- package/src/tuck.ts +79 -28
package/src/run.ts
CHANGED
|
@@ -4,22 +4,38 @@ import { textOf } from './tuck/core/content.js';
|
|
|
4
4
|
import type { Clip } from './clip.js';
|
|
5
5
|
|
|
6
6
|
export type CutEntry = { type: 'compaction'; summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown };
|
|
7
|
-
type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'
|
|
7
|
+
type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'> & Partial<Pick<ExtensionContext, 'model'>>;
|
|
8
|
+
const budgetIdentity = (model: Context['model']) => model &&
|
|
9
|
+
JSON.stringify([model.provider, model.api, model.id, model.contextWindow, model.maxTokens]);
|
|
8
10
|
export interface CutView { session: ExtensionContext['sessionManager']; keptFromId: string | undefined; hasTuckCut: boolean; pending: boolean }
|
|
9
11
|
|
|
10
12
|
/** The only owner of a cut that requests carry before Pi saves it. */
|
|
11
13
|
export class PendingCut {
|
|
12
|
-
private
|
|
13
|
-
private branchLength = 0;
|
|
14
|
+
private proposal?: { cut: CutEntry; manager: Context['sessionManager']; cwd: string; branchLength: number; anchor: string | undefined; budget?: string };
|
|
14
15
|
private preview?: { manager: Context['sessionManager']; cwd: string; leaf: string | null; view: CutView };
|
|
15
|
-
plan(cut: CutEntry,
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
plan(cut: CutEntry, ctx: Context) {
|
|
17
|
+
const branch = ctx.sessionManager.getBranch();
|
|
18
|
+
this.proposal = { cut, manager: ctx.sessionManager, cwd: ctx.cwd, branchLength: branch.length,
|
|
19
|
+
anchor: branch.at(-1)?.id, budget: budgetIdentity(ctx.model) };
|
|
20
|
+
this.preview = undefined;
|
|
21
|
+
}
|
|
22
|
+
clear() { this.proposal = undefined; this.preview = undefined; }
|
|
23
|
+
take(ctx: Context) {
|
|
24
|
+
if (!this.view(ctx).pending) return;
|
|
25
|
+
const cut = this.proposal?.cut;
|
|
26
|
+
this.clear();
|
|
27
|
+
return cut;
|
|
28
|
+
}
|
|
18
29
|
view(ctx: Context, entries: readonly SessionBoundaryDraft[] = []): CutView {
|
|
19
|
-
const live = ctx.sessionManager, leaf = live.getLeafId?.()
|
|
20
|
-
|
|
30
|
+
const live = ctx.sessionManager, leaf = live.getLeafId?.();
|
|
31
|
+
const proposal = this.proposal;
|
|
32
|
+
if (proposal && (proposal.manager !== live || proposal.cwd !== ctx.cwd || proposal.budget !== budgetIdentity(ctx.model))) this.clear();
|
|
33
|
+
const held = this.preview;
|
|
34
|
+
// Native entries are append-only. A changed leaf requires checking that the plan's anchor still precedes it.
|
|
21
35
|
if (!entries.length && leaf !== undefined && held && held.manager === live && held.cwd === ctx.cwd && held.leaf === leaf) return held.view;
|
|
22
|
-
const branch = live.getBranch()
|
|
36
|
+
const branch = live.getBranch();
|
|
37
|
+
if (this.proposal?.anchor !== undefined && branch[this.proposal.branchLength - 1]?.id !== this.proposal.anchor) this.clear();
|
|
38
|
+
const cut = this.proposal?.cut;
|
|
23
39
|
const remember = (view: CutView) => {
|
|
24
40
|
if (!entries.length && leaf !== undefined) this.preview = { manager: live, cwd: ctx.cwd, leaf, view };
|
|
25
41
|
return view;
|
|
@@ -30,7 +46,7 @@ export class PendingCut {
|
|
|
30
46
|
hasTuckCut: hasTuckCut(branch), pending: false });
|
|
31
47
|
}
|
|
32
48
|
// A compact-all plan predates the prompt. Keep from the first appended entry, skipping our capacity receipts.
|
|
33
|
-
const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.branchLength)
|
|
49
|
+
const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.proposal!.branchLength)
|
|
34
50
|
.find(entry => entry.type !== 'custom' || entry.customType !== 'pi-tuck-capacity')?.id || '');
|
|
35
51
|
const header = live.getHeader();
|
|
36
52
|
if (!header) throw new Error("Missing native session header for the prompt's cut");
|
|
@@ -85,7 +101,6 @@ export const RUN_TRANSITIONS: Readonly<Record<RunPhase, readonly RunPhase[]>> =
|
|
|
85
101
|
failed: ['failed', 'commit-failed'],
|
|
86
102
|
'commit-failed': ['commit-failed'],
|
|
87
103
|
};
|
|
88
|
-
let reportedInvalidTransition = false;
|
|
89
104
|
type RunState = { phase: Exclude<RunPhase, 'failed' | 'commit-failed'> } | { phase: 'failed' | 'commit-failed'; error: Error };
|
|
90
105
|
|
|
91
106
|
export class Run {
|
|
@@ -98,30 +113,41 @@ export class Run {
|
|
|
98
113
|
get expired() { return this.expiredPlan; }
|
|
99
114
|
/** Failure data, only present in a failed phase. The phase alone decides admission. */
|
|
100
115
|
get error() { return 'error' in this.state ? this.state.error : undefined; }
|
|
101
|
-
transition(phase: RunPhase,
|
|
116
|
+
transition(phase: RunPhase, error?: Error): void {
|
|
102
117
|
if (!RUN_TRANSITIONS[this.phase].includes(phase) || ((phase === 'failed' || phase === 'commit-failed') && !error)) {
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return false;
|
|
118
|
+
const fault = new Error(`pi-tuck: invalid run transition ${this.phase} -> ${phase}`);
|
|
119
|
+
// A rejected transition must stop the caller and latch admission shut.
|
|
120
|
+
// Preserve an existing terminal cause, especially a persistence fault.
|
|
121
|
+
if (this.state.phase !== 'failed' && this.state.phase !== 'commit-failed')
|
|
122
|
+
this.state = { phase: 'failed', error: fault };
|
|
123
|
+
throw fault;
|
|
110
124
|
}
|
|
111
125
|
this.state = phase === 'failed' || phase === 'commit-failed' ? { phase, error: error! } : { phase };
|
|
112
126
|
if (phase === 'expired') this.expiredPlan = true;
|
|
113
|
-
return true;
|
|
114
127
|
}
|
|
115
128
|
prompt?: StartingPrompt;
|
|
116
129
|
cut = new PendingCut();
|
|
117
130
|
clips = new Map<string, Clip>();
|
|
118
131
|
pendingBoundaryReceipts: string[] = [];
|
|
119
|
-
|
|
132
|
+
rejectedBudget?: { input: number; output: number };
|
|
133
|
+
private lengthRecovery: 'available' | 'pending' | 'used' = 'available';
|
|
134
|
+
get lengthRetryPending() { return this.lengthRecovery === 'pending'; }
|
|
135
|
+
get canRetryLength() { return this.phase === 'admitted' && this.lengthRecovery === 'available'; }
|
|
136
|
+
requestLengthRetry() {
|
|
137
|
+
if (!this.canRetryLength) throw new Error('pi-tuck: capacity recovery is unavailable for this run');
|
|
138
|
+
this.lengthRecovery = 'pending';
|
|
139
|
+
}
|
|
140
|
+
finishLengthRetry() {
|
|
141
|
+
if (this.lengthRecovery === 'pending') this.lengthRecovery = 'used';
|
|
142
|
+
}
|
|
143
|
+
/** Pi grants another recovery after a good reply or a new user message. */
|
|
144
|
+
rearmLengthRetry() { this.lengthRecovery = 'available';
|
|
145
|
+
}
|
|
120
146
|
/** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
|
|
121
147
|
nativeFloorPending = false;
|
|
122
148
|
refusalReceipted = false;
|
|
123
149
|
clear() {
|
|
124
150
|
this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
|
|
125
|
-
this.
|
|
151
|
+
this.rejectedBudget = undefined; this.nativeFloorPending = false; this.refusalReceipted = false; this.expiredPlan = false;
|
|
126
152
|
}
|
|
127
153
|
}
|
package/src/status.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { fileURLToPath } from "node:url";
|
|
3
3
|
|
|
4
|
+
export const CONTINUATION_CACHE_MISS = "Native continuation stopped because the server could not reuse the unfinished response without rebuilding context.";
|
|
5
|
+
|
|
4
6
|
/** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
|
|
5
7
|
export const LOADED_VERSION: string = (() => {
|
|
6
8
|
try {
|
|
@@ -18,13 +20,14 @@ export function statusText(input: {
|
|
|
18
20
|
branch: readonly { type: string; tokensBefore?: unknown; details?: unknown; customType?: unknown; data?: unknown }[];
|
|
19
21
|
pending?: boolean;
|
|
20
22
|
cutAt: number | undefined;
|
|
23
|
+
cacheSensitive?: boolean;
|
|
21
24
|
}): string {
|
|
22
|
-
if (!input.active) return `pi-tuck ${input.version} is
|
|
23
|
-
if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version}
|
|
25
|
+
if (!input.active) return `pi-tuck ${input.version} is inactive in this host.`;
|
|
26
|
+
if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
|
|
24
27
|
const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
|
|
25
28
|
const last = ours.at(-1), before = last?.tokensBefore, after = (last?.details as { tokensAfter?: unknown } | undefined)?.tokensAfter;
|
|
26
29
|
const count = (n: number) => n.toLocaleString("en-US");
|
|
27
|
-
const cutLine = ours.length === 0 ? input.pending ? "Cuts: none saved yet in this session." : "Cuts: none yet in this session.
|
|
30
|
+
const cutLine = ours.length === 0 ? input.pending ? "Cuts: none saved yet in this session." : "Cuts: none yet in this session. Recall becomes available after the first pi-tuck cut on this branch."
|
|
28
31
|
: `Cuts: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
|
|
29
32
|
const native = cuts.length - ours.length;
|
|
30
33
|
const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
|
|
@@ -32,10 +35,10 @@ export function statusText(input: {
|
|
|
32
35
|
return [
|
|
33
36
|
`pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
|
|
34
37
|
cutLine,
|
|
35
|
-
...(retries ? [`
|
|
38
|
+
...(retries ? [`Capacity retries on this branch: ${retries}.`] : []),
|
|
36
39
|
...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
|
|
37
40
|
...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
|
|
38
|
-
input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point:
|
|
41
|
+
input.cacheSensitive ? "Cut point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: cutAt ${input.cutAt} of the room, subject to the standard margin. Remove cutAt from pi-tuck.json to let it adapt.`,
|
|
39
42
|
"Search: by keyword.",
|
|
40
43
|
].join("\n");
|
|
41
44
|
}
|
package/src/tuck/core/format.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CLOSING_SEPARATOR } from "./transcript";
|
|
2
2
|
/** A summary's last words: it holds only the dialogue (whole or shrunk) and the file ledger. */
|
|
3
3
|
export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files listed above carry over. " +
|
|
4
|
-
"Files created by commands are not listed:
|
|
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;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export interface ReadableContentPart {
|
|
2
|
+
kind: "text" | "toolCall" | "thinking";
|
|
3
|
+
text: string;
|
|
4
|
+
offset: number;
|
|
5
|
+
toolName?: string;
|
|
6
|
+
arguments?: unknown;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Pi stores opaque/encrypted reasoning in thinkingSignature. The one exception: pi-ai's openai-completions adapter stores only the name of the
|
|
10
|
+
* response field the plain reasoning came from (OPENAI_COMPLETIONS_REASONING_FIELDS), which signs or encrypts nothing. Also refuse explicit
|
|
11
|
+
* redaction/encryption markers in imported session blocks. */
|
|
12
|
+
const PLAIN_REASONING_FIELDS: ReadonlySet<unknown> = new Set(["reasoning", "reasoning_content", "reasoning_text"]);
|
|
13
|
+
export function isPlainThinking(block: unknown): block is { type: "thinking"; thinking: string } {
|
|
14
|
+
if (!block || typeof block !== "object") return false;
|
|
15
|
+
const value = block as Record<string, unknown>;
|
|
16
|
+
return value.type === "thinking" && typeof value.thinking === "string" && (value.thinkingSignature === undefined || PLAIN_REASONING_FIELDS.has(value.thinkingSignature)) &&
|
|
17
|
+
(value.redacted === undefined || value.redacted === false) &&
|
|
18
|
+
(value.encrypted === undefined || value.encrypted === false) &&
|
|
19
|
+
value.encryptedContent === undefined && value.encrypted_content === undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Keep the existing text/tool-call prefix byte for byte, including empty text
|
|
23
|
+
* parts. Append plain thinking in block order so older recall offsets remain valid. */
|
|
24
|
+
export function readableContentParts(content: unknown, assistant = false): ReadableContentPart[] {
|
|
25
|
+
if (typeof content === "string") return [{ kind: "text", text: content, offset: 0 }];
|
|
26
|
+
if (!Array.isArray(content)) return [];
|
|
27
|
+
const parts: Omit<ReadableContentPart, "offset">[] = [];
|
|
28
|
+
for (const block of content) {
|
|
29
|
+
if (!block || typeof block !== "object") continue;
|
|
30
|
+
if (block.type === "text" && typeof block.text === "string") parts.push({ kind: "text", text: block.text });
|
|
31
|
+
else if (assistant && block.type === "toolCall" && typeof block.name === "string" && typeof block.id === "string" && "arguments" in block)
|
|
32
|
+
parts.push({ kind: "toolCall", toolName: block.name, arguments: block.arguments,
|
|
33
|
+
text: JSON.stringify({ toolCall: { name: block.name, id: block.id, arguments: block.arguments } }) });
|
|
34
|
+
}
|
|
35
|
+
if (assistant) for (const block of content)
|
|
36
|
+
if (isPlainThinking(block) && block.thinking.length) parts.push({ kind: "thinking", text: block.thinking });
|
|
37
|
+
let offset = 0;
|
|
38
|
+
return parts.map((part, at) => {
|
|
39
|
+
if (at) offset++;
|
|
40
|
+
const located = { ...part, offset };
|
|
41
|
+
offset += part.text.length;
|
|
42
|
+
return located;
|
|
43
|
+
});
|
|
44
|
+
}
|
package/src/tuck.ts
CHANGED
|
@@ -9,6 +9,8 @@ import { isTextOnly, textOf } from "./tuck/core/content";
|
|
|
9
9
|
import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
|
|
10
10
|
import { keptReadCandidates } from "./kept-reads.js";
|
|
11
11
|
import { keptSearchCandidates } from "./kept-searches.js";
|
|
12
|
+
import { fileObservations, thinkingRecords } from "./content-observations";
|
|
13
|
+
import { pathKey } from "./path-key";
|
|
12
14
|
import { convertToLlm, SessionManager, type ExtensionContext,
|
|
13
15
|
type SessionBeforeCompactEvent, type SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
14
16
|
import { ATTEMPT_NOTICE, createRecall, type RecallPolicy,
|
|
@@ -50,14 +52,15 @@ import { rankRecallRows } from "./tuck/core/search-entries";
|
|
|
50
52
|
export const tuck: Tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
51
53
|
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
52
54
|
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
53
|
-
export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId?: string) {
|
|
54
|
-
return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId
|
|
55
|
+
export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId?: string, keepRecentTokens?: number) {
|
|
56
|
+
return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId,
|
|
57
|
+
keepRecentTokens: event.preparation.settings?.keepRecentTokens ?? keepRecentTokens }, ctx, reserveTokens, measure, policy, retainCurrentInput);
|
|
55
58
|
}
|
|
56
59
|
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
|
|
57
60
|
/** `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
|
|
58
61
|
* a run a custom message starts); the session has moved on from an ended run.
|
|
59
62
|
* `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
|
|
60
|
-
export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean }, ctx: ExtensionContext,
|
|
63
|
+
export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean; keepRecentTokens?: number }, ctx: ExtensionContext,
|
|
61
64
|
reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true): Draft {
|
|
62
65
|
const { isHistorySource, readable } = createRecall(policy);
|
|
63
66
|
const projected = ctx.sessionManager.buildSessionProjection();
|
|
@@ -325,7 +328,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
325
328
|
const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
|
|
326
329
|
const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
|
|
327
330
|
const base = price(baseCharacters, preferredBoundary);
|
|
328
|
-
|
|
331
|
+
// Cap historical fill at native keep-recent for post-cut headroom parity, preserving the floor and preferred tail.
|
|
332
|
+
const target = Math.min(carriedTarget(model.contextWindow, reserveTokens, base, before), Math.max(base, offset + (input.keepRecentTokens ?? Infinity)));
|
|
329
333
|
// The old tail rule supplies an ordering boundary only. Its recent
|
|
330
334
|
// suffix follows the openings, and is charged to the same total grant.
|
|
331
335
|
const boundaries = [floorBoundary];
|
|
@@ -358,30 +362,18 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
358
362
|
const lists = listsAt(boundary);
|
|
359
363
|
const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
360
364
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
361
|
-
let
|
|
362
|
-
|
|
363
|
-
const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
364
|
-
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
365
|
-
.sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
366
|
-
for (const record of candidates) {
|
|
367
|
-
if ((counts.get(record.title!) ?? 0) === 4) continue;
|
|
368
|
-
const cost = lineCost([record]);
|
|
369
|
-
if (cost > allowance) continue;
|
|
370
|
-
keptResults.push(record); allowance -= cost;
|
|
371
|
-
counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
|
|
372
|
-
}
|
|
373
|
-
let ledger: TranscriptRecord[] = [...lists.records, ...keptResults];
|
|
365
|
+
let ledger: TranscriptRecord[] = lists.records;
|
|
366
|
+
let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
|
|
374
367
|
// List caps are existing ranking policy; only the carried target is a
|
|
375
368
|
// spending limit. Candidate list sizes have fixed, cached line prices.
|
|
376
|
-
while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
377
|
-
keptResults.pop();
|
|
378
|
-
ledger = [...lists.records, ...keptResults];
|
|
379
|
-
}
|
|
380
369
|
if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
381
370
|
ledger = [];
|
|
371
|
+
listedKeep = 0;
|
|
382
372
|
for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
|
|
383
373
|
const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
|
|
384
|
-
if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target)
|
|
374
|
+
if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
|
|
375
|
+
ledger = candidate; listedKeep = keep;
|
|
376
|
+
}
|
|
385
377
|
}
|
|
386
378
|
}
|
|
387
379
|
const mandatory = new Set([...protectedView.whole].filter(index => {
|
|
@@ -399,6 +391,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
399
391
|
const compiledBoundary = boundary;
|
|
400
392
|
// A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
|
|
401
393
|
const sourceKey = (record: TranscriptRecord) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
|
|
394
|
+
const keptResults: TranscriptRecord[] = [], thinking: TranscriptRecord[] = [];
|
|
402
395
|
const assemble = (compiled: string, at = compiledBoundary) => {
|
|
403
396
|
const split = compiled ? splitSummary(compiled) : undefined;
|
|
404
397
|
if (compiled && !split) throw new Error("pi-tuck returned an invalid summary");
|
|
@@ -439,11 +432,68 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
439
432
|
}
|
|
440
433
|
}
|
|
441
434
|
orderByOriginalSource(records, sourceIndices, originals.selectedIds);
|
|
442
|
-
const
|
|
443
|
-
|
|
435
|
+
const thoughtOpenings = thinking.filter(record => !moved.has(record.sourceIndex));
|
|
436
|
+
const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
|
|
437
|
+
return { summary, records: [...records, ...thoughtOpenings] };
|
|
444
438
|
};
|
|
445
439
|
const compiled = tuck.compileDialogue(compileInput);
|
|
446
440
|
let offer = assemble(compiled.text);
|
|
441
|
+
// After the complete dialogue fill, observations spend the remaining
|
|
442
|
+
// room before the native tail's older end. The pinned tail is untouched.
|
|
443
|
+
let keptResultCost = 0;
|
|
444
|
+
const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
445
|
+
const counts = new Map<string, number>();
|
|
446
|
+
const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
447
|
+
// Reads and searches share the lead rank, newest result first, and one
|
|
448
|
+
// allowance. Keep L2's independent four-item caps and whole-item skips.
|
|
449
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
450
|
+
.sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
451
|
+
for (const record of candidates) {
|
|
452
|
+
if ((counts.get(record.title!) ?? 0) === 4) continue;
|
|
453
|
+
const extra = lineCost([record]);
|
|
454
|
+
if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target) continue;
|
|
455
|
+
keptResults.push(record); keptResultCost += extra;
|
|
456
|
+
counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
|
|
457
|
+
}
|
|
458
|
+
if (keptResults.length) offer = assemble(compiled.text, boundary);
|
|
459
|
+
const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
|
|
460
|
+
const shownFiles = lists.files.slice(0, Math.min(listedKeep, MAX_LEDGER_LINES));
|
|
461
|
+
const keptReadPaths = new Set(keptResults.filter(record => record.title === "Kept-read").map(record => {
|
|
462
|
+
const heading = record.text!.slice(0, record.text!.indexOf("\n"));
|
|
463
|
+
return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
|
|
464
|
+
}));
|
|
465
|
+
const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
|
|
466
|
+
const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
|
|
467
|
+
for (const item of shownFiles) item.definitions = observations.get(item.path);
|
|
468
|
+
const outputs = new Set<(typeof lists.actions)[number]>(), definitions = new Set<(typeof lists.files)[number]>();
|
|
469
|
+
let observationCost = 0;
|
|
470
|
+
const fitsObservation = (extra: number) => price(offer.summary.length + observationCost + extra, boundary) <= target;
|
|
471
|
+
// Each kind gives way as whole items, oldest first; an oversized newest
|
|
472
|
+
// item cannot promote an older one. Pointer lines need no extra omission.
|
|
473
|
+
for (const item of shownActions) {
|
|
474
|
+
if (!item.outputTail) continue;
|
|
475
|
+
const extra = lineCost(actionRecords([item], 1, new Set([item]))) - lineCost(actionRecords([item], 1));
|
|
476
|
+
if (!fitsObservation(extra)) break;
|
|
477
|
+
outputs.add(item); observationCost += extra;
|
|
478
|
+
}
|
|
479
|
+
for (const item of shownFiles) {
|
|
480
|
+
if (!item.definitions) continue;
|
|
481
|
+
const extra = lineCost(ledgerRecords([item], 1, new Set([item]))) - lineCost(ledgerRecords([item], 1));
|
|
482
|
+
if (!fitsObservation(extra)) break;
|
|
483
|
+
definitions.add(item); observationCost += extra;
|
|
484
|
+
}
|
|
485
|
+
if (outputs.size || definitions.size) {
|
|
486
|
+
ledger = [...actionRecords(lists.actions, listedKeep, outputs), ...ledgerRecords(lists.files, listedKeep, definitions)];
|
|
487
|
+
offer = assemble(compiled.text, boundary);
|
|
488
|
+
}
|
|
489
|
+
// Plain thinking follows kept reads/searches, output tails and definition maps.
|
|
490
|
+
let thinkingCost = 0;
|
|
491
|
+
for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
|
|
492
|
+
const extra = lineCost([record]);
|
|
493
|
+
if (price(offer.summary.length + thinkingCost + extra, boundary) > target) break;
|
|
494
|
+
thinking.push(record); thinkingCost += extra;
|
|
495
|
+
}
|
|
496
|
+
if (thinking.length) offer = assemble(compiled.text, boundary);
|
|
447
497
|
// Only capacity left after all higher ranks can extend the native tail
|
|
448
498
|
// beyond its preferred rank boundary. No old allocator is consulted.
|
|
449
499
|
const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
|
|
@@ -482,12 +532,13 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
482
532
|
missing.forEach((unit, at) => counts[at + 1] = counts[at]! + unit.count);
|
|
483
533
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
484
534
|
});
|
|
485
|
-
const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
|
|
486
|
-
const
|
|
535
|
+
const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
|
|
536
|
+
const keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
|
|
487
537
|
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
488
538
|
const extensionPrice = (at: number) => {
|
|
489
|
-
//
|
|
490
|
-
|
|
539
|
+
// Kept results already spend this extension's price. They stay in
|
|
540
|
+
// the compacted prefix, so the native tail never repeats them.
|
|
541
|
+
if (keptResults.length && at <= lastKeptResultPosition) return Infinity;
|
|
491
542
|
let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
|
|
492
543
|
let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
|
|
493
544
|
for (const range of ranges) {
|