dsh-rwkv-plugin 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +50 -2
- package/cordis.patch.yml +59 -0
- package/lib/client.js +3148 -0
- package/lib/client.js.map +7 -0
- package/lib/index.js +6294 -0
- package/lib/index.js.map +7 -0
- package/lib/line-edit.js +1423 -0
- package/lib/line-edit.js.map +7 -0
- package/lib/todo.js +610 -0
- package/lib/todo.js.map +7 -0
- package/package.json +72 -4
- package/scripts/build.mjs +77 -0
- package/scripts/headless.ts +279 -0
- package/scripts/link-dsh.sh +31 -0
- package/scripts/relay-e2e.mjs +157 -0
- package/scripts/smoke.ts +116 -0
- package/scripts/state.ts +39 -0
- package/scripts/tokenizer-parity.ts +107 -0
- package/scripts/trace-stats.ts +33 -0
- package/src/adapter.ts +388 -0
- package/src/backend/generator.ts +221 -0
- package/src/backend/irwkv.ts +117 -0
- package/src/backend/lightning.ts +228 -0
- package/src/backend/stream.ts +97 -0
- package/src/client/AdapterPicker.tsx +264 -0
- package/src/client/DeveloperPanel.tsx +403 -0
- package/src/client/FoldNode.tsx +82 -0
- package/src/client/ModelCard.tsx +230 -0
- package/src/client/RwkvSettings.tsx +265 -0
- package/src/client/Segment.tsx +15 -0
- package/src/client/StatePicker.tsx +248 -0
- package/src/client/TraceFrames.tsx +462 -0
- package/src/client/TraceView.tsx +77 -0
- package/src/client/WirePanel.tsx +566 -0
- package/src/client/fields.tsx +362 -0
- package/src/client/index.tsx +109 -0
- package/src/client/styles.ts +277 -0
- package/src/client/traces-api.ts +222 -0
- package/src/client/url.ts +20 -0
- package/src/core/agent.ts +586 -0
- package/src/core/defaults.ts +51 -0
- package/src/core/dsh-prompt.ts +32 -0
- package/src/core/edit-modes/index.ts +108 -0
- package/src/core/edit-modes/line-edit.ts +793 -0
- package/src/core/edit-modes/literal.ts +26 -0
- package/src/core/edit-modes/shared.ts +213 -0
- package/src/core/edit-modes/tolerant.ts +558 -0
- package/src/core/fold-pairs.ts +407 -0
- package/src/core/fold-window.ts +563 -0
- package/src/core/line-edit.ts +33 -0
- package/src/core/parse.ts +290 -0
- package/src/core/policy.ts +500 -0
- package/src/core/prompt.ts +220 -0
- package/src/core/relay.ts +400 -0
- package/src/core/step-gates.ts +371 -0
- package/src/core/time-zone.ts +32 -0
- package/src/core/todo-state.ts +227 -0
- package/src/core/tolerant-edit.ts +14 -0
- package/src/core/tool-mappings.ts +209 -0
- package/src/core/tool-repairs.ts +255 -0
- package/src/core/tools.ts +162 -0
- package/src/core/worklist.ts +606 -0
- package/src/dsh-host.ts +48 -0
- package/src/edit-modes/folded-read-guard.ts +32 -0
- package/src/edit-modes/index.ts +26 -0
- package/src/edit-modes/line-edit.ts +154 -0
- package/src/edit-modes/literal.ts +9 -0
- package/src/edit-modes/observations.ts +234 -0
- package/src/edit-modes/syntax-check.ts +226 -0
- package/src/edit-modes/tolerant.ts +232 -0
- package/src/folded-read-guard.ts +6 -0
- package/src/history.ts +163 -0
- package/src/index.ts +287 -0
- package/src/line-edit.ts +15 -0
- package/src/live-wire.ts +133 -0
- package/src/paths.ts +91 -0
- package/src/relay-store.ts +59 -0
- package/src/result-budget.ts +225 -0
- package/src/routes.ts +324 -0
- package/src/session-setup.ts +150 -0
- package/src/syntax-check.ts +2 -0
- package/src/todo.ts +328 -0
- package/src/tokenizer.ts +48 -0
- package/src/tolerant-edit.ts +2 -0
- package/src/trace-stats.ts +225 -0
- package/src/traces.ts +289 -0
- package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
- package/vendor/rwkv-tokenizer/package.json +5 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
// Active turn window assembly for `auto-fold` and active `worklist`:
|
|
2
|
+
// checkpoint slicing, budget reminder replay, passive sliding/epoch folding,
|
|
3
|
+
// optional unedited-read pinning, and the hardCap safety valve.
|
|
4
|
+
|
|
5
|
+
import { countTokens } from '../tokenizer.ts'
|
|
6
|
+
import {
|
|
7
|
+
findLatestUneditedReadPair,
|
|
8
|
+
formatFoldedStepsNote,
|
|
9
|
+
formatStageArchiveNote,
|
|
10
|
+
historyItemPromptBytes,
|
|
11
|
+
maskResultInPlace,
|
|
12
|
+
READ_PIN_TOOLS,
|
|
13
|
+
type CallPair,
|
|
14
|
+
} from './fold-pairs.ts'
|
|
15
|
+
import type { HistoryItem } from './policy.ts'
|
|
16
|
+
import { isWorklistTool, TODO_PLAN_TOOL } from './todo-state.ts'
|
|
17
|
+
|
|
18
|
+
const MAX_SECOND_RECENT_PAIR_TOKENS = 2800
|
|
19
|
+
export const INIT_NUDGE_COOLDOWN_STEPS = 4
|
|
20
|
+
export const CHECKPOINT_NUDGE_COOLDOWN_STEPS = 3
|
|
21
|
+
|
|
22
|
+
export const WORKLIST_CHECKPOINT_NUDGE =
|
|
23
|
+
'Context budget reached for the current step. Call `todo_update` once to checkpoint verified facts into a concise `note` (<= 120 words: exact /app/... paths, line ranges, findings, and exit codes; keep `status: "in_progress"` if unfinished, or `"completed"` only if verified), or finish directly if ready to answer.'
|
|
24
|
+
|
|
25
|
+
export const WORKLIST_INIT_NUDGE =
|
|
26
|
+
'Context budget reached while exploring this task. If multi-step work remains, call `todo_plan` to list the remaining steps (then checkpoint verified /app/... paths and findings with `todo_update`); if only 1-2 quick steps or the final answer remain, finish directly without `todo_plan`.'
|
|
27
|
+
|
|
28
|
+
export type WorklistNudgeKind = 'init' | 'checkpoint'
|
|
29
|
+
|
|
30
|
+
export interface RecordedWorklistNudge {
|
|
31
|
+
/** Index in `history` of the `result` item immediately after which this reminder triggered. */
|
|
32
|
+
readonly afterResultIndex: number
|
|
33
|
+
readonly kind: WorklistNudgeKind
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function nudgeTextOf(kind: WorklistNudgeKind): string {
|
|
37
|
+
return kind === 'checkpoint' ? WORKLIST_CHECKPOINT_NUDGE : WORKLIST_INIT_NUDGE
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface InternalNudge extends RecordedWorklistNudge {
|
|
41
|
+
readonly pairIndex: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ActiveWindowOptions {
|
|
45
|
+
readonly baseOverhead: number
|
|
46
|
+
readonly budgetTokens: number
|
|
47
|
+
readonly hardCap: number
|
|
48
|
+
readonly keepRecentCount: number
|
|
49
|
+
readonly keepInitialPlan: boolean
|
|
50
|
+
readonly emptyThink: boolean
|
|
51
|
+
readonly emitLiveNudge: boolean
|
|
52
|
+
readonly passive: boolean
|
|
53
|
+
readonly pinUneditedRead: boolean
|
|
54
|
+
readonly cwd?: string
|
|
55
|
+
readonly fullTok: readonly number[]
|
|
56
|
+
readonly bareTok: readonly number[]
|
|
57
|
+
readonly forcedCutPairCount?: number
|
|
58
|
+
readonly forcedPinnedRead?: CallPair
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ContextFoldEvent {
|
|
62
|
+
readonly kind: 'in-place' | 'stage-archive' | 'prior-turn' | 'worklist' | 'relay'
|
|
63
|
+
readonly beforeTokens: number
|
|
64
|
+
readonly afterTokens: number
|
|
65
|
+
readonly foldedTools: number
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface ActiveWindowResult {
|
|
69
|
+
readonly items: HistoryItem[]
|
|
70
|
+
readonly duplicateFrom: number
|
|
71
|
+
readonly totalTokens: number
|
|
72
|
+
readonly checkpointAt?: number
|
|
73
|
+
readonly liveNudge?: string
|
|
74
|
+
readonly maskedCallIds?: ReadonlySet<string>
|
|
75
|
+
readonly foldEvent?: ContextFoldEvent
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function buildActiveWindow(
|
|
79
|
+
history: readonly HistoryItem[],
|
|
80
|
+
turnStart: number,
|
|
81
|
+
endIndex: number,
|
|
82
|
+
pairsSub: readonly CallPair[],
|
|
83
|
+
nudges: readonly InternalNudge[],
|
|
84
|
+
activeCheckpoints: ReadonlySet<number>,
|
|
85
|
+
options: ActiveWindowOptions,
|
|
86
|
+
): ActiveWindowResult {
|
|
87
|
+
const lastCheckpoint = [...pairsSub].reverse().find(pair => pair.notedUpdate && activeCheckpoints.has(pair.callIndex))
|
|
88
|
+
const firstPlanPair = pairsSub.find(pair => pair.ok && pair.name === TODO_PLAN_TOOL)
|
|
89
|
+
const unclosedPlanPair = lastCheckpoint === undefined
|
|
90
|
+
? [...pairsSub].reverse().find(pair => pair.ok && isWorklistTool(pair.name))
|
|
91
|
+
: undefined
|
|
92
|
+
|
|
93
|
+
let currentIndices: number[] = []
|
|
94
|
+
let duplicateFrom = turnStart
|
|
95
|
+
let checkpointAt: number | undefined
|
|
96
|
+
|
|
97
|
+
if (lastCheckpoint !== undefined) {
|
|
98
|
+
checkpointAt = lastCheckpoint.callIndex
|
|
99
|
+
const preWs = pairsSub.filter(pair => pair.callIndex < lastCheckpoint.callIndex && !isWorklistTool(pair.name))
|
|
100
|
+
const keptTail: CallPair[] = []
|
|
101
|
+
if (options.keepRecentCount >= 1 && preWs.length >= 1) {
|
|
102
|
+
const lastWs = preWs[preWs.length - 1]!
|
|
103
|
+
keptTail.unshift(lastWs)
|
|
104
|
+
if (options.keepRecentCount >= 2 && preWs.length >= 2) {
|
|
105
|
+
const prevWs = preWs[preWs.length - 2]!
|
|
106
|
+
const tailTokens = options.fullTok[prevWs.callIndex]! + options.fullTok[prevWs.resultIndex]!
|
|
107
|
+
+ options.fullTok[lastWs.callIndex]! + options.fullTok[lastWs.resultIndex]!
|
|
108
|
+
if (tailTokens <= MAX_SECOND_RECENT_PAIR_TOKENS) {
|
|
109
|
+
keptTail.unshift(prevWs)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
duplicateFrom = keptTail.length > 0 ? keptTail[0]!.callIndex : lastCheckpoint.resultIndex + 1
|
|
114
|
+
|
|
115
|
+
const keepPreIndices = new Set<number>()
|
|
116
|
+
if (options.keepInitialPlan && firstPlanPair !== undefined && firstPlanPair.callIndex < lastCheckpoint.callIndex) {
|
|
117
|
+
keepPreIndices.add(firstPlanPair.callIndex)
|
|
118
|
+
keepPreIndices.add(firstPlanPair.resultIndex)
|
|
119
|
+
}
|
|
120
|
+
for (const pair of keptTail) {
|
|
121
|
+
keepPreIndices.add(pair.callIndex)
|
|
122
|
+
keepPreIndices.add(pair.resultIndex)
|
|
123
|
+
}
|
|
124
|
+
if (options.pinUneditedRead && options.keepRecentCount >= 1 && !keptTail.some(pair => pair.ok && READ_PIN_TOOLS.has(pair.name))) {
|
|
125
|
+
const preFolded = preWs.filter(pair => !keepPreIndices.has(pair.callIndex))
|
|
126
|
+
const activeAtCheckpoint = pairsSub.filter(pair => keepPreIndices.has(pair.callIndex) || pair.callIndex >= lastCheckpoint.callIndex)
|
|
127
|
+
const pinnedPreRead = findLatestUneditedReadPair(
|
|
128
|
+
preFolded,
|
|
129
|
+
history,
|
|
130
|
+
pair => options.bareTok[pair.callIndex]! + options.bareTok[pair.resultIndex]!,
|
|
131
|
+
options.cwd,
|
|
132
|
+
activeAtCheckpoint,
|
|
133
|
+
)
|
|
134
|
+
if (pinnedPreRead !== undefined) {
|
|
135
|
+
keepPreIndices.add(pinnedPreRead.callIndex)
|
|
136
|
+
keepPreIndices.add(pinnedPreRead.resultIndex)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
for (let i = turnStart; i < lastCheckpoint.callIndex; i++) {
|
|
140
|
+
const kind = history[i]!.kind
|
|
141
|
+
if (kind === 'user' || kind === 'note' || keepPreIndices.has(i)) {
|
|
142
|
+
currentIndices.push(i)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
for (let i = lastCheckpoint.callIndex; i < endIndex; i++) {
|
|
146
|
+
currentIndices.push(i)
|
|
147
|
+
}
|
|
148
|
+
} else {
|
|
149
|
+
for (let i = turnStart; i < endIndex; i++) currentIndices.push(i)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const keptSet = new Set<number>(currentIndices)
|
|
153
|
+
const clearedReasoning = new Set<number>()
|
|
154
|
+
|
|
155
|
+
if (firstPlanPair !== undefined && keptSet.has(firstPlanPair.callIndex)) {
|
|
156
|
+
const planIdx = pairsSub.indexOf(firstPlanPair)
|
|
157
|
+
if (planIdx >= 0 && planIdx + 1 < pairsSub.length && !keptSet.has(pairsSub[planIdx + 1]!.callIndex)) {
|
|
158
|
+
clearedReasoning.add(firstPlanPair.callIndex)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
for (const pair of pairsSub) {
|
|
162
|
+
if (pair === firstPlanPair || !keptSet.has(pair.callIndex)) continue
|
|
163
|
+
const idx = pairsSub.indexOf(pair)
|
|
164
|
+
if (idx >= 0 && idx + 1 < pairsSub.length && !keptSet.has(pairsSub[idx + 1]!.callIndex)) {
|
|
165
|
+
clearedReasoning.add(pair.callIndex)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const protectedCallIndices = new Set<number>()
|
|
170
|
+
if (lastCheckpoint !== undefined) protectedCallIndices.add(lastCheckpoint.callIndex)
|
|
171
|
+
if (unclosedPlanPair !== undefined) protectedCallIndices.add(unclosedPlanPair.callIndex)
|
|
172
|
+
if (firstPlanPair !== undefined) protectedCallIndices.add(firstPlanPair.callIndex)
|
|
173
|
+
|
|
174
|
+
const droppedByHardCap: CallPair[] = []
|
|
175
|
+
const nudgeTokCache = {
|
|
176
|
+
init: countTokens(`User: ${WORKLIST_INIT_NUDGE}\n\n`),
|
|
177
|
+
checkpoint: countTokens(`User: ${WORKLIST_CHECKPOINT_NUDGE}\n\n`),
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const assemble = (): { items: HistoryItem[]; tokens: number; liveNudge?: string } => {
|
|
181
|
+
const out: HistoryItem[] = []
|
|
182
|
+
let tok = options.baseOverhead
|
|
183
|
+
let liveNudge: string | undefined
|
|
184
|
+
let ledgerInserted = false
|
|
185
|
+
const ledgerText = droppedByHardCap.length > 0 ? formatFoldedStepsNote(droppedByHardCap, history) : undefined
|
|
186
|
+
|
|
187
|
+
const byAfterResult = new Map<number, InternalNudge>()
|
|
188
|
+
const byBeforeNextCall = new Map<number, InternalNudge>()
|
|
189
|
+
for (const n of nudges) {
|
|
190
|
+
if (n.pairIndex === pairsSub.length - 1) {
|
|
191
|
+
if (keptSet.has(n.afterResultIndex)) byAfterResult.set(n.afterResultIndex, n)
|
|
192
|
+
} else if (n.pairIndex + 1 < pairsSub.length) {
|
|
193
|
+
const nextCallIdx = pairsSub[n.pairIndex + 1]!.callIndex
|
|
194
|
+
if (!keptSet.has(nextCallIdx)) continue
|
|
195
|
+
if (keptSet.has(n.afterResultIndex)) {
|
|
196
|
+
byAfterResult.set(n.afterResultIndex, n)
|
|
197
|
+
} else {
|
|
198
|
+
const nextItem = history[nextCallIdx]!
|
|
199
|
+
if (nextItem.kind === 'call' && Boolean(nextItem.reasoning) && !clearedReasoning.has(nextCallIdx)) {
|
|
200
|
+
byBeforeNextCall.set(nextCallIdx, n)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const hasAssistantAfter = (idx: number): boolean => {
|
|
207
|
+
for (let m = idx + 1; m < endIndex; m++) {
|
|
208
|
+
if (keptSet.has(m) && history[m]!.kind === 'assistant') return true
|
|
209
|
+
}
|
|
210
|
+
return false
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
for (const idx of currentIndices) {
|
|
214
|
+
const raw = history[idx]!
|
|
215
|
+
if (!ledgerInserted && ledgerText !== undefined && (raw.kind === 'call' || raw.kind === 'assistant')) {
|
|
216
|
+
out.push({ kind: 'note', text: ledgerText })
|
|
217
|
+
tok += countTokens(`User: ${ledgerText}\n\n`)
|
|
218
|
+
ledgerInserted = true
|
|
219
|
+
}
|
|
220
|
+
const preNudge = byBeforeNextCall.get(idx)
|
|
221
|
+
if (preNudge !== undefined) {
|
|
222
|
+
const text = nudgeTextOf(preNudge.kind)
|
|
223
|
+
out.push({ kind: 'note', text })
|
|
224
|
+
tok += nudgeTokCache[preNudge.kind]
|
|
225
|
+
}
|
|
226
|
+
if ((raw.kind === 'call' || raw.kind === 'assistant') && raw.reasoning && clearedReasoning.has(idx)) {
|
|
227
|
+
out.push({ ...raw, reasoning: undefined })
|
|
228
|
+
tok += options.bareTok[idx]!
|
|
229
|
+
} else {
|
|
230
|
+
out.push(raw)
|
|
231
|
+
tok += options.fullTok[idx]!
|
|
232
|
+
}
|
|
233
|
+
const postNudge = byAfterResult.get(idx)
|
|
234
|
+
if (postNudge !== undefined) {
|
|
235
|
+
const isLiveTail = postNudge.pairIndex === pairsSub.length - 1 && !hasAssistantAfter(idx)
|
|
236
|
+
if (!isLiveTail || options.emitLiveNudge) {
|
|
237
|
+
const text = nudgeTextOf(postNudge.kind)
|
|
238
|
+
out.push({ kind: 'note', text })
|
|
239
|
+
tok += nudgeTokCache[postNudge.kind]
|
|
240
|
+
if (isLiveTail) liveNudge = text
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return { items: out, tokens: tok, ...(liveNudge !== undefined ? { liveNudge } : {}) }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
let built = assemble()
|
|
248
|
+
|
|
249
|
+
if (!options.emptyThink && built.tokens > options.hardCap) {
|
|
250
|
+
for (const idx of currentIndices) {
|
|
251
|
+
if (built.tokens <= options.hardCap) break
|
|
252
|
+
const item = history[idx]!
|
|
253
|
+
if ((item.kind === 'call' || item.kind === 'assistant') && item.reasoning && !clearedReasoning.has(idx)) {
|
|
254
|
+
clearedReasoning.add(idx)
|
|
255
|
+
built = assemble()
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const droppablePairs = pairsSub.filter(pair =>
|
|
261
|
+
keptSet.has(pair.callIndex) && !protectedCallIndices.has(pair.callIndex),
|
|
262
|
+
)
|
|
263
|
+
const dropPairFromWindow = (pair: CallPair): void => {
|
|
264
|
+
droppedByHardCap.push(pair)
|
|
265
|
+
keptSet.delete(pair.callIndex)
|
|
266
|
+
keptSet.delete(pair.resultIndex)
|
|
267
|
+
currentIndices = currentIndices.filter(i => i !== pair.callIndex && i !== pair.resultIndex)
|
|
268
|
+
duplicateFrom = Math.max(duplicateFrom, pair.resultIndex + 1)
|
|
269
|
+
}
|
|
270
|
+
const insertPairInOrder = (pair: CallPair): void => {
|
|
271
|
+
keptSet.add(pair.callIndex)
|
|
272
|
+
keptSet.add(pair.resultIndex)
|
|
273
|
+
const next = [...currentIndices, pair.callIndex, pair.resultIndex]
|
|
274
|
+
next.sort((a, b) => a - b)
|
|
275
|
+
currentIndices = next
|
|
276
|
+
clearedReasoning.add(pair.callIndex)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (options.passive) {
|
|
280
|
+
if (options.forcedCutPairCount !== undefined) {
|
|
281
|
+
const cutTarget = Math.min(options.forcedCutPairCount, droppablePairs.length)
|
|
282
|
+
for (let c = 0; c < cutTarget; c++) {
|
|
283
|
+
const pair = droppablePairs.shift()!
|
|
284
|
+
if (options.forcedPinnedRead === pair) {
|
|
285
|
+
clearedReasoning.add(pair.callIndex)
|
|
286
|
+
duplicateFrom = Math.max(duplicateFrom, pair.resultIndex + 1)
|
|
287
|
+
continue
|
|
288
|
+
}
|
|
289
|
+
dropPairFromWindow(pair)
|
|
290
|
+
}
|
|
291
|
+
if (cutTarget > 0) built = assemble()
|
|
292
|
+
} else {
|
|
293
|
+
const keepFloor = Math.max(1, options.keepRecentCount)
|
|
294
|
+
while (droppablePairs.length > keepFloor && built.tokens > options.budgetTokens) {
|
|
295
|
+
dropPairFromWindow(droppablePairs.shift()!)
|
|
296
|
+
built = assemble()
|
|
297
|
+
}
|
|
298
|
+
if (options.pinUneditedRead && droppedByHardCap.length > 0 && options.keepRecentCount >= 1) {
|
|
299
|
+
const pinned = findLatestUneditedReadPair(
|
|
300
|
+
droppedByHardCap,
|
|
301
|
+
history,
|
|
302
|
+
pair => options.bareTok[pair.callIndex]! + options.bareTok[pair.resultIndex]!,
|
|
303
|
+
options.cwd,
|
|
304
|
+
droppablePairs,
|
|
305
|
+
)
|
|
306
|
+
if (pinned !== undefined) {
|
|
307
|
+
const pinIdx = droppedByHardCap.indexOf(pinned)
|
|
308
|
+
const prevIndices = currentIndices
|
|
309
|
+
const prevCleared = clearedReasoning.has(pinned.callIndex)
|
|
310
|
+
droppedByHardCap.splice(pinIdx, 1)
|
|
311
|
+
insertPairInOrder(pinned)
|
|
312
|
+
built = assemble()
|
|
313
|
+
if (built.tokens > options.budgetTokens) {
|
|
314
|
+
droppedByHardCap.splice(pinIdx, 0, pinned)
|
|
315
|
+
keptSet.delete(pinned.callIndex)
|
|
316
|
+
keptSet.delete(pinned.resultIndex)
|
|
317
|
+
currentIndices = prevIndices
|
|
318
|
+
if (!prevCleared) clearedReasoning.delete(pinned.callIndex)
|
|
319
|
+
built = assemble()
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
while (droppablePairs.length > 1 && built.tokens > options.hardCap) {
|
|
326
|
+
dropPairFromWindow(droppablePairs.shift()!)
|
|
327
|
+
built = assemble()
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
items: built.items,
|
|
332
|
+
duplicateFrom,
|
|
333
|
+
totalTokens: built.tokens,
|
|
334
|
+
...(checkpointAt !== undefined ? { checkpointAt } : {}),
|
|
335
|
+
...(built.liveNudge !== undefined ? { liveNudge: built.liveNudge } : {}),
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Epoch-jump folding replay (`passive: true` + `0 < epochTargetTokens < budgetTokens`):
|
|
341
|
+
* prefix stays 100% append-only until `totalTokens > budgetTokens`, then cuts
|
|
342
|
+
* oldest pairs down to `<= epochTargetTokens`.
|
|
343
|
+
*/
|
|
344
|
+
export function buildEpochJumpWindow(
|
|
345
|
+
history: readonly HistoryItem[],
|
|
346
|
+
turnStart: number,
|
|
347
|
+
pairs: readonly CallPair[],
|
|
348
|
+
triggeredNudges: readonly InternalNudge[],
|
|
349
|
+
activeCheckpoints: ReadonlySet<number>,
|
|
350
|
+
windowOpts: ActiveWindowOptions,
|
|
351
|
+
epochTargetTokens: number,
|
|
352
|
+
): ActiveWindowResult {
|
|
353
|
+
const keepFloor = Math.max(1, windowOpts.keepRecentCount)
|
|
354
|
+
let cutPairCount = 0
|
|
355
|
+
let frozenPinnedRead: CallPair | undefined
|
|
356
|
+
for (let k = 0; k < pairs.length; k++) {
|
|
357
|
+
const pairsSub = pairs.slice(0, k + 1)
|
|
358
|
+
const endAtK = pairs[k]!.resultIndex + 1
|
|
359
|
+
let win = buildActiveWindow(history, turnStart, endAtK, pairsSub, triggeredNudges, activeCheckpoints, {
|
|
360
|
+
...windowOpts,
|
|
361
|
+
forcedCutPairCount: cutPairCount,
|
|
362
|
+
forcedPinnedRead: frozenPinnedRead,
|
|
363
|
+
})
|
|
364
|
+
if (win.totalTokens > windowOpts.budgetTokens && (pairsSub.length - cutPairCount) > keepFloor) {
|
|
365
|
+
frozenPinnedRead = undefined
|
|
366
|
+
while ((pairsSub.length - cutPairCount) > keepFloor) {
|
|
367
|
+
cutPairCount++
|
|
368
|
+
win = buildActiveWindow(history, turnStart, endAtK, pairsSub, triggeredNudges, activeCheckpoints, {
|
|
369
|
+
...windowOpts,
|
|
370
|
+
forcedCutPairCount: cutPairCount,
|
|
371
|
+
})
|
|
372
|
+
if (win.totalTokens <= epochTargetTokens) break
|
|
373
|
+
}
|
|
374
|
+
if (windowOpts.pinUneditedRead && windowOpts.keepRecentCount >= 1 && cutPairCount > 0) {
|
|
375
|
+
const candidatePin = findLatestUneditedReadPair(
|
|
376
|
+
pairsSub.slice(0, cutPairCount),
|
|
377
|
+
history,
|
|
378
|
+
pair => windowOpts.bareTok[pair.callIndex]! + windowOpts.bareTok[pair.resultIndex]!,
|
|
379
|
+
windowOpts.cwd,
|
|
380
|
+
pairsSub.slice(cutPairCount),
|
|
381
|
+
)
|
|
382
|
+
if (candidatePin !== undefined) {
|
|
383
|
+
const withPin = buildActiveWindow(history, turnStart, endAtK, pairsSub, triggeredNudges, activeCheckpoints, {
|
|
384
|
+
...windowOpts,
|
|
385
|
+
forcedCutPairCount: cutPairCount,
|
|
386
|
+
forcedPinnedRead: candidatePin,
|
|
387
|
+
})
|
|
388
|
+
if (withPin.totalTokens <= windowOpts.budgetTokens) frozenPinnedRead = candidatePin
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return buildActiveWindow(history, turnStart, history.length, pairs, triggeredNudges, activeCheckpoints, {
|
|
394
|
+
...windowOpts,
|
|
395
|
+
forcedCutPairCount: cutPairCount,
|
|
396
|
+
forcedPinnedRead: frozenPinnedRead,
|
|
397
|
+
})
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export interface InPlaceWindowOptions {
|
|
401
|
+
readonly baseOverhead: number
|
|
402
|
+
readonly budgetTokens: number
|
|
403
|
+
readonly epochTargetTokens: number
|
|
404
|
+
readonly hardCap: number
|
|
405
|
+
readonly keepRecentCount: number
|
|
406
|
+
readonly exemptResultTokens: number
|
|
407
|
+
readonly emptyThink: boolean
|
|
408
|
+
readonly cwd?: string
|
|
409
|
+
readonly fullTok: readonly number[]
|
|
410
|
+
readonly bareTok: readonly number[]
|
|
411
|
+
readonly rawResultTok: readonly number[]
|
|
412
|
+
readonly reminderTokOfResult: (resultItem: Extract<HistoryItem, { kind: 'result' }>) => number
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Module 2 (`auto-fold v2`): causal batch in-place observation masking (`budgetTokens -> epochTargetTokens`)
|
|
417
|
+
* with `< exemptResultTokens` exemption, `keepRecentCount` floor, and git-free Stage Archive at `hardCap`.
|
|
418
|
+
*/
|
|
419
|
+
export function buildInPlaceFoldWindow(
|
|
420
|
+
history: readonly HistoryItem[],
|
|
421
|
+
turnStart: number,
|
|
422
|
+
pairs: readonly CallPair[],
|
|
423
|
+
opts: InPlaceWindowOptions,
|
|
424
|
+
): ActiveWindowResult {
|
|
425
|
+
const targetLow = opts.epochTargetTokens > 0 && opts.epochTargetTokens < opts.budgetTokens
|
|
426
|
+
? opts.epochTargetTokens
|
|
427
|
+
: opts.budgetTokens
|
|
428
|
+
const keepFloor = Math.max(0, opts.keepRecentCount)
|
|
429
|
+
|
|
430
|
+
const maskedByResultIdx = new Map<number, { item: Extract<HistoryItem, { kind: 'result' }>; tok: number }>()
|
|
431
|
+
const pairByResultIdx = new Map<number, CallPair>()
|
|
432
|
+
for (const pair of pairs) pairByResultIdx.set(pair.resultIndex, pair)
|
|
433
|
+
|
|
434
|
+
const getMasked = (pair: CallPair): { item: Extract<HistoryItem, { kind: 'result' }>; tok: number } => {
|
|
435
|
+
let entry = maskedByResultIdx.get(pair.resultIndex)
|
|
436
|
+
if (entry !== undefined) return entry
|
|
437
|
+
const callItem = history[pair.callIndex] as Extract<HistoryItem, { kind: 'call' }>
|
|
438
|
+
const resultItem = history[pair.resultIndex] as Extract<HistoryItem, { kind: 'result' }>
|
|
439
|
+
const maskedItem = maskResultInPlace(callItem, resultItem, opts.rawResultTok[pair.resultIndex])
|
|
440
|
+
const tok = countTokens(historyItemPromptBytes(maskedItem, opts.emptyThink)) + opts.reminderTokOfResult(maskedItem)
|
|
441
|
+
entry = { item: maskedItem, tok }
|
|
442
|
+
maskedByResultIdx.set(pair.resultIndex, entry)
|
|
443
|
+
return entry
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
let archivedCount = 0
|
|
447
|
+
const maskedCallIndices = new Set<number>()
|
|
448
|
+
const clearedReasoning = new Set<number>()
|
|
449
|
+
let lastStepFold: ContextFoldEvent | undefined
|
|
450
|
+
|
|
451
|
+
const assembleInPlace = (endIndex: number, pairsSub: readonly CallPair[]): { items: HistoryItem[]; tokens: number } => {
|
|
452
|
+
const archivedPairs = archivedCount > 0 ? pairsSub.slice(0, archivedCount) : []
|
|
453
|
+
const archivedIdxSet = new Set<number>()
|
|
454
|
+
for (const ap of archivedPairs) {
|
|
455
|
+
archivedIdxSet.add(ap.callIndex)
|
|
456
|
+
archivedIdxSet.add(ap.resultIndex)
|
|
457
|
+
}
|
|
458
|
+
const archiveText = archivedPairs.length > 0 ? formatStageArchiveNote(archivedPairs, history, opts.cwd) : undefined
|
|
459
|
+
const archiveTok = archiveText !== undefined ? countTokens(`User: ${archiveText}\n\n`) : 0
|
|
460
|
+
const items: HistoryItem[] = []
|
|
461
|
+
let tokens = opts.baseOverhead
|
|
462
|
+
let archiveInserted = false
|
|
463
|
+
|
|
464
|
+
for (let idx = turnStart; idx < endIndex; idx++) {
|
|
465
|
+
if (archivedIdxSet.has(idx)) continue
|
|
466
|
+
const raw = history[idx]!
|
|
467
|
+
if (!archiveInserted && archiveText !== undefined && (raw.kind === 'call' || raw.kind === 'assistant')) {
|
|
468
|
+
items.push({ kind: 'note', text: archiveText })
|
|
469
|
+
tokens += archiveTok
|
|
470
|
+
archiveInserted = true
|
|
471
|
+
}
|
|
472
|
+
const pair = raw.kind === 'result' ? pairByResultIdx.get(idx) : undefined
|
|
473
|
+
if (pair !== undefined && maskedCallIndices.has(pair.callIndex)) {
|
|
474
|
+
const m = getMasked(pair)
|
|
475
|
+
items.push(m.item)
|
|
476
|
+
tokens += m.tok
|
|
477
|
+
} else if ((raw.kind === 'call' || raw.kind === 'assistant') && raw.reasoning && clearedReasoning.has(idx)) {
|
|
478
|
+
items.push({ ...raw, reasoning: undefined })
|
|
479
|
+
tokens += opts.bareTok[idx]!
|
|
480
|
+
} else {
|
|
481
|
+
items.push(raw)
|
|
482
|
+
tokens += opts.fullTok[idx]!
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
if (!archiveInserted && archiveText !== undefined) {
|
|
486
|
+
items.push({ kind: 'note', text: archiveText })
|
|
487
|
+
tokens += archiveTok
|
|
488
|
+
}
|
|
489
|
+
return { items, tokens }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
for (let k = 0; k < pairs.length; k++) {
|
|
493
|
+
const isLast = k === pairs.length - 1
|
|
494
|
+
const pairsSub = pairs.slice(0, k + 1)
|
|
495
|
+
const endAtK = isLast ? history.length : pairs[k]!.resultIndex + 1
|
|
496
|
+
let cur = assembleInPlace(endAtK, pairsSub)
|
|
497
|
+
const beforeTokens = cur.tokens
|
|
498
|
+
const maskedBefore = maskedCallIndices.size
|
|
499
|
+
const archivedBefore = archivedCount
|
|
500
|
+
if (cur.tokens > opts.budgetTokens) {
|
|
501
|
+
const maskLimit = pairsSub.length - keepFloor
|
|
502
|
+
let changed = false
|
|
503
|
+
for (let pIdx = archivedCount; pIdx < maskLimit; pIdx++) {
|
|
504
|
+
if (cur.tokens <= targetLow) break
|
|
505
|
+
const pair = pairsSub[pIdx]!
|
|
506
|
+
if (maskedCallIndices.has(pair.callIndex)) continue
|
|
507
|
+
if (opts.rawResultTok[pair.resultIndex]! < opts.exemptResultTokens) continue
|
|
508
|
+
const maskedTok = getMasked(pair).tok
|
|
509
|
+
const saved = opts.fullTok[pair.resultIndex]! - maskedTok
|
|
510
|
+
if (saved <= 0) continue
|
|
511
|
+
maskedCallIndices.add(pair.callIndex)
|
|
512
|
+
cur.tokens -= saved
|
|
513
|
+
changed = true
|
|
514
|
+
}
|
|
515
|
+
if (changed) cur = assembleInPlace(endAtK, pairsSub)
|
|
516
|
+
}
|
|
517
|
+
if (!opts.emptyThink && cur.tokens > opts.hardCap) {
|
|
518
|
+
for (let idx = turnStart; idx < endAtK; idx++) {
|
|
519
|
+
if (cur.tokens <= opts.hardCap) break
|
|
520
|
+
const item = history[idx]!
|
|
521
|
+
if ((item.kind === 'call' || item.kind === 'assistant') && item.reasoning && !clearedReasoning.has(idx)) {
|
|
522
|
+
clearedReasoning.add(idx)
|
|
523
|
+
cur = assembleInPlace(endAtK, pairsSub)
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
while (cur.tokens > opts.hardCap && (pairsSub.length - archivedCount) > 1) {
|
|
528
|
+
const droppedPair = pairsSub[archivedCount]!
|
|
529
|
+
archivedCount++
|
|
530
|
+
maskedCallIndices.delete(droppedPair.callIndex)
|
|
531
|
+
cur = assembleInPlace(endAtK, pairsSub)
|
|
532
|
+
}
|
|
533
|
+
if (isLast) {
|
|
534
|
+
const deltaArchived = archivedCount - archivedBefore
|
|
535
|
+
const deltaMasked = Math.max(0, maskedCallIndices.size - (maskedBefore - deltaArchived))
|
|
536
|
+
const foldedTools = deltaArchived + deltaMasked
|
|
537
|
+
if (foldedTools > 0 || cur.tokens < beforeTokens) {
|
|
538
|
+
lastStepFold = {
|
|
539
|
+
kind: deltaArchived > 0 ? 'stage-archive' : 'in-place',
|
|
540
|
+
beforeTokens,
|
|
541
|
+
afterTokens: cur.tokens,
|
|
542
|
+
foldedTools,
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const finalBuilt = assembleInPlace(history.length, pairs)
|
|
549
|
+
const duplicateFrom = archivedCount > 0 ? pairs[archivedCount - 1]!.resultIndex + 1 : turnStart
|
|
550
|
+
const maskedCallIds = new Set<string>()
|
|
551
|
+
for (const callIdx of maskedCallIndices) {
|
|
552
|
+
const callItem = history[callIdx]
|
|
553
|
+
if (callItem?.kind === 'call') maskedCallIds.add(callItem.id)
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return {
|
|
557
|
+
items: finalBuilt.items,
|
|
558
|
+
duplicateFrom,
|
|
559
|
+
totalTokens: finalBuilt.tokens,
|
|
560
|
+
...(maskedCallIds.size > 0 ? { maskedCallIds } : {}),
|
|
561
|
+
...(lastStepFold !== undefined ? { foldEvent: lastStepFold } : {}),
|
|
562
|
+
}
|
|
563
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Re-export shim: pure `line-edit` engine and shared coordinate helpers live
|
|
2
|
+
// in `src/core/edit-modes/line-edit.ts` and `src/core/edit-modes/shared.ts`.
|
|
3
|
+
export {
|
|
4
|
+
applyAnchoredLineEdits,
|
|
5
|
+
applyLineEdit,
|
|
6
|
+
batchEditSummary,
|
|
7
|
+
batchSyntaxRejection,
|
|
8
|
+
editSummary,
|
|
9
|
+
isNonTrivialAnchor,
|
|
10
|
+
LINE_EDIT_CONTEXT_LINES,
|
|
11
|
+
LINE_EDIT_MODE,
|
|
12
|
+
MAX_LINE_EDIT_READ_LINES,
|
|
13
|
+
normalizeLineEditArgs,
|
|
14
|
+
parseLineEditHunks,
|
|
15
|
+
syntaxRejection,
|
|
16
|
+
type ApplyLineEditsOptions,
|
|
17
|
+
type BatchLineEditResult,
|
|
18
|
+
type RawLineEditHunk,
|
|
19
|
+
type ResolvedLineEdit,
|
|
20
|
+
} from './edit-modes/line-edit.ts'
|
|
21
|
+
export {
|
|
22
|
+
addSeen,
|
|
23
|
+
formatRanges,
|
|
24
|
+
renderWindow,
|
|
25
|
+
sandboxPolicyFor,
|
|
26
|
+
seenAfterBatchEdit,
|
|
27
|
+
seenAfterEdit,
|
|
28
|
+
unseenLines,
|
|
29
|
+
unseenRejection,
|
|
30
|
+
type LineEdit,
|
|
31
|
+
type LineEditResult,
|
|
32
|
+
type SeenLines,
|
|
33
|
+
} from './edit-modes/shared.ts'
|