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,500 @@
1
+ // Harness feedback text and per-turn state, ported from RWKV-Agent
2
+ // internal/agent (runner_policy.go, runner_config.go, protocol_g1.go,
3
+ // runner_turn.go, runner_answer_fallback.go). DSH executes the tools and keeps
4
+ // the history, so the turn state is rebuilt from that history on every request.
5
+
6
+ import { FOLDED_OUTPUT_MARKER } from './defaults.ts'
7
+ import { cleanFinalText, type ParseErrorKind } from './parse.ts'
8
+ import { recordToolCall, toolResponse, type Entry } from './prompt.ts'
9
+ import type { Args, WireTool } from './tools.ts'
10
+
11
+ export type HistoryItem =
12
+ | { readonly kind: 'user'; readonly text: string }
13
+ | { readonly kind: 'note'; readonly text: string }
14
+ | { readonly kind: 'assistant'; readonly text: string; readonly reasoning?: string }
15
+ | { readonly kind: 'call'; readonly id: string; readonly name: string; readonly args: Args; readonly reasoning?: string }
16
+ | { readonly kind: 'result'; readonly id: string; readonly name: string; readonly ok: boolean; readonly text: string }
17
+
18
+ export const POST_TOOL_REMINDER = `Use the Tool results above to continue the current task.
19
+ If the evidence is sufficient, answer now. Call another tool only for a specific missing fact.
20
+ Never repeat a successful tool call. Do not open a <think> block or repeat the Tool payload.`
21
+
22
+ /** nudge=think (agent-wire-think-v1.0): the reminder that does not forbid thinking. */
23
+ export const POST_TOOL_REMINDER_THINK = POST_TOOL_REMINDER.replace(
24
+ 'Do not open a <think> block or repeat the Tool payload.',
25
+ 'Do not repeat the Tool payload.',
26
+ )
27
+
28
+ export const DUPLICATE_ANSWER_REMINDER = `That tool call was rejected because it repeats a successful call.
29
+ Answer the current task from the evidence already collected.`
30
+
31
+ export const DUPLICATE_FAILED_REMINDER = `That tool call was rejected because it repeats an earlier failed call.
32
+ Tools are now unavailable. Answer from the Tool results, and clearly state anything that could not be verified.`
33
+
34
+ export const NOOP_EDIT_REMINDER = 'That edit call was rejected because old_string and new_string are identical, so the file would not change. '
35
+ + 'Provide the actual target text to change, or if the edits are already complete, answer the user directly.'
36
+
37
+ export const DUPLICATE_FAILED_RETRY_REMINDER = 'That tool call was rejected because it repeats an earlier failed call with the exact same arguments. '
38
+ + 'Do not repeat the same call. Inspect the previous error and change the arguments, try a different tool, or answer directly.'
39
+
40
+ /** harness v26: the first repeat of a successful call gets one more decision with an edit hint. */
41
+ export function duplicateRetryReminder(tools: readonly WireTool[]): string {
42
+ let prompt = 'That tool call was rejected because it repeats a successful call; its result is already above. Do not call it again.\n'
43
+ const edits = ['edit', 'edit_lines', 'write'].flatMap(dsh => tools.filter(tool => tool.dshName === dsh).map(tool => tool.name))
44
+ if (edits.length > 0) {
45
+ prompt += `If the task asks to change a file you have already read, make the change now with ${edits.join(' or ')}, using the text already shown.\n`
46
+ }
47
+ return `${prompt}If one specific fact is still missing, call a tool with different arguments. Otherwise answer now.`
48
+ }
49
+
50
+ /** Keyed by DSH tool name; the hint names the tools as the catalog shows them. */
51
+ const FAILURE_HINTS: Record<string, { companions: string[]; hint: (names: Record<string, string>) => string }> = {
52
+ read: {
53
+ companions: ['read', 'glob', 'grep'],
54
+ hint: n => `If the path is uncertain, use ${n.glob} or ${n.grep} before another ${n.read} call. `,
55
+ },
56
+ glob: {
57
+ companions: ['grep'],
58
+ hint: n => `Try an existing parent directory or workspace root, or use ${n.grep} for a known literal. `,
59
+ },
60
+ }
61
+
62
+ export function toolFailureReminder(name: string, error: string, recoveryBlocked: boolean, tools: readonly WireTool[]): string {
63
+ const summary = oneLine(error)
64
+ if (/already applied|no edit needed/i.test(summary)) {
65
+ return `${summary} Do not repeat this edit. Continue with any remaining changes, or answer the user directly if all work is done.`
66
+ }
67
+ let prompt = `The tool call failed: ${summary}. `
68
+ prompt += recoveryBlocked ? 'Do not call the same tool again in this turn. ' : 'Do not repeat the same call. '
69
+ const failed = tools.find(tool => tool.name === name)
70
+ const entry = failed === undefined ? undefined : FAILURE_HINTS[failed.dshName]
71
+ const names: Record<string, string> = Object.fromEntries(tools.map(tool => [tool.dshName, tool.name]))
72
+ if (entry && entry.companions.every(companion => names[companion] !== undefined)) prompt += entry.hint(names)
73
+ return `${prompt}Choose a different useful tool or answer with the limitation. Do not guess.`
74
+ }
75
+
76
+ export function oneStageAnswerInstruction(): string {
77
+ return `Tool execution is complete and tools are now unavailable.
78
+ Answer the original current task directly in ordinary text using the Tool results above. Do not call another tool or repeat the Tool results. If they are insufficient, say what could not be verified.`
79
+ }
80
+
81
+ export const ANSWER_STAGE_REASK = 'Answer the original current task in ordinary Markdown NOW using the Function outputs above. This is your final answer; tool calls are forbidden.'
82
+
83
+ export const EMPTY_EXIT_REASK = 'The no_tool decision with empty arguments was accepted. No tool will be executed. '
84
+ + 'No user-facing reason or answer was provided, and no tool evidence exists. '
85
+ + 'Answer the original current task directly in ordinary Markdown now. '
86
+ + 'Do not output another function call or repeat the no_tool action.'
87
+
88
+ export function correction(kind: ParseErrorKind): string {
89
+ const action = 'Either answer directly in ordinary text, or output exactly one '
90
+ + '<tool_call>{"name":"...","arguments":{...}}</tool_call> and nothing else.'
91
+ switch (kind) {
92
+ case 'unclosed-think':
93
+ return 'Your previous reasoning never finished and was cut off. Do not restart it. '
94
+ + `Close the thinking block with </think> immediately, then ${action} `
95
+ + 'Decide with the evidence you already have instead of reasoning further.'
96
+ case 'length':
97
+ return `Your previous response was cut off by the output limit. Be far more concise. Skip preamble and restated reasoning, then ${action}`
98
+ default:
99
+ return `Your previous response was invalid. ${action}`
100
+ }
101
+ }
102
+
103
+ export function isChinese(text: string): boolean {
104
+ return /\p{Script=Han}/u.test(text)
105
+ }
106
+
107
+ /** Prose opening prefilled for the last answer generation; a continuation mid-sentence rarely becomes a call. */
108
+ export function answerOpener(task: string): string {
109
+ return isChinese(task) ? '根据上面的工具结果,' : 'Based on the tool results above,'
110
+ }
111
+
112
+ const PLANNING_MARKERS = ['让我', '我需要', '我将', '我会再', '接下来', '再搜', '再查', 'let me', 'i need to', 'i will', 'i\'ll', 'next,']
113
+
114
+ export function hasPlanningMarker(text: string): boolean {
115
+ const lower = text.trim().toLowerCase()
116
+ return PLANNING_MARKERS.some(marker => lower.includes(marker))
117
+ }
118
+
119
+ /** Prose written before a tool frame, when it is a real answer and not a plan. */
120
+ export function salvageAnswerProse(output: string, opener = ''): string {
121
+ let text = output
122
+ const think = text.lastIndexOf('</think>')
123
+ if (think >= 0) text = text.slice(think + '</think>'.length)
124
+ const frame = text.toLowerCase().indexOf('<tool_call')
125
+ if (frame >= 0) text = text.slice(0, frame)
126
+ text = text.trim()
127
+ const rest = text.startsWith(opener) ? text.slice(opener.length).trim() : text
128
+ if ([...rest].length < 8) return ''
129
+ const lower = rest.toLowerCase()
130
+ return PLANNING_MARKERS.some(marker => lower.includes(marker)) ? '' : text
131
+ }
132
+
133
+ /** Extracts text inside the last closed <think>...</think> block, stripping any stray tool frames. */
134
+ export function extractThinkInner(output: string): string {
135
+ const close = output.lastIndexOf('</think>')
136
+ if (close < 0) return ''
137
+ const open = output.lastIndexOf('<think>', close)
138
+ if (open < 0) return ''
139
+ let inner = output.slice(open + '<think>'.length, close)
140
+ const frame = inner.toLowerCase().indexOf('<tool_call')
141
+ if (frame >= 0) inner = inner.slice(0, frame)
142
+ return inner.trim()
143
+ }
144
+
145
+ /**
146
+ * Stronger last-resort extraction for `fallbackSummary: false`: tries `salvageAnswerProse`
147
+ * first, then any post-think non-frame prose across attempts, and finally the clearest
148
+ * inner reasoning so deduced facts survive instead of "I looked up...".
149
+ */
150
+ export function salvageLastResortAnswer(outputs: readonly string[], opener = ''): string {
151
+ for (let index = outputs.length - 1; index >= 0; index--) {
152
+ const salvaged = salvageAnswerProse(outputs[index]!, opener)
153
+ if (salvaged !== '') return salvaged
154
+ }
155
+ for (let index = outputs.length - 1; index >= 0; index--) {
156
+ let text = outputs[index]!
157
+ const think = text.lastIndexOf('</think>')
158
+ if (think >= 0) text = text.slice(think + '</think>'.length)
159
+ const frame = text.toLowerCase().indexOf('<tool_call')
160
+ if (frame >= 0) text = text.slice(0, frame)
161
+ text = cleanFinalText(text.replace(/<\/?think>/g, ''))
162
+ if ([...text].length >= 4) return text
163
+ }
164
+ for (let index = outputs.length - 1; index >= 0; index--) {
165
+ const inner = cleanFinalText(extractThinkInner(outputs[index]!))
166
+ if ([...inner].length >= 4) return inner
167
+ }
168
+ return ''
169
+ }
170
+
171
+ /** Harness-written last resort: what was looked up and how it went; it never claims a fact. */
172
+ export function answerFallbackSummary(task: string, results: readonly TurnResult[]): string {
173
+ const zh = isChinese(task)
174
+ const lines = results.map(result => {
175
+ const outcome = result.ok ? (zh ? '成功' : 'succeeded') : (zh ? '失败' : 'failed')
176
+ return `- ${result.name}: ${outcome}`
177
+ })
178
+ const gotContent = results.some(result => result.ok)
179
+ if (zh) {
180
+ const head = lines.length > 0 ? `这次我做了这些查询:\n${lines.join('\n')}\n\n` : ''
181
+ return head + (gotContent
182
+ ? '工具返回了一些内容,但这次没能整理成答案。可以让我再试一次。'
183
+ : '没有找到能回答这个问题的内容。可以换个说法,或者告诉我具体要查的文件或网址。')
184
+ }
185
+ const head = lines.length > 0 ? `I looked up:\n${lines.join('\n')}\n\n` : ''
186
+ return head + (gotContent
187
+ ? 'The tools returned some content, but I could not turn it into an answer this time. You can ask me to try again.'
188
+ : 'Nothing I found answers the question. You can rephrase it, or give me a specific URL or file to check.')
189
+ }
190
+
191
+ function oneLine(text: string): string {
192
+ const line = text.trim().replace(/\s+/g, ' ')
193
+ return line.length > 300 ? `${line.slice(0, 297)}...` : line
194
+ }
195
+
196
+ function canonical(value: unknown): unknown {
197
+ if (Array.isArray(value)) return value.map(canonical)
198
+ if (typeof value === 'object' && value !== null) {
199
+ return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical((value as Args)[key])]))
200
+ }
201
+ return value
202
+ }
203
+
204
+ export function callKey(name: string, args: Args): string {
205
+ return `${name}\u0000${JSON.stringify(canonical(args))}`
206
+ }
207
+
208
+ /** Tools that change workspace files, under their trained and DSH names. */
209
+ const FILE_WRITERS = new Set(['edit_file', 'write_file', 'edit', 'edit_lines', 'write'])
210
+
211
+ /**
212
+ * Shell commands that look like they change files or the environment: an
213
+ * output redirect (not to /dev/null, not an fd duplication such as 2>&1), an
214
+ * in-place sed, tee, file operations, git operations that touch the tree, and
215
+ * package installs. A false positive only lets one more repeat through.
216
+ */
217
+ const SHELL_WRITE = new RegExp([
218
+ String.raw`(?<![<>&=-])\d?>>?(?![>&=])\s*(?!/dev/null\b)[^\s&|;)]`,
219
+ String.raw`\bsed\s+(?:-[a-zA-Z]*\s+)*-[a-zA-Z]*i`,
220
+ String.raw`\b(?:tee|mv|cp|rm|rmdir|touch|mkdir|chmod|ln|patch|truncate|unzip|tar)\b`,
221
+ String.raw`\bgit\s+(?:apply|checkout|restore|reset|commit|merge|rebase|stash|am|cherry-pick|add|rm|mv)\b`,
222
+ String.raw`\b(?:pip3?|npm|pnpm|yarn|uv|cargo|go)\s+(?:install|add|get)\b`,
223
+ ].join('|'))
224
+
225
+ /**
226
+ * A call that may change what a later read or test run sees: an edit or write
227
+ * of a file, or a shell command matching {@link SHELL_WRITE}.
228
+ */
229
+ export function targetFileSuffix(_name: string, args: Args): string {
230
+ const raw = typeof args.file_path === 'string' ? args.file_path : typeof args.path === 'string' ? args.path : ''
231
+ return raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
232
+ }
233
+
234
+ export function sameTargetFile(a: string, b: string): boolean {
235
+ return a !== '' && b !== '' && (a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`))
236
+ }
237
+
238
+ export function isMutatingCall(name: string, args: Args): boolean {
239
+ if (FILE_WRITERS.has(name)) return true
240
+ return name === 'bash' && typeof args.command === 'string' && SHELL_WRITE.test(args.command)
241
+ }
242
+
243
+ export interface TurnResult {
244
+ readonly name: string
245
+ readonly ok: boolean
246
+ }
247
+
248
+ export interface TurnState {
249
+ /** The current turn's user request, for language choices. */
250
+ readonly task: string
251
+ /** Workspace tool calls DSH executed in the current turn (excludes worklist bookkeeping). */
252
+ readonly steps: number
253
+ /** Consecutive worklist calls (`todo_plan`/`todo_update`) since the last workspace call. */
254
+ readonly consecutiveWorklistCalls: number
255
+ readonly results: readonly TurnResult[]
256
+ readonly successfulCalls: number
257
+ /**
258
+ * Successful calls since the latest successful mutating call (that call
259
+ * included): rereading a file or rerunning a test after a change is not a
260
+ * repeat, but repeating the change itself, or any call since, still is.
261
+ */
262
+ readonly successKeys: ReadonlySet<string>
263
+ /** Failed call key → successful-call count when it failed (no success since = same epoch). */
264
+ readonly failedEpochs: ReadonlyMap<string, number>
265
+ /** Canonical key of the immediately preceding non-bookkeeping workspace call in this gate window. */
266
+ readonly lastCallKey: string
267
+ /** Whether that immediately preceding workspace call succeeded. */
268
+ readonly lastCallOk: boolean
269
+ /** Count of each non-bookkeeping call key executed in the active epoch/window. */
270
+ readonly epochKeyCounts: ReadonlyMap<string, number>
271
+ /** Consecutive/current failed edits per target file path until a succeeding write/edit resets it. */
272
+ readonly perFileFailedEdits: ReadonlyMap<string, number>
273
+ readonly consecutiveFailedTool: string
274
+ readonly consecutiveFailures: number
275
+ }
276
+
277
+ const BOOKKEEPING_TOOLS = new Set(['todo_plan', 'todo_update'])
278
+
279
+ export function currentTurnStart(history: readonly HistoryItem[]): number {
280
+ for (let index = history.length - 1; index >= 0; index--) {
281
+ if (history[index]!.kind === 'user') return index
282
+ }
283
+ return 0
284
+ }
285
+
286
+ export interface TurnOptions {
287
+ /**
288
+ * First history item whose calls take part in the duplicate and failure
289
+ * gates. The relay and worklist modes reset them at each cut/checkpoint:
290
+ * earlier raw file reads were folded out, so re-reading a file slice after a
291
+ * cut is not a repeated call. Workspace steps still count from the user
292
+ * turn's start, so maxSteps is unchanged.
293
+ */
294
+ readonly duplicateFrom?: number
295
+ /**
296
+ * Tool-call IDs whose corresponding result was masked in-place in the active
297
+ * window (`auto-fold v2`). Re-reading an in-place-masked file is allowed,
298
+ * while unmasked short results keep duplicate-call protection.
299
+ */
300
+ readonly maskedCallIds?: ReadonlySet<string>
301
+ }
302
+
303
+ export function analyzeTurn(history: readonly HistoryItem[], options: TurnOptions = {}): TurnState {
304
+ const start = currentTurnStart(history)
305
+ const gateStart = Math.max(start, options.duplicateFrom ?? start)
306
+ const first = history[start]
307
+ const calls = new Map<string, { name: string; key: string; mutating: boolean; file: string }>()
308
+ const successKeys = new Set<string>()
309
+ const failedEpochs = new Map<string, number>()
310
+ const failedEditFiles = new Map<string, string>()
311
+ const epochKeyCounts = new Map<string, number>()
312
+ const readKeys = new Map<string, string>()
313
+ const perFileFailedEdits = new Map<string, number>()
314
+ const results: TurnResult[] = []
315
+ let workspaceSteps = 0
316
+ let consecutiveWorklistCalls = 0
317
+ let successfulCalls = 0
318
+ let lastCallKey = ''
319
+ let lastCallOk = false
320
+ let consecutiveFailedTool = ''
321
+ let consecutiveFailures = 0
322
+ const READ_TOOLS = new Set(['read', 'read_file'])
323
+ const EDIT_FAIL_TRACKERS = new Set(['edit', 'edit_file', 'edit_lines', 'write', 'write_file'])
324
+ for (let index = start; index < history.length; index++) {
325
+ const item = history[index]!
326
+ if (item.kind === 'call') {
327
+ calls.set(item.id, {
328
+ name: item.name,
329
+ key: callKey(item.name, item.args),
330
+ mutating: isMutatingCall(item.name, item.args),
331
+ file: targetFileSuffix(item.name, item.args),
332
+ })
333
+ }
334
+ if (item.kind !== 'result') continue
335
+ const { name: calledName, key, mutating, file } = calls.get(item.id) ?? {
336
+ name: item.name,
337
+ key: callKey(item.name, {}),
338
+ mutating: false,
339
+ file: '',
340
+ }
341
+ results.push({ name: item.name, ok: item.ok })
342
+ const isBookkeeping = BOOKKEEPING_TOOLS.has(calledName) || BOOKKEEPING_TOOLS.has(item.name)
343
+ if (isBookkeeping) {
344
+ consecutiveWorklistCalls++
345
+ } else {
346
+ workspaceSteps++
347
+ consecutiveWorklistCalls = 0
348
+ }
349
+ if (index < gateStart) continue
350
+ if (item.ok) {
351
+ if (mutating) {
352
+ successKeys.clear()
353
+ epochKeyCounts.clear()
354
+ readKeys.clear()
355
+ failedEditFiles.clear()
356
+ }
357
+ if (READ_TOOLS.has(calledName) && file !== '') {
358
+ // Re-reading file F unlocks retrying an edit on F that was previously blocked
359
+ // (e.g. by folded-read-guard after cross-turn auto-fold).
360
+ for (const [ek, ef] of [...failedEditFiles.entries()]) {
361
+ if (sameTargetFile(ef, file)) {
362
+ epochKeyCounts.delete(ek)
363
+ failedEpochs.delete(ek)
364
+ failedEditFiles.delete(ek)
365
+ if (lastCallKey === ek) lastCallKey = ''
366
+ }
367
+ }
368
+ }
369
+ if (EDIT_FAIL_TRACKERS.has(calledName) && file !== '') {
370
+ for (const tracked of [...perFileFailedEdits.keys()]) {
371
+ if (sameTargetFile(tracked, file)) perFileFailedEdits.delete(tracked)
372
+ }
373
+ }
374
+ const maskedInPlace = item.text.startsWith(FOLDED_OUTPUT_MARKER) || (options.maskedCallIds?.has(item.id) ?? false)
375
+ if (!maskedInPlace) {
376
+ successKeys.add(key)
377
+ if (!isBookkeeping) {
378
+ epochKeyCounts.set(key, (epochKeyCounts.get(key) ?? 0) + 1)
379
+ if (READ_TOOLS.has(calledName)) readKeys.set(key, file)
380
+ }
381
+ }
382
+ if (!isBookkeeping) {
383
+ lastCallKey = maskedInPlace ? '' : key
384
+ lastCallOk = true
385
+ }
386
+ failedEpochs.delete(key)
387
+ failedEditFiles.delete(key)
388
+ successfulCalls++
389
+ consecutiveFailedTool = ''
390
+ consecutiveFailures = 0
391
+ } else {
392
+ failedEpochs.set(key, successfulCalls)
393
+ if (!isBookkeeping) {
394
+ epochKeyCounts.set(key, (epochKeyCounts.get(key) ?? 0) + 1)
395
+ lastCallKey = key
396
+ lastCallOk = false
397
+ }
398
+ if (EDIT_FAIL_TRACKERS.has(calledName) && file !== '') {
399
+ failedEditFiles.set(key, file)
400
+ const isFoldedGuardBlock = /folded out of the active context window|has not been read/i.test(item.text)
401
+ if (!isFoldedGuardBlock) {
402
+ perFileFailedEdits.set(file, (perFileFailedEdits.get(file) ?? 0) + 1)
403
+ }
404
+ for (const [rk, rf] of [...readKeys.entries()]) {
405
+ if (sameTargetFile(rf, file)) {
406
+ epochKeyCounts.delete(rk)
407
+ readKeys.delete(rk)
408
+ }
409
+ }
410
+ }
411
+ if (item.name === consecutiveFailedTool) consecutiveFailures++
412
+ else {
413
+ consecutiveFailedTool = item.name
414
+ consecutiveFailures = 1
415
+ }
416
+ }
417
+ }
418
+ return {
419
+ task: first?.kind === 'user' ? first.text : '',
420
+ steps: workspaceSteps,
421
+ consecutiveWorklistCalls,
422
+ results,
423
+ successfulCalls,
424
+ successKeys,
425
+ failedEpochs,
426
+ lastCallKey,
427
+ lastCallOk,
428
+ epochKeyCounts,
429
+ perFileFailedEdits,
430
+ consecutiveFailedTool,
431
+ consecutiveFailures,
432
+ }
433
+ }
434
+
435
+ export const analyseHistory = analyzeTurn
436
+
437
+ export interface TranscriptOptions {
438
+ readonly tools: readonly WireTool[]
439
+ readonly postToolReminder: string
440
+ /**
441
+ * Add the per-step reminders after results of the current turn. Off for a
442
+ * recap request: it is not a step, and the model that writes the card must
443
+ * see the same bytes the teacher and the export rebuild.
444
+ */
445
+ readonly reminders?: boolean
446
+ /**
447
+ * Legacy: cut results longer than this when rendering. Live sessions are cut
448
+ * once, when the tool runs (src/result-budget.ts), so the plugin leaves this
449
+ * unset; only the pipeline sets it, to render data recorded before that.
450
+ */
451
+ readonly maxResultChars?: number
452
+ }
453
+
454
+ /**
455
+ * Legacy prompt-time cut (head 80%, tail 20%, no saved copy), for rendering
456
+ * data recorded before the execution-time budget (src/result-budget.ts).
457
+ */
458
+ export function truncateResult(text: string, maxChars: number | undefined): string {
459
+ if (maxChars === undefined || maxChars <= 0 || text.length <= maxChars) return text
460
+ const head = Math.floor(maxChars * 0.8)
461
+ const tail = maxChars - head
462
+ return `${text.slice(0, head)}\n…(${text.length - maxChars} characters omitted)…\n${text.slice(text.length - tail)}`
463
+ }
464
+
465
+ /**
466
+ * Transcript entries for the history. Earlier turns keep their calls, results
467
+ * and answers; the per-step reminders exist only in the current turn, as the
468
+ * Go runner commits a turn without them.
469
+ */
470
+ export function transcriptEntries(history: readonly HistoryItem[], options: TranscriptOptions): Entry[] {
471
+ const start = currentTurnStart(history)
472
+ const entries: Entry[] = []
473
+ history.forEach((item, index) => {
474
+ const current = index >= start
475
+ switch (item.kind) {
476
+ case 'user':
477
+ case 'note':
478
+ entries.push({ role: 'user', text: item.text })
479
+ break
480
+ case 'assistant':
481
+ entries.push({ role: 'assistant', text: item.text, ...(item.reasoning ? { reasoning: item.reasoning } : {}) })
482
+ break
483
+ case 'call':
484
+ entries.push({ role: 'assistant', text: recordToolCall(item.name, item.args), ...(item.reasoning ? { reasoning: item.reasoning } : {}) })
485
+ break
486
+ case 'result': {
487
+ const body = truncateResult(item.text, options.maxResultChars)
488
+ entries.push({ role: 'user', text: toolResponse(item.name, item.ok, body) })
489
+ if (!current || options.reminders === false) break
490
+ if (item.ok) {
491
+ if (options.postToolReminder) entries.push({ role: 'user', text: options.postToolReminder })
492
+ } else {
493
+ entries.push({ role: 'user', text: toolFailureReminder(item.name, item.text, false, options.tools) })
494
+ }
495
+ break
496
+ }
497
+ }
498
+ })
499
+ return entries
500
+ }