@juicesharp/rpiv-btw 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -66
- package/btw-budget.ts +403 -0
- package/btw-messages.ts +44 -0
- package/btw-ui.ts +33 -3
- package/btw.ts +159 -78
- package/docs/architecture.md +161 -0
- package/docs/context-model.md +95 -0
- package/package.json +7 -1
- package/pi-compat.ts +31 -0
package/README.md
CHANGED
|
@@ -1,94 +1,103 @@
|
|
|
1
|
-
# rpiv-btw
|
|
1
|
+
# @juicesharp/rpiv-btw
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@juicesharp/rpiv-btw)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
2
5
|
|
|
3
6
|
<div align="center">
|
|
4
7
|
<a href="https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-btw">
|
|
5
|
-
<
|
|
6
|
-
<img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-btw/docs/cover.png" alt="rpiv-btw cover" width="50%">
|
|
7
|
-
</picture>
|
|
8
|
+
<img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-btw/docs/cover.png" alt="rpiv-btw cover art: a Pi transcript with a /btw side question answered below it, labelled ephemeral and never written" width="50%">
|
|
8
9
|
</a>
|
|
9
10
|
</div>
|
|
10
11
|
|
|
11
|
-
Ask a side question without polluting the main conversation. `rpiv-btw` adds
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
Ask a side question without polluting the main conversation. `rpiv-btw` adds
|
|
13
|
+
`/btw <question>` to [Pi Agent](https://github.com/badlogic/pi-mono) — your same
|
|
14
|
+
primary model answers in a panel at the bottom of the terminal, using a read-only
|
|
15
|
+
clone of the current conversation as context. The answer never enters the
|
|
16
|
+
transcript and never touches disk.
|
|
14
17
|
|
|
15
18
|
## Install
|
|
16
19
|
|
|
17
|
-
```
|
|
20
|
+
```sh
|
|
18
21
|
pi install npm:@juicesharp/rpiv-btw
|
|
19
22
|
```
|
|
20
23
|
|
|
21
|
-
Restart your Pi
|
|
24
|
+
Restart your Pi session.
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
Type `/btw` followed by your question:
|
|
22
29
|
|
|
23
30
|
```
|
|
24
31
|
/btw why did we switch from sockets to SSE last week?
|
|
25
32
|
```
|
|
26
33
|
|
|
27
|
-
|
|
34
|
+
A panel opens at the bottom of the terminal with your question on a banner, a `…`
|
|
35
|
+
while the model works, and the answer when it arrives. Prior `/btw` questions from
|
|
36
|
+
this session are listed under the banner, so follow-ups have context.
|
|
28
37
|
|
|
29
|
-
|
|
38
|
+
`/btw` uses whatever model is already driving your session — there is nothing to
|
|
39
|
+
pick, but Pi needs an active model with working credentials (`/login`).
|
|
30
40
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
- your question on a banner,
|
|
34
|
-
- a `…` while the model is thinking,
|
|
35
|
-
- the answer when it arrives.
|
|
36
|
-
|
|
37
|
-
Prior `/btw` questions from the same session appear above the banner, so follow-ups have context.
|
|
38
|
-
|
|
39
|
-
### Keys
|
|
41
|
+

|
|
40
42
|
|
|
41
43
|
| Key | Action |
|
|
42
|
-
|
|
43
|
-
| `↑` / `↓` | Scroll the panel
|
|
44
|
-
| `x` | Clear this session's `/btw` history
|
|
45
|
-
| `Esc` |
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
-
|
|
58
|
-
|
|
59
|
-
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
rpiv-btw/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `↑` / `↓` | Scroll the panel whenever content overflows — the hint appears once the answer arrives |
|
|
46
|
+
| `x` | Clear this session's `/btw` history — hint shown only when you have prior entries |
|
|
47
|
+
| `Esc` | Dismiss the panel, cancelling the call if it is still running |
|
|
48
|
+
|
|
49
|
+
## What you get
|
|
50
|
+
|
|
51
|
+
- **Nothing leaks into the main chat** — the answer is drawn in an overlay, never
|
|
52
|
+
emitted as an agent message, never written to the transcript, never written to disk.
|
|
53
|
+
- **The side question already knows your work** — it is handed a read-only clone
|
|
54
|
+
of the current conversation branch, so you do not re-explain context.
|
|
55
|
+
- **Follow-ups have their own thread** — every `/btw` turn in a session is replayed
|
|
56
|
+
into the next one, so the side conversation remembers itself.
|
|
57
|
+
- **`Esc` cancels only the side question** — cancelling it never interrupts what
|
|
58
|
+
the main session is doing.
|
|
59
|
+
- **Survives `/new`, `/fork`, `/resume`, `/reload`** — history is held in the
|
|
60
|
+
running Pi process and clears when Pi exits.
|
|
61
|
+
- **Correct after compaction** — the context snapshot is rebuilt whenever the
|
|
62
|
+
conversation is compacted or re-branched, so a later `/btw` never answers off a
|
|
63
|
+
stale view.
|
|
64
|
+
- **No tools, plain text** — a side question cannot edit a file or run a command.
|
|
65
|
+
|
|
66
|
+
## Reference
|
|
67
|
+
|
|
68
|
+
- [Context model](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-btw/docs/context-model.md) — exactly what each `/btw` call
|
|
69
|
+
sends to the model: the branch snapshot and its invalidation rules, session
|
|
70
|
+
history threading, the cross-session question hint, and the no-pollution
|
|
71
|
+
guarantees.
|
|
72
|
+
- [Architecture](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-btw/docs/architecture.md) — modules, registered command and
|
|
73
|
+
hooks, overlay layout and key handling, process-scoped state, Pi host-version
|
|
74
|
+
tolerance, and the full error-message list.
|
|
75
|
+
|
|
76
|
+
## Requirements
|
|
77
|
+
|
|
78
|
+
- **An interactive terminal.** `/btw` refuses to run without a UI — it is not
|
|
79
|
+
available under `pi --print` or RPC.
|
|
80
|
+
- **An active primary model with resolvable credentials.** Any provider works.
|
|
79
81
|
|
|
80
82
|
## Troubleshooting
|
|
81
83
|
|
|
82
84
|
| Symptom | Cause | Fix |
|
|
83
|
-
|
|
84
|
-
| `/btw requires interactive mode` | Running
|
|
85
|
-
| `/btw requires an active model` | No primary model configured | Set one with `/login
|
|
86
|
-
|
|
|
87
|
-
|
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `/btw requires interactive mode` | Running under `pi --print …` or RPC | Run Pi interactively |
|
|
87
|
+
| `/btw requires an active model` | No primary model configured | Set one with `/login`, or edit Pi's own `~/.pi/agent/models.json` |
|
|
88
|
+
| `/btw model (…) has no API key available.` | Credentials for the active model do not resolve | Re-authenticate that provider |
|
|
89
|
+
| `Usage: /btw <question>` | `/btw` ran with no argument | Put the question on the same line |
|
|
90
|
+
| Pressing `X` does nothing | Only lowercase `x` is bound to clear history | Press `x` |
|
|
91
|
+
| History gone after restarting Pi | By design — state is process-scoped, never written to disk | Nothing to fix; your main session is unaffected |
|
|
92
|
+
|
|
93
|
+
## Related
|
|
94
|
+
|
|
95
|
+
- [`@juicesharp/rpiv-pi`](https://www.npmjs.com/package/@juicesharp/rpiv-pi) — the
|
|
96
|
+
umbrella package. It does not install `rpiv-btw`; install this one yourself when
|
|
97
|
+
you want `/btw`.
|
|
98
|
+
- [juicesharp/rpiv-mono](https://github.com/juicesharp/rpiv-mono#readme) — the rest
|
|
99
|
+
of the rpiv family.
|
|
88
100
|
|
|
89
101
|
## License
|
|
90
102
|
|
|
91
|
-
[
|
|
92
|
-
[](https://opensource.org/licenses/MIT)
|
|
93
|
-
|
|
94
|
-
MIT
|
|
103
|
+
MIT — see [LICENSE](LICENSE).
|
package/btw-budget.ts
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context-budget engine for /btw: bounds how much prior side-question history
|
|
3
|
+
* and cloned-primary-branch content ride into a fresh side call so the
|
|
4
|
+
* assembled context stays within the model's window.
|
|
5
|
+
*
|
|
6
|
+
* Pure host-primitive consumers — no ExtensionContext/globalThis access. The
|
|
7
|
+
* caller reads session state and passes plain data in; results are computed
|
|
8
|
+
* value-for-value with reference-identical message elements on the fast path
|
|
9
|
+
* (preserves byte-identical prompt prefix across /btw invocations → cache parity).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { Api, Message, Model, UserMessage } from "@earendil-works/pi-ai";
|
|
13
|
+
import {
|
|
14
|
+
calculateContextTokens,
|
|
15
|
+
convertToLlm,
|
|
16
|
+
estimateTokens,
|
|
17
|
+
findCutPoint,
|
|
18
|
+
getLastAssistantUsage,
|
|
19
|
+
type SessionEntry,
|
|
20
|
+
sessionEntryToContextMessages,
|
|
21
|
+
} from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import type { BtwTurn } from "./btw.js";
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// Budget constants — the engine's tuning surface. Defined in this leaf module so
|
|
26
|
+
// the btw.ts ↔ btw-budget.ts dependency is type-only at runtime (btw.ts re-exports
|
|
27
|
+
// them for the package's public surface).
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
export const BTW_HISTORY_TOKEN_BUDGET = 8192; // cap /btw history (newest-suffix of BtwTurn[])
|
|
30
|
+
export const BTW_CONTEXT_RESERVE = 16384; // matches host DEFAULT_COMPACTION_SETTINGS.reserveTokens
|
|
31
|
+
export const BTW_NO_ANCHOR_SAFETY_FACTOR = 1.2; // no-anchor fallback overcount, applied HERE (host does not)
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Result of {@link capHistory}: the newest suffix of `/btw` turns admitted into
|
|
35
|
+
* a fresh side-call context, plus accounting surfaced to the trim-notice overlay.
|
|
36
|
+
*/
|
|
37
|
+
export interface CappedHistory {
|
|
38
|
+
/** Newest-suffix turns, reference-identical to the input `history` elements. */
|
|
39
|
+
admitted: BtwTurn[];
|
|
40
|
+
/** Sum of `estimateTokens` over BOTH messages of every admitted turn (chars/4 each). */
|
|
41
|
+
estimate: number;
|
|
42
|
+
/** Older turns dropped to stay within `budget` (=== `history.length - admitted.length`). */
|
|
43
|
+
droppedTurns: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Pure maximal-suffix walk over `/btw` history.
|
|
48
|
+
*
|
|
49
|
+
* Admits the MAXIMAL newest suffix of whole turns (user+assistant, atomic) whose
|
|
50
|
+
* summed `estimateTokens` cost is `≤ budget`. Newer turns are never sacrificed
|
|
51
|
+
* to admit older ones: the walk extends greedily from the newest backward, and
|
|
52
|
+
* the first older turn that would overflow breaks it.
|
|
53
|
+
*
|
|
54
|
+
* Floor guarantee: `history.length >= 1` ⇒ `admitted.length >= 1`. If the newest
|
|
55
|
+
* turn ALONE exceeds `budget`, it is still admitted (a side call carries no
|
|
56
|
+
* history otherwise) and `estimate` carries its over-budget actual cost — never
|
|
57
|
+
* clamped to the budget.
|
|
58
|
+
*
|
|
59
|
+
* `admitted` is `history.slice(k)`: reference-identical elements, no copy/mutate.
|
|
60
|
+
* The caller (the build step) owns reading the session history; this function
|
|
61
|
+
* touches no `ExtensionContext`/`globalThis`/`getSessionHistory`.
|
|
62
|
+
*/
|
|
63
|
+
export function capHistory(history: BtwTurn[], budget = BTW_HISTORY_TOKEN_BUDGET): CappedHistory {
|
|
64
|
+
if (history.length === 0) return { admitted: [], estimate: 0, droppedTurns: 0 };
|
|
65
|
+
|
|
66
|
+
// Seed with the newest turn — this IS the floor guarantee: even an over-budget
|
|
67
|
+
// newest turn is admitted (estimate unclamped) so the side call always carries it.
|
|
68
|
+
let estimate =
|
|
69
|
+
estimateTokens(history[history.length - 1].userMessage) +
|
|
70
|
+
estimateTokens(history[history.length - 1].assistantMessage);
|
|
71
|
+
let k = history.length - 1;
|
|
72
|
+
|
|
73
|
+
// Greedily extend backward over older turns while the running sum stays within budget.
|
|
74
|
+
// All turns have positive cost, so the first overflow breaks the maximal suffix.
|
|
75
|
+
for (let i = history.length - 2; i >= 0; i--) {
|
|
76
|
+
const cost = estimateTokens(history[i].userMessage) + estimateTokens(history[i].assistantMessage);
|
|
77
|
+
if (estimate + cost > budget) break;
|
|
78
|
+
estimate += cost;
|
|
79
|
+
k = i;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
admitted: history.slice(k),
|
|
84
|
+
estimate,
|
|
85
|
+
droppedTurns: k,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
// Branch-fit engine — pure; no ctx/globalThis access.
|
|
91
|
+
// Value-imports the six host primitives (no re-implementation). Deliberately does
|
|
92
|
+
// NOT reuse the host's backward findTurnStartIndex for the forward turn-start scan
|
|
93
|
+
// (the host scans backward for compaction's summarize-prefix model; /btw cannot
|
|
94
|
+
// summarize, so it drops the prefix and keeps a suffix that opens on a turn-start).
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
export interface FitBranchInput {
|
|
98
|
+
/** Raw session entries from the snapshot (findCutPoint/getLastAssistantUsage contract). */
|
|
99
|
+
entries: SessionEntry[];
|
|
100
|
+
/** Cached converted branch messages (type==="message"-filtered via branchToMessages).
|
|
101
|
+
* Returned by reference on the fast path (byte-identical prefix). */
|
|
102
|
+
messages: Message[];
|
|
103
|
+
model: Model<Api>;
|
|
104
|
+
systemPrompt: string;
|
|
105
|
+
question: UserMessage;
|
|
106
|
+
/** capHistory estimate over admitted /btw turns (subtracted from the window). */
|
|
107
|
+
admittedEstimate: number;
|
|
108
|
+
/** Retry override: when set, skip the window formula and trim/stub to this
|
|
109
|
+
* many branch tokens directly; the cached snapshot is NOT re-read. */
|
|
110
|
+
keepBudget?: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface FitBranchResult {
|
|
114
|
+
messages: Message[];
|
|
115
|
+
branchWasTrimmed: boolean;
|
|
116
|
+
stubbed: boolean;
|
|
117
|
+
/** Budget fitBranch applied: window-computed on the default path, the passed-in
|
|
118
|
+
* override on the retry path. Populated on BOTH paths so buildBtwMessages surfaces
|
|
119
|
+
* it for the overflow-retry caller's Math.floor(built.keepBudget / 2). */
|
|
120
|
+
keepBudget: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Stub/truncation literals (research-grounded). BTW_STUB_TEXT is exported for the
|
|
124
|
+
// stub-content test assertion; BTW_TRUNCATE_MARKER_FMT stays private (test asserts the marker substring).
|
|
125
|
+
export const BTW_STUB_TEXT = "[tool result elided by /btw to fit the context window]";
|
|
126
|
+
const BTW_TRUNCATE_MARKER_FMT = (truncatedChars: number): string => `[... ${truncatedChars} characters truncated]`;
|
|
127
|
+
|
|
128
|
+
// Turn-start discriminator (message-level, NOT the host's entry-level isTurnStartEntry
|
|
129
|
+
// which excludes compaction). branchSummary/compactionSummary are included so a head
|
|
130
|
+
// compaction/branch summary can open the kept suffix after a cut (hybrid filter).
|
|
131
|
+
const TURN_START_ROLES: ReadonlySet<string> = new Set([
|
|
132
|
+
"user",
|
|
133
|
+
"bashExecution",
|
|
134
|
+
"custom",
|
|
135
|
+
"branchSummary",
|
|
136
|
+
"compactionSummary",
|
|
137
|
+
]);
|
|
138
|
+
|
|
139
|
+
/** chars/4 heuristic mirror of estimateTokens for the system-prompt STRING (estimateTokens
|
|
140
|
+
* takes a message, not a raw string). Math.ceil matches the host's conservative direction. */
|
|
141
|
+
function estimateTextTokens(text: string): number {
|
|
142
|
+
return Math.ceil(text.length / 4);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Skip guard: the window is usable only when the reserve fits. */
|
|
146
|
+
function isBudgetable(model: Model<Api>): boolean {
|
|
147
|
+
return model.contextWindow > 0 && model.contextWindow > model.maxTokens + BTW_CONTEXT_RESERVE;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Sum estimateTokens over an LLM message array (real host primitive, chars/4 per message). */
|
|
151
|
+
function estimateMessagesTokens(messages: Message[]): number {
|
|
152
|
+
let sum = 0;
|
|
153
|
+
for (const m of messages) sum += estimateTokens(m);
|
|
154
|
+
return sum;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Branch-usage estimate. Anchor = getLastAssistantUsage → calculateContextTokens
|
|
158
|
+
* (safe overcount: includes the main agent's system/tools that /btw omits) PLUS
|
|
159
|
+
* estimateTokens over every context message from entries AFTER the anchor — turns the
|
|
160
|
+
* provider has not metered (the user's latest turn, tool traffic behind an
|
|
161
|
+
* aborted/error assistant) still occupy the window and must count toward it.
|
|
162
|
+
* No anchor → sum(estimateTokens) × BTW_NO_ANCHOR_SAFETY_FACTOR (host applies no factor;
|
|
163
|
+
* btw-budget applies 1.2 itself). */
|
|
164
|
+
function estimateBranchTokens(entries: SessionEntry[]): number {
|
|
165
|
+
const usage = getLastAssistantUsage(entries);
|
|
166
|
+
if (usage) {
|
|
167
|
+
// Locate the anchor entry by Usage-object identity: getLastAssistantUsage returns
|
|
168
|
+
// the stored reference, so identity finds the anchor without re-implementing the
|
|
169
|
+
// host's validity predicate (skip aborted/error/all-zero). Walk newest-first,
|
|
170
|
+
// summing estimates until the anchor — those are exactly the post-anchor entries.
|
|
171
|
+
let tail = 0;
|
|
172
|
+
let anchorFound = false;
|
|
173
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
174
|
+
const e = entries[i];
|
|
175
|
+
if (e.type === "message" && e.message.role === "assistant" && e.message.usage === usage) {
|
|
176
|
+
anchorFound = true;
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
for (const m of sessionEntryToContextMessages(e)) tail += estimateTokens(m);
|
|
180
|
+
}
|
|
181
|
+
// Identity miss (a host returning a derived Usage object) would have made `tail`
|
|
182
|
+
// span the whole branch and double-count the anchored prefix — drop it instead.
|
|
183
|
+
return calculateContextTokens(usage) + (anchorFound ? tail : 0);
|
|
184
|
+
}
|
|
185
|
+
// No-anchor fallback: sum estimateTokens over every context-visible AgentMessage the
|
|
186
|
+
// entries produce (estimateTokens accepts AgentMessage, so no cast is needed), × 1.2.
|
|
187
|
+
let sum = 0;
|
|
188
|
+
for (const e of entries) {
|
|
189
|
+
for (const m of sessionEntryToContextMessages(e)) sum += estimateTokens(m);
|
|
190
|
+
}
|
|
191
|
+
return Math.ceil(sum * BTW_NO_ANCHOR_SAFETY_FACTOR);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Turn-start test on a raw entry, via the exported message conversion (message-level
|
|
195
|
+
* discriminator — includes compaction/branch summaries). */
|
|
196
|
+
function isTurnStartEntry(entry: SessionEntry): boolean {
|
|
197
|
+
return sessionEntryToContextMessages(entry).some((m) => TURN_START_ROLES.has(m.role));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Forward scan from `fromIndex` to the first turn-start entry at or after it. Returns
|
|
201
|
+
* the index, or -1 if none exists (caller falls back to stubbing). Scanning forward
|
|
202
|
+
* past a mid-turn assistant also skips its trailing toolResults → atomicity:
|
|
203
|
+
* no toolCall without its toolResult and vice versa. */
|
|
204
|
+
function forwardScanToTurnStart(entries: SessionEntry[], fromIndex: number): number {
|
|
205
|
+
for (let i = fromIndex; i < entries.length; i++) {
|
|
206
|
+
if (isTurnStartEntry(entries[i])) return i;
|
|
207
|
+
}
|
|
208
|
+
return -1;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Trim: findCutPoint over RAW entries (its contract), then a FORWARD scan to a
|
|
212
|
+
* turn-start (NOT the host's backward findTurnStartIndex), then unfiltered conversion so
|
|
213
|
+
* a head compaction/branch summary survives (hybrid filter). Returns {messages:null} when
|
|
214
|
+
* no valid cut (firstKeptEntryIndex<=0) or no turn-start exists — caller stubs the full cache. */
|
|
215
|
+
function trimBranch(entries: SessionEntry[], keepRecentTokens: number): { messages: Message[] | null } {
|
|
216
|
+
const cut = findCutPoint(entries, 0, entries.length, keepRecentTokens);
|
|
217
|
+
if (cut.firstKeptEntryIndex <= 0) return { messages: null }; // no valid cut → stub the cache
|
|
218
|
+
const startIdx = forwardScanToTurnStart(entries, cut.firstKeptEntryIndex);
|
|
219
|
+
if (startIdx < 0) return { messages: null }; // no turn-start in the kept suffix → stub the cache
|
|
220
|
+
const keptEntries = entries.slice(startIdx);
|
|
221
|
+
// Hybrid filter: after a cut, UNFILTERED sessionEntryToContextMessages (the sibling
|
|
222
|
+
// conversion seam — shares convertToLlm with branchToMessages, no duplication) so a
|
|
223
|
+
// head compaction/branch summary survives, matching the main agent's post-compact context.
|
|
224
|
+
const trimmed = convertToLlm(keptEntries.flatMap((e) => sessionEntryToContextMessages(e)));
|
|
225
|
+
return { messages: trimmed };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Phase 1 of {@link stubToFit}: oldest-first toolResult stubbing. Operates in-place
|
|
229
|
+
* on `result` (does NOT copy) — re-estimates before each slot via the termination guard
|
|
230
|
+
* and replaces over-budget `msg.role === "toolResult"` slots with the placeholder,
|
|
231
|
+
* preserving toolCallId/toolName/isError via spread (the paired ToolCall in the prior
|
|
232
|
+
* assistant stays). Returns `true` iff at least one slot was stubbed. */
|
|
233
|
+
function stubToolResultsToFit(result: Message[], budget: number): boolean {
|
|
234
|
+
let stubbed = false;
|
|
235
|
+
// Stub toolResult content oldest-first with the placeholder (preserves
|
|
236
|
+
// toolCallId/toolName/isError via spread; the paired ToolCall in the prior assistant stays).
|
|
237
|
+
for (let i = 0; i < result.length; i++) {
|
|
238
|
+
if (estimateMessagesTokens(result) <= budget) break;
|
|
239
|
+
const msg = result[i];
|
|
240
|
+
if (msg.role === "toolResult") {
|
|
241
|
+
result[i] = { ...msg, content: [{ type: "text", text: BTW_STUB_TEXT }] };
|
|
242
|
+
stubbed = true;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return stubbed;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Phase 2 of {@link stubToFit}: terminal truncation toward the token gap. Operates in-place
|
|
249
|
+
* on `result` (does NOT copy). One block per iteration, re-estimated each pass; a pass that
|
|
250
|
+
* fails to shrink the estimate breaks the loop — the truncation marker keeps every rewritten
|
|
251
|
+
* block at a floor length, so a budget below that floor (e.g. negative) would otherwise
|
|
252
|
+
* rewrite the same block forever; `priorEstimate` is seeded at +∞ so the first pass always
|
|
253
|
+
* proceeds. Returns `true` iff at least one block was truncated. */
|
|
254
|
+
function truncateToFit(result: Message[], budget: number): boolean {
|
|
255
|
+
let stubbed = false;
|
|
256
|
+
// Terminal fallback: truncate the largest text block toward the token gap
|
|
257
|
+
// (chars ≈ tokens×4, the inverse of estimateTokens' chars/4) with a marker. One block per
|
|
258
|
+
// iteration; re-estimate each pass. A pass that fails to shrink the estimate breaks the
|
|
259
|
+
// loop: the truncation marker keeps every rewritten block at a floor length, so a budget
|
|
260
|
+
// below that floor (e.g. negative) would otherwise rewrite the same block forever.
|
|
261
|
+
let priorEstimate = Number.POSITIVE_INFINITY;
|
|
262
|
+
while (estimateMessagesTokens(result) > budget) {
|
|
263
|
+
const estimate = estimateMessagesTokens(result);
|
|
264
|
+
if (estimate >= priorEstimate) break; // no progress — budget below the marker floor
|
|
265
|
+
priorEstimate = estimate;
|
|
266
|
+
const overTokens = estimate - budget;
|
|
267
|
+
const removeChars = Math.max(1, Math.ceil(overTokens * 4));
|
|
268
|
+
|
|
269
|
+
// Locate the largest text content block (string content OR a {type:"text"} part).
|
|
270
|
+
let target = { mi: -1, ci: -1, len: 0, isString: false };
|
|
271
|
+
for (let i = 0; i < result.length; i++) {
|
|
272
|
+
const content = result[i].content;
|
|
273
|
+
if (typeof content === "string") {
|
|
274
|
+
if (content.length > target.len) target = { mi: i, ci: -1, len: content.length, isString: true };
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
if (Array.isArray(content)) {
|
|
278
|
+
for (let j = 0; j < content.length; j++) {
|
|
279
|
+
const part = content[j];
|
|
280
|
+
if (part && part.type === "text" && part.text.length > target.len) {
|
|
281
|
+
target = { mi: i, ci: j, len: part.text.length, isString: false };
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (target.mi < 0 || target.len === 0) break; // nothing left to truncate — minimal result
|
|
287
|
+
|
|
288
|
+
// Reserve room for the marker itself so the rewritten block lands at ~(len - removeChars)
|
|
289
|
+
// chars total; without this the marker's own length leaks back into the estimate.
|
|
290
|
+
const markerReserve = BTW_TRUNCATE_MARKER_FMT(removeChars).length;
|
|
291
|
+
const keepChars = Math.max(0, target.len - removeChars - markerReserve);
|
|
292
|
+
const truncatedChars = target.len - keepChars;
|
|
293
|
+
const marker = BTW_TRUNCATE_MARKER_FMT(truncatedChars);
|
|
294
|
+
const msg = result[target.mi];
|
|
295
|
+
// Rebuild with role narrowing so each spread yields a valid Message variant
|
|
296
|
+
// (Message is a discriminated union — spreading the union and overriding `content`
|
|
297
|
+
// directly does not typecheck). Top-level branches are pure msg.role checks so
|
|
298
|
+
// narrowing flows into each arm; the user arm narrows string-vs-array content.
|
|
299
|
+
if (msg.role === "user") {
|
|
300
|
+
if (typeof msg.content === "string") {
|
|
301
|
+
result[target.mi] = { ...msg, content: `${msg.content.slice(0, keepChars)}${marker}` };
|
|
302
|
+
} else {
|
|
303
|
+
const content = [...msg.content];
|
|
304
|
+
const part = content[target.ci];
|
|
305
|
+
if (part.type === "text") {
|
|
306
|
+
content[target.ci] = { ...part, text: `${part.text.slice(0, keepChars)}${marker}` };
|
|
307
|
+
result[target.mi] = { ...msg, content };
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
} else if (msg.role === "assistant") {
|
|
311
|
+
const content = [...msg.content];
|
|
312
|
+
const part = content[target.ci];
|
|
313
|
+
if (part.type === "text") {
|
|
314
|
+
content[target.ci] = { ...part, text: `${part.text.slice(0, keepChars)}${marker}` };
|
|
315
|
+
result[target.mi] = { ...msg, content };
|
|
316
|
+
}
|
|
317
|
+
} else {
|
|
318
|
+
// toolResult (msg narrowed to ToolResultMessage)
|
|
319
|
+
const content = [...msg.content];
|
|
320
|
+
const part = content[target.ci];
|
|
321
|
+
if (part.type === "text") {
|
|
322
|
+
content[target.ci] = { ...part, text: `${part.text.slice(0, keepChars)}${marker}` };
|
|
323
|
+
result[target.mi] = { ...msg, content };
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
stubbed = true;
|
|
327
|
+
}
|
|
328
|
+
return stubbed;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Oversized-turn stubbing + terminal truncation. Operates on a SHALLOW copy
|
|
332
|
+
* (`messages.slice()`) — the copy lives HERE, in one place, and guards both phases —
|
|
333
|
+
* and replaces slots via object spread so the cached snapshot's array AND its message
|
|
334
|
+
* objects are never mutated. Phase 1 ({@link stubToolResultsToFit}) stubs toolResults
|
|
335
|
+
* oldest-first; phase 2 ({@link truncateToFit}) truncates the largest text block toward
|
|
336
|
+
* the token gap. Signature and return shape are unchanged. */
|
|
337
|
+
function stubToFit(messages: Message[], budget: number): { messages: Message[]; stubbed: boolean } {
|
|
338
|
+
const result = messages.slice(); // shallow: new array, shared message objects — one place, guards both phases
|
|
339
|
+
const stubbedTool = stubToolResultsToFit(result, budget);
|
|
340
|
+
const stubbedTruncated = truncateToFit(result, budget);
|
|
341
|
+
return { messages: result, stubbed: stubbedTool || stubbedTruncated };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Orchestrating pure branch-fit. Fast path returns the cached `messages` by reference
|
|
345
|
+
* (byte-identical prefix). Otherwise forward-scan trim, then stub/truncate. `keepBudget`
|
|
346
|
+
* is populated on every path. */
|
|
347
|
+
export function fitBranch(input: FitBranchInput): FitBranchResult {
|
|
348
|
+
const { entries, messages, model, systemPrompt, question, admittedEstimate } = input;
|
|
349
|
+
|
|
350
|
+
// --- Budget resolution ---
|
|
351
|
+
let branchKeepBudget: number;
|
|
352
|
+
if (input.keepBudget !== undefined) {
|
|
353
|
+
// Retry path: skip the window formula AND the skip guard; trim/stub
|
|
354
|
+
// directly to this many branch tokens. The cached snapshot is not re-read.
|
|
355
|
+
branchKeepBudget = input.keepBudget;
|
|
356
|
+
} else {
|
|
357
|
+
const available = model.contextWindow - model.maxTokens - BTW_CONTEXT_RESERVE;
|
|
358
|
+
const windowBudget = available - estimateTextTokens(systemPrompt) - estimateTokens(question) - admittedEstimate;
|
|
359
|
+
if (!isBudgetable(model)) {
|
|
360
|
+
// Skip guard: window unusable → fast-path the cached messages, no trim.
|
|
361
|
+
// keepBudget is still populated (the window-derived value, possibly negative on an
|
|
362
|
+
// unusable window) so the caller's read never sees undefined — see Notes / Deferred.
|
|
363
|
+
return { messages, branchWasTrimmed: false, stubbed: false, keepBudget: windowBudget };
|
|
364
|
+
}
|
|
365
|
+
branchKeepBudget = windowBudget;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// --- Fast path: branch fits → return cached messages by reference (byte-identical prefix) ---
|
|
369
|
+
const branchUsage = estimateBranchTokens(entries);
|
|
370
|
+
if (branchUsage <= branchKeepBudget) {
|
|
371
|
+
return { messages, branchWasTrimmed: false, stubbed: false, keepBudget: branchKeepBudget };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// --- Forward-scan trim ---
|
|
375
|
+
const trim = trimBranch(entries, branchKeepBudget);
|
|
376
|
+
if (trim.messages) {
|
|
377
|
+
// Trimmed suffix fits → done (trimmed only).
|
|
378
|
+
if (estimateMessagesTokens(trim.messages) <= branchKeepBudget) {
|
|
379
|
+
return { messages: trim.messages, branchWasTrimmed: true, stubbed: false, keepBudget: branchKeepBudget };
|
|
380
|
+
}
|
|
381
|
+
// Still over after trimming → stub the TRIMMED suffix (branchWasTrimmed stays true).
|
|
382
|
+
const stubbed = stubToFit(trim.messages, branchKeepBudget);
|
|
383
|
+
return {
|
|
384
|
+
messages: stubbed.messages,
|
|
385
|
+
branchWasTrimmed: true,
|
|
386
|
+
stubbed: stubbed.stubbed,
|
|
387
|
+
keepBudget: branchKeepBudget,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// --- No-cut-possible fallback: no valid cut or no turn-start → stub the full
|
|
392
|
+
// cached messages (branchWasTrimmed FALSE — findCutPoint found nothing to cut).
|
|
393
|
+
// When stubbing changed nothing (anchor-metered usage over budget but the raw
|
|
394
|
+
// estimates already fit), return the ORIGINAL cached array — best effort, and
|
|
395
|
+
// the reference-parity guarantee holds. ---
|
|
396
|
+
const stubbed = stubToFit(messages, branchKeepBudget);
|
|
397
|
+
return {
|
|
398
|
+
messages: stubbed.stubbed ? stubbed.messages : messages,
|
|
399
|
+
branchWasTrimmed: false,
|
|
400
|
+
stubbed: stubbed.stubbed,
|
|
401
|
+
keepBudget: branchKeepBudget,
|
|
402
|
+
};
|
|
403
|
+
}
|
package/btw-messages.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cycle-break leaf module.
|
|
3
|
+
*
|
|
4
|
+
* Owns the `BtwTurn` interface and the `userMessageText` / `assistantMessageText`
|
|
5
|
+
* message-text extractors, moved here from `btw.ts` to sever the sole runtime
|
|
6
|
+
* VALUE back-edge `btw-ui.ts → btw.ts` (the cluster-2 cycle-break, L1-06).
|
|
7
|
+
*
|
|
8
|
+
* This module imports ONLY `type { AssistantMessage, UserMessage }` from
|
|
9
|
+
* `@earendil-works/pi-ai` — it has NO `./btw.js` import, so the leaf introduces
|
|
10
|
+
* no back-edge into `btw.ts`. `btw.ts` re-exports all three symbols so the
|
|
11
|
+
* package surface (and the `*.test.ts` imports from `./btw.js`) is unchanged.
|
|
12
|
+
*
|
|
13
|
+
* The phantom type-only cycle `btw.ts ↔ btw-budget.ts` (`btw-budget.ts:22`
|
|
14
|
+
* `import type { BtwTurn } from "./btw.js"`) is intentionally left in place —
|
|
15
|
+
* it is runtime-inert (erased) and repointing it is owned by no phase in this
|
|
16
|
+
* plan (see plan risk r6).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { AssistantMessage, UserMessage } from "@earendil-works/pi-ai";
|
|
20
|
+
|
|
21
|
+
// Real messages — no fabrication. userMessage is built at call time; assistantMessage
|
|
22
|
+
// is the unmodified completeSimple response. Stable object references across calls →
|
|
23
|
+
// byte-identical prompt prefix on subsequent /btw invocations (cache parity).
|
|
24
|
+
export interface BtwTurn {
|
|
25
|
+
userMessage: UserMessage;
|
|
26
|
+
assistantMessage: AssistantMessage;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Extract text from a UserMessage's content.
|
|
30
|
+
export function userMessageText(msg: UserMessage): string {
|
|
31
|
+
if (typeof msg.content === "string") return msg.content;
|
|
32
|
+
return msg.content
|
|
33
|
+
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
34
|
+
.map((c) => c.text)
|
|
35
|
+
.join("\n");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Extract text from an AssistantMessage's content (text parts only).
|
|
39
|
+
export function assistantMessageText(msg: AssistantMessage): string {
|
|
40
|
+
return msg.content
|
|
41
|
+
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
42
|
+
.map((c) => c.text)
|
|
43
|
+
.join("\n");
|
|
44
|
+
}
|