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,407 @@
1
+ // History pair pairing, folded ledger formatting, completed-turn backbone
2
+ // compaction, and path-level read/write tracking (`foldedUnreadPaths` +
3
+ // `findLatestUneditedReadPair`) shared by `auto-fold` and active `worklist`.
4
+
5
+ import { countTokens } from '../tokenizer.ts'
6
+ import { FOLDED_OUTPUT_MARKER } from './defaults.ts'
7
+ import type { HistoryItem } from './policy.ts'
8
+ import { collapseBlock, recordToolCall, toolResponse } from './prompt.ts'
9
+ import { isNotedTodoUpdateCall, isWorklistTool } from './todo-state.ts'
10
+
11
+ export { FOLDED_OUTPUT_MARKER }
12
+
13
+ export const MAX_PINNED_UNEDITED_READ_TOKENS = 2400
14
+ const MAX_PRIOR_TURN_FALLBACK_RESULT_CHARS = 1600
15
+ const PRIOR_TURN_FOLDED_MARKER = '...(prior-turn output folded)...'
16
+
17
+ export const READ_PIN_TOOLS: ReadonlySet<string> = new Set(['read', 'read_file'])
18
+ export const WRITE_PIN_TOOLS: ReadonlySet<string> = new Set(['edit', 'edit_file', 'edit_lines', 'write', 'write_file'])
19
+ const READ_WRITE_TOOLS: ReadonlySet<string> = new Set(['read', 'read_file', 'write', 'write_file'])
20
+
21
+ export interface CallPair {
22
+ readonly callIndex: number
23
+ readonly resultIndex: number
24
+ readonly name: string
25
+ readonly ok: boolean
26
+ readonly notedUpdate: boolean
27
+ }
28
+
29
+ /** Rendering of one HistoryItem as prompt bytes, for exact RWKV token counting. */
30
+ export function historyItemPromptBytes(item: HistoryItem, historyEmptyThink = false): string {
31
+ switch (item.kind) {
32
+ case 'call': {
33
+ const action = recordToolCall(item.name, item.args)
34
+ const think = historyEmptyThink ? '' : collapseBlock(item.reasoning ?? '')
35
+ return `Assistant: <think>${think}</think>${action}\n\n`
36
+ }
37
+ case 'assistant': {
38
+ const action = collapseBlock(item.text)
39
+ const think = historyEmptyThink ? '' : collapseBlock(item.reasoning ?? '')
40
+ return `Assistant: <think>${think}</think>${action}\n\n`
41
+ }
42
+ case 'result':
43
+ return `User: ${toolResponse(item.name, item.ok, item.text)}\n\n`
44
+ default:
45
+ return `User: ${item.text}\n\n`
46
+ }
47
+ }
48
+
49
+ export function itemsTokens(items: readonly HistoryItem[], historyEmptyThink = false): number {
50
+ let total = 0
51
+ for (const item of items) total += countTokens(historyItemPromptBytes(item, historyEmptyThink))
52
+ return total
53
+ }
54
+
55
+ /** Completed (call, result) pairs inside `history[from..to)`. */
56
+ export function collectPairs(history: readonly HistoryItem[], from: number, to: number): CallPair[] {
57
+ const calls = new Map<string, { index: number; item: Extract<HistoryItem, { kind: 'call' }> }>()
58
+ const pairs: CallPair[] = []
59
+ for (let index = from; index < to; index++) {
60
+ const item = history[index]!
61
+ if (item.kind === 'call') {
62
+ calls.set(item.id, { index, item })
63
+ } else if (item.kind === 'result') {
64
+ const match = calls.get(item.id)
65
+ if (match !== undefined) {
66
+ pairs.push({
67
+ callIndex: match.index,
68
+ resultIndex: index,
69
+ name: match.item.name,
70
+ ok: item.ok,
71
+ notedUpdate: item.ok && isNotedTodoUpdateCall(match.item),
72
+ })
73
+ }
74
+ }
75
+ }
76
+ return pairs
77
+ }
78
+
79
+ function summarizeCallPair(
80
+ callItem: Extract<HistoryItem, { kind: 'call' }>,
81
+ resultItem: Extract<HistoryItem, { kind: 'result' }>,
82
+ ): string {
83
+ const args = callItem.args
84
+ const rawKey = args.file_path ?? args.path ?? args.pattern ?? args.command ?? args.url ?? args.query
85
+ let target = ''
86
+ if (typeof rawKey === 'string' && rawKey.trim() !== '') {
87
+ const clean = rawKey.trim().replace(/\s+/g, ' ')
88
+ target = clean.length > 80 ? `${clean.slice(0, 77)}...` : clean
89
+ if (callItem.name === 'edit_lines' && Array.isArray(args.edits) && args.edits.length > 0) {
90
+ const first = args.edits[0] as Record<string, unknown> | undefined
91
+ if (first && first.start_line !== undefined && first.end_line !== undefined) {
92
+ const extra = args.edits.length > 1 ? ` (+${args.edits.length - 1})` : ''
93
+ target = `${target}:${String(first.start_line)}-${String(first.end_line)}${extra}`
94
+ }
95
+ } else if (callItem.name === 'edit_lines' && args.start_line !== undefined && args.end_line !== undefined) {
96
+ target = `${target}:${String(args.start_line)}-${String(args.end_line)}`
97
+ }
98
+ }
99
+ let outcome = resultItem.ok ? 'ok' : 'error'
100
+ if (resultItem.ok && callItem.name === 'bash') {
101
+ const m = /\[exit code: (\d+)\]/.exec(resultItem.text)
102
+ outcome = m ? `exit ${m[1]}` : 'exit 0'
103
+ }
104
+ return `- ${callItem.name}${target ? ` ${target}` : ''} -> ${outcome}`
105
+ }
106
+
107
+ export function formatFoldedStepsNote(pairs: readonly CallPair[], history: readonly HistoryItem[]): string {
108
+ const lines = pairs.map(pair =>
109
+ summarizeCallPair(
110
+ history[pair.callIndex] as Extract<HistoryItem, { kind: 'call' }>,
111
+ history[pair.resultIndex] as Extract<HistoryItem, { kind: 'result' }>,
112
+ ),
113
+ )
114
+ return `[Earlier workspace steps in this turn (raw outputs folded; re-read a file before calling edit if its read output is no longer shown):\n${lines.join('\n')}]`
115
+ }
116
+
117
+ function compactPriorResult(item: Extract<HistoryItem, { kind: 'result' }>): HistoryItem {
118
+ if (item.text.length <= MAX_PRIOR_TURN_FALLBACK_RESULT_CHARS) return item
119
+ const trimmed = item.text.trim()
120
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) return item
121
+ const head = 1100
122
+ const tail = 400
123
+ return {
124
+ ...item,
125
+ text: `${item.text.slice(0, head)}\n${PRIOR_TURN_FOLDED_MARKER}\n${item.text.slice(item.text.length - tail)}`,
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Fold one finished earlier turn `[from, to)` down to its user/final backbone:
131
+ * - when a worklist was used, keep its final `todo_plan`/`todo_update` snapshot;
132
+ * - when NO worklist was used (unplanned fallback), always keep the last real
133
+ * workspace call/result pair (plus a 1-line-per-step ledger of earlier pairs)
134
+ * so subsequent turns retain concrete workspace context and tool-calling shape.
135
+ */
136
+ export function foldCompletedTurn(history: readonly HistoryItem[], from: number, to: number): HistoryItem[] {
137
+ const pairs = collectPairs(history, from, to)
138
+ const lastWorklist = [...pairs].reverse().find(pair => pair.ok && isWorklistTool(pair.name))
139
+ const fallbackPair = lastWorklist === undefined
140
+ ? ([...pairs].reverse().find(pair => pair.ok) ?? pairs[pairs.length - 1])
141
+ : undefined
142
+ const earlierUnplannedPairs = lastWorklist === undefined && fallbackPair !== undefined
143
+ ? pairs.filter(pair => pair.callIndex !== fallbackPair.callIndex)
144
+ : []
145
+ const hasFinal = history.slice(from, to).some(item => item.kind === 'assistant')
146
+
147
+ const keptIndices = new Set<number>()
148
+ for (let index = from; index < to; index++) {
149
+ const kind = history[index]!.kind
150
+ if (kind === 'user' || kind === 'note' || kind === 'assistant') keptIndices.add(index)
151
+ }
152
+ if (lastWorklist !== undefined) {
153
+ keptIndices.add(lastWorklist.callIndex)
154
+ keptIndices.add(lastWorklist.resultIndex)
155
+ } else if (fallbackPair !== undefined) {
156
+ keptIndices.add(fallbackPair.callIndex)
157
+ keptIndices.add(fallbackPair.resultIndex)
158
+ }
159
+
160
+ const out: HistoryItem[] = []
161
+ let insertedLedger = false
162
+ for (let index = from; index < to; index++) {
163
+ if (!keptIndices.has(index)) continue
164
+ if (!insertedLedger && earlierUnplannedPairs.length > 0 && fallbackPair !== undefined && index === fallbackPair.callIndex) {
165
+ out.push({ kind: 'note', text: formatFoldedStepsNote(earlierUnplannedPairs, history) })
166
+ insertedLedger = true
167
+ }
168
+ const item = history[index]!
169
+ if (hasFinal && fallbackPair !== undefined && index === fallbackPair.resultIndex && item.kind === 'result') {
170
+ out.push(compactPriorResult(item))
171
+ } else if ((item.kind === 'call' || item.kind === 'assistant') && item.reasoning) {
172
+ out.push({ ...item, reasoning: undefined })
173
+ } else {
174
+ out.push(item)
175
+ }
176
+ }
177
+ return out
178
+ }
179
+
180
+ function normalizePosixPath(raw: string): string {
181
+ const isAbs = raw.startsWith('/')
182
+ const parts: string[] = []
183
+ for (const part of raw.split('/')) {
184
+ if (part === '' || part === '.') continue
185
+ if (part === '..') {
186
+ if (parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
187
+ else if (!isAbs) parts.push('..')
188
+ continue
189
+ }
190
+ parts.push(part)
191
+ }
192
+ if (isAbs) return `/${parts.join('/')}`
193
+ return parts.length > 0 ? parts.join('/') : '.'
194
+ }
195
+
196
+ export function isRuntimeContextNote(item: HistoryItem): boolean {
197
+ return item.kind === 'note' && (
198
+ item.text.includes('Current working directory:')
199
+ || item.text.includes('Current DSH file policy:')
200
+ )
201
+ }
202
+
203
+ export function displayCleanPath(raw: unknown, cwd?: string): string | undefined {
204
+ if (typeof raw !== 'string') return undefined
205
+ const trimmed = raw.trim()
206
+ if (trimmed === '') return undefined
207
+ if (!trimmed.startsWith('/')) return normalizePosixPath(trimmed)
208
+ const abs = normalizePosixPath(trimmed)
209
+ if (cwd !== undefined && cwd.trim() !== '') {
210
+ const base = normalizePosixPath(cwd.trim())
211
+ if (base !== '/' && abs === base) return '.'
212
+ if (base !== '/' && abs.startsWith(`${base}/`)) return abs.slice(base.length + 1)
213
+ }
214
+ return abs
215
+ }
216
+
217
+ export function collectModifiedFiles(
218
+ pairs: readonly CallPair[],
219
+ history: readonly HistoryItem[],
220
+ cwd?: string,
221
+ ): string[] {
222
+ const seen = new Set<string>()
223
+ const out: string[] = []
224
+ for (const pair of pairs) {
225
+ if (!pair.ok || !WRITE_PIN_TOOLS.has(pair.name)) continue
226
+ const callItem = history[pair.callIndex]
227
+ if (callItem?.kind !== 'call') continue
228
+ const path = displayCleanPath(callItem.args.file_path ?? callItem.args.path, cwd)
229
+ if (path !== undefined && !seen.has(path)) {
230
+ seen.add(path)
231
+ out.push(path)
232
+ }
233
+ }
234
+ return out
235
+ }
236
+
237
+ export function maskResultInPlace(
238
+ callItem: Extract<HistoryItem, { kind: 'call' }>,
239
+ resultItem: Extract<HistoryItem, { kind: 'result' }>,
240
+ rawResultTokens?: number,
241
+ ): Extract<HistoryItem, { kind: 'result' }> {
242
+ if (resultItem.text.startsWith(FOLDED_OUTPUT_MARKER)) return resultItem
243
+ const args = callItem.args
244
+ const firstQuery = Array.isArray(args.queries) && args.queries.length > 0 ? args.queries[0] : undefined
245
+ const rawKey = args.file_path ?? args.path ?? args.pattern ?? args.command ?? args.url ?? args.query ?? firstQuery
246
+ let target = ''
247
+ if (typeof rawKey === 'string' && rawKey.trim() !== '') {
248
+ const clean = rawKey.trim().replace(/\s+/g, ' ')
249
+ target = clean.length > 80 ? `${clean.slice(0, 77)}...` : clean
250
+ if (callItem.name === 'edit_lines' && Array.isArray(args.edits) && args.edits.length > 0) {
251
+ const first = args.edits[0] as Record<string, unknown> | undefined
252
+ if (first && first.start_line !== undefined && first.end_line !== undefined) {
253
+ const extra = args.edits.length > 1 ? ` (+${args.edits.length - 1})` : ''
254
+ target = `${target}:${String(first.start_line)}-${String(first.end_line)}${extra}`
255
+ }
256
+ } else if (callItem.name === 'edit_lines' && args.start_line !== undefined && args.end_line !== undefined) {
257
+ target = `${target}:${String(args.start_line)}-${String(args.end_line)}`
258
+ }
259
+ }
260
+ const trimmedTrailing = resultItem.text.endsWith('\n') ? resultItem.text.slice(0, -1) : resultItem.text
261
+ const lineCount = resultItem.text === '' ? 0 : trimmedTrailing.split('\n').length
262
+ const tokCount = rawResultTokens ?? countTokens(resultItem.text)
263
+ let exitInfo = ''
264
+ if (callItem.name === 'bash') {
265
+ const m = /\[exit code: (\d+)\]/.exec(resultItem.text)
266
+ exitInfo = m ? `, exit ${m[1]}` : (resultItem.ok ? ', exit 0' : ', error')
267
+ } else if (!resultItem.ok) {
268
+ exitInfo = ', error'
269
+ }
270
+ const details = target !== ''
271
+ ? `${target}, ${lineCount} lines, ${tokCount} tokens`
272
+ : `${lineCount} lines, ${tokCount} tokens`
273
+ return {
274
+ ...resultItem,
275
+ text: `${FOLDED_OUTPUT_MARKER}${callItem.name} output omitted (${details})${exitInfo}; re-read if exact content is needed before edit]`,
276
+ }
277
+ }
278
+
279
+ export function formatStageArchiveNote(
280
+ pairs: readonly CallPair[],
281
+ history: readonly HistoryItem[],
282
+ cwd?: string,
283
+ ): string {
284
+ const files = collectModifiedFiles(pairs, history, cwd)
285
+ const fileSummary = files.length > 0 ? files.join(', ') : 'none'
286
+ return `[Stage archive — earlier steps in this turn modified: ${fileSummary}; ${pairs.length} steps archived. Re-read any file before editing.]`
287
+ }
288
+
289
+ /**
290
+ * Module 1 (`auto-fold v2`): immediately fold a completed prior turn `[from, to)`
291
+ * to `user` message(s) + Turn 1 `runtime-context` `note` + 1-line modified-files
292
+ * summary (if any) + final `assistant` reply (with past reasoning cleared).
293
+ */
294
+ export function foldCompletedTurnCompact(
295
+ history: readonly HistoryItem[],
296
+ from: number,
297
+ to: number,
298
+ cwd?: string,
299
+ ): HistoryItem[] {
300
+ const pairs = collectPairs(history, from, to)
301
+ const modifiedFiles = collectModifiedFiles(pairs, history, cwd)
302
+ const headItems: HistoryItem[] = []
303
+ const assistantItems: HistoryItem[] = []
304
+ for (let index = from; index < to; index++) {
305
+ const item = history[index]!
306
+ if (item.kind === 'user' || isRuntimeContextNote(item)) {
307
+ headItems.push(item)
308
+ } else if (item.kind === 'assistant') {
309
+ assistantItems.push(item.reasoning ? { ...item, reasoning: undefined } : item)
310
+ }
311
+ }
312
+ const out: HistoryItem[] = [...headItems]
313
+ if (modifiedFiles.length > 0) {
314
+ out.push({ kind: 'note', text: `[Modified files in this turn: ${modifiedFiles.join(', ')}]` })
315
+ }
316
+ out.push(...assistantItems)
317
+ return out
318
+ }
319
+
320
+ function canonicalToolTarget(raw: unknown, cwd?: string): string | undefined {
321
+ if (typeof raw !== 'string') return undefined
322
+ const trimmed = raw.trim()
323
+ if (trimmed === '') return undefined
324
+ if (trimmed.startsWith('/')) return normalizePosixPath(trimmed)
325
+ if (cwd !== undefined && cwd.trim() !== '') {
326
+ const base = cwd.trim().replace(/\/+$/, '') || '/'
327
+ return normalizePosixPath(`${base}/${trimmed}`)
328
+ }
329
+ return normalizePosixPath(trimmed)
330
+ }
331
+
332
+ function pairTargetPath(pair: CallPair, history: readonly HistoryItem[], cwd?: string): string | undefined {
333
+ const item = history[pair.callIndex]
334
+ if (item?.kind !== 'call') return undefined
335
+ return canonicalToolTarget(item.args.file_path ?? item.args.path, cwd)
336
+ }
337
+
338
+ /**
339
+ * Files whose earlier successful `read` or `write` output was folded out of
340
+ * `foldedItems` without a subsequent verbatim `read` or `write` remaining in
341
+ * the active window.
342
+ */
343
+ export function foldedUnreadPaths(
344
+ history: readonly HistoryItem[],
345
+ foldedItems: readonly HistoryItem[],
346
+ cwd?: string,
347
+ ): string[] {
348
+ const everObserved = new Set<string>()
349
+ for (const pair of collectPairs(history, 0, history.length)) {
350
+ if (!pair.ok || !READ_WRITE_TOOLS.has(pair.name)) continue
351
+ const callItem = history[pair.callIndex] as Extract<HistoryItem, { kind: 'call' }>
352
+ const target = canonicalToolTarget(callItem.args.file_path ?? callItem.args.path, cwd)
353
+ if (target !== undefined) everObserved.add(target)
354
+ }
355
+ if (everObserved.size === 0) return []
356
+
357
+ const visibleInWindow = new Set<string>()
358
+ for (const pair of collectPairs(foldedItems, 0, foldedItems.length)) {
359
+ if (!pair.ok || !READ_WRITE_TOOLS.has(pair.name)) continue
360
+ const callItem = foldedItems[pair.callIndex] as Extract<HistoryItem, { kind: 'call' }>
361
+ const resultItem = foldedItems[pair.resultIndex] as Extract<HistoryItem, { kind: 'result' }>
362
+ const target = canonicalToolTarget(callItem.args.file_path ?? callItem.args.path, cwd)
363
+ if (target === undefined) continue
364
+ if (
365
+ (pair.name === 'read' || pair.name === 'read_file')
366
+ && (resultItem.text.startsWith(FOLDED_OUTPUT_MARKER) || resultItem.text.includes(PRIOR_TURN_FOLDED_MARKER))
367
+ ) {
368
+ visibleInWindow.delete(target)
369
+ continue
370
+ }
371
+ visibleInWindow.add(target)
372
+ }
373
+
374
+ return [...everObserved].filter(path => !visibleInWindow.has(path))
375
+ }
376
+
377
+ /**
378
+ * Find the most recent successful `read` pair among `foldedPairs` that has not
379
+ * been followed by a write, fits within `MAX_PINNED_UNEDITED_READ_TOKENS`, and
380
+ * is not already superseded by a read/write on the same path in `activePairs`.
381
+ */
382
+ export function findLatestUneditedReadPair(
383
+ foldedPairs: readonly CallPair[],
384
+ history: readonly HistoryItem[],
385
+ pairTokens: (pair: CallPair) => number,
386
+ cwd: string | undefined,
387
+ activePairs: readonly CallPair[],
388
+ ): CallPair | undefined {
389
+ let candidate: CallPair | undefined
390
+ for (let i = foldedPairs.length - 1; i >= 0; i--) {
391
+ const pair = foldedPairs[i]!
392
+ if (pair.ok && WRITE_PIN_TOOLS.has(pair.name)) return undefined
393
+ if (pair.ok && READ_PIN_TOOLS.has(pair.name) && pairTargetPath(pair, history, cwd) !== undefined) {
394
+ if (pairTokens(pair) > MAX_PINNED_UNEDITED_READ_TOKENS) return undefined
395
+ candidate = pair
396
+ break
397
+ }
398
+ }
399
+ if (candidate === undefined) return undefined
400
+ const target = pairTargetPath(candidate, history, cwd)
401
+ const superseded = activePairs.some(pair =>
402
+ pair.ok
403
+ && (READ_PIN_TOOLS.has(pair.name) || WRITE_PIN_TOOLS.has(pair.name))
404
+ && pairTargetPath(pair, history, cwd) === target,
405
+ )
406
+ return superseded ? undefined : candidate
407
+ }