pi-tuck 1.10.2 → 1.10.5
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 +24 -0
- package/README.md +2 -2
- package/dist/src/budget.d.ts +0 -2
- package/dist/src/budget.js +1 -3
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +1 -4
- package/dist/src/compaction.js +46 -18
- package/dist/src/content-observations.d.ts +0 -6
- package/dist/src/content-observations.js +5 -5
- package/dist/src/diagnostic-replay.js +6 -6
- package/dist/src/diagnostics.d.ts +0 -1
- package/dist/src/diagnostics.js +2 -3
- package/dist/src/history-image.d.ts +0 -2
- package/dist/src/history-image.js +1 -1
- package/dist/src/kept-reads.d.ts +3 -0
- package/dist/src/kept-reads.js +51 -0
- package/dist/src/omissions.d.ts +3 -6
- package/dist/src/omissions.js +3 -10
- package/dist/src/recall.js +2 -2
- package/dist/src/thrash.d.ts +0 -6
- package/dist/src/thrash.js +1 -1
- package/dist/src/tuck/core/format.d.ts +2 -0
- package/dist/src/tuck/core/format.js +3 -0
- package/dist/src/tuck/core/token-estimate.d.ts +2 -8
- package/dist/src/tuck/core/token-estimate.js +3 -9
- package/dist/src/tuck/core/tool-args.d.ts +0 -1
- package/dist/src/tuck/core/tool-args.js +1 -1
- package/dist/src/tuck/core/transcript.d.ts +3 -2
- package/dist/src/tuck/cut.d.ts +0 -1
- package/dist/src/tuck/cut.js +0 -3
- package/dist/src/tuck.d.ts +2 -2
- package/dist/src/tuck.js +16 -13
- package/package.json +1 -1
- package/src/budget.ts +1 -4
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +42 -17
- package/src/content-observations.ts +5 -5
- package/src/diagnostic-replay.ts +7 -6
- package/src/diagnostics.ts +2 -3
- package/src/history-image.ts +1 -1
- package/src/kept-reads.ts +40 -0
- package/src/omissions.ts +3 -10
- package/src/recall.ts +3 -3
- package/src/thrash.ts +1 -7
- package/src/tuck/core/format.ts +3 -0
- package/src/tuck/core/token-estimate.ts +4 -20
- package/src/tuck/core/tool-args.ts +1 -1
- package/src/tuck/core/transcript.ts +2 -2
- package/src/tuck/cut.ts +0 -4
- package/src/tuck.ts +16 -13
- package/dist/src/tuck/core/render-entries.d.ts +0 -6
- package/dist/src/tuck/core/render-entries.js +0 -1
- package/src/tuck/core/render-entries.ts +0 -6
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,30 @@
|
|
|
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.10.5]
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- Thinking-only retry: when a reply is cut short by Pi's own reply limit while it is still thinking, the retry now plans an ordinary trim.
|
|
11
|
+
That trim keeps the action and file lists and the kept results, including prompt-named command outputs, and is made as small as Pi's
|
|
12
|
+
limit allows to give the full reply room. It used to go straight to the smallest possible summary (prompts cut to 80 characters, no
|
|
13
|
+
actions or files), so the agent continued with almost no memory of its work. The smallest summary is now only the fallback when no
|
|
14
|
+
ordinary trim gives the room.
|
|
15
|
+
- Smallest summary: it now carries the outputs of commands a prompt told the agent to run (within the 8,000-character cap), and its
|
|
16
|
+
closing words no longer point to "actions and files listed above", since it keeps none.
|
|
17
|
+
|
|
18
|
+
## [1.10.4]
|
|
19
|
+
|
|
20
|
+
Not published: its release check failed on a test-only type error. Its fixes ship in 1.10.5.
|
|
21
|
+
|
|
22
|
+
## [1.10.3]
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- Summary: the output of a command a prompt told the agent to run (such as "New telex. Run: telex read NAME") is now carried, newest four
|
|
27
|
+
first and at most 8,000 characters in all (the rest is cut with a recall pointer), ahead of kept reads and searches. An agent driven by messages gets its tasks only as such tool results, and the summary kept
|
|
28
|
+
just a pointer to them, so a queued task could fall out of view after a cut.
|
|
29
|
+
|
|
6
30
|
## [1.10.2]
|
|
7
31
|
|
|
8
32
|
### 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.10.
|
|
15
|
+
This README describes pi-tuck 1.10.5. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.10.5` or `pi install git:github.com/galyavin/pi-tuck@v1.10.5`. 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 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. 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
|
|
package/dist/src/budget.d.ts
CHANGED
|
@@ -55,8 +55,6 @@ export declare const incomingEventTokens: (event: BeforeAgentStartEvent) => numb
|
|
|
55
55
|
export declare const requestTokens: (messages: Messages, systemPrompt: string) => number;
|
|
56
56
|
/** The saved conversation as the model receives it from this compactor, counted after Pi's conversion. This is the planner's measure too. */
|
|
57
57
|
export declare const projectedConversationTokens: (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy) => number;
|
|
58
|
-
/** As `projectedConversationTokens`, but a summary that is not in this compactor's format is counted as it is instead of failing: what the planner measures with, so that a cut can replace one. */
|
|
59
|
-
export declare const measurableConversationTokens: (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy) => number;
|
|
60
58
|
/** Raw reserve for the cut planner: the window less the raw tokens that fit the target room, plus the input no cut can remove. */
|
|
61
59
|
export declare const planningReserve: (window: number, targetRoom: number, factor: number, mandatory: number) => number;
|
|
62
60
|
export type Target = "band" | "room";
|
package/dist/src/budget.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
|
|
2
2
|
import { convertToLlm, estimateTokens } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import {
|
|
3
|
+
import { projectedMessages } from "./omissions.js";
|
|
4
4
|
import { isDiscardedResponse } from "./protocol.js";
|
|
5
5
|
import { MAX_TAIL_TOKENS } from "./tuck/cut.js";
|
|
6
6
|
/** Triggers fire this fraction of the room early. The margin absorbs request growth a boundary cannot see; it never enters the calibration factor. */
|
|
@@ -74,8 +74,6 @@ export const requestTokens = (messages, systemPrompt) => {
|
|
|
74
74
|
};
|
|
75
75
|
/** The saved conversation as the model receives it from this compactor, counted after Pi's conversion. This is the planner's measure too. */
|
|
76
76
|
export const projectedConversationTokens = (messages, ctx, policy) => conversationTokens(projectedMessages(messages, ctx, policy));
|
|
77
|
-
/** As `projectedConversationTokens`, but a summary that is not in this compactor's format is counted as it is instead of failing: what the planner measures with, so that a cut can replace one. */
|
|
78
|
-
export const measurableConversationTokens = (messages, ctx, policy) => conversationTokens(measurableMessages(messages, ctx, policy));
|
|
79
77
|
/** Raw reserve for the cut planner: the window less the raw tokens that fit the target room, plus the input no cut can remove. */
|
|
80
78
|
export const planningReserve = (window, targetRoom, factor, mandatory) => window - Math.floor(targetRoom / factor) + mandatory;
|
|
81
79
|
/** The least share of the saved conversation a cut due only at the lean line must free. */
|
package/dist/src/build-id.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const BUILD_ID = "
|
|
1
|
+
export declare const BUILD_ID = "092a7cfa8000bf0285eb4fd76580b229336faaf9af7b50d3c30b11d0f1a8d787";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "092a7cfa8000bf0285eb4fd76580b229336faaf9af7b50d3c30b11d0f1a8d787";
|
package/dist/src/compaction.d.ts
CHANGED
|
@@ -2,18 +2,15 @@ import { Run } from "./run.js";
|
|
|
2
2
|
import { type RecorderOptions } from "./diagnostics.js";
|
|
3
3
|
import { type AgentMessage } from "./budget.js";
|
|
4
4
|
import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import type
|
|
5
|
+
import { type RecallPolicy } from "./recall.js";
|
|
6
6
|
/** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
|
|
7
7
|
export declare const refusalNotice: (message: string, factor: number) => string;
|
|
8
8
|
/** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
|
|
9
9
|
export declare const overflowNotice: (contextWindow: number, bound: number, learned: boolean) => string;
|
|
10
|
-
/** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
|
|
11
10
|
/** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
|
|
12
11
|
export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
|
|
13
12
|
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
14
13
|
export declare const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
15
|
-
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
|
|
16
|
-
export declare const ACT_NOW_LIMIT = 2;
|
|
17
14
|
/** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
|
|
18
15
|
* or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
|
|
19
16
|
export declare function actNowsInARow(branch: readonly SessionEntry[]): number;
|
package/dist/src/compaction.js
CHANGED
|
@@ -2,7 +2,7 @@ import { textOf } from "./tuck/core/content.js";
|
|
|
2
2
|
import { PendingCut, StartingPrompt, Run } from "./run.js";
|
|
3
3
|
import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
|
|
4
4
|
import { BUILD_ID } from "./build-id.js";
|
|
5
|
-
import {
|
|
5
|
+
import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import { readFileSync } from "node:fs";
|
|
8
8
|
import { homedir } from "node:os";
|
|
@@ -12,7 +12,7 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
12
12
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
13
13
|
import { projectedMessages } from "./omissions.js";
|
|
14
14
|
import { applyClips, clipBudgets, clipFor } from "./clip.js";
|
|
15
|
-
import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens,
|
|
15
|
+
import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
|
|
16
16
|
import { getCurrentSystemMessage, isContextOverflow, normalizeContext } from "@earendil-works/pi-ai";
|
|
17
17
|
import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
18
18
|
import { Type } from "typebox";
|
|
@@ -62,7 +62,6 @@ export const refusalNotice = (message, factor) => message + "; shorten the input
|
|
|
62
62
|
/** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
|
|
63
63
|
export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
|
|
64
64
|
(learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
|
|
65
|
-
/** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
|
|
66
65
|
/** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
|
|
67
66
|
export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
|
|
68
67
|
`The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
|
|
@@ -70,7 +69,7 @@ export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used
|
|
|
70
69
|
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
71
70
|
export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
72
71
|
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
|
|
73
|
-
|
|
72
|
+
const ACT_NOW_LIMIT = 2;
|
|
74
73
|
/** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
|
|
75
74
|
* or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
|
|
76
75
|
export function actNowsInARow(branch) {
|
|
@@ -183,11 +182,6 @@ export async function installCompaction(pi, options = {}) {
|
|
|
183
182
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
184
183
|
if (!validCutAt(cutAt))
|
|
185
184
|
throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
186
|
-
const hostAccess = () => {
|
|
187
|
-
if (!active())
|
|
188
|
-
throw new Error("Compaction host is inactive");
|
|
189
|
-
options.assertAccess?.();
|
|
190
|
-
};
|
|
191
185
|
const view = (ctx, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
|
|
192
186
|
const liveCut = new PendingCut();
|
|
193
187
|
const recorder = new IncidentRecorder(options.diagnostics);
|
|
@@ -210,7 +204,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
210
204
|
if (recorder.enabled) {
|
|
211
205
|
try {
|
|
212
206
|
const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
|
|
213
|
-
recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build:
|
|
207
|
+
recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build: BUILD_ID, receiptId: proposalId, entries: filtered.entries, branchEntryIds: ctx.sessionManager.getBranch().map(e => e.id), header: ctx.sessionManager.getHeader(), contextWindow: ctx.model?.contextWindow, reserve, tokensBefore, retainCurrentInput, operatorManual, previousSummary }, filtered.partial || Boolean(options.recallPolicy?.readAttemptMarker));
|
|
214
208
|
recorder.capture("proposal", "selected-draft-not-saved", attached);
|
|
215
209
|
}
|
|
216
210
|
catch {
|
|
@@ -483,7 +477,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
483
477
|
const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
|
|
484
478
|
// The planner counts with the same function, except that it does not fail on a summary in another format: a cut can replace one
|
|
485
479
|
// (an operator's /compact repairs a session whose saved summary is foreign). Identical to the strict one for this compactor's summaries.
|
|
486
|
-
const plannerMeasureFor = (ctx) => Object.assign((messages) =>
|
|
480
|
+
const plannerMeasureFor = (ctx) => Object.assign((messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
|
|
487
481
|
const hostMessages = (ctx) => options.hostMessages?.(ctx) ?? [];
|
|
488
482
|
const toolShapes = (names) => {
|
|
489
483
|
const selected = new Set(names);
|
|
@@ -612,7 +606,9 @@ export async function installCompaction(pi, options = {}) {
|
|
|
612
606
|
const access = () => {
|
|
613
607
|
if (failure())
|
|
614
608
|
throw failure();
|
|
615
|
-
|
|
609
|
+
if (!active())
|
|
610
|
+
throw new Error("Compaction host is inactive");
|
|
611
|
+
options.assertAccess?.();
|
|
616
612
|
};
|
|
617
613
|
pi.on("input", async (event, ctx) => {
|
|
618
614
|
if (!ctx.isIdle() || run?.phase === "starting")
|
|
@@ -1195,6 +1191,40 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1195
1191
|
markBoundary(entries);
|
|
1196
1192
|
return { entries, continue: false };
|
|
1197
1193
|
};
|
|
1194
|
+
// A retry's cut is an ordinary planned cut (summary with the action and file lists and kept results), shrunk until Pi's own clamp gives
|
|
1195
|
+
// the raised reply room, at most three times. Only when no such plan exists does the retry fall back to the deepest floor.
|
|
1196
|
+
const retryDecision = (ctx, asIs, host, pending) => {
|
|
1197
|
+
const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
|
|
1198
|
+
const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
|
|
1199
|
+
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1200
|
+
const { response, room } = limits(ctx), want = response - piMargin, band = decisionBand(ctx, room);
|
|
1201
|
+
let target = room;
|
|
1202
|
+
for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
|
|
1203
|
+
const targetBand = target === room ? band : target;
|
|
1204
|
+
const decision = chooseCut({ before, mandatory, room: target, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), opportunistic: false,
|
|
1205
|
+
unreduced: "Length-retry compaction did not reduce context within the estimated request budget",
|
|
1206
|
+
plan: (kind) => {
|
|
1207
|
+
const reserve = planReserve(kind, target, targetBand, mandatory, ctx);
|
|
1208
|
+
const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
1209
|
+
protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
1210
|
+
if (!draft.compaction)
|
|
1211
|
+
return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1212
|
+
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
1213
|
+
assertNativeToolRounds(kept);
|
|
1214
|
+
return { draft: true, after: measureFor(ctx)(kept), compaction: draft.compaction, reserve, messages: kept };
|
|
1215
|
+
},
|
|
1216
|
+
});
|
|
1217
|
+
if (decision.kind !== "cut")
|
|
1218
|
+
return undefined;
|
|
1219
|
+
const check = requestClamp(projectedRequest(decision.plan.messages, ctx, host, pending, ctx.getSystemPrompt(), pi.getActiveTools(), true), ctx);
|
|
1220
|
+
if (check.cap === undefined)
|
|
1221
|
+
return undefined;
|
|
1222
|
+
if (check.leavesFloor && check.cap >= want)
|
|
1223
|
+
return decision;
|
|
1224
|
+
target = Math.floor(target * (check.estimate - (want - check.cap)) / check.estimate);
|
|
1225
|
+
}
|
|
1226
|
+
return undefined;
|
|
1227
|
+
};
|
|
1198
1228
|
const retryLength = (event, ctx) => {
|
|
1199
1229
|
// Exhausting the full per-request allowance is not evidence that input is too large.
|
|
1200
1230
|
// Preserve the unfinished response; provider-native continuation owns this case.
|
|
@@ -1219,7 +1249,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1219
1249
|
const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
|
|
1220
1250
|
const asIsCheck = requestClamp(asIs, view);
|
|
1221
1251
|
const previousClips = new Map(clips());
|
|
1222
|
-
const decision = deepestDecision(view, false, true);
|
|
1252
|
+
const decision = retryDecision(view, asIs, hostInput, event.context.pendingMessages) ?? deepestDecision(view, false, true);
|
|
1223
1253
|
const cut = decision.kind === "cut" ? {
|
|
1224
1254
|
...decision,
|
|
1225
1255
|
messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
|
|
@@ -1319,7 +1349,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1319
1349
|
};
|
|
1320
1350
|
// A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
|
|
1321
1351
|
// atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
|
|
1322
|
-
const guardCut = (messages, tokens,
|
|
1352
|
+
const guardCut = (messages, tokens, ctx) => {
|
|
1323
1353
|
const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
|
|
1324
1354
|
const before = conversationTokens(source), mandatory = tokens - before;
|
|
1325
1355
|
const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
|
|
@@ -1429,9 +1459,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1429
1459
|
return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx);
|
|
1430
1460
|
}
|
|
1431
1461
|
}
|
|
1432
|
-
|
|
1433
|
-
run.pendingBoundaryReceipts = [];
|
|
1434
|
-
}
|
|
1462
|
+
run.pendingBoundaryReceipts = [];
|
|
1435
1463
|
}
|
|
1436
1464
|
// Pi commits these entries before the run settles.
|
|
1437
1465
|
try {
|
|
@@ -1474,7 +1502,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1474
1502
|
const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
|
|
1475
1503
|
piClamp && !requestClamp(messages, ctx).leavesFloor;
|
|
1476
1504
|
if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1477
|
-
const cut = guardCut(messages, tokens,
|
|
1505
|
+
const cut = guardCut(messages, tokens, ctx);
|
|
1478
1506
|
messages = cut.messages;
|
|
1479
1507
|
native = Boolean(cut.native);
|
|
1480
1508
|
system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import type { TranscriptRecord } from "./tuck/core/transcript.js";
|
|
3
|
-
export declare const MAX_OUTPUT_TAIL_LINES = 3;
|
|
4
|
-
export declare const MAX_OUTPUT_TAIL_CHARACTERS = 200;
|
|
5
|
-
export declare const MAX_DEFINITION_LINES = 40;
|
|
6
|
-
export declare const MAX_DEFINITION_CHARACTERS = 800;
|
|
7
|
-
/** Mechanical line matches only; no language detection or inferred symbols. */
|
|
8
|
-
export declare const DEFINITION_PATTERNS: readonly RegExp[];
|
|
9
3
|
/** The last nonempty physical lines, with a leading marker whenever earlier text was cut.
|
|
10
4
|
* The marker and embedded newlines spend the same 200-character allowance. */
|
|
11
5
|
export declare function outputTail(output: string): string | undefined;
|
|
@@ -3,12 +3,12 @@ import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
|
3
3
|
import { extractPath } from "./tuck/core/tool-args.js";
|
|
4
4
|
import { readableContentParts } from "./tuck/core/readable-content.js";
|
|
5
5
|
import { MAX_RECALL_CHARACTERS } from "./recall.js";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
const MAX_OUTPUT_TAIL_LINES = 3;
|
|
7
|
+
const MAX_OUTPUT_TAIL_CHARACTERS = 200;
|
|
8
|
+
const MAX_DEFINITION_LINES = 40;
|
|
9
|
+
const MAX_DEFINITION_CHARACTERS = 800;
|
|
10
10
|
/** Mechanical line matches only; no language detection or inferred symbols. */
|
|
11
|
-
|
|
11
|
+
const DEFINITION_PATTERNS = [
|
|
12
12
|
/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:func|def|function)\b/u,
|
|
13
13
|
/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:type|struct|interface|class)\b/u,
|
|
14
14
|
/^\s*export\s+(?:const|let)\b/u,
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { tuck, tuckObservedDraft } from './tuck.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { projectedConversationTokens } from './budget.js';
|
|
4
|
+
import { BUILD_ID } from './build-id.js';
|
|
5
5
|
export function inspectIncident(records) {
|
|
6
6
|
const inputs = records.filter(r => r.kind === 'replay-input');
|
|
7
7
|
const results = inputs.map(record => {
|
|
8
8
|
const i = record.data;
|
|
9
|
-
if (record.partial || i.build !==
|
|
9
|
+
if (record.partial || i.build !== BUILD_ID || !i.entries || !i.header || !Array.isArray(i.branchEntryIds) || i.branchEntryIds.some(id => typeof id !== 'string') || !Number.isSafeInteger(i.contextWindow) || !Number.isSafeInteger(i.reserve) || !Number.isSafeInteger(i.tokensBefore))
|
|
10
10
|
return { mode: 'partial-inspection', notice: 'Missing/redacted inputs or nonmatching build; no deterministic replay claim.' };
|
|
11
11
|
const manager = SessionManager.inMemory('/offline-compaction-replay', undefined, [i.header, ...i.entries]);
|
|
12
|
-
if (i.branchEntryIds
|
|
12
|
+
if (i.branchEntryIds.length)
|
|
13
13
|
manager.branch(i.branchEntryIds.at(-1));
|
|
14
14
|
const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } };
|
|
15
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary }, ctx, i.reserve, messages =>
|
|
15
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary }, ctx, i.reserve, messages => projectedConversationTokens(messages, ctx), {}, i.retainCurrentInput);
|
|
16
16
|
const proposal = records.find(r => r.kind === 'proposal' && r.data?.details?.diagnosticReceipt?.id === i.receiptId)?.data;
|
|
17
17
|
const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
|
|
18
18
|
return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
|
|
19
19
|
});
|
|
20
|
-
return { build:
|
|
20
|
+
return { build: BUILD_ID, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
|
|
21
21
|
}
|
|
22
22
|
export function readableIncident(records) {
|
|
23
23
|
return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type RecallPolicy } from './recall.js';
|
|
2
2
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
export declare const DIAGNOSTIC_BUILD = "40fe96e6b860dcdd5a9a060eac86b30698e64e377f1d2c4d9e243308cb2a6bf9";
|
|
4
3
|
export interface Receipt {
|
|
5
4
|
id: string;
|
|
6
5
|
build: string;
|
package/dist/src/diagnostics.js
CHANGED
|
@@ -6,10 +6,9 @@ import { join, resolve, relative, isAbsolute, dirname, basename } from 'node:pat
|
|
|
6
6
|
import { homedir } from 'node:os';
|
|
7
7
|
import { createRecall } from './recall.js';
|
|
8
8
|
import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
|
|
9
|
-
export const DIAGNOSTIC_BUILD = BUILD_ID;
|
|
10
9
|
export function attachReceipt(draft, reason, reserveTokens, contextWindow, resolved = {}) {
|
|
11
10
|
const details = draft.details && typeof draft.details === 'object' ? draft.details : {};
|
|
12
|
-
const receipt = { id: randomUUID(), build:
|
|
11
|
+
const receipt = { id: randomUUID(), build: BUILD_ID, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
|
|
13
12
|
return { ...draft, details: { ...details, diagnosticReceipt: receipt } };
|
|
14
13
|
}
|
|
15
14
|
export function receiptId(entry) {
|
|
@@ -154,7 +153,7 @@ export class IncidentRecorder {
|
|
|
154
153
|
this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
|
|
155
154
|
this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs);
|
|
156
155
|
this.timer.unref();
|
|
157
|
-
this.capture('start', 'operator-session-control', { id: this.id, build:
|
|
156
|
+
this.capture('start', 'operator-session-control', { id: this.id, build: BUILD_ID, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
|
|
158
157
|
}
|
|
159
158
|
measureInline(operation) { if (!this.enabled)
|
|
160
159
|
return operation(); const started = performance.now(); try {
|
|
@@ -49,8 +49,6 @@ export type HistoryAroundPage = {
|
|
|
49
49
|
omitted: number;
|
|
50
50
|
};
|
|
51
51
|
};
|
|
52
|
-
/** Factual locators only; no interpretation of pixels or claim of current truth. */
|
|
53
|
-
export declare function imageSource(entry: SessionEntry): ImageSource | undefined;
|
|
54
52
|
/** Explicit one-block delivery from the supplied branch; no path reads or resize. */
|
|
55
53
|
export declare function historyImage(branch: readonly SessionEntry[], input: ImageRead, policy?: RecallPolicy): {
|
|
56
54
|
content: (TextContent | ImageContent)[];
|
|
@@ -14,7 +14,7 @@ function images(entry) {
|
|
|
14
14
|
return entry.message.content.filter((block) => block.type === "image");
|
|
15
15
|
}
|
|
16
16
|
/** Factual locators only; no interpretation of pixels or claim of current truth. */
|
|
17
|
-
|
|
17
|
+
function imageSource(entry) {
|
|
18
18
|
const imageCount = images(entry).length;
|
|
19
19
|
if (!imageCount || entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "toolResult"))
|
|
20
20
|
return;
|
package/dist/src/kept-reads.d.ts
CHANGED
|
@@ -2,3 +2,6 @@ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agen
|
|
|
2
2
|
import type { TranscriptRecord } from "./tuck/core/transcript.js";
|
|
3
3
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
4
4
|
export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, exclude?: ReadonlySet<string>): TranscriptRecord[];
|
|
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
|
+
* first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
|
|
7
|
+
export declare function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
|
package/dist/src/kept-reads.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { classifyBash } from "./bash-command.js";
|
|
2
2
|
import { pathKey } from "./path-key.js";
|
|
3
|
+
import { isDiscardedResponse } from "./protocol.js";
|
|
3
4
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
4
5
|
import { extractPath } from "./tuck/core/tool-args.js";
|
|
5
6
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
@@ -65,3 +66,53 @@ export function keptReadCandidates(entries, indices, resolvable, exclude = new S
|
|
|
65
66
|
}
|
|
66
67
|
return records;
|
|
67
68
|
}
|
|
69
|
+
/** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
|
|
70
|
+
const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
|
|
71
|
+
const words = (text) => text.replace(/\s+/gu, " ").trim();
|
|
72
|
+
/** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
|
|
73
|
+
* first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
|
|
74
|
+
export function promptOutputCandidates(entries, indices, resolvable) {
|
|
75
|
+
const results = new Map(), named = new Map();
|
|
76
|
+
let prompt;
|
|
77
|
+
for (const entry of entries) {
|
|
78
|
+
if (entry.type !== "message")
|
|
79
|
+
continue;
|
|
80
|
+
const message = entry.message;
|
|
81
|
+
if (message.role === "user") {
|
|
82
|
+
prompt = words(textOf(message.content));
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (message.role === "toolResult") {
|
|
86
|
+
results.set(message.toolCallId, entry);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (message.role !== "assistant" || prompt === undefined || isDiscardedResponse(message))
|
|
90
|
+
continue;
|
|
91
|
+
for (const block of message.content) {
|
|
92
|
+
if (block.type !== "toolCall" || block.name !== "bash" || typeof block.arguments?.command !== "string")
|
|
93
|
+
continue;
|
|
94
|
+
const command = block.arguments.command, lead = words(command.split(/[|;&<>]|\d>/u)[0]);
|
|
95
|
+
if (lead.includes(" ") && prompt.includes(lead))
|
|
96
|
+
named.set(block.id, command);
|
|
97
|
+
}
|
|
98
|
+
prompt = undefined;
|
|
99
|
+
}
|
|
100
|
+
const records = [];
|
|
101
|
+
let room = MAX_PROMPT_OUTPUT_CHARACTERS;
|
|
102
|
+
for (const [id, command] of [...named].reverse()) {
|
|
103
|
+
const entry = results.get(id), sourceIndex = entry && indices.get(entry.id);
|
|
104
|
+
if (entry?.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content) ||
|
|
105
|
+
sourceIndex === undefined || !resolvable(entry))
|
|
106
|
+
continue;
|
|
107
|
+
const text = textOf(entry.message.content);
|
|
108
|
+
if (!text.length)
|
|
109
|
+
continue;
|
|
110
|
+
const kept = text.length <= room ? text : `${text.slice(0, room)}\n… (truncated; whole output: tuck_recall {"index":${sourceIndex}})`;
|
|
111
|
+
records.push({ kind: "section", title: "Kept-prompt-output", sourceIndex,
|
|
112
|
+
text: `bash ${words(command)} (run as a user prompt asked; output as recorded at #${sourceIndex}):\n${kept}` });
|
|
113
|
+
room -= Math.min(room, text.length);
|
|
114
|
+
if (!room || records.length === MAX_PROMPT_OUTPUTS)
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
return records;
|
|
118
|
+
}
|
package/dist/src/omissions.d.ts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
1
|
import type { ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { type RecallPolicy } from './recall.js';
|
|
3
|
-
/** Native branch edits supply exclusion; original global indices supply provenance. */
|
|
4
|
-
export declare function omittedSourceIndices(entries: readonly SessionEntry[], branch: readonly SessionEntry[]): ReadonlySet<number>;
|
|
5
3
|
/** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or inference about meaning. */
|
|
6
4
|
export declare function filterOmittedSummary(summary: string, omitted: ReadonlySet<number>, sources?: readonly SessionEntry[], rangeOmitted?: ReadonlySet<number>): string;
|
|
7
|
-
/** Custom quotes carry native entry identity; no text matching or legacy fallback. */
|
|
8
|
-
export declare function filterCustomQuotes(summary: string, entries: readonly SessionEntry[], branch: readonly SessionEntry[], policy?: RecallPolicy): string;
|
|
9
5
|
type ProjectedMessages = ReturnType<ExtensionContext['sessionManager']['buildSessionProjection']>['messages'];
|
|
6
|
+
/** The saved conversation as this compactor delivers it: native omissions and ineligible custom quotes removed from its own summaries. A
|
|
7
|
+
* summary of another format (Pi's own /compact before pi-tuck was loaded, an empty draft) cannot be filtered and goes out as it is, as
|
|
8
|
+
* native Pi sends it; the next pi-tuck cut replaces it. Failing closed on it left such a session unable to send any prompt (issue #1). */
|
|
10
9
|
export declare function projectedMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages;
|
|
11
|
-
/** The planner's name for the same projection (kept for its callers). */
|
|
12
|
-
export declare function measurableMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages;
|
|
13
10
|
export {};
|
package/dist/src/omissions.js
CHANGED
|
@@ -4,7 +4,7 @@ import { textOf } from "./tuck/core/content.js";
|
|
|
4
4
|
import { isDiscardedResponse } from "./protocol.js";
|
|
5
5
|
import { createRecall } from './recall.js';
|
|
6
6
|
/** Native branch edits supply exclusion; original global indices supply provenance. */
|
|
7
|
-
|
|
7
|
+
function omittedSourceIndices(entries, branch) {
|
|
8
8
|
const edits = new Set();
|
|
9
9
|
for (const entry of branch)
|
|
10
10
|
if (entry.type === 'context_edit') {
|
|
@@ -94,7 +94,7 @@ export function filterOmittedSummary(summary, omitted, sources, rangeOmitted = o
|
|
|
94
94
|
return transcriptHeader(version) + '\n' + retained.join('\n') + closing;
|
|
95
95
|
}
|
|
96
96
|
/** Custom quotes carry native entry identity; no text matching or legacy fallback. */
|
|
97
|
-
|
|
97
|
+
function filterCustomQuotes(summary, entries, branch, policy = {}) {
|
|
98
98
|
const split = splitSummary(summary);
|
|
99
99
|
if (!split)
|
|
100
100
|
throw new Error('Cannot resolve custom sources in an unsupported compaction summary');
|
|
@@ -131,7 +131,7 @@ export function filterCustomQuotes(summary, entries, branch, policy = {}) {
|
|
|
131
131
|
/** The saved conversation as this compactor delivers it: native omissions and ineligible custom quotes removed from its own summaries. A
|
|
132
132
|
* summary of another format (Pi's own /compact before pi-tuck was loaded, an empty draft) cannot be filtered and goes out as it is, as
|
|
133
133
|
* native Pi sends it; the next pi-tuck cut replaces it. Failing closed on it left such a session unable to send any prompt (issue #1). */
|
|
134
|
-
function
|
|
134
|
+
export function projectedMessages(messages, ctx, policy) {
|
|
135
135
|
const entries = ctx.sessionManager.getEntries(), branch = ctx.sessionManager.getBranch();
|
|
136
136
|
const omitted = omittedSourceIndices(entries, branch);
|
|
137
137
|
const lastCut = branch.findLastIndex(entry => entry.type === 'compaction');
|
|
@@ -149,10 +149,3 @@ function projectMessages(messages, ctx, policy) {
|
|
|
149
149
|
return messages.map(message => message.role === 'compactionSummary' && splitSummary(message.summary) !== undefined
|
|
150
150
|
? { ...message, summary: filterCustomQuotes(filterOmittedSummary(message.summary, omitted, entries, cut?.type === 'compaction' && cut.summary === message.summary ? afterCut : new Set()), entries, branch, policy) } : message);
|
|
151
151
|
}
|
|
152
|
-
export function projectedMessages(messages, ctx, policy) {
|
|
153
|
-
return projectMessages(messages, ctx, policy);
|
|
154
|
-
}
|
|
155
|
-
/** The planner's name for the same projection (kept for its callers). */
|
|
156
|
-
export function measurableMessages(messages, ctx, policy) {
|
|
157
|
-
return projectMessages(messages, ctx, policy);
|
|
158
|
-
}
|
package/dist/src/recall.js
CHANGED
|
@@ -69,7 +69,7 @@ export function createRecall(policy = {}) {
|
|
|
69
69
|
else if (entry.type === "custom_message")
|
|
70
70
|
value = { role: "custom", text: textContent(entry.content) };
|
|
71
71
|
else if (entry.type === "message") {
|
|
72
|
-
const message = entry.message;
|
|
72
|
+
const message = entry.message, link = links?.get(entry.id);
|
|
73
73
|
if (message.role === "user" || message.role === "assistant" || message.role === "custom")
|
|
74
74
|
value = { role: message.role, text: textContent(message.content, message.role === "assistant"),
|
|
75
75
|
...(message.role === "assistant" && message.stopReason !== undefined ? { stopReason: message.stopReason } : {}) };
|
|
@@ -81,7 +81,7 @@ export function createRecall(policy = {}) {
|
|
|
81
81
|
toolName: message.toolName.slice(0, MAX_TOOL_METADATA),
|
|
82
82
|
toolCallId: message.toolCallId.slice(0, MAX_TOOL_METADATA),
|
|
83
83
|
isError: message.isError,
|
|
84
|
-
...(
|
|
84
|
+
...(link ? { producerRead: { entryId: link.entryId, offset: link.offset, limit: link.limit }, producerTime: link.sourceTime } : {}),
|
|
85
85
|
...(message.toolName.length > MAX_TOOL_METADATA || message.toolCallId.length > MAX_TOOL_METADATA
|
|
86
86
|
? { metadataTruncated: true } : {}),
|
|
87
87
|
};
|
package/dist/src/thrash.d.ts
CHANGED
|
@@ -3,12 +3,6 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
|
3
3
|
export declare const THRASH_WINDOW_REPLIES = 3;
|
|
4
4
|
/** Re-reads per cut at which a session is thrashing. */
|
|
5
5
|
export declare const THRASH_BAR = 0.5;
|
|
6
|
-
/**
|
|
7
|
-
* Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
|
|
8
|
-
* limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
|
|
9
|
-
* within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
|
|
10
|
-
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
11
|
-
*/
|
|
12
6
|
export interface Rereads {
|
|
13
7
|
cuts: number;
|
|
14
8
|
rereads: number;
|
package/dist/src/thrash.js
CHANGED
|
@@ -32,7 +32,7 @@ export function rereadsAfterCuts(branch) {
|
|
|
32
32
|
const args = block.arguments, path = extractPath(args);
|
|
33
33
|
if (!path)
|
|
34
34
|
continue;
|
|
35
|
-
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut:
|
|
35
|
+
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: current, soon: current > 0 && replies <= THRASH_WINDOW_REPLIES });
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
else if (message.role === "toolResult") {
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export declare const CLOSING_INSTRUCTION: string;
|
|
3
3
|
/** Parsing never depends on this wording (transcript.ts splitSummary). */
|
|
4
4
|
export declare const DIALOGUE_SUFFIX: string;
|
|
5
|
+
/** The deepest floor's last words: it lists no actions or files, so it does not claim to. */
|
|
6
|
+
export declare const DEEPEST_SUFFIX: string;
|
|
5
7
|
/** The closing words when working files follow: the re-read rule stays for every other file. */
|
|
6
8
|
export declare const WORKING_FILES_INSTRUCTION: string;
|
|
7
9
|
/** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
|
|
@@ -4,6 +4,9 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
|
|
|
4
4
|
"Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
|
|
5
5
|
/** Parsing never depends on this wording (transcript.ts splitSummary). */
|
|
6
6
|
export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
|
|
7
|
+
/** The deepest floor's last words: it lists no actions or files, so it does not claim to. */
|
|
8
|
+
export const DEEPEST_SUFFIX = CLOSING_SEPARATOR + "Only the dialogue and the outputs shown above carry over; no list of actions or files was kept. " +
|
|
9
|
+
"Before re-running a command, read its earlier output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
|
|
7
10
|
const REREAD = "Re-read a file before editing it or importing from it.";
|
|
8
11
|
/** The closing words when working files follow: the re-read rule stays for every other file. */
|
|
9
12
|
export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD, "Re-read a file before editing it or importing from it, unless it is one of the working files below.");
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
export declare const DEFAULT_CHARS_PER_TOKEN = 4;
|
|
2
2
|
export declare const MIN_CHARS_PER_TOKEN = 2;
|
|
3
3
|
export declare const MAX_CHARS_PER_TOKEN = 6;
|
|
4
|
-
export
|
|
5
|
-
export interface TokenEstimateCalibration {
|
|
6
|
-
mode: TokenEstimateMode;
|
|
4
|
+
export declare const calibrateCharsPerToken: (sourceChars: number, sourceTokens: number | undefined) => {
|
|
7
5
|
charsPerToken: number;
|
|
8
|
-
|
|
9
|
-
sourceTokens?: number;
|
|
10
|
-
rawCharsPerToken?: number;
|
|
11
|
-
}
|
|
12
|
-
export declare const calibrateCharsPerToken: (sourceChars: number, sourceTokens: number | undefined) => TokenEstimateCalibration;
|
|
6
|
+
};
|
|
13
7
|
export declare const estimateTokensFromChars: (chars: number, charsPerToken?: number) => number;
|
|
14
8
|
/**
|
|
15
9
|
* Chars attributed to one image part, mirroring pi-agent-core's own
|