@seanhogg/builderforce-memory 2026.10.82 → 2026.10.83
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/dist/working/fold.d.ts +15 -0
- package/dist/working/fold.d.ts.map +1 -1
- package/dist/working/fold.js +17 -6
- package/dist/working/fold.js.map +1 -1
- package/dist/working/index.d.ts +2 -0
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +1 -0
- package/dist/working/index.js.map +1 -1
- package/dist/working/runElision.d.ts +54 -0
- package/dist/working/runElision.d.ts.map +1 -0
- package/dist/working/runElision.js +137 -0
- package/dist/working/runElision.js.map +1 -0
- package/dist/working/transcript.d.ts +8 -2
- package/dist/working/transcript.d.ts.map +1 -1
- package/dist/working/transcript.js +40 -9
- package/dist/working/transcript.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +3 -0
- package/src/contract/regression.inRunWindow.test.ts +175 -0
- package/src/contract/types.contract.test.ts +11 -0
- package/src/working/fold.ts +19 -7
- package/src/working/index.ts +2 -0
- package/src/working/runElision.ts +149 -0
- package/src/working/transcript.ts +41 -7
package/dist/working/fold.d.ts
CHANGED
|
@@ -26,6 +26,21 @@ export declare const NARRATION_OVERLAP = 0.8;
|
|
|
26
26
|
export declare function supersededReadMarker(path: string, step: number): string;
|
|
27
27
|
/** B7's replacement for a tool-call turn's narration that merely repeats the previous one. */
|
|
28
28
|
export declare const PROGRESS_NOTE = "(progress note)";
|
|
29
|
+
/** An OpenAI-style tool call, read defensively (a host's shape is not trusted). Shared with `runElision.ts`. */
|
|
30
|
+
export interface NamedToolCall {
|
|
31
|
+
id?: unknown;
|
|
32
|
+
function?: {
|
|
33
|
+
name?: unknown;
|
|
34
|
+
arguments?: unknown;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export declare function callsOf(m: TranscriptMessage): NamedToolCall[];
|
|
38
|
+
export declare function nameOf(call: NamedToolCall): string | null;
|
|
39
|
+
/**
|
|
40
|
+
* The first non-empty string argument of a tool call among `keys`, in that order — from the object form or parsed out of
|
|
41
|
+
* a JSON string. Null when none is present or the arguments are not JSON (a malformed call names no target).
|
|
42
|
+
*/
|
|
43
|
+
export declare function stringArgOf(call: NamedToolCall, keys: readonly string[]): string | null;
|
|
29
44
|
/**
|
|
30
45
|
* Jaccard similarity of two texts' word sets (lower-cased `[a-z0-9_]` words): |A ∩ B| / |A ∪ B|, 0 when either has no word.
|
|
31
46
|
* The measure B7 folds repeated narration by (see {@link isRepeatedNarration}).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fold.d.ts","sourceRoot":"","sources":["../../src/working/fold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,2FAA2F;AAC3F,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,wFAAwF;AACxF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,8FAA8F;AAC9F,eAAO,MAAM,aAAa,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"fold.d.ts","sourceRoot":"","sources":["../../src/working/fold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,2FAA2F;AAC3F,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,wFAAwF;AACxF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,8FAA8F;AAC9F,eAAO,MAAM,aAAa,oBAAoB,CAAC;AAE/C,gHAAgH;AAChH,MAAM,WAAW,aAAa;IAC5B,EAAE,CAAC,EAAE,OAAO,CAAC;IACb,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;CACpD;AAOD,wBAAgB,OAAO,CAAC,CAAC,EAAE,iBAAiB,GAAG,aAAa,EAAE,CAE7D;AAED,wBAAgB,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,MAAM,GAAG,IAAI,CAGzD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,GAAG,IAAI,CAgBvF;AA4CD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAOxD;AAED;;wFAEwF;AACxF,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAO3D;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,SAAoB,GAAG,OAAO,CAExG;AAyBD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,iBAAiB,EAAE,IAAI,EAAE,SAAS,CAAC,EAAE,GAAG,CAAC,EAAE,CA0CxF;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,iBAAiB,EAAE,IAAI,EAAE,SAAS,CAAC,EAAE,EAAE,OAAO,SAAoB,GAAG,CAAC,EAAE,CAqBvH;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,iBAAiB,EAAE,IAAI,EAAE,SAAS,CAAC,EAAE,GAAG,CAAC,EAAE,CAE1F"}
|
package/dist/working/fold.js
CHANGED
|
@@ -27,15 +27,18 @@ export function supersededReadMarker(path, step) {
|
|
|
27
27
|
}
|
|
28
28
|
/** B7's replacement for a tool-call turn's narration that merely repeats the previous one. */
|
|
29
29
|
export const PROGRESS_NOTE = '(progress note)';
|
|
30
|
-
function callsOf(m) {
|
|
30
|
+
export function callsOf(m) {
|
|
31
31
|
return Array.isArray(m.tool_calls) ? m.tool_calls : [];
|
|
32
32
|
}
|
|
33
|
-
function nameOf(call) {
|
|
33
|
+
export function nameOf(call) {
|
|
34
34
|
const name = call.function?.name;
|
|
35
35
|
return typeof name === 'string' && name.length > 0 ? name : null;
|
|
36
36
|
}
|
|
37
|
-
/**
|
|
38
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The first non-empty string argument of a tool call among `keys`, in that order — from the object form or parsed out of
|
|
39
|
+
* a JSON string. Null when none is present or the arguments are not JSON (a malformed call names no target).
|
|
40
|
+
*/
|
|
41
|
+
export function stringArgOf(call, keys) {
|
|
39
42
|
const raw = call.function?.arguments;
|
|
40
43
|
let parsed = raw;
|
|
41
44
|
if (typeof raw === 'string') {
|
|
@@ -48,8 +51,16 @@ function pathOf(call) {
|
|
|
48
51
|
}
|
|
49
52
|
if (!parsed || typeof parsed !== 'object')
|
|
50
53
|
return null;
|
|
51
|
-
const
|
|
52
|
-
|
|
54
|
+
for (const key of keys) {
|
|
55
|
+
const value = parsed[key];
|
|
56
|
+
if (typeof value === 'string' && value.length > 0)
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
/** The `path` argument of a tool call. */
|
|
62
|
+
function pathOf(call) {
|
|
63
|
+
return stringArgOf(call, ['path']);
|
|
53
64
|
}
|
|
54
65
|
/** The tool result answering `call`: by `tool_call_id` when present, else positionally. */
|
|
55
66
|
function resultFor(convo, call, callIndex) {
|
package/dist/working/fold.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fold.js","sourceRoot":"","sources":["../../src/working/fold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,2FAA2F;AAC3F,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,C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rankByCount } from './rank.js';
|
|
|
29
29
|
export type { Observation, WorkingMemorySnapshot, ConsolidatedMemory, ConsolidateOptions } from './types.js';
|
|
30
30
|
export { HISTORY_WINDOW, HISTORY_TOKEN_BUDGET, COMPACT_TAIL_TOKEN_BUDGET, windowed, stillInWorkingContext, transcriptTokens, buildWorkingTranscript, } from './transcript.js';
|
|
31
31
|
export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
|
|
32
|
+
export { MIN_ELIDED_RESULT_TOKENS, elideRunResults, elidedResultStub } from './runElision.js';
|
|
33
|
+
export type { RunElisionBudget } from './runElision.js';
|
|
32
34
|
export { NARRATION_OVERLAP, PROGRESS_NOTE, supersededReadMarker, foldSupersededReads, foldRepeatedNarration, foldWorkingTranscript, wordOverlap, wordContained, isRepeatedNarration, } from './fold.js';
|
|
33
35
|
export { DEFAULT_MAX_MERGE_DEPTH, chunkText, chunkedTextSummary } from './textSummary.js';
|
|
34
36
|
export type { ChunkedTextSummaryOptions } from './textSummary.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/working/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,YAAY,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA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YAAY,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC"}
|
package/dist/working/index.js
CHANGED
|
@@ -27,6 +27,7 @@ export { consolidate, mergeConsolidated, consolidatedKey, consolidatedFiles, wit
|
|
|
27
27
|
export { CONSOLIDATED_KEY_PREFIX, CONSOLIDATED_ROOT_AREA, MAX_RECALLED_MAPS, areaOfPath, areasNamedIn, areasOfPathsIn, consolidatedArea, consolidatedFactsFor, } from './codemapAreas.js';
|
|
28
28
|
export { rankByCount } from './rank.js';
|
|
29
29
|
export { HISTORY_WINDOW, HISTORY_TOKEN_BUDGET, COMPACT_TAIL_TOKEN_BUDGET, windowed, stillInWorkingContext, transcriptTokens, buildWorkingTranscript, } from './transcript.js';
|
|
30
|
+
export { MIN_ELIDED_RESULT_TOKENS, elideRunResults, elidedResultStub } from './runElision.js';
|
|
30
31
|
export { NARRATION_OVERLAP, PROGRESS_NOTE, supersededReadMarker, foldSupersededReads, foldRepeatedNarration, foldWorkingTranscript, wordOverlap, wordContained, isRepeatedNarration, } from './fold.js';
|
|
31
32
|
export { DEFAULT_MAX_MERGE_DEPTH, chunkText, chunkedTextSummary } from './textSummary.js';
|
|
32
33
|
export { TRANSCRIPT_SUMMARY_PROMPT, TRANSCRIPT_SUMMARY_MAX_TOKENS, TRANSCRIPT_SUMMARY_INPUT_TOKENS, renderForSummary, summaryChunks, summarizeTranscript } from './summary.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/working/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,yBAAyB,EACzB,QAAQ,EACR,qBAAqB,EACrB,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,WAAW,EACX,aAAa,EACb,mBAAmB,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,uBAAuB,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE1F,OAAO,EAAE,yBAAyB,EAAE,6BAA6B,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAE/K,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,qBAAqB,EACrB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,EACrB,sBAAsB,EACtB,oBAAoB,EACpB,cAAc,GACf,MAAM,0BAA0B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/working/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,yBAAyB,EACzB,QAAQ,EACR,qBAAqB,EACrB,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,wBAAwB,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAE9F,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,WAAW,EACX,aAAa,EACb,mBAAmB,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,uBAAuB,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE1F,OAAO,EAAE,yBAAyB,EAAE,6BAA6B,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAE/K,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,qBAAqB,EACrB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,EACrB,sBAAsB,EACtB,oBAAoB,EACpB,cAAc,GACf,MAAM,0BAA0B,CAAC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-run elision — how the drop-oldest window keeps ONE long run inside the history budget.
|
|
3
|
+
*
|
|
4
|
+
* The window ({@link windowed}) drops whole turns from the front, but never past the most
|
|
5
|
+
* recent user turn: a request must open on a user turn, and that turn is the run's task. So
|
|
6
|
+
* inside a single long run nothing after the prompt was ever dropped, and with the summary
|
|
7
|
+
* unavailable (timed out, failed) the prompt grew by every tool result the run produced —
|
|
8
|
+
* VS Code chat #128305 went from 31k to 191k tokens over one run, the 64k budget never
|
|
9
|
+
* applying.
|
|
10
|
+
*
|
|
11
|
+
* This is the cut INSIDE the run. Everything stays — the user turn, every assistant turn (its
|
|
12
|
+
* narration, a plan, the tool calls it made), and every tool result's ROW — but a tool result
|
|
13
|
+
* older than the recent tail has its CONTENT replaced by one line naming the tool, its target
|
|
14
|
+
* and its size ({@link elidedResultStub}). A call and its result are never split (the row
|
|
15
|
+
* stays, only its content shrinks), so strict vendors accept the request; and the model is
|
|
16
|
+
* told what it no longer sees and how to get it back.
|
|
17
|
+
*
|
|
18
|
+
* The cut moves in fixed chunks counted from the run's own start, so the elided prefix — what
|
|
19
|
+
* a provider prefix cache hashes — changes once per chunk of new work, not on every turn.
|
|
20
|
+
*
|
|
21
|
+
* Pure: no `node:*`, no I/O.
|
|
22
|
+
*/
|
|
23
|
+
import type { HandoffMessage } from '../handoff/types.js';
|
|
24
|
+
/** The budget an in-run cut works to — the transcript module supplies its own constants. */
|
|
25
|
+
export interface RunElisionBudget {
|
|
26
|
+
/** The history budget: below it (counting `extraTokens`) nothing is elided. */
|
|
27
|
+
budgetTokens: number;
|
|
28
|
+
/** How much of the run's most recent work stays verbatim once it is over. */
|
|
29
|
+
tailTokens: number;
|
|
30
|
+
/** The step the cut moves in, counted from the run's start (prefix-cache hysteresis). */
|
|
31
|
+
chunkTokens: number;
|
|
32
|
+
/** The fewest most-recent messages kept verbatim, however large. */
|
|
33
|
+
minTailMessages: number;
|
|
34
|
+
/** Tokens the caller sends in front of these messages (a memo note) — charged to the budget. */
|
|
35
|
+
extraTokens?: number;
|
|
36
|
+
}
|
|
37
|
+
/** A result this small costs less to keep than its stub saves — never elided. */
|
|
38
|
+
export declare const MIN_ELIDED_RESULT_TOKENS = 200;
|
|
39
|
+
/**
|
|
40
|
+
* The one line an elided tool result becomes: the tool, what it was called on, and how big
|
|
41
|
+
* the result was — so the model knows what it no longer sees and that it can fetch it again.
|
|
42
|
+
*/
|
|
43
|
+
export declare function elidedResultStub(tool: string, target: string | null, chars: number): string;
|
|
44
|
+
/**
|
|
45
|
+
* Elide the content of the current run's older tool results so `msgs` fits the budget.
|
|
46
|
+
* Returns the input itself (same reference) when it already fits or nothing could be elided;
|
|
47
|
+
* otherwise a new list whose elided rows are shallow copies with only `content` changed.
|
|
48
|
+
*
|
|
49
|
+
* The run is everything after the LAST user turn (all of `msgs` when there is none). Rows
|
|
50
|
+
* before it, the user turn itself, every assistant turn, results under
|
|
51
|
+
* {@link MIN_ELIDED_RESULT_TOKENS}, plan/ledger results and the verbatim tail are kept as sent.
|
|
52
|
+
*/
|
|
53
|
+
export declare function elideRunResults<M extends HandoffMessage>(msgs: readonly M[], budget: RunElisionBudget): M[];
|
|
54
|
+
//# sourceMappingURL=runElision.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runElision.d.ts","sourceRoot":"","sources":["../../src/working/runElision.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG1D,4FAA4F;AAC5F,MAAM,WAAW,gBAAgB;IAC/B,+EAA+E;IAC/E,YAAY,EAAE,MAAM,CAAC;IACrB,6EAA6E;IAC7E,UAAU,EAAE,MAAM,CAAC;IACnB,yFAAyF;IACzF,WAAW,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,eAAe,EAAE,MAAM,CAAC;IACxB,gGAAgG;IAChG,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,iFAAiF;AACjF,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAiB5C;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAI3F;AAoDD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,cAAc,EAAE,IAAI,EAAE,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,GAAG,CAAC,EAAE,CAoB3G"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-run elision — how the drop-oldest window keeps ONE long run inside the history budget.
|
|
3
|
+
*
|
|
4
|
+
* The window ({@link windowed}) drops whole turns from the front, but never past the most
|
|
5
|
+
* recent user turn: a request must open on a user turn, and that turn is the run's task. So
|
|
6
|
+
* inside a single long run nothing after the prompt was ever dropped, and with the summary
|
|
7
|
+
* unavailable (timed out, failed) the prompt grew by every tool result the run produced —
|
|
8
|
+
* VS Code chat #128305 went from 31k to 191k tokens over one run, the 64k budget never
|
|
9
|
+
* applying.
|
|
10
|
+
*
|
|
11
|
+
* This is the cut INSIDE the run. Everything stays — the user turn, every assistant turn (its
|
|
12
|
+
* narration, a plan, the tool calls it made), and every tool result's ROW — but a tool result
|
|
13
|
+
* older than the recent tail has its CONTENT replaced by one line naming the tool, its target
|
|
14
|
+
* and its size ({@link elidedResultStub}). A call and its result are never split (the row
|
|
15
|
+
* stays, only its content shrinks), so strict vendors accept the request; and the model is
|
|
16
|
+
* told what it no longer sees and how to get it back.
|
|
17
|
+
*
|
|
18
|
+
* The cut moves in fixed chunks counted from the run's own start, so the elided prefix — what
|
|
19
|
+
* a provider prefix cache hashes — changes once per chunk of new work, not on every turn.
|
|
20
|
+
*
|
|
21
|
+
* Pure: no `node:*`, no I/O.
|
|
22
|
+
*/
|
|
23
|
+
import { contentText, defaultEstimateTokens, messageTokens as handoffMessageTokens } from '../handoff/budget.js';
|
|
24
|
+
import { callsOf, nameOf, stringArgOf } from './fold.js';
|
|
25
|
+
/** A result this small costs less to keep than its stub saves — never elided. */
|
|
26
|
+
export const MIN_ELIDED_RESULT_TOKENS = 200;
|
|
27
|
+
/**
|
|
28
|
+
* Tools whose results the model steers by, never elided: the run's plan or ledger, and the answer to a question the
|
|
29
|
+
* run asked (`ask_user` answered in the run is the person's — or Auto's — direction, a directive like the user turn).
|
|
30
|
+
*/
|
|
31
|
+
const PINNED_RESULT_TOOL = /plan|todo|ledger|ask_?user/i;
|
|
32
|
+
/** The arguments a stub names as the call's target, in order of preference. */
|
|
33
|
+
const TARGET_ARGS = ['path', 'file_path', 'file', 'pattern', 'query', 'url', 'command'];
|
|
34
|
+
/** The longest target a stub quotes. */
|
|
35
|
+
const MAX_TARGET_CHARS = 120;
|
|
36
|
+
/** Every stub starts with this — a stub is never elided again. */
|
|
37
|
+
const STUB_PREFIX = '[result elided:';
|
|
38
|
+
/**
|
|
39
|
+
* The one line an elided tool result becomes: the tool, what it was called on, and how big
|
|
40
|
+
* the result was — so the model knows what it no longer sees and that it can fetch it again.
|
|
41
|
+
*/
|
|
42
|
+
export function elidedResultStub(tool, target, chars) {
|
|
43
|
+
const kb = Math.max(1, Math.round(chars / 1024));
|
|
44
|
+
const on = target ? ` ${target.length > MAX_TARGET_CHARS ? `${target.slice(0, MAX_TARGET_CHARS)}…` : target}` : '';
|
|
45
|
+
return `${STUB_PREFIX} ${tool}${on}, ${kb} KB — re-read if needed]`;
|
|
46
|
+
}
|
|
47
|
+
function messageTokens(m) {
|
|
48
|
+
return handoffMessageTokens(m, defaultEstimateTokens);
|
|
49
|
+
}
|
|
50
|
+
/** The call each tool row answers: by `tool_call_id`, else the next unanswered call of the turn before it. */
|
|
51
|
+
function callsAnswered(msgs) {
|
|
52
|
+
const byId = new Map();
|
|
53
|
+
const answered = new Map();
|
|
54
|
+
let unanswered = [];
|
|
55
|
+
msgs.forEach((m, i) => {
|
|
56
|
+
if (m.role === 'assistant') {
|
|
57
|
+
unanswered = callsOf(m).slice();
|
|
58
|
+
for (const call of unanswered)
|
|
59
|
+
if (typeof call.id === 'string' && call.id.length > 0)
|
|
60
|
+
byId.set(call.id, call);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (m.role !== 'tool')
|
|
64
|
+
return;
|
|
65
|
+
const call = (m.tool_call_id ? byId.get(m.tool_call_id) : undefined) ?? unanswered[0];
|
|
66
|
+
if (!call)
|
|
67
|
+
return;
|
|
68
|
+
unanswered = unanswered.filter((c) => c !== call);
|
|
69
|
+
answered.set(i, call);
|
|
70
|
+
});
|
|
71
|
+
return answered;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Where the verbatim tail begins: `runStart` while the run's own messages fit the tail, else
|
|
75
|
+
* the first fixed cut point (the message after which the run's running total crosses a
|
|
76
|
+
* multiple of `chunkTokens`) that leaves at most `tailTokens` after it — never inside the
|
|
77
|
+
* last `minTailMessages`.
|
|
78
|
+
*/
|
|
79
|
+
function runCut(sizes, runStart, budget) {
|
|
80
|
+
let tail = 0;
|
|
81
|
+
for (let i = runStart; i < sizes.length; i++)
|
|
82
|
+
tail += sizes[i];
|
|
83
|
+
let cut = runStart;
|
|
84
|
+
if (tail > budget.tailTokens) {
|
|
85
|
+
let crossed = 0;
|
|
86
|
+
let nextCut = budget.chunkTokens;
|
|
87
|
+
for (let i = runStart; i < sizes.length; i++) {
|
|
88
|
+
crossed += sizes[i];
|
|
89
|
+
tail -= sizes[i];
|
|
90
|
+
if (crossed < nextCut)
|
|
91
|
+
continue;
|
|
92
|
+
while (crossed >= nextCut)
|
|
93
|
+
nextCut += budget.chunkTokens;
|
|
94
|
+
cut = i + 1;
|
|
95
|
+
// The first cut POINT that leaves the tail within budget — the tail may drop under it between two points.
|
|
96
|
+
if (tail <= budget.tailTokens)
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return Math.min(cut, Math.max(runStart, sizes.length - budget.minTailMessages));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Elide the content of the current run's older tool results so `msgs` fits the budget.
|
|
104
|
+
* Returns the input itself (same reference) when it already fits or nothing could be elided;
|
|
105
|
+
* otherwise a new list whose elided rows are shallow copies with only `content` changed.
|
|
106
|
+
*
|
|
107
|
+
* The run is everything after the LAST user turn (all of `msgs` when there is none). Rows
|
|
108
|
+
* before it, the user turn itself, every assistant turn, results under
|
|
109
|
+
* {@link MIN_ELIDED_RESULT_TOKENS}, plan/ledger results and the verbatim tail are kept as sent.
|
|
110
|
+
*/
|
|
111
|
+
export function elideRunResults(msgs, budget) {
|
|
112
|
+
const sizes = msgs.map(messageTokens);
|
|
113
|
+
const total = sizes.reduce((sum, n) => sum + n, 0) + (budget.extraTokens ?? 0);
|
|
114
|
+
if (total <= budget.budgetTokens)
|
|
115
|
+
return msgs;
|
|
116
|
+
const runStart = msgs.map((m) => m.role).lastIndexOf('user') + 1;
|
|
117
|
+
const cut = runCut(sizes, runStart, budget);
|
|
118
|
+
if (cut <= runStart)
|
|
119
|
+
return msgs;
|
|
120
|
+
const answered = callsAnswered(msgs);
|
|
121
|
+
let changed = false;
|
|
122
|
+
const out = msgs.map((m, i) => {
|
|
123
|
+
if (i < runStart || i >= cut || m.role !== 'tool' || sizes[i] < MIN_ELIDED_RESULT_TOKENS)
|
|
124
|
+
return m;
|
|
125
|
+
const text = contentText(m.content);
|
|
126
|
+
if (text.startsWith(STUB_PREFIX))
|
|
127
|
+
return m;
|
|
128
|
+
const call = answered.get(i);
|
|
129
|
+
const tool = (call && nameOf(call)) ?? 'tool';
|
|
130
|
+
if (PINNED_RESULT_TOOL.test(tool))
|
|
131
|
+
return m;
|
|
132
|
+
changed = true;
|
|
133
|
+
return { ...m, content: elidedResultStub(tool, call ? stringArgOf(call, TARGET_ARGS) : null, text.length) };
|
|
134
|
+
});
|
|
135
|
+
return changed ? out : msgs;
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=runElision.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runElision.js","sourceRoot":"","sources":["../../src/working/runElision.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,aAAa,IAAI,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEjH,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAsB,MAAM,WAAW,CAAC;AAgB7E,iFAAiF;AACjF,MAAM,CAAC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAE5C;;;GAGG;AACH,MAAM,kB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AAM,QAAQ,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IACrC,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QAC5B,IAAI,CAAC,GAAG,QAAQ,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,CAAC,CAAE,GAAG,wBAAwB;YAAE,OAAO,CAAC,CAAC;QACpG,MAAM,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC;YAAE,OAAO,CAAC,CAAC;QAC3C,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC7B,MAAM,IAAI,GAAG,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,MAAM,CAAC;QAC9C,IAAI,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YAAE,OAAO,CAAC,CAAC;QAC5C,OAAO,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAO,CAAC;IACnH,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAE,IAAY,CAAC;AACvC,CAAC"}
|
|
@@ -85,8 +85,12 @@ export declare const HISTORY_TOKEN_DROP_CHUNK: number;
|
|
|
85
85
|
* invalid for strict vendors — Gemini rejects a request whose conversation does not
|
|
86
86
|
* begin with a user turn (the cascade `[googleai] 400 INVALID_ARGUMENT` after a long
|
|
87
87
|
* tool loop crossed the window boundary). The most recent user turn is never dropped:
|
|
88
|
-
* correctness over the size cap, when a
|
|
89
|
-
*
|
|
88
|
+
* correctness over the size cap, when a single turn is itself oversized.
|
|
89
|
+
*
|
|
90
|
+
* A RUN that outgrows the budget after that user turn is cut inside ({@link elideRunResults}):
|
|
91
|
+
* its older tool results become one-line stubs, keeping the user turn, every assistant turn
|
|
92
|
+
* and a ~{@link COMPACT_TAIL_TOKEN_BUDGET}-token verbatim tail. Without it one long run grew
|
|
93
|
+
* the prompt by every result it produced (chat #128305: 31k → 191k tokens).
|
|
90
94
|
*
|
|
91
95
|
* A consolidation marker that LEADS the transcript (a reloaded chat's seed begins with its saved
|
|
92
96
|
* fold note) is never dropped: it is the note that stands for everything before the rest, and
|
|
@@ -101,6 +105,8 @@ export declare function windowed<M extends TranscriptMessage>(convo: M[]): M[];
|
|
|
101
105
|
* front. Deliberately conservative: it judges against the CURRENT transcript (which has
|
|
102
106
|
* grown since the last working set was built), so it can only ever call a message gone a
|
|
103
107
|
* turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
|
|
108
|
+
* A result the in-run cut elided ({@link elideRunResults}) is gone too: the model sees its
|
|
109
|
+
* stub, not the row.
|
|
104
110
|
*/
|
|
105
111
|
export declare function stillInWorkingContext<M extends TranscriptMessage>(state: WorkingTranscriptState<M>, anchor: unknown): boolean;
|
|
106
112
|
/** The fewest recent messages the verbatim tail keeps, however large they are. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAI1D,yF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,yBAAyB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAY3G;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAGnG;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,iBAAiB,EAC3D,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,CAAC,EAAE,EACV,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,GACjB,CAAC,EAAE,CAQL;AAaD;4EAC4E;AAC5E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,SAAS,iBAAiB,EAAE,GAAG,MAAM,CAE3E;AAQD;kEACkE;AAClE,MAAM,WAAW,cAAc;IAC7B,eAAe,EAAE,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,SAAS,iBAAiB,EACtE,KAAK,EAAE,sBAAsB,CAAC,CAAC,CAAC,EAChC,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,EAChD,QAAQ,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,GACvC,OAAO,CAAC,CAAC,EAAE,CAAC,CA4Bd"}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { defaultEstimateTokens, messageTokens as handoffMessageTokens, tokensOf as handoffTokensOf } from '../handoff/budget.js';
|
|
15
15
|
import { CONSOLIDATION_MARKER_PREFIX } from './consolidationMarker.js';
|
|
16
|
+
import { elideRunResults } from './runElision.js';
|
|
16
17
|
/** How much history we send to the model (message-count ceiling). */
|
|
17
18
|
export const HISTORY_WINDOW = 80;
|
|
18
19
|
/**
|
|
@@ -111,8 +112,12 @@ function tokenWindowStart(convo) {
|
|
|
111
112
|
* invalid for strict vendors — Gemini rejects a request whose conversation does not
|
|
112
113
|
* begin with a user turn (the cascade `[googleai] 400 INVALID_ARGUMENT` after a long
|
|
113
114
|
* tool loop crossed the window boundary). The most recent user turn is never dropped:
|
|
114
|
-
* correctness over the size cap, when a
|
|
115
|
-
*
|
|
115
|
+
* correctness over the size cap, when a single turn is itself oversized.
|
|
116
|
+
*
|
|
117
|
+
* A RUN that outgrows the budget after that user turn is cut inside ({@link elideRunResults}):
|
|
118
|
+
* its older tool results become one-line stubs, keeping the user turn, every assistant turn
|
|
119
|
+
* and a ~{@link COMPACT_TAIL_TOKEN_BUDGET}-token verbatim tail. Without it one long run grew
|
|
120
|
+
* the prompt by every result it produced (chat #128305: 31k → 191k tokens).
|
|
116
121
|
*
|
|
117
122
|
* A consolidation marker that LEADS the transcript (a reloaded chat's seed begins with its saved
|
|
118
123
|
* fold note) is never dropped: it is the note that stands for everything before the rest, and
|
|
@@ -128,9 +133,18 @@ export function windowed(convo) {
|
|
|
128
133
|
while (convo[start].role !== 'user')
|
|
129
134
|
start += 1;
|
|
130
135
|
const lead = convo[0];
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
136
|
+
const window = start > 0 && isLeadingMarker(lead) ? [lead, ...convo.slice(start)] : convo.slice(start);
|
|
137
|
+
return elideRunResults(window, runElisionBudget());
|
|
138
|
+
}
|
|
139
|
+
/** The in-run cut's budget: the history budget, the compacted tail, the token drop chunk. */
|
|
140
|
+
function runElisionBudget(extraTokens = 0) {
|
|
141
|
+
return {
|
|
142
|
+
budgetTokens: HISTORY_TOKEN_BUDGET,
|
|
143
|
+
tailTokens: COMPACT_TAIL_TOKEN_BUDGET,
|
|
144
|
+
chunkTokens: HISTORY_TOKEN_DROP_CHUNK,
|
|
145
|
+
minTailMessages: COMPACT_TAIL_TURNS,
|
|
146
|
+
extraTokens,
|
|
147
|
+
};
|
|
134
148
|
}
|
|
135
149
|
/** Is this row a saved consolidation note (the visible marker the next seed starts from)? */
|
|
136
150
|
function isLeadingMarker(m) {
|
|
@@ -142,14 +156,20 @@ function isLeadingMarker(m) {
|
|
|
142
156
|
* front. Deliberately conservative: it judges against the CURRENT transcript (which has
|
|
143
157
|
* grown since the last working set was built), so it can only ever call a message gone a
|
|
144
158
|
* turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
|
|
159
|
+
* A result the in-run cut elided ({@link elideRunResults}) is gone too: the model sees its
|
|
160
|
+
* stub, not the row.
|
|
145
161
|
*/
|
|
146
162
|
export function stillInWorkingContext(state, anchor) {
|
|
147
163
|
const convo = state.transcript;
|
|
148
164
|
const idx = convo.indexOf(anchor);
|
|
149
165
|
if (idx < 0)
|
|
150
166
|
return false;
|
|
151
|
-
|
|
152
|
-
|
|
167
|
+
const memo = state.compactMemo;
|
|
168
|
+
if (memo) {
|
|
169
|
+
if (idx < verbatimStart(convo, memo.coveredEnd))
|
|
170
|
+
return false;
|
|
171
|
+
return boundedCompacted('', convo, memo.note, memo.coveredEnd).includes(convo[idx]);
|
|
172
|
+
}
|
|
153
173
|
return windowed(convo).includes(convo[idx]);
|
|
154
174
|
}
|
|
155
175
|
// ---------------------------------------------------------------------------
|
|
@@ -236,6 +256,16 @@ export function assembleCompacted(systemPrompt, convo, note, coveredEnd) {
|
|
|
236
256
|
out.push(...convo.slice(tailStart));
|
|
237
257
|
return out;
|
|
238
258
|
}
|
|
259
|
+
/**
|
|
260
|
+
* {@link assembleCompacted}, kept inside the history budget: when the note's verbatim
|
|
261
|
+
* remainder has outgrown it and no new fold was made (the summary failed or timed out),
|
|
262
|
+
* the current run's older tool results are elided ({@link elideRunResults}) — the note and
|
|
263
|
+
* the system prompt are kept, the note charged to the budget as the window charges it.
|
|
264
|
+
*/
|
|
265
|
+
function boundedCompacted(systemPrompt, convo, note, coveredEnd) {
|
|
266
|
+
const [system, noteRow, ...rest] = assembleCompacted(systemPrompt, convo, note, coveredEnd);
|
|
267
|
+
return [system, noteRow, ...elideRunResults(rest, runElisionBudget(transcriptTokens([noteRow])))];
|
|
268
|
+
}
|
|
239
269
|
/** Estimated tokens of a message list — the ONE count compaction budgets by, exported so
|
|
240
270
|
* a run measures what compaction kept out of a call with the same rule. */
|
|
241
271
|
export function transcriptTokens(msgs) {
|
|
@@ -276,9 +306,10 @@ export async function buildWorkingTranscript(state, systemPrompt, summarize, onF
|
|
|
276
306
|
: convo.slice(from, to);
|
|
277
307
|
const summary = to > from ? await summarize(fold) : null;
|
|
278
308
|
if (summary == null) {
|
|
279
|
-
// Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest
|
|
309
|
+
// Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest —
|
|
310
|
+
// either way cut inside the run once it outgrows the budget (`elideRunResults`).
|
|
280
311
|
return memo
|
|
281
|
-
?
|
|
312
|
+
? boundedCompacted(systemPrompt, convo, memo.note, memo.coveredEnd)
|
|
282
313
|
: [{ role: 'system', content: systemPrompt }, ...windowed(convo)];
|
|
283
314
|
}
|
|
284
315
|
const note = `Compressed memory of the earlier part of this conversation:\n${summary}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,qBAAqB,EAAE,aAAa,IAAI,oBAAoB,EAAE,QAAQ,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEjI,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,qBAAqB,EAAE,aAAa,IAAI,oBAAoB,EAAE,QAAQ,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEjI,OAAO,EAAE,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AAQ,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,IAAI,GAAG,gEAAgE,OAAO,EAAE,CAAC;IACvF,KAAK,CAAC,WAAW,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;IAC7C,QAAQ,CAAC,EAAE,eAAe,EAAE,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,CAAC;IAC/D,OAAO,iBAAiB,CAAC,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;AAC1D,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seanhogg/builderforce-memory",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.83",
|
|
4
4
|
"description": "BuilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, persistent agent memory, and token-saving agent-run memory (code maps, a prompt-cache-safe working memory, chunked transcript windowing) for BuilderForce.ai agents.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -747,6 +747,7 @@
|
|
|
747
747
|
"HISTORY_WINDOW",
|
|
748
748
|
"MAX_RECALLED_MAPS",
|
|
749
749
|
"MIN_CONSOLIDATED_FILES",
|
|
750
|
+
"MIN_ELIDED_RESULT_TOKENS",
|
|
750
751
|
"NARRATION_OVERLAP",
|
|
751
752
|
"PROGRESS_NOTE",
|
|
752
753
|
"TRANSCRIPT_SUMMARY_INPUT_TOKENS",
|
|
@@ -767,6 +768,8 @@
|
|
|
767
768
|
"consolidationMarkerContent",
|
|
768
769
|
"consolidationMarkerOf",
|
|
769
770
|
"consolidationMetadata",
|
|
771
|
+
"elideRunResults",
|
|
772
|
+
"elidedResultStub",
|
|
770
773
|
"foldKeepFromId",
|
|
771
774
|
"foldRepeatedNarration",
|
|
772
775
|
"foldSupersededReads",
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.inRunWindow.test.ts — the drop-oldest window never cut INSIDE a run.
|
|
3
|
+
*
|
|
4
|
+
* VS Code chat #128305 (VSIX 2026.10.204): one long run's prompt grew from 31k tokens at step 0 by ~4–5k a turn to 191k,
|
|
5
|
+
* with no reduction. The fold's summary kept timing out, so every turn fell back to `windowed`, which clamps its cut at
|
|
6
|
+
* the last user turn — and inside one run that turn is the prompt, so nothing after it was ever dropped and the 64k
|
|
7
|
+
* history budget never applied. The window now elides the run's older tool results (`elideRunResults`): the user turn,
|
|
8
|
+
* every assistant turn and a ~40k verbatim tail stay; a call and its result are never split.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
buildWorkingTranscript,
|
|
13
|
+
COMPACT_TAIL_TOKEN_BUDGET,
|
|
14
|
+
elidedResultStub,
|
|
15
|
+
elideRunResults,
|
|
16
|
+
HISTORY_TOKEN_BUDGET,
|
|
17
|
+
MIN_ELIDED_RESULT_TOKENS,
|
|
18
|
+
stillInWorkingContext,
|
|
19
|
+
transcriptTokens,
|
|
20
|
+
windowed,
|
|
21
|
+
type TranscriptMessage,
|
|
22
|
+
type WorkingTranscriptState,
|
|
23
|
+
} from '../working/index.js';
|
|
24
|
+
|
|
25
|
+
/** ~4.5k tokens: one file window of a coding run. */
|
|
26
|
+
const RESULT = (i: number) => `// file ${i}\n${'x'.repeat(18_000)}`;
|
|
27
|
+
|
|
28
|
+
/** One acting turn: an assistant tool call and the result that answers it. */
|
|
29
|
+
function step(i: number, tool = 'read_file', content = RESULT(i)): TranscriptMessage[] {
|
|
30
|
+
const id = `call_${i}`;
|
|
31
|
+
return [
|
|
32
|
+
{
|
|
33
|
+
role: 'assistant',
|
|
34
|
+
content: `Reading the next file (${i}).`,
|
|
35
|
+
tool_calls: [{ id, type: 'function', function: { name: tool, arguments: JSON.stringify({ path: `src/f${i}.ts` }) } }],
|
|
36
|
+
},
|
|
37
|
+
{ role: 'tool', tool_call_id: id, content },
|
|
38
|
+
];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A single run: the person's request, then `turns` tool steps and nothing else. */
|
|
42
|
+
function run(turns: number): TranscriptMessage[] {
|
|
43
|
+
const out: TranscriptMessage[] = [{ role: 'user', content: 'Review the Visualizer and fix what is broken.' }];
|
|
44
|
+
for (let i = 0; i < turns; i++) out.push(...step(i));
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Every assistant tool call is answered by the row right after it, and every tool row answers the call before it. */
|
|
49
|
+
function pairingIntact(msgs: readonly TranscriptMessage[]): boolean {
|
|
50
|
+
return msgs.every((m, i) => {
|
|
51
|
+
if (m.role !== 'tool') return true;
|
|
52
|
+
const prev = msgs[i - 1] as TranscriptMessage & { tool_calls?: Array<{ id: string }> };
|
|
53
|
+
return prev?.role === 'assistant' && (prev.tool_calls ?? []).some((c) => c.id === m.tool_call_id);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
describe('regression: chat #128305 — the fallback window cuts inside one long run', () => {
|
|
58
|
+
it('regression: a 40-turn run stays inside the history budget, keeps every row, the request and a verbatim tail', () => {
|
|
59
|
+
const convo = run(40);
|
|
60
|
+
expect(transcriptTokens(convo)).toBeGreaterThan(2.5 * HISTORY_TOKEN_BUDGET); // ~182k: what every turn used to send
|
|
61
|
+
const w = windowed(convo);
|
|
62
|
+
expect(transcriptTokens(w)).toBeLessThan(48_000); // ~44k: the ~40k tail, the request, every call and its stub
|
|
63
|
+
expect(transcriptTokens(w)).toBeLessThanOrEqual(HISTORY_TOKEN_BUDGET);
|
|
64
|
+
expect(w).toHaveLength(convo.length); // nothing dropped: rows are elided in place
|
|
65
|
+
expect(w[0]).toBe(convo[0]); // the request, verbatim
|
|
66
|
+
expect(pairingIntact(w)).toBe(true);
|
|
67
|
+
// Every assistant turn is the transcript's own row.
|
|
68
|
+
w.forEach((m, i) => { if (m.role === 'assistant') expect(m).toBe(convo[i]); });
|
|
69
|
+
// The most recent results are verbatim, and together within the tail budget.
|
|
70
|
+
const firstVerbatim = w.findIndex((m, i) => m.role === 'tool' && m === convo[i]);
|
|
71
|
+
expect(firstVerbatim).toBeGreaterThan(1);
|
|
72
|
+
expect(w.slice(firstVerbatim).every((m, i) => m === convo[firstVerbatim + i])).toBe(true);
|
|
73
|
+
expect(transcriptTokens(w.slice(firstVerbatim))).toBeLessThanOrEqual(COMPACT_TAIL_TOKEN_BUDGET);
|
|
74
|
+
// An older result is one line naming the tool, its target and its size.
|
|
75
|
+
expect(w[2]!.content).toBe(elidedResultStub('read_file', 'src/f0.ts', String(convo[2]!.content).length));
|
|
76
|
+
expect(w[2]!.content).toBe('[result elided: read_file src/f0.ts, 18 KB — re-read if needed]');
|
|
77
|
+
expect(w[2]!.tool_call_id).toBe('call_0');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('regression: with the summary failing every turn, buildWorkingTranscript stays bounded across the whole run', async () => {
|
|
81
|
+
const state: WorkingTranscriptState = { transcript: [], compactMemo: null };
|
|
82
|
+
let peak = 0;
|
|
83
|
+
for (let turn = 1; turn <= 40; turn++) {
|
|
84
|
+
state.transcript = run(turn);
|
|
85
|
+
const out = await buildWorkingTranscript(state, 'sys', async () => null, () => undefined);
|
|
86
|
+
expect(pairingIntact(out.slice(1))).toBe(true);
|
|
87
|
+
const sent = transcriptTokens(out.slice(1));
|
|
88
|
+
// Once over the budget, the cut leaves the ~40k tail plus the calls and their stubs — on EVERY turn, not only some.
|
|
89
|
+
if (transcriptTokens(state.transcript) > HISTORY_TOKEN_BUDGET) expect(sent).toBeLessThan(48_000);
|
|
90
|
+
peak = Math.max(peak, sent);
|
|
91
|
+
}
|
|
92
|
+
expect(peak).toBeLessThanOrEqual(HISTORY_TOKEN_BUDGET);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('regression: a memo held from an earlier fold does not let the verbatim remainder grow without bound when the next summary fails', async () => {
|
|
96
|
+
const convo = run(40);
|
|
97
|
+
const state: WorkingTranscriptState = { transcript: convo, compactMemo: { note: 'Compressed memory: the first steps.', coveredEnd: 3 } };
|
|
98
|
+
const out = await buildWorkingTranscript(state, 'sys', async () => null, () => undefined);
|
|
99
|
+
expect(out[0]).toEqual({ role: 'system', content: 'sys' });
|
|
100
|
+
expect(out[1]!.content).toBe('Compressed memory: the first steps.');
|
|
101
|
+
expect(transcriptTokens(out.slice(1))).toBeLessThanOrEqual(HISTORY_TOKEN_BUDGET);
|
|
102
|
+
expect(pairingIntact(out.slice(1).filter((m) => m.role !== 'user'))).toBe(true);
|
|
103
|
+
expect(state.compactMemo!.coveredEnd).toBe(3); // a failed summary keeps the note it had
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('regression: an elided result is out of the working context (the read cache replays it), a tail result is in', () => {
|
|
107
|
+
const convo = run(40);
|
|
108
|
+
const state: WorkingTranscriptState = { transcript: convo, compactMemo: null };
|
|
109
|
+
expect(stillInWorkingContext(state, convo[2])).toBe(false);
|
|
110
|
+
expect(stillInWorkingContext(state, convo[convo.length - 1])).toBe(true);
|
|
111
|
+
const memoState: WorkingTranscriptState = { transcript: convo, compactMemo: { note: 'n', coveredEnd: 3 } };
|
|
112
|
+
expect(stillInWorkingContext(memoState, convo[4])).toBe(false);
|
|
113
|
+
expect(stillInWorkingContext(memoState, convo[convo.length - 1])).toBe(true);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('regression: the elided prefix moves in chunks, not on every turn (prefix-cache stability)', () => {
|
|
117
|
+
let changes = 0;
|
|
118
|
+
let previous = -1;
|
|
119
|
+
for (let turn = 15; turn <= 40; turn++) {
|
|
120
|
+
const w = windowed(run(turn));
|
|
121
|
+
const cut = w.filter((m) => m.role === 'tool' && String(m.content).startsWith('[result elided:')).length;
|
|
122
|
+
if (cut !== previous) changes += 1;
|
|
123
|
+
previous = cut;
|
|
124
|
+
}
|
|
125
|
+
// 26 turns of ~4.5k tokens each, a 16k chunk: the cut moves about once every 3–4 turns.
|
|
126
|
+
expect(changes).toBeLessThan(13);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('keeps plan/ledger results, small results, and everything before the run', () => {
|
|
130
|
+
const big = 'y'.repeat(18_000);
|
|
131
|
+
const convo: TranscriptMessage[] = [
|
|
132
|
+
{ role: 'user', content: 'earlier request' },
|
|
133
|
+
{ role: 'assistant', content: 'earlier answer' },
|
|
134
|
+
{ role: 'user', content: 'the request' },
|
|
135
|
+
...step(0, 'update_plan', big),
|
|
136
|
+
...step(1, 'read_file', 'tiny'),
|
|
137
|
+
];
|
|
138
|
+
for (let i = 2; i < 30; i++) convo.push(...step(i));
|
|
139
|
+
const w = elideRunResults(convo, { budgetTokens: HISTORY_TOKEN_BUDGET, tailTokens: COMPACT_TAIL_TOKEN_BUDGET, chunkTokens: 16_000, minTailMessages: 8 });
|
|
140
|
+
expect(w.slice(0, 3)).toEqual(convo.slice(0, 3));
|
|
141
|
+
expect(w[4]).toBe(convo[4]); // the plan result
|
|
142
|
+
expect(w[6]).toBe(convo[6]); // under MIN_ELIDED_RESULT_TOKENS
|
|
143
|
+
expect(MIN_ELIDED_RESULT_TOKENS).toBeGreaterThan(0);
|
|
144
|
+
expect(String(w[8]!.content)).toMatch(/^\[result elided: read_file src\/f2\.ts, \d+ KB — re-read if needed\]$/);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('regression: an answered ask_user result (the run\'s direction) is never elided, however old or large', () => {
|
|
148
|
+
const answer = `Use the second approach. ${'z'.repeat(4_000)}`; // a detailed answer, well over MIN_ELIDED_RESULT_TOKENS
|
|
149
|
+
const convo: TranscriptMessage[] = [{ role: 'user', content: 'the request' }, ...step(0, 'ask_user', answer)];
|
|
150
|
+
for (let i = 1; i < 30; i++) convo.push(...step(i));
|
|
151
|
+
const w = windowed(convo);
|
|
152
|
+
expect(w[2]).toBe(convo[2]); // the answer, verbatim
|
|
153
|
+
expect(String(w[4]!.content).startsWith('[result elided: read_file')).toBe(true); // an older read beside it IS cut
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('returns the input itself when it fits, and is idempotent once elided', () => {
|
|
157
|
+
const short = run(3);
|
|
158
|
+
expect(windowed(short)).toEqual(short);
|
|
159
|
+
const budget = { budgetTokens: HISTORY_TOKEN_BUDGET, tailTokens: COMPACT_TAIL_TOKEN_BUDGET, chunkTokens: 16_000, minTailMessages: 8 };
|
|
160
|
+
expect(elideRunResults(short, budget)).toBe(short);
|
|
161
|
+
const once = elideRunResults(run(40), budget);
|
|
162
|
+
expect(elideRunResults(once, budget)).toBe(once);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('names a positional result (no tool_call_id) by the call before it, and stubs without a target when none is named', () => {
|
|
166
|
+
const convo: TranscriptMessage[] = [{ role: 'user', content: 'go' }];
|
|
167
|
+
for (let i = 0; i < 30; i++) {
|
|
168
|
+
convo.push({ role: 'assistant', content: '', tool_calls: [{ id: '', type: 'function', function: { name: 'search_code', arguments: '{}' } }] });
|
|
169
|
+
convo.push({ role: 'tool', content: RESULT(i) });
|
|
170
|
+
}
|
|
171
|
+
const w = windowed(convo);
|
|
172
|
+
expect(w[2]!.content).toBe(elidedResultStub('search_code', null, String(convo[2]!.content).length));
|
|
173
|
+
expect(String(w[2]!.content)).toBe('[result elided: search_code, 18 KB — re-read if needed]');
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -49,6 +49,7 @@ import type {
|
|
|
49
49
|
effectiveGuards, factStoreDump, loadFactGraph, memoryFactStore, rootRouters, saveFactGraph, sweepFactStore,
|
|
50
50
|
} from '../knowledge/index.js';
|
|
51
51
|
import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
|
|
52
|
+
import type { elidedResultStub, elideRunResults, RunElisionBudget, TranscriptMessage, windowed } from '../working/index.js';
|
|
52
53
|
|
|
53
54
|
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
|
|
54
55
|
type Expect<T extends true> = T;
|
|
@@ -479,6 +480,16 @@ export type ResolvedMount_shape = Expect<Equal<ResolvedMount, {
|
|
|
479
480
|
}>>;
|
|
480
481
|
export type EffectiveEntryPoint_extra_keys = Expect<Equal<Exclude<keyof EffectiveEntryPoint, keyof EntryPointFact>, 'file' | 'via' | 'guardsInferred'>>;
|
|
481
482
|
|
|
483
|
+
/* ── working transcript: the in-run cut (chat #128305) ──────────────────────────────────────────────────────── */
|
|
484
|
+
// `windowed` keeps its signature (brain-embedded's fallback window and read-cache check call it); the cut is inside it.
|
|
485
|
+
export type windowed_signature = Expect<Equal<typeof windowed, <M extends TranscriptMessage>(convo: M[]) => M[]>>;
|
|
486
|
+
export type elideRunResults_signature = Expect<Equal<
|
|
487
|
+
typeof elideRunResults, <M extends TranscriptMessage>(msgs: readonly M[], budget: RunElisionBudget) => M[]
|
|
488
|
+
>>;
|
|
489
|
+
export type RunElisionBudget_keys = Expect<Equal<keyof RunElisionBudget, 'budgetTokens' | 'tailTokens' | 'chunkTokens' | 'minTailMessages' | 'extraTokens'>>;
|
|
490
|
+
export type RunElisionBudget_extraTokens_is_optional = Expect<Equal<IsOptional<RunElisionBudget, 'extraTokens'>, true>>;
|
|
491
|
+
export type elidedResultStub_signature = Expect<Equal<typeof elidedResultStub, (tool: string, target: string | null, chars: number) => string>>;
|
|
492
|
+
|
|
482
493
|
describe('type contract', () => {
|
|
483
494
|
it('is enforced by `npm run check:contract-types` (tsc over tsconfig.contract.json), not at run time', () => {
|
|
484
495
|
// The values above only exist so the `satisfies` / `@ts-expect-error` lines are real code; this proves the file loads.
|
package/src/working/fold.ts
CHANGED
|
@@ -33,7 +33,8 @@ export function supersededReadMarker(path: string, step: number): string {
|
|
|
33
33
|
/** B7's replacement for a tool-call turn's narration that merely repeats the previous one. */
|
|
34
34
|
export const PROGRESS_NOTE = '(progress note)';
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
/** An OpenAI-style tool call, read defensively (a host's shape is not trusted). Shared with `runElision.ts`. */
|
|
37
|
+
export interface NamedToolCall {
|
|
37
38
|
id?: unknown;
|
|
38
39
|
function?: { name?: unknown; arguments?: unknown };
|
|
39
40
|
}
|
|
@@ -43,17 +44,20 @@ interface ToolResult {
|
|
|
43
44
|
error?: unknown;
|
|
44
45
|
}
|
|
45
46
|
|
|
46
|
-
function callsOf(m: TranscriptMessage): NamedToolCall[] {
|
|
47
|
+
export function callsOf(m: TranscriptMessage): NamedToolCall[] {
|
|
47
48
|
return Array.isArray(m.tool_calls) ? (m.tool_calls as NamedToolCall[]) : [];
|
|
48
49
|
}
|
|
49
50
|
|
|
50
|
-
function nameOf(call: NamedToolCall): string | null {
|
|
51
|
+
export function nameOf(call: NamedToolCall): string | null {
|
|
51
52
|
const name = call.function?.name;
|
|
52
53
|
return typeof name === 'string' && name.length > 0 ? name : null;
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
56
|
+
/**
|
|
57
|
+
* The first non-empty string argument of a tool call among `keys`, in that order — from the object form or parsed out of
|
|
58
|
+
* a JSON string. Null when none is present or the arguments are not JSON (a malformed call names no target).
|
|
59
|
+
*/
|
|
60
|
+
export function stringArgOf(call: NamedToolCall, keys: readonly string[]): string | null {
|
|
57
61
|
const raw = call.function?.arguments;
|
|
58
62
|
let parsed: unknown = raw;
|
|
59
63
|
if (typeof raw === 'string') {
|
|
@@ -64,8 +68,16 @@ function pathOf(call: NamedToolCall): string | null {
|
|
|
64
68
|
}
|
|
65
69
|
}
|
|
66
70
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
67
|
-
const
|
|
68
|
-
|
|
71
|
+
for (const key of keys) {
|
|
72
|
+
const value = (parsed as Record<string, unknown>)[key];
|
|
73
|
+
if (typeof value === 'string' && value.length > 0) return value;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The `path` argument of a tool call. */
|
|
79
|
+
function pathOf(call: NamedToolCall): string | null {
|
|
80
|
+
return stringArgOf(call, ['path']);
|
|
69
81
|
}
|
|
70
82
|
|
|
71
83
|
/** The tool result answering `call`: by `tool_call_id` when present, else positionally. */
|
package/src/working/index.ts
CHANGED
|
@@ -54,6 +54,8 @@ export {
|
|
|
54
54
|
buildWorkingTranscript,
|
|
55
55
|
} from './transcript.js';
|
|
56
56
|
export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
|
|
57
|
+
export { MIN_ELIDED_RESULT_TOKENS, elideRunResults, elidedResultStub } from './runElision.js';
|
|
58
|
+
export type { RunElisionBudget } from './runElision.js';
|
|
57
59
|
export {
|
|
58
60
|
NARRATION_OVERLAP,
|
|
59
61
|
PROGRESS_NOTE,
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-run elision — how the drop-oldest window keeps ONE long run inside the history budget.
|
|
3
|
+
*
|
|
4
|
+
* The window ({@link windowed}) drops whole turns from the front, but never past the most
|
|
5
|
+
* recent user turn: a request must open on a user turn, and that turn is the run's task. So
|
|
6
|
+
* inside a single long run nothing after the prompt was ever dropped, and with the summary
|
|
7
|
+
* unavailable (timed out, failed) the prompt grew by every tool result the run produced —
|
|
8
|
+
* VS Code chat #128305 went from 31k to 191k tokens over one run, the 64k budget never
|
|
9
|
+
* applying.
|
|
10
|
+
*
|
|
11
|
+
* This is the cut INSIDE the run. Everything stays — the user turn, every assistant turn (its
|
|
12
|
+
* narration, a plan, the tool calls it made), and every tool result's ROW — but a tool result
|
|
13
|
+
* older than the recent tail has its CONTENT replaced by one line naming the tool, its target
|
|
14
|
+
* and its size ({@link elidedResultStub}). A call and its result are never split (the row
|
|
15
|
+
* stays, only its content shrinks), so strict vendors accept the request; and the model is
|
|
16
|
+
* told what it no longer sees and how to get it back.
|
|
17
|
+
*
|
|
18
|
+
* The cut moves in fixed chunks counted from the run's own start, so the elided prefix — what
|
|
19
|
+
* a provider prefix cache hashes — changes once per chunk of new work, not on every turn.
|
|
20
|
+
*
|
|
21
|
+
* Pure: no `node:*`, no I/O.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { contentText, defaultEstimateTokens, messageTokens as handoffMessageTokens } from '../handoff/budget.js';
|
|
25
|
+
import type { HandoffMessage } from '../handoff/types.js';
|
|
26
|
+
import { callsOf, nameOf, stringArgOf, type NamedToolCall } from './fold.js';
|
|
27
|
+
|
|
28
|
+
/** The budget an in-run cut works to — the transcript module supplies its own constants. */
|
|
29
|
+
export interface RunElisionBudget {
|
|
30
|
+
/** The history budget: below it (counting `extraTokens`) nothing is elided. */
|
|
31
|
+
budgetTokens: number;
|
|
32
|
+
/** How much of the run's most recent work stays verbatim once it is over. */
|
|
33
|
+
tailTokens: number;
|
|
34
|
+
/** The step the cut moves in, counted from the run's start (prefix-cache hysteresis). */
|
|
35
|
+
chunkTokens: number;
|
|
36
|
+
/** The fewest most-recent messages kept verbatim, however large. */
|
|
37
|
+
minTailMessages: number;
|
|
38
|
+
/** Tokens the caller sends in front of these messages (a memo note) — charged to the budget. */
|
|
39
|
+
extraTokens?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A result this small costs less to keep than its stub saves — never elided. */
|
|
43
|
+
export const MIN_ELIDED_RESULT_TOKENS = 200;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Tools whose results the model steers by, never elided: the run's plan or ledger, and the answer to a question the
|
|
47
|
+
* run asked (`ask_user` answered in the run is the person's — or Auto's — direction, a directive like the user turn).
|
|
48
|
+
*/
|
|
49
|
+
const PINNED_RESULT_TOOL = /plan|todo|ledger|ask_?user/i;
|
|
50
|
+
|
|
51
|
+
/** The arguments a stub names as the call's target, in order of preference. */
|
|
52
|
+
const TARGET_ARGS = ['path', 'file_path', 'file', 'pattern', 'query', 'url', 'command'] as const;
|
|
53
|
+
|
|
54
|
+
/** The longest target a stub quotes. */
|
|
55
|
+
const MAX_TARGET_CHARS = 120;
|
|
56
|
+
|
|
57
|
+
/** Every stub starts with this — a stub is never elided again. */
|
|
58
|
+
const STUB_PREFIX = '[result elided:';
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The one line an elided tool result becomes: the tool, what it was called on, and how big
|
|
62
|
+
* the result was — so the model knows what it no longer sees and that it can fetch it again.
|
|
63
|
+
*/
|
|
64
|
+
export function elidedResultStub(tool: string, target: string | null, chars: number): string {
|
|
65
|
+
const kb = Math.max(1, Math.round(chars / 1024));
|
|
66
|
+
const on = target ? ` ${target.length > MAX_TARGET_CHARS ? `${target.slice(0, MAX_TARGET_CHARS)}…` : target}` : '';
|
|
67
|
+
return `${STUB_PREFIX} ${tool}${on}, ${kb} KB — re-read if needed]`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function messageTokens(m: HandoffMessage): number {
|
|
71
|
+
return handoffMessageTokens(m, defaultEstimateTokens);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The call each tool row answers: by `tool_call_id`, else the next unanswered call of the turn before it. */
|
|
75
|
+
function callsAnswered(msgs: readonly HandoffMessage[]): Map<number, NamedToolCall> {
|
|
76
|
+
const byId = new Map<string, NamedToolCall>();
|
|
77
|
+
const answered = new Map<number, NamedToolCall>();
|
|
78
|
+
let unanswered: NamedToolCall[] = [];
|
|
79
|
+
msgs.forEach((m, i) => {
|
|
80
|
+
if (m.role === 'assistant') {
|
|
81
|
+
unanswered = callsOf(m).slice();
|
|
82
|
+
for (const call of unanswered) if (typeof call.id === 'string' && call.id.length > 0) byId.set(call.id, call);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (m.role !== 'tool') return;
|
|
86
|
+
const call = (m.tool_call_id ? byId.get(m.tool_call_id) : undefined) ?? unanswered[0];
|
|
87
|
+
if (!call) return;
|
|
88
|
+
unanswered = unanswered.filter((c) => c !== call);
|
|
89
|
+
answered.set(i, call);
|
|
90
|
+
});
|
|
91
|
+
return answered;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Where the verbatim tail begins: `runStart` while the run's own messages fit the tail, else
|
|
96
|
+
* the first fixed cut point (the message after which the run's running total crosses a
|
|
97
|
+
* multiple of `chunkTokens`) that leaves at most `tailTokens` after it — never inside the
|
|
98
|
+
* last `minTailMessages`.
|
|
99
|
+
*/
|
|
100
|
+
function runCut(sizes: readonly number[], runStart: number, budget: RunElisionBudget): number {
|
|
101
|
+
let tail = 0;
|
|
102
|
+
for (let i = runStart; i < sizes.length; i++) tail += sizes[i]!;
|
|
103
|
+
let cut = runStart;
|
|
104
|
+
if (tail > budget.tailTokens) {
|
|
105
|
+
let crossed = 0;
|
|
106
|
+
let nextCut = budget.chunkTokens;
|
|
107
|
+
for (let i = runStart; i < sizes.length; i++) {
|
|
108
|
+
crossed += sizes[i]!;
|
|
109
|
+
tail -= sizes[i]!;
|
|
110
|
+
if (crossed < nextCut) continue;
|
|
111
|
+
while (crossed >= nextCut) nextCut += budget.chunkTokens;
|
|
112
|
+
cut = i + 1;
|
|
113
|
+
// The first cut POINT that leaves the tail within budget — the tail may drop under it between two points.
|
|
114
|
+
if (tail <= budget.tailTokens) break;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return Math.min(cut, Math.max(runStart, sizes.length - budget.minTailMessages));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Elide the content of the current run's older tool results so `msgs` fits the budget.
|
|
122
|
+
* Returns the input itself (same reference) when it already fits or nothing could be elided;
|
|
123
|
+
* otherwise a new list whose elided rows are shallow copies with only `content` changed.
|
|
124
|
+
*
|
|
125
|
+
* The run is everything after the LAST user turn (all of `msgs` when there is none). Rows
|
|
126
|
+
* before it, the user turn itself, every assistant turn, results under
|
|
127
|
+
* {@link MIN_ELIDED_RESULT_TOKENS}, plan/ledger results and the verbatim tail are kept as sent.
|
|
128
|
+
*/
|
|
129
|
+
export function elideRunResults<M extends HandoffMessage>(msgs: readonly M[], budget: RunElisionBudget): M[] {
|
|
130
|
+
const sizes = msgs.map(messageTokens);
|
|
131
|
+
const total = sizes.reduce((sum, n) => sum + n, 0) + (budget.extraTokens ?? 0);
|
|
132
|
+
if (total <= budget.budgetTokens) return msgs as M[];
|
|
133
|
+
const runStart = msgs.map((m) => m.role).lastIndexOf('user') + 1;
|
|
134
|
+
const cut = runCut(sizes, runStart, budget);
|
|
135
|
+
if (cut <= runStart) return msgs as M[];
|
|
136
|
+
const answered = callsAnswered(msgs);
|
|
137
|
+
let changed = false;
|
|
138
|
+
const out = msgs.map((m, i) => {
|
|
139
|
+
if (i < runStart || i >= cut || m.role !== 'tool' || sizes[i]! < MIN_ELIDED_RESULT_TOKENS) return m;
|
|
140
|
+
const text = contentText(m.content);
|
|
141
|
+
if (text.startsWith(STUB_PREFIX)) return m;
|
|
142
|
+
const call = answered.get(i);
|
|
143
|
+
const tool = (call && nameOf(call)) ?? 'tool';
|
|
144
|
+
if (PINNED_RESULT_TOOL.test(tool)) return m;
|
|
145
|
+
changed = true;
|
|
146
|
+
return { ...m, content: elidedResultStub(tool, call ? stringArgOf(call, TARGET_ARGS) : null, text.length) } as M;
|
|
147
|
+
});
|
|
148
|
+
return changed ? out : (msgs as M[]);
|
|
149
|
+
}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
import { defaultEstimateTokens, messageTokens as handoffMessageTokens, tokensOf as handoffTokensOf } from '../handoff/budget.js';
|
|
16
16
|
import type { HandoffMessage } from '../handoff/types.js';
|
|
17
17
|
import { CONSOLIDATION_MARKER_PREFIX } from './consolidationMarker.js';
|
|
18
|
+
import { elideRunResults, type RunElisionBudget } from './runElision.js';
|
|
18
19
|
|
|
19
20
|
/** A transcript message — the hand-off packer's shape, so both count a message alike. */
|
|
20
21
|
export type TranscriptMessage = HandoffMessage;
|
|
@@ -137,8 +138,12 @@ function tokenWindowStart(convo: readonly TranscriptMessage[]): number {
|
|
|
137
138
|
* invalid for strict vendors — Gemini rejects a request whose conversation does not
|
|
138
139
|
* begin with a user turn (the cascade `[googleai] 400 INVALID_ARGUMENT` after a long
|
|
139
140
|
* tool loop crossed the window boundary). The most recent user turn is never dropped:
|
|
140
|
-
* correctness over the size cap, when a
|
|
141
|
-
*
|
|
141
|
+
* correctness over the size cap, when a single turn is itself oversized.
|
|
142
|
+
*
|
|
143
|
+
* A RUN that outgrows the budget after that user turn is cut inside ({@link elideRunResults}):
|
|
144
|
+
* its older tool results become one-line stubs, keeping the user turn, every assistant turn
|
|
145
|
+
* and a ~{@link COMPACT_TAIL_TOKEN_BUDGET}-token verbatim tail. Without it one long run grew
|
|
146
|
+
* the prompt by every result it produced (chat #128305: 31k → 191k tokens).
|
|
142
147
|
*
|
|
143
148
|
* A consolidation marker that LEADS the transcript (a reloaded chat's seed begins with its saved
|
|
144
149
|
* fold note) is never dropped: it is the note that stands for everything before the rest, and
|
|
@@ -152,8 +157,19 @@ export function windowed<M extends TranscriptMessage>(convo: M[]): M[] {
|
|
|
152
157
|
let start = Math.min(Math.max(messageWindowStart(convo.length), tokenWindowStart(convo)), lastUser);
|
|
153
158
|
while (convo[start]!.role !== 'user') start += 1;
|
|
154
159
|
const lead = convo[0]!;
|
|
155
|
-
|
|
156
|
-
return
|
|
160
|
+
const window = start > 0 && isLeadingMarker(lead) ? [lead, ...convo.slice(start)] : convo.slice(start);
|
|
161
|
+
return elideRunResults(window, runElisionBudget());
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The in-run cut's budget: the history budget, the compacted tail, the token drop chunk. */
|
|
165
|
+
function runElisionBudget(extraTokens = 0): RunElisionBudget {
|
|
166
|
+
return {
|
|
167
|
+
budgetTokens: HISTORY_TOKEN_BUDGET,
|
|
168
|
+
tailTokens: COMPACT_TAIL_TOKEN_BUDGET,
|
|
169
|
+
chunkTokens: HISTORY_TOKEN_DROP_CHUNK,
|
|
170
|
+
minTailMessages: COMPACT_TAIL_TURNS,
|
|
171
|
+
extraTokens,
|
|
172
|
+
};
|
|
157
173
|
}
|
|
158
174
|
|
|
159
175
|
/** Is this row a saved consolidation note (the visible marker the next seed starts from)? */
|
|
@@ -167,12 +183,18 @@ function isLeadingMarker(m: TranscriptMessage): boolean {
|
|
|
167
183
|
* front. Deliberately conservative: it judges against the CURRENT transcript (which has
|
|
168
184
|
* grown since the last working set was built), so it can only ever call a message gone a
|
|
169
185
|
* turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
|
|
186
|
+
* A result the in-run cut elided ({@link elideRunResults}) is gone too: the model sees its
|
|
187
|
+
* stub, not the row.
|
|
170
188
|
*/
|
|
171
189
|
export function stillInWorkingContext<M extends TranscriptMessage>(state: WorkingTranscriptState<M>, anchor: unknown): boolean {
|
|
172
190
|
const convo = state.transcript;
|
|
173
191
|
const idx = convo.indexOf(anchor as M);
|
|
174
192
|
if (idx < 0) return false;
|
|
175
|
-
|
|
193
|
+
const memo = state.compactMemo;
|
|
194
|
+
if (memo) {
|
|
195
|
+
if (idx < verbatimStart(convo, memo.coveredEnd)) return false;
|
|
196
|
+
return boundedCompacted('', convo, memo.note, memo.coveredEnd).includes(convo[idx]!);
|
|
197
|
+
}
|
|
176
198
|
return windowed(convo).includes(convo[idx]!);
|
|
177
199
|
}
|
|
178
200
|
|
|
@@ -269,6 +291,17 @@ export function assembleCompacted<M extends TranscriptMessage>(
|
|
|
269
291
|
return out;
|
|
270
292
|
}
|
|
271
293
|
|
|
294
|
+
/**
|
|
295
|
+
* {@link assembleCompacted}, kept inside the history budget: when the note's verbatim
|
|
296
|
+
* remainder has outgrown it and no new fold was made (the summary failed or timed out),
|
|
297
|
+
* the current run's older tool results are elided ({@link elideRunResults}) — the note and
|
|
298
|
+
* the system prompt are kept, the note charged to the budget as the window charges it.
|
|
299
|
+
*/
|
|
300
|
+
function boundedCompacted<M extends TranscriptMessage>(systemPrompt: string, convo: M[], note: string, coveredEnd: number): M[] {
|
|
301
|
+
const [system, noteRow, ...rest] = assembleCompacted(systemPrompt, convo, note, coveredEnd);
|
|
302
|
+
return [system!, noteRow!, ...elideRunResults(rest, runElisionBudget(transcriptTokens([noteRow!])))];
|
|
303
|
+
}
|
|
304
|
+
|
|
272
305
|
/** Estimated tokens of a message list — the ONE count compaction budgets by, exported so
|
|
273
306
|
* a run measures what compaction kept out of a call with the same rule. */
|
|
274
307
|
export function transcriptTokens(msgs: readonly TranscriptMessage[]): number {
|
|
@@ -324,9 +357,10 @@ export async function buildWorkingTranscript<M extends TranscriptMessage>(
|
|
|
324
357
|
: convo.slice(from, to);
|
|
325
358
|
const summary = to > from ? await summarize(fold) : null;
|
|
326
359
|
if (summary == null) {
|
|
327
|
-
// Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest
|
|
360
|
+
// Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest —
|
|
361
|
+
// either way cut inside the run once it outgrows the budget (`elideRunResults`).
|
|
328
362
|
return memo
|
|
329
|
-
?
|
|
363
|
+
? boundedCompacted(systemPrompt, convo, memo.note, memo.coveredEnd)
|
|
330
364
|
: [{ role: 'system', content: systemPrompt } as M, ...windowed(convo)];
|
|
331
365
|
}
|
|
332
366
|
const note = `Compressed memory of the earlier part of this conversation:\n${summary}`;
|