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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/cordis.patch.yml +59 -0
  4. package/lib/client.js +3148 -0
  5. package/lib/client.js.map +7 -0
  6. package/lib/index.js +6294 -0
  7. package/lib/index.js.map +7 -0
  8. package/lib/line-edit.js +1423 -0
  9. package/lib/line-edit.js.map +7 -0
  10. package/lib/todo.js +610 -0
  11. package/lib/todo.js.map +7 -0
  12. package/package.json +72 -4
  13. package/scripts/build.mjs +77 -0
  14. package/scripts/headless.ts +279 -0
  15. package/scripts/link-dsh.sh +31 -0
  16. package/scripts/relay-e2e.mjs +157 -0
  17. package/scripts/smoke.ts +116 -0
  18. package/scripts/state.ts +39 -0
  19. package/scripts/tokenizer-parity.ts +107 -0
  20. package/scripts/trace-stats.ts +33 -0
  21. package/src/adapter.ts +388 -0
  22. package/src/backend/generator.ts +221 -0
  23. package/src/backend/irwkv.ts +117 -0
  24. package/src/backend/lightning.ts +228 -0
  25. package/src/backend/stream.ts +97 -0
  26. package/src/client/AdapterPicker.tsx +264 -0
  27. package/src/client/DeveloperPanel.tsx +403 -0
  28. package/src/client/FoldNode.tsx +82 -0
  29. package/src/client/ModelCard.tsx +230 -0
  30. package/src/client/RwkvSettings.tsx +265 -0
  31. package/src/client/Segment.tsx +15 -0
  32. package/src/client/StatePicker.tsx +248 -0
  33. package/src/client/TraceFrames.tsx +462 -0
  34. package/src/client/TraceView.tsx +77 -0
  35. package/src/client/WirePanel.tsx +566 -0
  36. package/src/client/fields.tsx +362 -0
  37. package/src/client/index.tsx +109 -0
  38. package/src/client/styles.ts +277 -0
  39. package/src/client/traces-api.ts +222 -0
  40. package/src/client/url.ts +20 -0
  41. package/src/core/agent.ts +586 -0
  42. package/src/core/defaults.ts +51 -0
  43. package/src/core/dsh-prompt.ts +32 -0
  44. package/src/core/edit-modes/index.ts +108 -0
  45. package/src/core/edit-modes/line-edit.ts +793 -0
  46. package/src/core/edit-modes/literal.ts +26 -0
  47. package/src/core/edit-modes/shared.ts +213 -0
  48. package/src/core/edit-modes/tolerant.ts +558 -0
  49. package/src/core/fold-pairs.ts +407 -0
  50. package/src/core/fold-window.ts +563 -0
  51. package/src/core/line-edit.ts +33 -0
  52. package/src/core/parse.ts +290 -0
  53. package/src/core/policy.ts +500 -0
  54. package/src/core/prompt.ts +220 -0
  55. package/src/core/relay.ts +400 -0
  56. package/src/core/step-gates.ts +371 -0
  57. package/src/core/time-zone.ts +32 -0
  58. package/src/core/todo-state.ts +227 -0
  59. package/src/core/tolerant-edit.ts +14 -0
  60. package/src/core/tool-mappings.ts +209 -0
  61. package/src/core/tool-repairs.ts +255 -0
  62. package/src/core/tools.ts +162 -0
  63. package/src/core/worklist.ts +606 -0
  64. package/src/dsh-host.ts +48 -0
  65. package/src/edit-modes/folded-read-guard.ts +32 -0
  66. package/src/edit-modes/index.ts +26 -0
  67. package/src/edit-modes/line-edit.ts +154 -0
  68. package/src/edit-modes/literal.ts +9 -0
  69. package/src/edit-modes/observations.ts +234 -0
  70. package/src/edit-modes/syntax-check.ts +226 -0
  71. package/src/edit-modes/tolerant.ts +232 -0
  72. package/src/folded-read-guard.ts +6 -0
  73. package/src/history.ts +163 -0
  74. package/src/index.ts +287 -0
  75. package/src/line-edit.ts +15 -0
  76. package/src/live-wire.ts +133 -0
  77. package/src/paths.ts +91 -0
  78. package/src/relay-store.ts +59 -0
  79. package/src/result-budget.ts +225 -0
  80. package/src/routes.ts +324 -0
  81. package/src/session-setup.ts +150 -0
  82. package/src/syntax-check.ts +2 -0
  83. package/src/todo.ts +328 -0
  84. package/src/tokenizer.ts +48 -0
  85. package/src/tolerant-edit.ts +2 -0
  86. package/src/trace-stats.ts +225 -0
  87. package/src/traces.ts +289 -0
  88. package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
  89. package/vendor/rwkv-tokenizer/package.json +5 -0
  90. package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
  91. package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
  92. package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
@@ -0,0 +1,606 @@
1
+ // Context-folding orchestrator shared by `auto-fold` (`passive: true`) and
2
+ // active stateful worklist (`todo_plan` + `todo_update`).
3
+ //
4
+ // Submodules:
5
+ // - `todo-state.ts`: active `todo_plan` / `todo_update` state transitions & UI projection
6
+ // - `fold-pairs.ts`: pair extraction, completed-turn backbone, `foldedUnreadPaths`, unedited-read pinning
7
+ // - `fold-window.ts`: active-turn window assembly, reminder replay, sliding/epoch/in-place cuts, hardCap safety valve
8
+ //
9
+ // Shared by the student plugin (`decideStep`), the teacher overlay (`teacher.ts`)
10
+ // and the training exporter (`export.ts`) so prompt bytes match everywhere.
11
+
12
+ import { countTokens } from '../tokenizer.ts'
13
+ import {
14
+ DEFAULT_ACTIVE_WORKLIST_BUDGET_TOKENS,
15
+ DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS,
16
+ DEFAULT_AUTOFOLD_HARD_CAP_TOKENS,
17
+ DEFAULT_AUTOFOLD_HARD_SLACK_TOKENS,
18
+ DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS,
19
+ DEFAULT_BACKBONE_MAX_TOKENS,
20
+ DEFAULT_KEEP_RECENT_PAIRS,
21
+ DEFAULT_WORKLIST_BUDGET_TOKENS,
22
+ DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS,
23
+ DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS,
24
+ DEFAULT_WORKLIST_HARD_SLACK_TOKENS,
25
+ DEFAULT_WORKLIST_MIN_FOLD_TOKENS,
26
+ FOLDED_OUTPUT_MARKER,
27
+ } from './defaults.ts'
28
+ import {
29
+ collectPairs,
30
+ foldCompletedTurn,
31
+ foldCompletedTurnCompact,
32
+ foldedUnreadPaths,
33
+ historyItemPromptBytes,
34
+ isRuntimeContextNote,
35
+ itemsTokens,
36
+ } from './fold-pairs.ts'
37
+ import {
38
+ buildActiveWindow,
39
+ buildEpochJumpWindow,
40
+ buildInPlaceFoldWindow,
41
+ CHECKPOINT_NUDGE_COOLDOWN_STEPS,
42
+ INIT_NUDGE_COOLDOWN_STEPS,
43
+ nudgeTextOf,
44
+ WORKLIST_CHECKPOINT_NUDGE,
45
+ WORKLIST_INIT_NUDGE,
46
+ type ActiveWindowResult,
47
+ type ContextFoldEvent,
48
+ type InternalNudge,
49
+ type RecordedWorklistNudge,
50
+ type WorklistNudgeKind,
51
+ } from './fold-window.ts'
52
+ import { toolFailureReminder, transcriptEntries, type HistoryItem, type TranscriptOptions } from './policy.ts'
53
+ import { cleanChatText, type Entry } from './prompt.ts'
54
+ import { isWorklistTool } from './todo-state.ts'
55
+ import type { WireTool } from './tools.ts'
56
+
57
+ export {
58
+ DEFAULT_ACTIVE_WORKLIST_BUDGET_TOKENS,
59
+ DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS,
60
+ DEFAULT_AUTOFOLD_HARD_CAP_TOKENS,
61
+ DEFAULT_AUTOFOLD_HARD_SLACK_TOKENS,
62
+ DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS,
63
+ DEFAULT_BACKBONE_MAX_TOKENS,
64
+ DEFAULT_KEEP_RECENT_PAIRS,
65
+ DEFAULT_WORKLIST_BUDGET_TOKENS,
66
+ DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS,
67
+ DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS,
68
+ DEFAULT_WORKLIST_HARD_SLACK_TOKENS,
69
+ DEFAULT_WORKLIST_MIN_FOLD_TOKENS,
70
+ FOLDED_OUTPUT_MARKER,
71
+ }
72
+
73
+ export {
74
+ applyTodoPlan,
75
+ applyTodoUpdate,
76
+ formatWorklist,
77
+ isNotedTodoUpdateCall,
78
+ isWorklistTool,
79
+ normalizeWorklistStatus,
80
+ parsePlanItems,
81
+ projectNativeTodos,
82
+ TODO_PLAN_TOOL,
83
+ TODO_UPDATE_TOOL,
84
+ WORKLIST_TOOLS,
85
+ type TodoUpdateInput,
86
+ type WorklistItem,
87
+ type WorklistStatus,
88
+ } from './todo-state.ts'
89
+
90
+ export { foldedUnreadPaths }
91
+
92
+ export {
93
+ nudgeTextOf,
94
+ WORKLIST_CHECKPOINT_NUDGE,
95
+ WORKLIST_INIT_NUDGE,
96
+ type ContextFoldEvent,
97
+ type RecordedWorklistNudge,
98
+ type WorklistNudgeKind,
99
+ }
100
+
101
+ export interface WorklistOptions {
102
+ /** Minimum RWKV prompt tokens required before folding kicks in (legacy/active worklist). */
103
+ readonly minFoldTokens?: number
104
+ /** Total RWKV token high watermark (default: 13500 in auto-fold, 12000 in active worklist). */
105
+ readonly budgetTokens: number
106
+ /** Hard RWKV token safety ceiling (defaults to `budgetTokens + 1000` in auto-fold v2, `budgetTokens + 3000` in legacy). */
107
+ readonly hardCapTokens?: number
108
+ /** Maximum RWKV tokens kept for completed earlier user turns (default: 2000 in auto-fold v2, 5000 in worklist). */
109
+ readonly backboneMaxTokens?: number
110
+ /** Recent workspace call/result pairs kept verbatim across a fold (default: 3 in auto-fold v2, 2 in worklist). */
111
+ readonly keepRecentPairs?: number
112
+ /** Whether to retain the initial `todo_plan` pair in the folded active turn (default: true). */
113
+ readonly keepInitialPlan?: boolean
114
+ /** Whether to inject `WORKLIST_SYSTEM_GUIDANCE` into the system prompt (default: true). */
115
+ readonly systemGuidance?: boolean
116
+ /** Auto-fold (`passive: true`): omit active `todo_*` tools, guidance, and budget nudges. */
117
+ readonly passive?: boolean
118
+ /** Epoch-jump low watermark target in `auto-fold` (default: 9000 in auto-fold v2). */
119
+ readonly epochTargetTokens?: number
120
+ /** Pin up to one latest unedited `read` pair (<= 2400 tokens) across a fold boundary (default: false). */
121
+ readonly pinUneditedRead?: boolean
122
+ /** Module 1 (`auto-fold v2`): fold completed prior turns immediately on turn boundary (`<= backboneMaxTokens`). */
123
+ readonly immediatePriorFold?: boolean
124
+ /** Module 2 (`auto-fold v2`): mask old tool results in-place instead of pulling pairs into a top ledger. */
125
+ readonly inPlaceMask?: boolean
126
+ /** Module 2 (`auto-fold v2`): tool results below this RWKV token count are exempt from in-place masking (default: 250). */
127
+ readonly exemptResultTokens?: number
128
+ }
129
+
130
+ export interface FoldWorklistInput {
131
+ readonly systemTokens: number
132
+ readonly minFoldTokens?: number
133
+ readonly budgetTokens: number
134
+ readonly hardCapTokens?: number
135
+ readonly backboneMaxTokens?: number
136
+ readonly keepRecentPairs?: number
137
+ readonly keepInitialPlan?: boolean
138
+ /** Extra per-step reminder tokens rendered after each result in active turn (`User: ${POST_TOOL_REMINDER_THINK}\n\n`). */
139
+ readonly reminderTokens?: number
140
+ /** Tool catalog used to compute exact failure-reminder token overhead when a result failed. */
141
+ readonly tools?: readonly WireTool[]
142
+ /** False (default): include past step reasoning in token count; true: empty `<think></think>`. */
143
+ readonly historyEmptyThink?: boolean
144
+ /** Exact non-withdrawn reminders recorded during teacher collection, used by export.ts for path-mapped parity. */
145
+ readonly recordedNudges?: readonly RecordedWorklistNudge[]
146
+ /** Legacy override for single-step tests. */
147
+ readonly forceNudge?: boolean
148
+ /** Whether to emit a live tail reminder on the current step (default: true). */
149
+ readonly emitLiveNudge?: boolean
150
+ /** Passive auto-fold mode: watermark-gated cross-turn & in-turn folding with zero nudges or todo checkpoints. */
151
+ readonly passive?: boolean
152
+ /** Optional epoch-jump target in passive auto-fold mode (0 disables). */
153
+ readonly epochTargetTokens?: number
154
+ /** Pin latest unedited `read` across a fold boundary (default: false). */
155
+ readonly pinUneditedRead?: boolean
156
+ /** Module 1 (`auto-fold v2`): fold completed prior turns immediately on turn boundary. */
157
+ readonly immediatePriorFold?: boolean
158
+ /** Module 2 (`auto-fold v2`): mask old tool results in-place. */
159
+ readonly inPlaceMask?: boolean
160
+ /** Module 2 (`auto-fold v2`): exempt short tool results `< exemptResultTokens` RWKV tokens. */
161
+ readonly exemptResultTokens?: number
162
+ /** Session working directory for normalizing relative vs absolute paths in `foldedUnread` & notes. */
163
+ readonly cwd?: string
164
+ }
165
+
166
+ export interface WorklistFoldResult {
167
+ readonly items: HistoryItem[]
168
+ readonly duplicateFrom: number
169
+ readonly promptTokens: number
170
+ readonly nudge?: string
171
+ readonly nudges?: readonly RecordedWorklistNudge[]
172
+ readonly checkpointAt?: number
173
+ readonly foldedUnread: readonly string[]
174
+ readonly maskedCallIds?: ReadonlySet<string>
175
+ readonly foldEvent?: ContextFoldEvent
176
+ }
177
+
178
+ export interface WorklistEntryOptions extends TranscriptOptions {
179
+ readonly systemTokens: number
180
+ readonly minFoldTokens?: number
181
+ readonly budgetTokens: number
182
+ readonly hardCapTokens?: number
183
+ readonly backboneMaxTokens?: number
184
+ readonly keepRecentPairs?: number
185
+ readonly keepInitialPlan?: boolean
186
+ readonly historyEmptyThink?: boolean
187
+ readonly recordedNudges?: readonly RecordedWorklistNudge[]
188
+ readonly forceNudge?: boolean
189
+ readonly passive?: boolean
190
+ readonly epochTargetTokens?: number
191
+ readonly pinUneditedRead?: boolean
192
+ readonly immediatePriorFold?: boolean
193
+ readonly inPlaceMask?: boolean
194
+ readonly exemptResultTokens?: number
195
+ readonly cwd?: string
196
+ }
197
+
198
+ function truncateTextToBudget(text: string, maxTokens: number): string {
199
+ if (maxTokens <= 8) return '...'
200
+ let lo = 0
201
+ let hi = text.length
202
+ const suffix = ' ...(truncated)'
203
+ while (lo < hi) {
204
+ const mid = Math.ceil((lo + hi) / 2)
205
+ const candidate = `${text.slice(0, mid).trimEnd()}${suffix}`
206
+ if (countTokens(`User: ${candidate}\n\n`) <= maxTokens) lo = mid
207
+ else hi = mid - 1
208
+ }
209
+ return lo > 0 ? `${text.slice(0, lo).trimEnd()}${suffix}` : '...'
210
+ }
211
+
212
+ function foldPriorTurnsCompact(
213
+ history: readonly HistoryItem[],
214
+ userStarts: readonly number[],
215
+ emptyThink: boolean,
216
+ backboneMax: number,
217
+ cwd?: string,
218
+ ): { priorItems: HistoryItem[]; priorTokens: number } {
219
+ if (userStarts.length <= 1) return { priorItems: [], priorTokens: 0 }
220
+
221
+ const priorTurns: HistoryItem[][] = []
222
+ for (let t = 0; t < userStarts.length - 1; t++) {
223
+ const from = t === 0 ? 0 : userStarts[t]!
224
+ const to = userStarts[t + 1]!
225
+ priorTurns.push(foldCompletedTurnCompact(history, from, to, cwd))
226
+ }
227
+
228
+ let priorTokens = priorTurns.reduce((sum, turn) => sum + itemsTokens(turn, emptyThink), 0)
229
+
230
+ // Pass 1: truncate older prior turns' assistant replies first.
231
+ for (let t = 0; t < priorTurns.length && priorTokens > backboneMax; t++) {
232
+ const turn = priorTurns[t]!
233
+ let changed = false
234
+ const nextTurn = turn.map(item => {
235
+ if (item.kind !== 'assistant' || item.text.length <= 200) return item
236
+ changed = true
237
+ return { ...item, text: `${item.text.slice(0, 180).trimEnd()} ...(truncated)` }
238
+ })
239
+ if (changed) {
240
+ const oldTok = itemsTokens(turn, emptyThink)
241
+ const newTok = itemsTokens(nextTurn, emptyThink)
242
+ priorTurns[t] = nextTurn
243
+ priorTokens += newTok - oldTok
244
+ }
245
+ }
246
+
247
+ // Pass 2: drop oldest non-Turn-1 prior turns while preserving Turn 1 (`priorTurns[0]`).
248
+ while (priorTurns.length > 1 && priorTokens > backboneMax) {
249
+ const [dropped] = priorTurns.splice(1, 1)
250
+ if (dropped !== undefined) priorTokens -= itemsTokens(dropped, emptyThink)
251
+ }
252
+
253
+ // Pass 3: if Turn 1 alone still exceeds backboneMax, strip its assistant reply and
254
+ // cap its user text while ALWAYS preserving Turn 1's runtime-context note(s).
255
+ if (priorTurns.length === 1 && priorTokens > backboneMax) {
256
+ const turn0 = priorTurns[0]!
257
+ const runtimeNotes = turn0.filter(isRuntimeContextNote)
258
+ const nonAssistant = turn0.filter(item => item.kind !== 'assistant')
259
+ let candidate: HistoryItem[] = nonAssistant
260
+ let candidateTok = itemsTokens(candidate, emptyThink)
261
+ if (candidateTok > backboneMax) {
262
+ const runtimeTok = itemsTokens(runtimeNotes, emptyThink)
263
+ const remainingForUser = Math.max(16, backboneMax - runtimeTok)
264
+ const users = turn0.filter((item): item is Extract<HistoryItem, { kind: 'user' }> => item.kind === 'user')
265
+ const perUserBudget = users.length > 0 ? Math.floor(remainingForUser / users.length) : remainingForUser
266
+ candidate = turn0.flatMap<HistoryItem>(item => {
267
+ if (isRuntimeContextNote(item)) return [item]
268
+ if (item.kind === 'user') return [{ kind: 'user' as const, text: truncateTextToBudget(item.text, perUserBudget) }]
269
+ return []
270
+ })
271
+ candidateTok = itemsTokens(candidate, emptyThink)
272
+ }
273
+ priorTurns[0] = candidate
274
+ priorTokens = candidateTok
275
+ }
276
+
277
+ return { priorItems: priorTurns.flat(), priorTokens }
278
+ }
279
+
280
+ function foldPriorTurns(
281
+ history: readonly HistoryItem[],
282
+ userStarts: readonly number[],
283
+ turnStart: number,
284
+ emptyThink: boolean,
285
+ passive: boolean,
286
+ immediatePriorFold: boolean,
287
+ minFoldTokens: number,
288
+ backboneMax: number,
289
+ baseFixed: number,
290
+ cwd?: string,
291
+ ): { priorItems: HistoryItem[]; priorTokens: number } {
292
+ if (immediatePriorFold) {
293
+ return foldPriorTurnsCompact(history, userStarts, emptyThink, backboneMax, cwd)
294
+ }
295
+ const priorTurns: HistoryItem[][] = []
296
+ if (passive && userStarts.length > 1) {
297
+ const rawTurns: HistoryItem[][] = []
298
+ const foldedTurns: HistoryItem[][] = []
299
+ for (let t = 0; t < userStarts.length - 1; t++) {
300
+ const from = t === 0 ? 0 : userStarts[t]!
301
+ const to = userStarts[t + 1]!
302
+ rawTurns.push(history.slice(from, to))
303
+ foldedTurns.push(foldCompletedTurn(history, from, to))
304
+ }
305
+ const activeRawTokens = itemsTokens(history.slice(turnStart), emptyThink)
306
+ if (minFoldTokens > 0) {
307
+ for (const raw of rawTurns) priorTurns.push(raw)
308
+ let totalPrior = priorTurns.reduce((sum, turn) => sum + itemsTokens(turn, emptyThink), 0)
309
+ for (let t = 0; t < priorTurns.length; t++) {
310
+ if (baseFixed + totalPrior + activeRawTokens < minFoldTokens) break
311
+ const oldTok = itemsTokens(priorTurns[t]!, emptyThink)
312
+ const newTok = itemsTokens(foldedTurns[t]!, emptyThink)
313
+ priorTurns[t] = foldedTurns[t]!
314
+ totalPrior += newTok - oldTok
315
+ }
316
+ for (let t = 0; t < priorTurns.length && totalPrior > backboneMax; t++) {
317
+ if (priorTurns[t] === foldedTurns[t]) continue
318
+ const oldTok = itemsTokens(priorTurns[t]!, emptyThink)
319
+ const newTok = itemsTokens(foldedTurns[t]!, emptyThink)
320
+ priorTurns[t] = foldedTurns[t]!
321
+ totalPrior += newTok - oldTok
322
+ }
323
+ } else {
324
+ for (const folded of foldedTurns) priorTurns.push(folded)
325
+ }
326
+ } else {
327
+ for (let t = 0; t < userStarts.length - 1; t++) {
328
+ const from = t === 0 ? 0 : userStarts[t]!
329
+ const to = userStarts[t + 1]!
330
+ priorTurns.push(foldCompletedTurn(history, from, to))
331
+ }
332
+ }
333
+
334
+ let priorTokens = priorTurns.reduce((sum, turn) => sum + itemsTokens(turn, emptyThink), 0)
335
+ while (priorTurns.length > 0 && priorTokens > backboneMax) {
336
+ const dropped = priorTurns.shift()!
337
+ priorTokens -= itemsTokens(dropped, emptyThink)
338
+ }
339
+ return { priorItems: priorTurns.flat(), priorTokens }
340
+ }
341
+
342
+ /**
343
+ * Pure context-folding plan over `history`. Produces the exact `HistoryItem[]`
344
+ * sequence kept in the prompt, the `duplicateFrom` gate boundary, and whether
345
+ * a new budget reminder triggered at the tail of this step.
346
+ */
347
+ export function foldWorklist(history: readonly HistoryItem[], input: FoldWorklistInput): WorklistFoldResult {
348
+ const emptyThink = input.historyEmptyThink ?? false
349
+ if (history.length === 0) {
350
+ return { items: [], duplicateFrom: 0, promptTokens: input.systemTokens, foldedUnread: [] }
351
+ }
352
+
353
+ const userStarts: number[] = []
354
+ for (let i = 0; i < history.length; i++) {
355
+ if (history[i]!.kind === 'user') userStarts.push(i)
356
+ }
357
+ if (userStarts.length === 0) {
358
+ const tok = input.systemTokens + itemsTokens(history, emptyThink)
359
+ return { items: [...history], duplicateFrom: 0, promptTokens: tok, foldedUnread: [] }
360
+ }
361
+
362
+ const passive = input.passive === true
363
+ const legacyV1Passive = passive
364
+ && input.inPlaceMask === undefined
365
+ && input.immediatePriorFold === undefined
366
+ && input.minFoldTokens !== undefined
367
+ && input.minFoldTokens > 0
368
+ const immediatePriorFold = input.immediatePriorFold ?? (passive && !legacyV1Passive)
369
+ const inPlaceMask = input.inPlaceMask ?? (passive && !legacyV1Passive)
370
+ const minFoldTokens = Math.max(0, input.minFoldTokens ?? 0)
371
+ const turnStart = userStarts.length === 1 ? 0 : userStarts[userStarts.length - 1]!
372
+ const backboneMax = input.backboneMaxTokens
373
+ ?? (immediatePriorFold ? DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS : DEFAULT_BACKBONE_MAX_TOKENS)
374
+
375
+ const baseReminderTok = input.reminderTokens ?? 0
376
+ const framingTok = baseReminderTok > 0 ? countTokens('System: \n\nAssistant: <think') : 0
377
+ const baseFixed = input.systemTokens + framingTok
378
+
379
+ const { priorItems, priorTokens } = foldPriorTurns(
380
+ history,
381
+ userStarts,
382
+ turnStart,
383
+ emptyThink,
384
+ passive,
385
+ immediatePriorFold,
386
+ minFoldTokens,
387
+ backboneMax,
388
+ baseFixed,
389
+ input.cwd,
390
+ )
391
+
392
+ const pairs = collectPairs(history, turnStart, history.length)
393
+ const baseOverhead = input.systemTokens + framingTok + priorTokens
394
+ const hardCap = input.hardCapTokens !== undefined && input.hardCapTokens > 0
395
+ ? input.hardCapTokens
396
+ : (inPlaceMask
397
+ ? input.budgetTokens + DEFAULT_AUTOFOLD_HARD_SLACK_TOKENS
398
+ : input.budgetTokens + DEFAULT_WORKLIST_HARD_SLACK_TOKENS)
399
+ const keepRecentCount = Math.max(
400
+ 0,
401
+ input.keepRecentPairs ?? (inPlaceMask ? DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS : DEFAULT_KEEP_RECENT_PAIRS),
402
+ )
403
+ const exemptResultTokens = Math.max(
404
+ 0,
405
+ input.exemptResultTokens ?? (inPlaceMask ? DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS : 0),
406
+ )
407
+ const keepInitialPlan = input.keepInitialPlan !== false
408
+ const emitLiveNudge = input.emitLiveNudge !== false
409
+
410
+ const reminderTokOfResult = (res: Extract<HistoryItem, { kind: 'result' }>): number => {
411
+ if (baseReminderTok <= 0) return 0
412
+ if (res.ok) return baseReminderTok
413
+ return countTokens(`User: ${cleanChatText(toolFailureReminder(res.name, res.text, false, input.tools ?? []))}\n\n`)
414
+ }
415
+
416
+ const fullTok = new Array<number>(history.length).fill(0)
417
+ const bareTok = new Array<number>(history.length).fill(0)
418
+ const rawResultTok = new Array<number>(history.length).fill(0)
419
+ for (let i = turnStart; i < history.length; i++) {
420
+ const item = history[i]!
421
+ if (item.kind === 'result') {
422
+ rawResultTok[i] = countTokens(item.text)
423
+ fullTok[i] = countTokens(historyItemPromptBytes(item, emptyThink)) + reminderTokOfResult(item)
424
+ bareTok[i] = fullTok[i]!
425
+ } else {
426
+ fullTok[i] = countTokens(historyItemPromptBytes(item, emptyThink))
427
+ bareTok[i] = (item.kind === 'call' || item.kind === 'assistant') && item.reasoning && !emptyThink
428
+ ? countTokens(historyItemPromptBytes({ ...item, reasoning: undefined }, emptyThink))
429
+ : fullTok[i]!
430
+ }
431
+ }
432
+
433
+ const epochTargetTokens = Math.max(
434
+ 0,
435
+ input.epochTargetTokens ?? (inPlaceMask ? DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS : 0),
436
+ )
437
+
438
+ let finalWin: ActiveWindowResult
439
+ const triggeredNudges: InternalNudge[] = []
440
+
441
+ if (passive && inPlaceMask) {
442
+ finalWin = buildInPlaceFoldWindow(history, turnStart, pairs, {
443
+ baseOverhead,
444
+ budgetTokens: input.budgetTokens,
445
+ epochTargetTokens,
446
+ hardCap,
447
+ keepRecentCount,
448
+ exemptResultTokens,
449
+ emptyThink,
450
+ cwd: input.cwd,
451
+ fullTok,
452
+ bareTok,
453
+ rawResultTok,
454
+ reminderTokOfResult,
455
+ })
456
+ } else {
457
+ const windowOpts = {
458
+ baseOverhead,
459
+ budgetTokens: input.budgetTokens,
460
+ hardCap,
461
+ keepRecentCount,
462
+ keepInitialPlan,
463
+ emptyThink,
464
+ emitLiveNudge,
465
+ passive,
466
+ pinUneditedRead: input.pinUneditedRead === true,
467
+ cwd: input.cwd,
468
+ fullTok,
469
+ bareTok,
470
+ }
471
+
472
+ const activeCheckpoints = new Set<number>()
473
+ const recordedByResult = input.recordedNudges !== undefined
474
+ ? new Map(input.recordedNudges.map(n => [n.afterResultIndex, n.kind]))
475
+ : undefined
476
+
477
+ for (let k = 0; !passive && k < pairs.length; k++) {
478
+ const pair = pairs[k]!
479
+ const pairsSub = pairs.slice(0, k + 1)
480
+
481
+ if (pair.notedUpdate) {
482
+ if (minFoldTokens <= 0) {
483
+ activeCheckpoints.add(pair.callIndex)
484
+ } else {
485
+ const winBeforeFold = buildActiveWindow(
486
+ history, turnStart, pair.resultIndex + 1, pairsSub, triggeredNudges, activeCheckpoints, windowOpts,
487
+ )
488
+ if (winBeforeFold.totalTokens >= minFoldTokens) {
489
+ activeCheckpoints.add(pair.callIndex)
490
+ }
491
+ }
492
+ }
493
+
494
+ if (recordedByResult !== undefined) {
495
+ const kind = recordedByResult.get(pair.resultIndex)
496
+ if (kind !== undefined) {
497
+ triggeredNudges.push({ pairIndex: k, afterResultIndex: pair.resultIndex, kind })
498
+ }
499
+ continue
500
+ }
501
+
502
+ const isFinalStepOverride = input.forceNudge !== undefined && k === pairs.length - 1 && pair.resultIndex === history.length - 1
503
+ if (isFinalStepOverride) {
504
+ if (input.forceNudge) {
505
+ const hasPlanAtK = pairsSub.some(p => p.ok && isWorklistTool(p.name))
506
+ triggeredNudges.push({
507
+ pairIndex: k,
508
+ afterResultIndex: pair.resultIndex,
509
+ kind: hasPlanAtK ? 'checkpoint' : 'init',
510
+ })
511
+ }
512
+ continue
513
+ }
514
+
515
+ const winAtK = buildActiveWindow(
516
+ history, turnStart, pair.resultIndex + 1, pairsSub, triggeredNudges, activeCheckpoints, windowOpts,
517
+ )
518
+ const lastCheckpointAtK = [...pairsSub].reverse().find(p => p.notedUpdate && activeCheckpoints.has(p.callIndex))
519
+ const checkpointPairIdx = lastCheckpointAtK !== undefined ? pairsSub.indexOf(lastCheckpointAtK) : -1
520
+ const searchAfter = lastCheckpointAtK !== undefined ? lastCheckpointAtK.resultIndex + 1 : turnStart
521
+ const unfoldedWs = pairsSub.filter(p => p.callIndex >= searchAfter && !isWorklistTool(p.name)).length
522
+ const hasPlanAtK = pairsSub.some(p => p.ok && isWorklistTool(p.name))
523
+ const kind: WorklistNudgeKind = hasPlanAtK ? 'checkpoint' : 'init'
524
+ const cooldown = kind === 'init' ? INIT_NUDGE_COOLDOWN_STEPS : CHECKPOINT_NUDGE_COOLDOWN_STEPS
525
+ const prevSameKind = [...triggeredNudges].reverse().find(n => n.pairIndex > checkpointPairIdx && n.kind === kind)
526
+ const onCooldown = prevSameKind !== undefined && (k - prevSameKind.pairIndex) < cooldown
527
+
528
+ if (!onCooldown && unfoldedWs >= 1 && winAtK.totalTokens > input.budgetTokens) {
529
+ triggeredNudges.push({ pairIndex: k, afterResultIndex: pair.resultIndex, kind })
530
+ }
531
+ }
532
+
533
+ finalWin = passive && epochTargetTokens > 0 && epochTargetTokens < input.budgetTokens
534
+ ? buildEpochJumpWindow(history, turnStart, pairs, triggeredNudges, activeCheckpoints, windowOpts, epochTargetTokens)
535
+ : buildActiveWindow(history, turnStart, history.length, pairs, triggeredNudges, activeCheckpoints, windowOpts)
536
+ }
537
+
538
+ const recorded: RecordedWorklistNudge[] = triggeredNudges.map(({ afterResultIndex, kind }) => ({ afterResultIndex, kind }))
539
+ const items = [...priorItems, ...finalWin.items]
540
+
541
+ let foldEvent = finalWin.foldEvent
542
+ if (foldEvent === undefined && immediatePriorFold && pairs.length === 0 && userStarts.length > 1) {
543
+ const prevFrom = userStarts.length === 2 ? 0 : userStarts[userStarts.length - 2]!
544
+ const prevSlice = history.slice(prevFrom, turnStart)
545
+ const prevToolCount = prevSlice.filter(item => item.kind === 'call').length
546
+ if (prevToolCount > 0) {
547
+ const rawPrevTok = itemsTokens(prevSlice, emptyThink)
548
+ const foldedPrevTok = itemsTokens(foldCompletedTurnCompact(history, prevFrom, turnStart, input.cwd), emptyThink)
549
+ const saved = rawPrevTok - foldedPrevTok
550
+ if (saved >= 100) {
551
+ foldEvent = {
552
+ kind: 'prior-turn',
553
+ beforeTokens: finalWin.totalTokens + saved,
554
+ afterTokens: finalWin.totalTokens,
555
+ foldedTools: prevToolCount,
556
+ }
557
+ }
558
+ }
559
+ }
560
+
561
+ return {
562
+ items,
563
+ duplicateFrom: finalWin.duplicateFrom,
564
+ promptTokens: finalWin.totalTokens,
565
+ ...(finalWin.liveNudge !== undefined ? { nudge: finalWin.liveNudge } : {}),
566
+ ...(recorded.length > 0 ? { nudges: recorded } : {}),
567
+ ...(finalWin.checkpointAt !== undefined ? { checkpointAt: finalWin.checkpointAt } : {}),
568
+ ...(finalWin.maskedCallIds !== undefined ? { maskedCallIds: finalWin.maskedCallIds } : {}),
569
+ ...(foldEvent !== undefined ? { foldEvent } : {}),
570
+ foldedUnread: foldedUnreadPaths(history, items, input.cwd),
571
+ }
572
+ }
573
+
574
+ /** Build RWKV prompt entries (after System:) + TurnState gate boundary for `worklist` / `auto-fold` mode. */
575
+ export function worklistEntries(
576
+ history: readonly HistoryItem[],
577
+ options: WorklistEntryOptions,
578
+ ): { entries: Entry[]; fold: WorklistFoldResult } {
579
+ const reminderTokens = options.reminders === false || !options.postToolReminder
580
+ ? 0
581
+ : countTokens(`User: ${cleanChatText(options.postToolReminder)}\n\n`)
582
+ const fold = foldWorklist(history, {
583
+ systemTokens: options.systemTokens,
584
+ ...options.minFoldTokens === undefined ? {} : { minFoldTokens: options.minFoldTokens },
585
+ budgetTokens: options.budgetTokens,
586
+ ...options.hardCapTokens === undefined ? {} : { hardCapTokens: options.hardCapTokens },
587
+ ...options.backboneMaxTokens === undefined ? {} : { backboneMaxTokens: options.backboneMaxTokens },
588
+ ...options.keepRecentPairs === undefined ? {} : { keepRecentPairs: options.keepRecentPairs },
589
+ ...options.keepInitialPlan === undefined ? {} : { keepInitialPlan: options.keepInitialPlan },
590
+ reminderTokens,
591
+ tools: options.tools,
592
+ ...options.historyEmptyThink === undefined ? {} : { historyEmptyThink: options.historyEmptyThink },
593
+ ...options.recordedNudges === undefined ? {} : { recordedNudges: options.recordedNudges },
594
+ ...options.forceNudge === undefined ? {} : { forceNudge: options.forceNudge },
595
+ ...options.passive === undefined ? {} : { passive: options.passive },
596
+ ...options.epochTargetTokens === undefined ? {} : { epochTargetTokens: options.epochTargetTokens },
597
+ ...options.pinUneditedRead === undefined ? {} : { pinUneditedRead: options.pinUneditedRead },
598
+ ...options.immediatePriorFold === undefined ? {} : { immediatePriorFold: options.immediatePriorFold },
599
+ ...options.inPlaceMask === undefined ? {} : { inPlaceMask: options.inPlaceMask },
600
+ ...options.exemptResultTokens === undefined ? {} : { exemptResultTokens: options.exemptResultTokens },
601
+ ...options.cwd === undefined ? {} : { cwd: options.cwd },
602
+ emitLiveNudge: options.reminders !== false,
603
+ })
604
+ const entries = transcriptEntries(fold.items, options)
605
+ return { entries, fold }
606
+ }
@@ -0,0 +1,48 @@
1
+ // Structural DSH host interfaces shared across `tolerant-edit.ts`,
2
+ // `result-budget.ts`, and `line-edit.ts`. Kept free of `@deepseek-ai/*` runtime
3
+ // imports so `rwkv-agent-pipeline` plugins can import hooks directly when
4
+ // `/opt/dsh-rwkv-plugin/node_modules` is an empty tmpfs inside Docker.
5
+
6
+ export interface SandboxPolicyLike {
7
+ resolve(request?: { session?: object }): unknown
8
+ }
9
+
10
+ export interface SessionHeaderLike {
11
+ readonly header?: { readonly id?: string }
12
+ requestHeader?(): { config?: { provider?: string } } | undefined
13
+ }
14
+
15
+ export interface AgentLike {
16
+ readonly session?: SessionHeaderLike & object
17
+ readonly options?: { readonly provider?: string }
18
+ }
19
+
20
+ export interface ToolExecLike {
21
+ readonly name: string
22
+ readonly callId?: string
23
+ readonly arguments?: unknown
24
+ readonly parent?: unknown
25
+ readonly agent?: AgentLike
26
+ readonly signal?: AbortSignal
27
+ }
28
+
29
+ export interface WorkingDirectoryServiceLike {
30
+ ensure(agent: unknown, signal?: AbortSignal): Promise<string>
31
+ }
32
+
33
+ export function providerOfExec(exec: { readonly agent?: AgentLike }): string | undefined {
34
+ return exec.agent?.session?.requestHeader?.()?.config?.provider ?? exec.agent?.options?.provider
35
+ }
36
+
37
+ export function sessionIdOfExec(exec: { readonly agent?: AgentLike }): string | undefined {
38
+ return exec.agent?.session?.header?.id
39
+ }
40
+
41
+ export async function ensureExecWorkingDir(
42
+ host: { get(name: string): unknown },
43
+ exec: { readonly agent?: unknown; readonly signal?: AbortSignal },
44
+ ): Promise<string | undefined> {
45
+ const workingDirectory = host.get('workingDirectory') as WorkingDirectoryServiceLike | undefined
46
+ if (exec.agent === undefined || workingDirectory === undefined) return undefined
47
+ return workingDirectory.ensure(exec.agent, exec.signal)
48
+ }
@@ -0,0 +1,32 @@
1
+ // Per-session tracker of files whose earlier `read` or `write` output was
2
+ // folded out of the active context window and has not yet been re-read.
3
+
4
+ const MAX_TRACKED_SESSIONS = 512
5
+ const foldedUnreadBySession = new Map<string, ReadonlySet<string>>()
6
+
7
+ export function setFoldedUnreadPaths(sessionId: string | undefined, paths: readonly string[]): void {
8
+ if (sessionId === undefined || sessionId === '') return
9
+ if (paths.length === 0) {
10
+ foldedUnreadBySession.delete(sessionId)
11
+ return
12
+ }
13
+ if (foldedUnreadBySession.has(sessionId)) foldedUnreadBySession.delete(sessionId)
14
+ foldedUnreadBySession.set(sessionId, new Set(paths))
15
+ while (foldedUnreadBySession.size > MAX_TRACKED_SESSIONS) {
16
+ const oldest = foldedUnreadBySession.keys().next().value
17
+ if (oldest === undefined) break
18
+ foldedUnreadBySession.delete(oldest)
19
+ }
20
+ }
21
+
22
+ export function isFoldedUnreadPath(sessionId: string | undefined, candidates: readonly (string | undefined)[]): boolean {
23
+ if (sessionId === undefined || sessionId === '') return false
24
+ const blocked = foldedUnreadBySession.get(sessionId)
25
+ if (blocked === undefined || blocked.size === 0) return false
26
+ return candidates.some(candidate => candidate !== undefined && candidate !== '' && blocked.has(candidate))
27
+ }
28
+
29
+ export function foldedUnreadErrorMessage(displayPath: string, toolName = 'edit'): string {
30
+ return `The earlier read output for ${displayPath} was folded out of the active context window. `
31
+ + `Call \`read\` on ${displayPath} again to inspect its current content before calling \`${toolName}\`.`
32
+ }