pi-tuck 1.12.1 → 1.13.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 +18 -0
- package/README.md +4 -2
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/clip.d.ts +3 -2
- package/dist/src/clip.js +4 -3
- package/dist/src/compaction.js +3 -4
- package/dist/src/history-tools.js +6 -4
- package/dist/src/kept-reads.d.ts +5 -0
- package/dist/src/kept-reads.js +70 -0
- package/dist/src/ledger.js +8 -7
- package/dist/src/legacy-cleanup.js +1 -1
- package/dist/src/llama-continuation.js +3 -2
- package/dist/src/recall.d.ts +6 -13
- package/dist/src/recall.js +10 -10
- package/dist/src/thrash.js +0 -1
- package/dist/src/tuck/core/search-entries.js +1 -2
- package/dist/src/tuck.js +30 -12
- package/package.json +1 -1
- package/src/build-id.ts +1 -1
- package/src/clip.ts +4 -3
- package/src/compaction.ts +3 -5
- package/src/history-tools.ts +6 -2
- package/src/kept-reads.ts +56 -0
- package/src/ledger.ts +8 -4
- package/src/legacy-cleanup.ts +1 -1
- package/src/llama-continuation.ts +3 -2
- package/src/recall.ts +16 -15
- package/src/thrash.ts +0 -1
- package/src/tuck/core/search-entries.ts +1 -2
- package/src/tuck.ts +29 -12
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,24 @@
|
|
|
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.13.1]
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- Internal cleanup across the code, tests and benchmark scripts, with no change to any request.
|
|
11
|
+
|
|
12
|
+
## [1.13.0]
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- Kept tail after a cut: when the tool round just older than the kept turns would leave the kept tail short (a large read, command
|
|
17
|
+
output or file write that does not fit the tail), the summary now carries that round in a closing "Kept-round" section: its calls
|
|
18
|
+
and their text results, within two thirds of a quarter of the summary room. Parts that do not fit are clipped to their head and
|
|
19
|
+
tail with a `tuck_recall` locator for the rest, call arguments included. On recorded sessions, cuts whose kept context falls below
|
|
20
|
+
80% of the tail size went from 59 to 11 of 9,272. The 11 that remain: 5 at a 48k window, where the summary share cannot hold a
|
|
21
|
+
full tail; 4 where the crossing round is mostly the model's thinking, which is not carried; 1 where the entry before the kept turns
|
|
22
|
+
records no tokens; 1 where the newest entry is a length-stopped reply that the cut drops.
|
|
23
|
+
|
|
6
24
|
## [1.12.1]
|
|
7
25
|
|
|
8
26
|
### Fixed
|
package/README.md
CHANGED
|
@@ -12,11 +12,11 @@ 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.13.1. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.13.1` or `pi install git:github.com/galyavin/pi-tuck@v1.13.1`. To uninstall, run `pi remove` with the source you installed.
|
|
16
16
|
|
|
17
17
|
## Compaction and recall
|
|
18
18
|
|
|
19
|
-
A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It carries the output of a command a prompt told the agent to run (such as "Run: telex read NAME"), the newest four and at most 8,000 characters in all, since an agent driven by messages gets its tasks that way. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
|
|
19
|
+
A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It carries the output of a command a prompt told the agent to run (such as "Run: telex read NAME"), the newest four and at most 8,000 characters in all, since an agent driven by messages gets its tasks that way. When the tool round just before the kept turns is too large to keep with them, the summary carries it, clipped where needed, with a `tuck_recall` locator for each clipped part. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
|
|
20
20
|
|
|
21
21
|
Files the agent has read more than once are carried whole after the summary, most-read first, as far as a share of the summary allows. A file is carried only when its last read covered the whole file and the file on disk still holds exactly that text; the agent can edit from a carried copy without re-reading it. When a session's cuts keep dropping files the agent then reads again unchanged, pi-tuck moves its trim point later, to native Pi's (the larger of the room and `keepRecentTokens`), while keeping room for the next reply. Cuts still trim to the usual size.
|
|
22
22
|
|
|
@@ -132,6 +132,8 @@ See [Contributing](CONTRIBUTING.md) for stress tests and [the changelog](CHANGEL
|
|
|
132
132
|
- **128k recall replay.** Completed answer sets at cuts 1–4 supported the registered 3-point margin against Pi's summaries and kept messages. The scoring excluded 52 of 95 pi-tuck sets that aborted. [Retention results](benchmark/RESULTS-MAIN.md)
|
|
133
133
|
- **32k live run.** pi-tuck 1.0.5 resolved 120 of 150 tasks versus Pi's 94 and observation masking's 117. The one-sided 95% lower bounds were +10.7 and −2.7 points, respectively. pi-tuck recorded one dead task against a target of zero. [32k results](benchmark/RESULTS-32K-ACCEPT.md)
|
|
134
134
|
|
|
135
|
+
Tested so far: Qwen3.8 Flash Next (local) at a 128k window, DeepSeek V4.1 Flash at a 32k window, and a local model at 272k and 230k windows in the [72-hour run](docs/case-study-long-run.md). Other models and windows have not been measured.
|
|
136
|
+
|
|
135
137
|
The [benchmark index](benchmark/README.md) records the models, versions, plans, and scope of each result.
|
|
136
138
|
|
|
137
139
|
## Author
|
package/dist/src/build-id.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const BUILD_ID = "
|
|
1
|
+
export declare const BUILD_ID = "033d8cbd5b696806f9d3a049a2d5380e4bb05cca6763108ffa1afa8ee51d9872";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "033d8cbd5b696806f9d3a049a2d5380e4bb05cca6763108ffa1afa8ee51d9872";
|
package/dist/src/clip.d.ts
CHANGED
|
@@ -4,12 +4,13 @@ export interface Clip {
|
|
|
4
4
|
toolCallId: string;
|
|
5
5
|
content: ToolResultMessage["content"];
|
|
6
6
|
}
|
|
7
|
-
/** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
|
|
7
|
+
/** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
|
|
8
|
+
* `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
|
|
8
9
|
export declare const clipText: (text: string, keep: number, locator: {
|
|
9
10
|
entryId: string;
|
|
10
11
|
} | {
|
|
11
12
|
index: number;
|
|
12
|
-
}) => string;
|
|
13
|
+
}, base?: number) => string;
|
|
13
14
|
/** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
|
|
14
15
|
* The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
|
|
15
16
|
* reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
|
package/dist/src/clip.js
CHANGED
|
@@ -3,12 +3,13 @@ import { MAX_RECALL_CHARACTERS } from "./recall.js";
|
|
|
3
3
|
/** The text `tuck_recall {entryId, offset}` reads from a text-only result; any other result is not clipped. */
|
|
4
4
|
const textOf = (message) => message.content.every(block => block.type === "text")
|
|
5
5
|
? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
|
|
6
|
-
/** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
|
|
7
|
-
|
|
6
|
+
/** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
|
|
7
|
+
* `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
|
|
8
|
+
export const clipText = (text, keep, locator, base = 0) => {
|
|
8
9
|
const head = Math.ceil(keep / 2), tail = keep - head;
|
|
9
10
|
return text.slice(0, head) +
|
|
10
11
|
`\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
|
|
11
|
-
`tuck_recall ${JSON.stringify({ ...locator, offset: head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
|
|
12
|
+
`tuck_recall ${JSON.stringify({ ...locator, offset: base + head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
|
|
12
13
|
};
|
|
13
14
|
const clipped = (text, keep, entryId) => [{ type: "text", text: clipText(text, keep, { entryId }) }];
|
|
14
15
|
/** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
|
package/dist/src/compaction.js
CHANGED
|
@@ -266,7 +266,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
266
266
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
267
267
|
if (!validCutAt(cutAt))
|
|
268
268
|
throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
269
|
-
const view = (ctx
|
|
269
|
+
const view = (ctx) => (run?.cut ?? liveCut).view(ctx);
|
|
270
270
|
const liveCut = new PendingCut();
|
|
271
271
|
const recorder = new IncidentRecorder(options.diagnostics);
|
|
272
272
|
let proposalId;
|
|
@@ -587,9 +587,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
587
587
|
const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
|
|
588
588
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
589
589
|
const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
|
|
590
|
-
// The planner counts with the same function,
|
|
591
|
-
|
|
592
|
-
const plannerMeasureFor = (ctx) => Object.assign((messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
|
|
590
|
+
// The planner counts with the same function, and also prices a single message.
|
|
591
|
+
const plannerMeasureFor = (ctx) => Object.assign(measureFor(ctx), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
|
|
593
592
|
const hostMessages = (ctx) => options.hostMessages?.(ctx) ?? [];
|
|
594
593
|
const toolShapes = (names) => {
|
|
595
594
|
const selected = new Set(names);
|
|
@@ -10,10 +10,13 @@ export function historyToolNames(pi, names, enabled) {
|
|
|
10
10
|
const registered = new Set(pi.getAllTools().map(tool => tool.name));
|
|
11
11
|
return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
|
|
13
|
+
const setIfChanged = (pi, current, next) => {
|
|
15
14
|
if (current.length !== next.length || current.some((name, index) => name !== next[index]))
|
|
16
15
|
pi.setActiveTools(next);
|
|
16
|
+
};
|
|
17
|
+
export function applyHistoryTools(pi, enabled) {
|
|
18
|
+
const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
|
|
19
|
+
setIfChanged(pi, current, next);
|
|
17
20
|
}
|
|
18
21
|
/** Match only our part of Pi's saved declaration snapshot, so its loop records no activation/removal message. Legacy sessions can
|
|
19
22
|
* already declare our tools; new sessions declare them only in the request projection. Executable tools are restored at turn_start. */
|
|
@@ -21,8 +24,7 @@ export function stageHistoryTools(pi, messages) {
|
|
|
21
24
|
const declared = new Set(getCurrentTools(convertToLlm(messages)).map(tool => tool.name));
|
|
22
25
|
const current = pi.getActiveTools();
|
|
23
26
|
const next = historyToolNames(pi, current, true).filter(name => !own(name) || declared.has(name));
|
|
24
|
-
|
|
25
|
-
pi.setActiveTools(next);
|
|
27
|
+
setIfChanged(pi, current, next);
|
|
26
28
|
return next;
|
|
27
29
|
}
|
|
28
30
|
/** Pi has already declared the request's tools before queued user messages are appended. A prompt cut planned on such a message needs its declarations
|
package/dist/src/kept-reads.d.ts
CHANGED
|
@@ -5,3 +5,8 @@ export declare function keptReadCandidates(entries: readonly (SessionEntry | Ses
|
|
|
5
5
|
/** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
|
|
6
6
|
* first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
|
|
7
7
|
export declare function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
|
|
8
|
+
/** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
|
|
9
|
+
* results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
|
|
10
|
+
* tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
|
|
11
|
+
* Nothing when no round ends at the boundary, a result is not text, a result cannot be recalled, or the budget cannot hold even the locators. */
|
|
12
|
+
export declare function crossingRoundRecord(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, budget: number): TranscriptRecord | undefined;
|
package/dist/src/kept-reads.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { classifyBash } from "./bash-command.js";
|
|
2
|
+
import { conversationTokens } from "./budget.js";
|
|
3
|
+
import { clipText } from "./clip.js";
|
|
2
4
|
import { pathKey } from "./path-key.js";
|
|
3
5
|
import { isDiscardedResponse } from "./protocol.js";
|
|
4
6
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
7
|
+
import { readableContentParts } from "./tuck/core/readable-content.js";
|
|
5
8
|
import { extractPath } from "./tuck/core/tool-args.js";
|
|
6
9
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
7
10
|
export function keptReadCandidates(entries, indices, resolvable, exclude = new Set()) {
|
|
@@ -119,3 +122,70 @@ export function promptOutputCandidates(entries, indices, resolvable) {
|
|
|
119
122
|
}
|
|
120
123
|
return records;
|
|
121
124
|
}
|
|
125
|
+
/** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
|
|
126
|
+
* results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
|
|
127
|
+
* tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
|
|
128
|
+
* Nothing when no round ends at the boundary, a result is not text, a result cannot be recalled, or the budget cannot hold even the locators. */
|
|
129
|
+
export function crossingRoundRecord(entries, boundary, indices, resolvable, budget) {
|
|
130
|
+
const results = [];
|
|
131
|
+
let at = boundary - 1;
|
|
132
|
+
for (; at >= 0; at--) {
|
|
133
|
+
const entry = entries[at];
|
|
134
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult")
|
|
135
|
+
break;
|
|
136
|
+
results.unshift({ entry, message: entry.message });
|
|
137
|
+
}
|
|
138
|
+
const call = entries[at];
|
|
139
|
+
if (!results.length || call?.type !== "message" || call.message.role !== "assistant")
|
|
140
|
+
return undefined;
|
|
141
|
+
// Each call's arguments and their place in the readable text: {"toolCall":{"name":…,"id":…,"arguments":ARGS}}
|
|
142
|
+
const parts = new Map(readableContentParts(call.message.content, true).flatMap(part => {
|
|
143
|
+
if (part.kind !== "toolCall")
|
|
144
|
+
return [];
|
|
145
|
+
const args = JSON.stringify(part.arguments) ?? "";
|
|
146
|
+
return [[JSON.parse(part.text).toolCall.id,
|
|
147
|
+
{ name: part.toolName, args, offset: part.offset + part.text.length - args.length - 2 }]];
|
|
148
|
+
}));
|
|
149
|
+
const sourceIndex = indices.get(results[0].entry.id);
|
|
150
|
+
if (sourceIndex === undefined || results.some(({ entry, message }) => !parts.has(message.toolCallId) || !isTextOnly(message.content) ||
|
|
151
|
+
indices.get(entry.id) === undefined || !resolvable(entry)))
|
|
152
|
+
return undefined;
|
|
153
|
+
const callIndex = indices.get(call.id), callLocatable = callIndex !== undefined && resolvable(call);
|
|
154
|
+
const size = (text) => conversationTokens([{ role: "user", content: text, timestamp: 0 }]);
|
|
155
|
+
// One item per call's arguments and per result; arguments that cannot be recalled keep a fixed 400-character head.
|
|
156
|
+
const items = results.flatMap(({ entry, message }) => {
|
|
157
|
+
const part = parts.get(message.toolCallId);
|
|
158
|
+
const args = callLocatable ? { text: part.args, locator: { index: callIndex }, base: part.offset }
|
|
159
|
+
: { text: part.args.length > 400 ? `${part.args.slice(0, 400)}…` : part.args, locator: undefined, base: 0 };
|
|
160
|
+
return [args, { text: textOf(message.content), locator: { index: indices.get(entry.id) }, base: 0 }];
|
|
161
|
+
}).map((item, index) => ({ ...item, index, size: size(item.text) }));
|
|
162
|
+
const shown = [];
|
|
163
|
+
let left = budget - Math.ceil(results.reduce((n, { message }) => n + parts.get(message.toolCallId).name.length + 4, 0) / 4);
|
|
164
|
+
const order = [...items].sort((a, b) => a.size - b.size);
|
|
165
|
+
for (const [rank, item] of order.entries()) {
|
|
166
|
+
const share = Math.floor(left / (order.length - rank));
|
|
167
|
+
if (item.size <= share || !item.locator) {
|
|
168
|
+
shown[item.index] = item.text;
|
|
169
|
+
left -= item.size;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const locator = item.locator, clip = (keep) => clipText(item.text, keep, locator, item.base);
|
|
173
|
+
if (size(clip(0)) > share)
|
|
174
|
+
return undefined;
|
|
175
|
+
let low = 0, high = item.text.length;
|
|
176
|
+
while (low < high) {
|
|
177
|
+
const mid = Math.ceil((low + high) / 2);
|
|
178
|
+
if (size(clip(mid)) <= share)
|
|
179
|
+
low = mid;
|
|
180
|
+
else
|
|
181
|
+
high = mid - 1;
|
|
182
|
+
}
|
|
183
|
+
shown[item.index] = clip(low);
|
|
184
|
+
left -= size(shown[item.index]);
|
|
185
|
+
}
|
|
186
|
+
if (left < 0)
|
|
187
|
+
return undefined;
|
|
188
|
+
const body = results.map(({ message }, i) => `${parts.get(message.toolCallId).name} ${shown[2 * i]}:\n${shown[2 * i + 1]}`).join("\n\n");
|
|
189
|
+
return { kind: "section", title: "Kept-round", sourceIndex,
|
|
190
|
+
text: `the tool round just before the kept tail (as recorded at #${sourceIndex}; clipped where a recall locator says so):\n${body}` };
|
|
191
|
+
}
|
package/dist/src/ledger.js
CHANGED
|
@@ -15,13 +15,17 @@ export const head = (text, max) => {
|
|
|
15
15
|
return text;
|
|
16
16
|
return text.slice(0, /[\uD800-\uDBFF]/u.test(text[max - 1]) ? max - 1 : max);
|
|
17
17
|
};
|
|
18
|
-
|
|
19
|
-
* A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
|
|
20
|
-
export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
|
|
18
|
+
const resultsByCall = (entries) => {
|
|
21
19
|
const results = new Map();
|
|
22
20
|
for (const entry of entries)
|
|
23
21
|
if (entry.type === "message" && entry.message.role === "toolResult")
|
|
24
22
|
results.set(entry.message.toolCallId, entry);
|
|
23
|
+
return results;
|
|
24
|
+
};
|
|
25
|
+
/** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
|
|
26
|
+
* A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
|
|
27
|
+
export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
|
|
28
|
+
const results = resultsByCall(entries);
|
|
25
29
|
const last = new Map();
|
|
26
30
|
for (const entry of entries) {
|
|
27
31
|
if (entry.type !== "message" || entry.message.role !== "assistant")
|
|
@@ -66,10 +70,7 @@ export const ACTIONS_HEADING = "Tool calls other than read, write, edit and hist
|
|
|
66
70
|
/** The calls exactly as recorded, newest first, with the command (or else the arguments) flattened to one line. A call from a failed or
|
|
67
71
|
* aborted response is not listed; a call whose result is an error is marked. */
|
|
68
72
|
export function actionItems(entries, indices, resolvable, failedCalls) {
|
|
69
|
-
const results =
|
|
70
|
-
for (const entry of entries)
|
|
71
|
-
if (entry.type === "message" && entry.message.role === "toolResult")
|
|
72
|
-
results.set(entry.message.toolCallId, entry);
|
|
73
|
+
const results = resultsByCall(entries);
|
|
73
74
|
const calls = [];
|
|
74
75
|
for (const entry of entries) {
|
|
75
76
|
if (entry.type !== "message" || entry.message.role !== "assistant")
|
|
@@ -128,7 +128,7 @@ export function cleanupLegacyFiles(ctx) {
|
|
|
128
128
|
}
|
|
129
129
|
const children = await readdir(root);
|
|
130
130
|
started = true;
|
|
131
|
-
const names = [...directories, ...children.filter(name => temporaryDirectory.
|
|
131
|
+
const names = [...directories, ...children.filter(name => temporaryDirectory.test(name))];
|
|
132
132
|
const candidates = [];
|
|
133
133
|
for (const name of names) {
|
|
134
134
|
const path = join(root, name);
|
|
@@ -5,6 +5,7 @@ const wire = (value) => {
|
|
|
5
5
|
throw new Error("Expected a Chat Completions request");
|
|
6
6
|
return value;
|
|
7
7
|
};
|
|
8
|
+
const cancelled = (message) => ({ ...message, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" });
|
|
8
9
|
const promptTokens = (message) => message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
|
|
9
10
|
export function llamaContinuationStream(profile, native) {
|
|
10
11
|
return (model, context, options) => {
|
|
@@ -98,7 +99,7 @@ export function llamaContinuationStream(profile, native) {
|
|
|
98
99
|
clearTimeout(admissionTimer);
|
|
99
100
|
}
|
|
100
101
|
if (signal.aborted) {
|
|
101
|
-
first =
|
|
102
|
+
first = cancelled(first);
|
|
102
103
|
}
|
|
103
104
|
else if (!cacheVerified) {
|
|
104
105
|
first = { ...first, errorMessage: CONTINUATION_CACHE_MISS };
|
|
@@ -150,7 +151,7 @@ export function llamaContinuationStream(profile, native) {
|
|
|
150
151
|
if (!first)
|
|
151
152
|
throw error;
|
|
152
153
|
if (signal.aborted)
|
|
153
|
-
first =
|
|
154
|
+
first = cancelled(first);
|
|
154
155
|
}
|
|
155
156
|
finally {
|
|
156
157
|
if (thinkingEnd)
|
package/dist/src/recall.d.ts
CHANGED
|
@@ -76,6 +76,9 @@ export interface ReadableEntry {
|
|
|
76
76
|
arguments: Record<string, unknown>;
|
|
77
77
|
};
|
|
78
78
|
}
|
|
79
|
+
type ProducerLink = NonNullable<ReadableEntry["producerRead"]> & {
|
|
80
|
+
sourceTime: SourceTime;
|
|
81
|
+
};
|
|
79
82
|
interface DiscoveryEntry extends ReadableEntry {
|
|
80
83
|
sourceText: string;
|
|
81
84
|
ranges: {
|
|
@@ -85,20 +88,10 @@ interface DiscoveryEntry extends ReadableEntry {
|
|
|
85
88
|
}
|
|
86
89
|
export declare function createRecall(policy?: RecallPolicy): {
|
|
87
90
|
isHistorySource: (entry: SessionEntry) => boolean;
|
|
88
|
-
readable: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string,
|
|
89
|
-
sourceTime: SourceTime;
|
|
90
|
-
}>) => ReadableEntry | undefined;
|
|
91
|
+
readable: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>) => ReadableEntry | undefined;
|
|
91
92
|
recallAttempts: (branch: readonly SessionEntry[]) => ReadonlyMap<string, RecordedAttempt | null>;
|
|
92
|
-
producerReads: (branch: readonly SessionEntry[]) => Map<string,
|
|
93
|
-
|
|
94
|
-
offset: number;
|
|
95
|
-
limit: number;
|
|
96
|
-
} & {
|
|
97
|
-
sourceTime: SourceTime;
|
|
98
|
-
}>;
|
|
99
|
-
discoveryEntry: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & {
|
|
100
|
-
sourceTime: SourceTime;
|
|
101
|
-
}>) => DiscoveryEntry | undefined;
|
|
93
|
+
producerReads: (branch: readonly SessionEntry[]) => Map<string, ProducerLink>;
|
|
94
|
+
discoveryEntry: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>) => DiscoveryEntry | undefined;
|
|
102
95
|
discoveryExcerpt: (row: DiscoveryEntry, query: PreparedKeywordQuery) => {
|
|
103
96
|
snippet: string;
|
|
104
97
|
totalCharacters: number;
|
package/dist/src/recall.js
CHANGED
|
@@ -264,16 +264,6 @@ export function createRecall(policy = {}) {
|
|
|
264
264
|
return { snippet: row.sourceText.slice(range.start, range.end), totalCharacters: row.sourceText.length,
|
|
265
265
|
read: { entryId: row.entryId, offset: range.start, limit: range.end - range.start } };
|
|
266
266
|
}
|
|
267
|
-
/**
|
|
268
|
-
* The host supplies this role's current branch; this function never opens a path.
|
|
269
|
-
* Query is a case-insensitive literal over eligible source ranges. Offset/limit
|
|
270
|
-
* page the concatenation of matching texts, with no added separators. Without an
|
|
271
|
-
* explicit offset, a source-scoped query returns the whole matching readable
|
|
272
|
-
* source when it fits, otherwise disjoint exact match windows;
|
|
273
|
-
* unscoped browsing starts up to 120 characters before its first match.
|
|
274
|
-
* Returned nextOffset uses the same filter and can page through any long entry.
|
|
275
|
-
* At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
|
|
276
|
-
*/
|
|
277
267
|
/** Add factual call context to a demanded complete receipt, never to discovery or partial pages. */
|
|
278
268
|
function contextualReceipt(branch, entryId, fragment) {
|
|
279
269
|
const read = fragment.producerRead;
|
|
@@ -301,6 +291,16 @@ export function createRecall(policy = {}) {
|
|
|
301
291
|
return fragment;
|
|
302
292
|
} // An incomplete or malformed prefix remains only a locator.
|
|
303
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* The host supplies this role's current branch; this function never opens a path.
|
|
296
|
+
* Query is a case-insensitive literal over eligible source ranges. Offset/limit
|
|
297
|
+
* page the concatenation of matching texts, with no added separators. Without an
|
|
298
|
+
* explicit offset, a source-scoped query returns the whole matching readable
|
|
299
|
+
* source when it fits, otherwise disjoint exact match windows;
|
|
300
|
+
* unscoped browsing starts up to 120 characters before its first match.
|
|
301
|
+
* Returned nextOffset uses the same filter and can page through any long entry.
|
|
302
|
+
* At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
|
|
303
|
+
*/
|
|
304
304
|
function recallHistory(branch, options = {}) {
|
|
305
305
|
const { query, entryId } = options;
|
|
306
306
|
if (query !== undefined && (typeof query !== "string" || !query.length || query.length > MAX_RECALL_QUERY_CHARACTERS))
|
package/dist/src/thrash.js
CHANGED
|
@@ -24,7 +24,6 @@ export function rereadsAfterCuts(branch) {
|
|
|
24
24
|
current = epoch[i];
|
|
25
25
|
replies = 0;
|
|
26
26
|
}
|
|
27
|
-
const cuts = current;
|
|
28
27
|
replies++;
|
|
29
28
|
for (const block of message.content) {
|
|
30
29
|
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
|
|
@@ -70,9 +70,8 @@ const bm25Score = (doc, terms, ctx) => {
|
|
|
70
70
|
};
|
|
71
71
|
/** Rank already-eligible recall rows; filtering and paging belong to the caller. */
|
|
72
72
|
export const rankRecallRows = (rows, query) => {
|
|
73
|
-
const rawQuery = query.trim();
|
|
74
73
|
const checkBudget = startBudget();
|
|
75
|
-
const prepared = prepareKeywordQuery(
|
|
74
|
+
const prepared = prepareKeywordQuery(query);
|
|
76
75
|
const terms = prepared.terms;
|
|
77
76
|
// Preserve the role prefix and trailing space of the original BM25 documents.
|
|
78
77
|
const docs = rows.map((row) => `${row.role} ${row.text} `);
|
package/dist/src/tuck.js
CHANGED
|
@@ -7,7 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.j
|
|
|
7
7
|
import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
9
9
|
import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
|
|
10
|
-
import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
|
|
10
|
+
import { crossingRoundRecord, keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
|
|
11
11
|
import { workingSetCandidates } from "./working-set.js";
|
|
12
12
|
import { keptSearchCandidates } from "./kept-searches.js";
|
|
13
13
|
import { clipText } from "./clip.js";
|
|
@@ -42,6 +42,7 @@ export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {},
|
|
|
42
42
|
* `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
|
|
43
43
|
export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true) {
|
|
44
44
|
const { isHistorySource, readable } = createRecall(policy);
|
|
45
|
+
const resolvable = (entry) => readable(entry) !== undefined;
|
|
45
46
|
const projected = ctx.sessionManager.buildSessionProjection();
|
|
46
47
|
if (input.branchEntries.some(entry => entry.type === "context_edit" && entry.replacement !== null))
|
|
47
48
|
return { unavailable: "pi-tuck does not support replacement context edits" };
|
|
@@ -164,7 +165,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
164
165
|
if (!header)
|
|
165
166
|
throw new Error("Missing native session header");
|
|
166
167
|
const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
|
|
167
|
-
const minimumOpeningLength = 80, openingLength = Math.max(
|
|
168
|
+
const minimumOpeningLength = 80, openingLength = Math.max(minimumOpeningLength, Math.floor(Math.sqrt(room * 4)));
|
|
168
169
|
// At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
|
|
169
170
|
const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
|
|
170
171
|
const positions = new Map(entries.map((entry, at) => [entry.id, at]));
|
|
@@ -217,7 +218,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
217
218
|
for (let at = branch.length - 1; at >= 0; at--)
|
|
218
219
|
native[at] += native[at + 1];
|
|
219
220
|
const nativeAt = (boundary) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary].id)];
|
|
220
|
-
const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
|
|
221
|
+
const originalBoundary = preferredBoundary, tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
|
|
221
222
|
// Move only the older end, to the newest whole protocol-safe entries
|
|
222
223
|
// within the shared tail size. Required current/fresh native sources
|
|
223
224
|
// stay whole even when their floor exceeds that preferred amount.
|
|
@@ -336,7 +337,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
336
337
|
// existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
|
|
337
338
|
if (input.deepest) {
|
|
338
339
|
// The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
|
|
339
|
-
const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices,
|
|
340
|
+
const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, resolvable);
|
|
340
341
|
const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
|
|
341
342
|
const projection = preview(summary, floorBoundary);
|
|
342
343
|
assertNativeToolRounds(projection);
|
|
@@ -351,8 +352,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
351
352
|
const cached = listCache.get(boundary);
|
|
352
353
|
if (cached)
|
|
353
354
|
return cached;
|
|
354
|
-
const compacted = entries.slice(0, boundary)
|
|
355
|
-
const files = ledgerItems(compacted, indices,
|
|
355
|
+
const compacted = entries.slice(0, boundary);
|
|
356
|
+
const files = ledgerItems(compacted, indices, resolvable, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolvable, failedCalls);
|
|
356
357
|
const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
|
|
357
358
|
listCache.set(boundary, lists);
|
|
358
359
|
return lists;
|
|
@@ -403,7 +404,6 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
403
404
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
404
405
|
// The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
|
|
405
406
|
// WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
|
|
406
|
-
const resolvable = (entry) => readable(entry) !== undefined;
|
|
407
407
|
const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
|
|
408
408
|
if (workingSet.files.length) {
|
|
409
409
|
const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
|
|
@@ -419,13 +419,14 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
419
419
|
}
|
|
420
420
|
const carriedKeys = new Set(carried.map(file => file.key));
|
|
421
421
|
let ledger = lists.records;
|
|
422
|
-
|
|
422
|
+
const maxListLines = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
|
|
423
|
+
let listedKeep = maxListLines;
|
|
423
424
|
// List caps are existing ranking policy; only the carried target is a
|
|
424
425
|
// spending limit. Candidate list sizes have fixed, cached line prices.
|
|
425
426
|
if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
426
427
|
ledger = [];
|
|
427
428
|
listedKeep = 0;
|
|
428
|
-
for (let keep = 0; keep <= Math.min(
|
|
429
|
+
for (let keep = 0; keep <= Math.min(maxListLines, Math.max(lists.files.length, lists.actions.length)); keep++) {
|
|
429
430
|
const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
|
|
430
431
|
if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
|
|
431
432
|
ledger = candidate;
|
|
@@ -438,7 +439,19 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
438
439
|
return row?.message.role === "user" && isTextOnly(row.message.content);
|
|
439
440
|
}));
|
|
440
441
|
const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
|
|
442
|
+
// The tool round the tail boundary passed (the one crossing the tail size) rides in the closing section, so the tail is not left far
|
|
443
|
+
// below its size. It is paid from the summary, up to what the native tail leaves of that size, and is reserved before the dialogue fills.
|
|
444
|
+
let crossingRound;
|
|
441
445
|
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
|
|
446
|
+
if (boundary === preferredBoundary && (preferredBoundary > originalBoundary || budgetCut) && boundary < entries.length) {
|
|
447
|
+
const crossing = entries.slice(0, boundary).findLastIndex(entry => !(entry.type === "message" && entry.message.role === "toolResult"));
|
|
448
|
+
const tail = crossing < 0 ? 0 : carriedTailTokens(Math.max(nativeAt(originalBoundary), nativeAt(crossing))) - nativeAt(boundary);
|
|
449
|
+
// Like the working set, at most WORKING_SET_SHARE of what the summary may spend beyond its protected rows: the dialogue keeps the rest.
|
|
450
|
+
const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * maxBriefChars / 4));
|
|
451
|
+
if (size > 0)
|
|
452
|
+
crossingRound = crossingRoundRecord(entries, boundary, indices, resolvable, size);
|
|
453
|
+
}
|
|
454
|
+
const crossingCost = crossingRound ? lineCost([crossingRound]) : 0;
|
|
442
455
|
const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
|
|
443
456
|
sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
|
|
444
457
|
ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
|
|
@@ -600,7 +613,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
600
613
|
if ((counts.get(record.title) ?? 0) === 4)
|
|
601
614
|
continue;
|
|
602
615
|
const extra = lineCost([record]);
|
|
603
|
-
if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target)
|
|
616
|
+
if (keptResultCost + extra > keptResultCap || price(offer.summary.length + crossingCost + keptResultCost + extra, boundary) > target)
|
|
604
617
|
continue;
|
|
605
618
|
keptResults.push(record);
|
|
606
619
|
keptResultCost += extra;
|
|
@@ -620,7 +633,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
620
633
|
item.definitions = observations.get(item.path);
|
|
621
634
|
const outputs = new Set(), definitions = new Set();
|
|
622
635
|
let observationCost = 0;
|
|
623
|
-
const fitsObservation = (extra) => price(offer.summary.length + observationCost + extra, boundary) <= target;
|
|
636
|
+
const fitsObservation = (extra) => price(offer.summary.length + crossingCost + observationCost + extra, boundary) <= target;
|
|
624
637
|
// Each kind gives way as whole items, oldest first; an oversized newest
|
|
625
638
|
// item cannot promote an older one. Pointer lines need no extra omission.
|
|
626
639
|
for (const item of shownActions) {
|
|
@@ -649,7 +662,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
649
662
|
let thinkingCost = 0;
|
|
650
663
|
for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
|
|
651
664
|
const extra = lineCost([record]);
|
|
652
|
-
if (price(offer.summary.length + thinkingCost + extra, boundary) > target)
|
|
665
|
+
if (price(offer.summary.length + crossingCost + thinkingCost + extra, boundary) > target)
|
|
653
666
|
break;
|
|
654
667
|
thinking.push(record);
|
|
655
668
|
thinkingCost += extra;
|
|
@@ -734,6 +747,11 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
734
747
|
if (boundary !== compiledBoundary)
|
|
735
748
|
offer = assemble(compiled.text, boundary);
|
|
736
749
|
}
|
|
750
|
+
// Still the preferred boundary (leftover room did not take the round into the native tail): the round rides in the summary instead.
|
|
751
|
+
if (crossingRound && boundary === preferredBoundary && price(offer.summary.length + crossingCost, boundary) <= target) {
|
|
752
|
+
keptResults.unshift(crossingRound);
|
|
753
|
+
offer = assemble(compiled.text, boundary);
|
|
754
|
+
}
|
|
737
755
|
const projection = preview(offer.summary, boundary);
|
|
738
756
|
assertNativeToolRounds(projection);
|
|
739
757
|
const after = measure(projection);
|
package/package.json
CHANGED
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "033d8cbd5b696806f9d3a049a2d5380e4bb05cca6763108ffa1afa8ee51d9872";
|
package/src/clip.ts
CHANGED
|
@@ -9,12 +9,13 @@ export interface Clip { toolCallId: string; content: ToolResultMessage["content"
|
|
|
9
9
|
const textOf = (message: ToolResultMessage) => message.content.every(block => block.type === "text")
|
|
10
10
|
? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
|
|
11
11
|
|
|
12
|
-
/** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
|
|
13
|
-
|
|
12
|
+
/** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
|
|
13
|
+
* `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
|
|
14
|
+
export const clipText = (text: string, keep: number, locator: { entryId: string } | { index: number }, base = 0): string => {
|
|
14
15
|
const head = Math.ceil(keep / 2), tail = keep - head;
|
|
15
16
|
return text.slice(0, head) +
|
|
16
17
|
`\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
|
|
17
|
-
`tuck_recall ${JSON.stringify({ ...locator, offset: head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
|
|
18
|
+
`tuck_recall ${JSON.stringify({ ...locator, offset: base + head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
|
|
18
19
|
};
|
|
19
20
|
|
|
20
21
|
const clipped = (text: string, keep: number, entryId: string): ToolResultMessage["content"] => [{ type: "text", text: clipText(text, keep, { entryId }) }];
|
package/src/compaction.ts
CHANGED
|
@@ -271,7 +271,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
271
271
|
};
|
|
272
272
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
273
273
|
if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
274
|
-
const view = (ctx: ExtensionContext
|
|
274
|
+
const view = (ctx: ExtensionContext) => (run?.cut ?? liveCut).view(ctx);
|
|
275
275
|
const liveCut = new PendingCut();
|
|
276
276
|
const recorder = new IncidentRecorder(options.diagnostics);
|
|
277
277
|
let proposalId: string | undefined;
|
|
@@ -527,10 +527,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
527
527
|
const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
|
|
528
528
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
529
529
|
const measureFor = (ctx: ExtensionContext) => (messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
|
|
530
|
-
// The planner counts with the same function,
|
|
531
|
-
|
|
532
|
-
const plannerMeasureFor = (ctx: ExtensionContext) => Object.assign(
|
|
533
|
-
(messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy),
|
|
530
|
+
// The planner counts with the same function, and also prices a single message.
|
|
531
|
+
const plannerMeasureFor = (ctx: ExtensionContext) => Object.assign(measureFor(ctx),
|
|
534
532
|
{ messageTokens: (message: Messages[number]) => conversationTokens(applyClips([message], clips())) });
|
|
535
533
|
const hostMessages = (ctx: ExtensionContext) => options.hostMessages?.(ctx) ?? [];
|
|
536
534
|
const toolShapes = (names: Iterable<string>) => {
|
package/src/history-tools.ts
CHANGED
|
@@ -14,9 +14,13 @@ export function historyToolNames(pi: ExtensionAPI, names: readonly string[], ena
|
|
|
14
14
|
return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
const setIfChanged = (pi: ExtensionAPI, current: readonly string[], next: string[]): void => {
|
|
18
|
+
if (current.length !== next.length || current.some((name, index) => name !== next[index])) pi.setActiveTools(next);
|
|
19
|
+
};
|
|
20
|
+
|
|
17
21
|
export function applyHistoryTools(pi: ExtensionAPI, enabled: boolean): void {
|
|
18
22
|
const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
|
|
19
|
-
|
|
23
|
+
setIfChanged(pi, current, next);
|
|
20
24
|
}
|
|
21
25
|
|
|
22
26
|
/** Match only our part of Pi's saved declaration snapshot, so its loop records no activation/removal message. Legacy sessions can
|
|
@@ -25,7 +29,7 @@ export function stageHistoryTools(pi: ExtensionAPI, messages: Messages): string[
|
|
|
25
29
|
const declared = new Set(getCurrentTools(convertToLlm(messages)).map(tool => tool.name));
|
|
26
30
|
const current = pi.getActiveTools();
|
|
27
31
|
const next = historyToolNames(pi, current, true).filter(name => !own(name) || declared.has(name));
|
|
28
|
-
|
|
32
|
+
setIfChanged(pi, current, next);
|
|
29
33
|
return next;
|
|
30
34
|
}
|
|
31
35
|
|
package/src/kept-reads.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ToolResultMessage } from "@earendil-works/pi-ai";
|
|
2
3
|
import { classifyBash } from "./bash-command";
|
|
4
|
+
import { conversationTokens, type Messages } from "./budget";
|
|
5
|
+
import { clipText } from "./clip";
|
|
3
6
|
import { pathKey } from "./path-key";
|
|
4
7
|
import { isDiscardedResponse } from "./protocol";
|
|
5
8
|
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
9
|
+
import { readableContentParts } from "./tuck/core/readable-content";
|
|
6
10
|
import { extractPath } from "./tuck/core/tool-args";
|
|
7
11
|
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
8
12
|
|
|
@@ -94,3 +98,55 @@ export function promptOutputCandidates(entries: readonly (SessionEntry | Session
|
|
|
94
98
|
}
|
|
95
99
|
return records;
|
|
96
100
|
}
|
|
101
|
+
|
|
102
|
+
/** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
|
|
103
|
+
* results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
|
|
104
|
+
* tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
|
|
105
|
+
* Nothing when no round ends at the boundary, a result is not text, a result cannot be recalled, or the budget cannot hold even the locators. */
|
|
106
|
+
export function crossingRoundRecord(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>,
|
|
107
|
+
resolvable: (entry: SessionEntry) => boolean, budget: number): TranscriptRecord | undefined {
|
|
108
|
+
const results: { entry: SessionEntry; message: ToolResultMessage }[] = [];
|
|
109
|
+
let at = boundary - 1;
|
|
110
|
+
for (; at >= 0; at--) {
|
|
111
|
+
const entry = entries[at]!;
|
|
112
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult") break;
|
|
113
|
+
results.unshift({ entry, message: entry.message as ToolResultMessage });
|
|
114
|
+
}
|
|
115
|
+
const call = entries[at];
|
|
116
|
+
if (!results.length || call?.type !== "message" || call.message.role !== "assistant") return undefined;
|
|
117
|
+
// Each call's arguments and their place in the readable text: {"toolCall":{"name":…,"id":…,"arguments":ARGS}}
|
|
118
|
+
const parts = new Map(readableContentParts(call.message.content, true).flatMap(part => {
|
|
119
|
+
if (part.kind !== "toolCall") return [];
|
|
120
|
+
const args = JSON.stringify(part.arguments) ?? "";
|
|
121
|
+
return [[(JSON.parse(part.text) as { toolCall: { id: string } }).toolCall.id,
|
|
122
|
+
{ name: part.toolName!, args, offset: part.offset + part.text.length - args.length - 2 }] as const];
|
|
123
|
+
}));
|
|
124
|
+
const sourceIndex = indices.get(results[0]!.entry.id);
|
|
125
|
+
if (sourceIndex === undefined || results.some(({ entry, message }) => !parts.has(message.toolCallId) || !isTextOnly(message.content) ||
|
|
126
|
+
indices.get(entry.id) === undefined || !resolvable(entry))) return undefined;
|
|
127
|
+
const callIndex = indices.get(call.id), callLocatable = callIndex !== undefined && resolvable(call);
|
|
128
|
+
const size = (text: string) => conversationTokens([{ role: "user", content: text, timestamp: 0 }] as Messages);
|
|
129
|
+
// One item per call's arguments and per result; arguments that cannot be recalled keep a fixed 400-character head.
|
|
130
|
+
const items = results.flatMap(({ entry, message }) => {
|
|
131
|
+
const part = parts.get(message.toolCallId)!;
|
|
132
|
+
const args = callLocatable ? { text: part.args, locator: { index: callIndex } as { index: number } | undefined, base: part.offset }
|
|
133
|
+
: { text: part.args.length > 400 ? `${part.args.slice(0, 400)}…` : part.args, locator: undefined, base: 0 };
|
|
134
|
+
return [args, { text: textOf(message.content), locator: { index: indices.get(entry.id)! }, base: 0 }];
|
|
135
|
+
}).map((item, index) => ({ ...item, index, size: size(item.text) }));
|
|
136
|
+
const shown: string[] = [];
|
|
137
|
+
let left = budget - Math.ceil(results.reduce((n, { message }) => n + parts.get(message.toolCallId)!.name.length + 4, 0) / 4);
|
|
138
|
+
const order = [...items].sort((a, b) => a.size - b.size);
|
|
139
|
+
for (const [rank, item] of order.entries()) {
|
|
140
|
+
const share = Math.floor(left / (order.length - rank));
|
|
141
|
+
if (item.size <= share || !item.locator) { shown[item.index] = item.text; left -= item.size; continue; }
|
|
142
|
+
const locator = item.locator, clip = (keep: number) => clipText(item.text, keep, locator, item.base);
|
|
143
|
+
if (size(clip(0)) > share) return undefined;
|
|
144
|
+
let low = 0, high = item.text.length;
|
|
145
|
+
while (low < high) { const mid = Math.ceil((low + high) / 2); if (size(clip(mid)) <= share) low = mid; else high = mid - 1; }
|
|
146
|
+
shown[item.index] = clip(low); left -= size(shown[item.index]!);
|
|
147
|
+
}
|
|
148
|
+
if (left < 0) return undefined;
|
|
149
|
+
const body = results.map(({ message }, i) => `${parts.get(message.toolCallId)!.name} ${shown[2 * i]}:\n${shown[2 * i + 1]}`).join("\n\n");
|
|
150
|
+
return { kind: "section", title: "Kept-round", sourceIndex,
|
|
151
|
+
text: `the tool round just before the kept tail (as recorded at #${sourceIndex}; clipped where a recall locator says so):\n${body}` };
|
|
152
|
+
}
|
package/src/ledger.ts
CHANGED
|
@@ -25,12 +25,17 @@ export const head = (text: string, max: number): string => {
|
|
|
25
25
|
* `resolvable` says tuck_recall {index} reads the locator, so only then is it shown. A read whose result is missing points at its call. */
|
|
26
26
|
export interface LedgerItem { path: string; operation: "wrote/edited" | "read"; sourceIndex?: number; locatorIndex?: number; resolvable: boolean; definitions?: FileObservation }
|
|
27
27
|
|
|
28
|
+
const resultsByCall = (entries: readonly SessionEntry[]): Map<string, SessionEntry> => {
|
|
29
|
+
const results = new Map<string, SessionEntry>();
|
|
30
|
+
for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
|
|
31
|
+
return results;
|
|
32
|
+
};
|
|
33
|
+
|
|
28
34
|
/** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
|
|
29
35
|
* A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
|
|
30
36
|
export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean,
|
|
31
37
|
failedCalls: ReadonlySet<string>, cwd?: string): LedgerItem[] {
|
|
32
|
-
const results =
|
|
33
|
-
for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
|
|
38
|
+
const results = resultsByCall(entries);
|
|
34
39
|
const last = new Map<string, { path: string; operation: LedgerItem["operation"]; entry: SessionEntry; target: SessionEntry }>();
|
|
35
40
|
for (const entry of entries) {
|
|
36
41
|
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
@@ -79,8 +84,7 @@ export interface ActionItem { text: string; failed: boolean; sourceIndex?: numbe
|
|
|
79
84
|
* aborted response is not listed; a call whose result is an error is marked. */
|
|
80
85
|
export function actionItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean,
|
|
81
86
|
failedCalls: ReadonlySet<string>): ActionItem[] {
|
|
82
|
-
const results =
|
|
83
|
-
for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
|
|
87
|
+
const results = resultsByCall(entries);
|
|
84
88
|
const calls: { text: string; failed: boolean; result?: SessionEntry; command: boolean }[] = [];
|
|
85
89
|
for (const entry of entries) {
|
|
86
90
|
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
package/src/legacy-cleanup.ts
CHANGED
|
@@ -97,7 +97,7 @@ export function cleanupLegacyFiles(ctx: ExtensionContext): Promise<void> {
|
|
|
97
97
|
if (process.platform === "win32" || !await realDirectory(root)) { started = true; return; }
|
|
98
98
|
const children = await readdir(root);
|
|
99
99
|
started = true;
|
|
100
|
-
const names = [...directories, ...children.filter(name => temporaryDirectory.
|
|
100
|
+
const names = [...directories, ...children.filter(name => temporaryDirectory.test(name))];
|
|
101
101
|
const candidates: string[] = [];
|
|
102
102
|
for (const name of names) {
|
|
103
103
|
const path = join(root, name);
|
|
@@ -13,6 +13,7 @@ const wire = (value: unknown): Wire => {
|
|
|
13
13
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a Chat Completions request");
|
|
14
14
|
return value as Wire;
|
|
15
15
|
};
|
|
16
|
+
const cancelled = (message: AssistantMessage): AssistantMessage => ({ ...message, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" });
|
|
16
17
|
const promptTokens = (message: AssistantMessage) => message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
|
|
17
18
|
|
|
18
19
|
export function llamaContinuationStream(profile: LlamaContinuation, native: ApiStreamSimpleFunction) {
|
|
@@ -103,7 +104,7 @@ export function llamaContinuationStream(profile: LlamaContinuation, native: ApiS
|
|
|
103
104
|
clearTimeout(admissionTimer);
|
|
104
105
|
}
|
|
105
106
|
if (signal.aborted) {
|
|
106
|
-
first =
|
|
107
|
+
first = cancelled(first);
|
|
107
108
|
} else if (!cacheVerified) {
|
|
108
109
|
first = { ...first, errorMessage: CONTINUATION_CACHE_MISS };
|
|
109
110
|
} else if (second.stopReason !== "error" && second.stopReason !== "aborted" &&
|
|
@@ -151,7 +152,7 @@ export function llamaContinuationStream(profile: LlamaContinuation, native: ApiS
|
|
|
151
152
|
} catch (error) {
|
|
152
153
|
if (!first) throw error;
|
|
153
154
|
if (signal.aborted)
|
|
154
|
-
first =
|
|
155
|
+
first = cancelled(first);
|
|
155
156
|
} finally {
|
|
156
157
|
if (thinkingEnd) output.push(thinkingEnd);
|
|
157
158
|
}
|
package/src/recall.ts
CHANGED
|
@@ -61,6 +61,7 @@ export interface ReadableEntry {
|
|
|
61
61
|
producerCall?: { sourceTime: SourceTime; name: string; id: string; arguments: Record<string, unknown> };
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
type ProducerLink = NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime };
|
|
64
65
|
interface DiscoveryEntry extends ReadableEntry {
|
|
65
66
|
sourceText: string;
|
|
66
67
|
ranges: { start: number; end: number }[];
|
|
@@ -117,7 +118,7 @@ function textContent(content: unknown, assistant = false): string {
|
|
|
117
118
|
return readableContentParts(content, assistant).map(part => part.text).join("\n");
|
|
118
119
|
}
|
|
119
120
|
|
|
120
|
-
function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string,
|
|
121
|
+
function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>): ReadableEntry | undefined {
|
|
121
122
|
if (!isHistorySource(entry)) return;
|
|
122
123
|
let value: Omit<ReadableEntry, "entryId" | "sourceTime"> | undefined;
|
|
123
124
|
if (entry.type === "compaction") value = { role: "compaction", text: entry.summary };
|
|
@@ -154,7 +155,7 @@ function producerReads(branch: readonly SessionEntry[]) {
|
|
|
154
155
|
for (const entry of branch) identities.set(entry.id, (identities.get(entry.id) ?? 0) + 1);
|
|
155
156
|
const usable = (entry: SessionEntry) => typeof entry.id === "string" && entry.id.length > 0 &&
|
|
156
157
|
entry.id.length <= MAX_RECALL_ENTRY_ID_CHARACTERS && identities.get(entry.id) === 1 && isHistorySource(entry);
|
|
157
|
-
type Call = { order: number; name: string; export?: boolean; read?:
|
|
158
|
+
type Call = { order: number; name: string; export?: boolean; read?: ProducerLink };
|
|
158
159
|
const calls = new Map<string, Call[]>(), receipts = new Map<string, { entry: SessionEntry; order: number; name: string }[]>();
|
|
159
160
|
for (const [order, entry] of branch.entries()) {
|
|
160
161
|
if (entry.type !== "message") continue;
|
|
@@ -182,7 +183,7 @@ function producerReads(branch: readonly SessionEntry[]) {
|
|
|
182
183
|
}
|
|
183
184
|
if (!valid || !usable(entry)) for (const call of local) delete call.read;
|
|
184
185
|
}
|
|
185
|
-
const links = new Map<string,
|
|
186
|
+
const links = new Map<string, ProducerLink>();
|
|
186
187
|
for (const [id, producers] of calls) {
|
|
187
188
|
const results = receipts.get(id), call = producers[0], result = results?.[0];
|
|
188
189
|
if (producers.length === 1 && results?.length === 1 && call?.read && result && usable(result.entry) &&
|
|
@@ -193,7 +194,7 @@ function producerReads(branch: readonly SessionEntry[]) {
|
|
|
193
194
|
}
|
|
194
195
|
|
|
195
196
|
/** Match ranges address the unmodified readable source, including mixed messages. */
|
|
196
|
-
function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<string,
|
|
197
|
+
function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<string, ProducerLink>): { start: number; end: number }[] {
|
|
197
198
|
// Saved views repeat selected originals; discovery must not rank that repetition.
|
|
198
199
|
// Explicit ID reads still expose the saved view through readable().
|
|
199
200
|
if (entry.type === "compaction") return [];
|
|
@@ -214,7 +215,7 @@ function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<
|
|
|
214
215
|
}
|
|
215
216
|
|
|
216
217
|
/** Ranking uses filtered text; excerpts retain the original readable coordinates. */
|
|
217
|
-
function discoveryEntry(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string,
|
|
218
|
+
function discoveryEntry(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>): DiscoveryEntry | undefined {
|
|
218
219
|
const row = readable(entry, attempts, links);
|
|
219
220
|
if (!row) return;
|
|
220
221
|
const ranges = discoveryRanges(entry, row.text, links);
|
|
@@ -287,16 +288,6 @@ function discoveryWholeRange(row: DiscoveryEntry, passage: ReturnType<typeof dis
|
|
|
287
288
|
read: { entryId: row.entryId, offset: range.start, limit: range.end - range.start } };
|
|
288
289
|
}
|
|
289
290
|
|
|
290
|
-
/**
|
|
291
|
-
* The host supplies this role's current branch; this function never opens a path.
|
|
292
|
-
* Query is a case-insensitive literal over eligible source ranges. Offset/limit
|
|
293
|
-
* page the concatenation of matching texts, with no added separators. Without an
|
|
294
|
-
* explicit offset, a source-scoped query returns the whole matching readable
|
|
295
|
-
* source when it fits, otherwise disjoint exact match windows;
|
|
296
|
-
* unscoped browsing starts up to 120 characters before its first match.
|
|
297
|
-
* Returned nextOffset uses the same filter and can page through any long entry.
|
|
298
|
-
* At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
|
|
299
|
-
*/
|
|
300
291
|
/** Add factual call context to a demanded complete receipt, never to discovery or partial pages. */
|
|
301
292
|
function contextualReceipt(branch: readonly SessionEntry[], entryId: string | undefined, fragment: RecallFragment): RecallFragment {
|
|
302
293
|
const read = fragment.producerRead;
|
|
@@ -318,6 +309,16 @@ function contextualReceipt(branch: readonly SessionEntry[], entryId: string | un
|
|
|
318
309
|
} catch { return fragment; } // An incomplete or malformed prefix remains only a locator.
|
|
319
310
|
}
|
|
320
311
|
|
|
312
|
+
/**
|
|
313
|
+
* The host supplies this role's current branch; this function never opens a path.
|
|
314
|
+
* Query is a case-insensitive literal over eligible source ranges. Offset/limit
|
|
315
|
+
* page the concatenation of matching texts, with no added separators. Without an
|
|
316
|
+
* explicit offset, a source-scoped query returns the whole matching readable
|
|
317
|
+
* source when it fits, otherwise disjoint exact match windows;
|
|
318
|
+
* unscoped browsing starts up to 120 characters before its first match.
|
|
319
|
+
* Returned nextOffset uses the same filter and can page through any long entry.
|
|
320
|
+
* At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
|
|
321
|
+
*/
|
|
321
322
|
function recallHistory(branch: readonly SessionEntry[], options: RecallOptions = {}): RecallPage {
|
|
322
323
|
const { query, entryId } = options;
|
|
323
324
|
if (query !== undefined && (typeof query !== "string" || !query.length || query.length > MAX_RECALL_QUERY_CHARACTERS))
|
package/src/thrash.ts
CHANGED
|
@@ -23,7 +23,6 @@ export function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads {
|
|
|
23
23
|
if (message.role === "assistant") {
|
|
24
24
|
if (isDiscardedResponse(message)) continue;
|
|
25
25
|
if (epoch[i] !== current) { current = epoch[i]; replies = 0; }
|
|
26
|
-
const cuts = current;
|
|
27
26
|
replies++;
|
|
28
27
|
for (const block of message.content) {
|
|
29
28
|
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
|
|
@@ -90,9 +90,8 @@ const bm25Score = (doc: string, terms: readonly KeywordMatcher[], ctx: BM25Conte
|
|
|
90
90
|
|
|
91
91
|
/** Rank already-eligible recall rows; filtering and paging belong to the caller. */
|
|
92
92
|
export const rankRecallRows = (rows: readonly { role: string; text: string }[], query: string): number[] => {
|
|
93
|
-
const rawQuery = query.trim();
|
|
94
93
|
const checkBudget = startBudget();
|
|
95
|
-
const prepared = prepareKeywordQuery(
|
|
94
|
+
const prepared = prepareKeywordQuery(query);
|
|
96
95
|
const terms = prepared.terms;
|
|
97
96
|
// Preserve the role prefix and trailing space of the original BM25 documents.
|
|
98
97
|
const docs = rows.map((row) => `${row.role} ${row.text} `);
|
package/src/tuck.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
|
|
|
7
7
|
import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
|
|
8
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
|
-
import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
|
|
10
|
+
import { crossingRoundRecord, keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
|
|
11
11
|
import { workingSetCandidates, type WorkingFile } from "./working-set.js";
|
|
12
12
|
import { keptSearchCandidates } from "./kept-searches.js";
|
|
13
13
|
import { clipText } from "./clip.js";
|
|
@@ -71,6 +71,7 @@ export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: Ext
|
|
|
71
71
|
export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean; keepRecentTokens?: number }, ctx: ExtensionContext,
|
|
72
72
|
reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true): Draft {
|
|
73
73
|
const { isHistorySource, readable } = createRecall(policy);
|
|
74
|
+
const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
74
75
|
const projected = ctx.sessionManager.buildSessionProjection();
|
|
75
76
|
if (input.branchEntries.some(entry => entry.type === "context_edit" && entry.replacement !== null))
|
|
76
77
|
return { unavailable: "pi-tuck does not support replacement context edits" };
|
|
@@ -183,7 +184,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
183
184
|
const header = ctx.sessionManager.getHeader();
|
|
184
185
|
if (!header) throw new Error("Missing native session header");
|
|
185
186
|
const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
|
|
186
|
-
const minimumOpeningLength = 80, openingLength = Math.max(
|
|
187
|
+
const minimumOpeningLength = 80, openingLength = Math.max(minimumOpeningLength, Math.floor(Math.sqrt(room * 4)));
|
|
187
188
|
// At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
|
|
188
189
|
const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
|
|
189
190
|
const positions = new Map(entries.map((entry, at) => [entry.id, at]));
|
|
@@ -226,7 +227,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
226
227
|
}
|
|
227
228
|
for (let at = branch.length - 1; at >= 0; at--) native[at] += native[at + 1]!;
|
|
228
229
|
const nativeAt = (boundary: number) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary]!.id)!]!;
|
|
229
|
-
const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
|
|
230
|
+
const originalBoundary = preferredBoundary, tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
|
|
230
231
|
// Move only the older end, to the newest whole protocol-safe entries
|
|
231
232
|
// within the shared tail size. Required current/fresh native sources
|
|
232
233
|
// stay whole even when their floor exceeds that preferred amount.
|
|
@@ -323,7 +324,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
323
324
|
// existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
|
|
324
325
|
if (input.deepest) {
|
|
325
326
|
// The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
|
|
326
|
-
const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices,
|
|
327
|
+
const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, resolvable);
|
|
327
328
|
const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
|
|
328
329
|
const projection = preview(summary, floorBoundary);
|
|
329
330
|
assertNativeToolRounds(projection);
|
|
@@ -337,8 +338,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
337
338
|
const listsAt = (boundary: number) => {
|
|
338
339
|
const cached = listCache.get(boundary);
|
|
339
340
|
if (cached) return cached;
|
|
340
|
-
const compacted = entries.slice(0, boundary)
|
|
341
|
-
const files = ledgerItems(compacted, indices,
|
|
341
|
+
const compacted = entries.slice(0, boundary);
|
|
342
|
+
const files = ledgerItems(compacted, indices, resolvable, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolvable, failedCalls);
|
|
342
343
|
const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
|
|
343
344
|
listCache.set(boundary, lists);
|
|
344
345
|
return lists;
|
|
@@ -383,7 +384,6 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
383
384
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
384
385
|
// The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
|
|
385
386
|
// WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
|
|
386
|
-
const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
387
387
|
const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
|
|
388
388
|
if (workingSet.files.length) {
|
|
389
389
|
const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
|
|
@@ -397,13 +397,14 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
397
397
|
}
|
|
398
398
|
const carriedKeys = new Set(carried.map(file => file.key));
|
|
399
399
|
let ledger: TranscriptRecord[] = lists.records;
|
|
400
|
-
|
|
400
|
+
const maxListLines = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
|
|
401
|
+
let listedKeep = maxListLines;
|
|
401
402
|
// List caps are existing ranking policy; only the carried target is a
|
|
402
403
|
// spending limit. Candidate list sizes have fixed, cached line prices.
|
|
403
404
|
if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
404
405
|
ledger = [];
|
|
405
406
|
listedKeep = 0;
|
|
406
|
-
for (let keep = 0; keep <= Math.min(
|
|
407
|
+
for (let keep = 0; keep <= Math.min(maxListLines, Math.max(lists.files.length, lists.actions.length)); keep++) {
|
|
407
408
|
const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
|
|
408
409
|
if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
|
|
409
410
|
ledger = candidate; listedKeep = keep;
|
|
@@ -415,7 +416,18 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
415
416
|
return row?.message.role === "user" && isTextOnly(row.message.content);
|
|
416
417
|
}));
|
|
417
418
|
const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
|
|
419
|
+
// The tool round the tail boundary passed (the one crossing the tail size) rides in the closing section, so the tail is not left far
|
|
420
|
+
// below its size. It is paid from the summary, up to what the native tail leaves of that size, and is reserved before the dialogue fills.
|
|
421
|
+
let crossingRound: TranscriptRecord | undefined;
|
|
418
422
|
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
|
|
423
|
+
if (boundary === preferredBoundary && (preferredBoundary > originalBoundary || budgetCut) && boundary < entries.length) {
|
|
424
|
+
const crossing = entries.slice(0, boundary).findLastIndex(entry => !(entry.type === "message" && entry.message.role === "toolResult"));
|
|
425
|
+
const tail = crossing < 0 ? 0 : carriedTailTokens(Math.max(nativeAt(originalBoundary), nativeAt(crossing))) - nativeAt(boundary);
|
|
426
|
+
// Like the working set, at most WORKING_SET_SHARE of what the summary may spend beyond its protected rows: the dialogue keeps the rest.
|
|
427
|
+
const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * maxBriefChars / 4));
|
|
428
|
+
if (size > 0) crossingRound = crossingRoundRecord(entries, boundary, indices, resolvable, size);
|
|
429
|
+
}
|
|
430
|
+
const crossingCost = crossingRound ? lineCost([crossingRound]) : 0;
|
|
419
431
|
const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
|
|
420
432
|
sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
|
|
421
433
|
ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
|
|
@@ -556,7 +568,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
556
568
|
for (const record of candidates) {
|
|
557
569
|
if ((counts.get(record.title!) ?? 0) === 4) continue;
|
|
558
570
|
const extra = lineCost([record]);
|
|
559
|
-
if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target) continue;
|
|
571
|
+
if (keptResultCost + extra > keptResultCap || price(offer.summary.length + crossingCost + keptResultCost + extra, boundary) > target) continue;
|
|
560
572
|
keptResults.push(record); keptResultCost += extra;
|
|
561
573
|
counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
|
|
562
574
|
}
|
|
@@ -572,7 +584,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
572
584
|
for (const item of shownFiles) item.definitions = observations.get(item.path);
|
|
573
585
|
const outputs = new Set<(typeof lists.actions)[number]>(), definitions = new Set<(typeof lists.files)[number]>();
|
|
574
586
|
let observationCost = 0;
|
|
575
|
-
const fitsObservation = (extra: number) => price(offer.summary.length + observationCost + extra, boundary) <= target;
|
|
587
|
+
const fitsObservation = (extra: number) => price(offer.summary.length + crossingCost + observationCost + extra, boundary) <= target;
|
|
576
588
|
// Each kind gives way as whole items, oldest first; an oversized newest
|
|
577
589
|
// item cannot promote an older one. Pointer lines need no extra omission.
|
|
578
590
|
for (const item of shownActions) {
|
|
@@ -595,7 +607,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
595
607
|
let thinkingCost = 0;
|
|
596
608
|
for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
|
|
597
609
|
const extra = lineCost([record]);
|
|
598
|
-
if (price(offer.summary.length + thinkingCost + extra, boundary) > target) break;
|
|
610
|
+
if (price(offer.summary.length + crossingCost + thinkingCost + extra, boundary) > target) break;
|
|
599
611
|
thinking.push(record); thinkingCost += extra;
|
|
600
612
|
}
|
|
601
613
|
if (thinking.length) offer = assemble(compiled.text, boundary);
|
|
@@ -663,6 +675,11 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
663
675
|
}
|
|
664
676
|
if (boundary !== compiledBoundary) offer = assemble(compiled.text, boundary);
|
|
665
677
|
}
|
|
678
|
+
// Still the preferred boundary (leftover room did not take the round into the native tail): the round rides in the summary instead.
|
|
679
|
+
if (crossingRound && boundary === preferredBoundary && price(offer.summary.length + crossingCost, boundary) <= target) {
|
|
680
|
+
keptResults.unshift(crossingRound);
|
|
681
|
+
offer = assemble(compiled.text, boundary);
|
|
682
|
+
}
|
|
666
683
|
const projection = preview(offer.summary, boundary);
|
|
667
684
|
assertNativeToolRounds(projection);
|
|
668
685
|
const after = measure(projection);
|