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,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/edit-modes/line-edit.ts", "../src/core/edit-modes/shared.ts", "../src/core/edit-modes/tolerant.ts", "../src/core/edit-modes/line-edit.ts", "../src/edit-modes/folded-read-guard.ts", "../src/edit-modes/observations.ts", "../src/dsh-host.ts", "../src/core/todo-state.ts", "../src/core/tool-mappings.ts", "../src/core/tool-repairs.ts", "../src/result-budget.ts", "../src/edit-modes/syntax-check.ts", "../src/line-edit.ts"],
4
+ "sourcesContent": ["// Host DSH tool implementation for `editMode: 'line-edit'`\n// (Anchored Batch Line-Edit v2).\n//\n// Registers `edit_lines` supporting both canonical atomic multi-hunk batches\n// (`{ file_path, edits: [{ start_line, end_line, start_text, end_text?, new_text }] }`)\n// and backward-compatible single-hunk shorthand\n// (`{ file_path, start_line, end_line, start_text?, end_text?, new_text }`),\n// guarded by session read observations, file-version lock, visible-line window,\n// folded-read guard (with verified-anchor bypass on observed file versions),\n// and pre-write incremental syntax check.\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { defineTool } from '@deepseek-ai/dsh-tools'\nimport {\n applyAnchoredLineEdits,\n batchEditSummary,\n batchSyntaxRejection,\n isNonTrivialAnchor,\n LINE_EDIT_CONTEXT_LINES,\n parseLineEditHunks,\n type RawLineEditHunk,\n} from '../core/edit-modes/line-edit.ts'\nimport {\n sandboxPolicyFor,\n seenAfterBatchEdit,\n unseenLines,\n unseenRejection,\n} from '../core/edit-modes/shared.ts'\nimport type { SandboxPolicyLike } from '../dsh-host.ts'\nimport { foldedUnreadErrorMessage } from './folded-read-guard.ts'\nimport {\n attachObservations,\n EDIT_LINES_TOOL,\n remediateStaleVersion,\n resolveTargetWithGuards,\n type LineEditExecLike,\n type LineEditHostContext,\n type Observations,\n} from './observations.ts'\nimport { introducedSyntaxError } from './syntax-check.ts'\n\nexport interface AnchoredLineEditArgs {\n file_path: string\n edits?: RawLineEditHunk[] | string\n start_line?: number\n end_line?: number\n start_text?: string\n end_text?: string\n new_text?: string\n}\n\nexport function createLineEditToolDefinition(\n host: LineEditHostContext,\n observations: Observations,\n): unknown {\n return defineTool({\n name: EDIT_LINES_TOOL,\n description:\n 'Atomically apply one or more non-overlapping anchored line-range edits to an existing UTF-8 text file. '\n + 'Pass `edits: [{ start_line, end_line, start_text, end_text?, new_text }]` (pre-edit 1-based line numbers; `end_line = start_line - 1` inserts before `start_line`; empty `new_text` deletes). '\n + 'Always include `start_text` (the original text at `start_line` without line-number prefix) so minor line drift auto-aligns cleanly. Single-hunk top-level `start_line`/`end_line`/`new_text` shorthand is also accepted.',\n parameters: {\n file_path: { type: 'string', required: true, description: 'Path to edit, resolved by the filesystem backend. Read the file first.' },\n edits: {\n type: 'array',\n description: 'One or more non-overlapping anchored edits evaluated against pre-edit 1-based line numbers.',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n start_line: { type: 'number', required: true, description: '1-based first line to replace (from read output).' },\n end_line: { type: 'number', required: true, description: '1-based last line to replace (start_line - 1 inserts before start_line).' },\n start_text: { type: 'string', description: 'Original text of line start_line without line-number prefix (verifies and auto-aligns line drift).' },\n end_text: { type: 'string', description: 'Optional original text of line end_line for multi-line spans.' },\n new_text: { type: 'string', required: true, description: 'Replacement lines without line-number prefixes (empty string deletes).' },\n },\n },\n },\n start_line: { type: 'number', description: 'Single-hunk shorthand: 1-based first line to replace.' },\n end_line: { type: 'number', description: 'Single-hunk shorthand: 1-based last line to replace (start_line - 1 inserts).' },\n start_text: { type: 'string', description: 'Single-hunk shorthand: original text of line start_line without line-number prefix.' },\n end_text: { type: 'string', description: 'Single-hunk shorthand: optional original text of line end_line.' },\n new_text: { type: 'string', description: 'Single-hunk shorthand: replacement lines without line numbers.' },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n path: { type: 'string', required: true, description: 'Canonical absolute path in the filesystem execution world.' },\n summary: { type: 'string', required: true },\n },\n },\n render: (_args: unknown, value: { summary: string }) => [{ type: 'text', text: value.summary }],\n },\n async execute(args: AnchoredLineEditArgs, exec: LineEditExecLike) {\n const hunks = parseLineEditHunks(args as unknown as Record<string, unknown>)\n if (typeof hunks === 'string') throw new Error(hunks)\n const allNonTrivialAnchored = hunks.every(h => isNonTrivialAnchor(h.startText, 8))\n const { target, guard, folded } = await resolveTargetWithGuards(\n host,\n observations,\n args.file_path,\n exec,\n { allowFolded: allNonTrivialAnchored },\n )\n try {\n const text = await host.fs.readText(target, exec.signal)\n const edited = applyAnchoredLineEdits(text, target.displayPath, hunks)\n if (typeof edited === 'string') throw new Error(edited)\n\n const allVerified = allNonTrivialAnchored && edited.hunks.every(h => h.anchorVerified)\n if (folded && !allVerified) {\n throw new Error(foldedUnreadErrorMessage(target.displayPath, EDIT_LINES_TOOL))\n }\n\n if (guard.lines !== 'all' && !folded) {\n for (const h of edited.hunks) {\n const rawHunk = hunks[h.index]\n const startAnchored = h.anchorVerified && isNonTrivialAnchor(rawHunk?.startText, 8)\n const endAnchored = h.endAnchorVerified && isNonTrivialAnchor(rawHunk?.endText, 4)\n if (startAnchored && (h.endLine <= h.startLine || endAnchored)) continue\n const missing = unseenLines(guard.lines, h, edited.before.length)\n if (missing.length > 0) {\n throw new Error(unseenRejection(target.displayPath, missing, guard.lines, edited.before.length, LINE_EDIT_CONTEXT_LINES))\n }\n }\n }\n\n const broken = await introducedSyntaxError(text, edited.content, target.displayPath)\n if (broken !== undefined) throw new Error(batchSyntaxRejection(target.displayPath, edited, broken))\n\n const expected = guard.version === undefined ? undefined : { kind: guard.kind, version: guard.version }\n const policy = sandboxPolicyFor(host.get('sandboxPolicy') as SandboxPolicyLike | undefined, exec.agent?.session)\n const outcome = await host.fs.writeText(target, edited.content, expected, exec.signal, policy)\n host.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec)\n observations.setLines(\n exec,\n target,\n seenAfterBatchEdit(guard.lines, edited.hunks, edited.after.length, LINE_EDIT_CONTEXT_LINES),\n )\n return { path: host.fs.processPath(target), summary: batchEditSummary(target.displayPath, edited) }\n } catch (error: unknown) {\n throw remediateStaleVersion(error)\n }\n },\n } as never)\n}\n\nexport function applyLineEditPlugin(ctx: Context): void {\n const host = ctx as unknown as LineEditHostContext\n const observations = attachObservations(host)\n host.tools.register(createLineEditToolDefinition(host, observations))\n}\n", "// Shared coordinate, window rendering, seen-line tracking, and sandbox policy\n// primitives used by coordinate-based line editing (`line-edit`).\n// Pure functions with zero DSH or Node runtime imports.\n\nexport interface LineEdit {\n /** First line replaced (1-based). */\n readonly startLine: number\n /** Last line replaced; startLine - 1 replaces nothing (an insert before startLine). */\n readonly endLine: number\n /** Optional anchor text of line `startLine` (without line-number prefix) for drift verification & self-healing. */\n readonly startText?: string\n /** Optional anchor text of line `endLine` for multi-line spans. */\n readonly endText?: string\n /** Lines that take their place; empty deletes them. One trailing newline is ignored. */\n readonly newText: string\n}\n\nexport interface LineEditResult {\n /** The whole new file text, in the file's own line endings. */\n readonly content: string\n /** Lines before and after the edit (LF, no trailing newline). */\n readonly before: readonly string[]\n readonly after: readonly string[]\n readonly removed: number\n readonly added: number\n /** Resolved 1-based line range (may differ from requested if self-healed via `start_text` / `end_text`). */\n readonly resolvedStart?: number\n readonly resolvedEnd?: number\n readonly alignedNote?: string\n readonly anchorVerified?: boolean\n readonly strippedLineNumbers?: boolean\n readonly reindented?: boolean\n}\n\nexport const pluralLines = (count: number): string => `${count} line${count === 1 ? '' : 's'}`\n\n/** Split text into LF lines along with its detected line ending and trailing-newline flag. */\nexport function splitDocumentLines(text: string): {\n readonly eol: '\\r\\n' | '\\n'\n readonly trailingNewline: boolean\n readonly lines: readonly string[]\n} {\n const eol = text.includes('\\r\\n') ? '\\r\\n' : '\\n'\n const normalized = eol === '\\r\\n' ? text.replace(/\\r\\n/g, '\\n') : text\n const trailingNewline = normalized.endsWith('\\n')\n const lines = normalized === '' ? [] : (trailingNewline ? normalized.slice(0, -1) : normalized).split('\\n')\n return { eol, trailingNewline, lines }\n}\n\n/** Reassemble edited LF lines while preserving the original file's EOL and trailing newline. */\nexport function joinDocumentLines(\n after: readonly string[],\n eol: '\\r\\n' | '\\n',\n trailingNewline: boolean,\n wasEmpty: boolean,\n): string {\n const keepNewline = trailingNewline || (wasEmpty && after.length > 0)\n const joined = after.join('\\n') + (keepNewline && after.length > 0 ? '\\n' : '')\n return eol === '\\r\\n' ? joined.replace(/\\n/g, '\\r\\n') : joined\n}\n\n/**\n * Render lines `from..to` with neutral headers (`=== path (lines X-Y of Z) ===`).\n * Avoids SWE-agent's `[File: path (N lines total)]` banner which empirically\n * hijacks raw RWKV-7 weights into emitting `str_replace_editor` calls.\n */\nexport function renderWindow(displayPath: string, lines: readonly string[], from: number, to: number): string {\n if (lines.length === 0) return `=== ${displayPath} (empty file, 0 lines) ===`\n const first = Math.max(1, Math.min(lines.length, from))\n const last = Math.max(first, Math.min(lines.length, to))\n const out = [`=== ${displayPath} (lines ${first}-${last} of ${lines.length}) ===`]\n if (first > 1) out.push(`(${pluralLines(first - 1)} above)`)\n for (let n = first; n <= last; n++) out.push(`${n}: ${lines[n - 1]}`)\n if (last < lines.length) out.push(`(${pluralLines(lines.length - last)} below)`)\n return out.join('\\n')\n}\n\n// --- Seen-line window tracking ----------------------------------------------\n\n/** Lines (1-based) of the current file version shown to the model; `'all'` when whole or untracked. */\nexport type SeenLines = ReadonlySet<number> | 'all'\n\n/** Add lines `first..last` (inclusive) to `seen`. */\nexport function addSeen(seen: SeenLines, first: number, last: number): SeenLines {\n if (seen === 'all') return seen\n const next = new Set(seen)\n for (let n = Math.max(1, first); n <= last; n++) next.add(n)\n return next\n}\n\n/**\n * Lines the edit needs the model to have seen that it has not: the replaced\n * lines, or for an insert a neighbour (the line before or after the gap).\n */\nexport function unseenLines(\n seen: SeenLines,\n edit: { readonly startLine: number; readonly endLine: number; readonly newText?: string },\n total: number,\n): number[] {\n if (seen === 'all') return []\n const { startLine: start, endLine: end } = edit\n if (end >= start) {\n const missing: number[] = []\n for (let n = start; n <= end; n++) if (!seen.has(n)) missing.push(n)\n return missing\n }\n const neighbours = [start - 1, start].filter(n => n >= 1 && n <= total)\n return neighbours.length === 0 || neighbours.some(n => seen.has(n)) ? [] : neighbours\n}\n\n/** Lines seen after a single edit: old ones renumbered, plus the new lines and result window. */\nexport function seenAfterEdit(\n seen: SeenLines,\n edit: { readonly startLine: number; readonly endLine: number; readonly newText?: string },\n result: Pick<LineEditResult, 'added' | 'removed' | 'after'>,\n contextLines = 3,\n): SeenLines {\n if (seen === 'all') return seen\n const { startLine: start, endLine: end } = edit\n const delta = result.added - result.removed\n const next = new Set<number>()\n for (const n of seen) {\n if (n < start) next.add(n)\n else if (n > end) next.add(n + delta)\n }\n const total = result.after.length\n const from = Math.max(1, start - contextLines)\n const to = Math.min(total, start + Math.max(result.added, 1) - 1 + contextLines)\n for (let n = from; n <= to; n++) next.add(n)\n return next\n}\n\n/** Lines seen after an atomic multi-hunk edit (hunks given in pre-edit ascending order). */\nexport function seenAfterBatchEdit(\n seen: SeenLines,\n hunks: readonly { readonly startLine: number; readonly endLine: number; readonly removed: number; readonly added: number }[],\n afterTotal: number,\n contextLines = 3,\n): SeenLines {\n if (seen === 'all') return seen\n const ordered = [...hunks].sort((a, b) => a.startLine - b.startLine)\n // Remap existing seen line numbers across all pre-edit hunks in one pass.\n const next = new Set<number>()\n for (const n of seen) {\n let shift = 0\n let overwritten = false\n for (const h of ordered) {\n if (h.endLine >= h.startLine && n >= h.startLine && n <= h.endLine) {\n overwritten = true\n break\n }\n if (n > h.endLine || (h.endLine < h.startLine && n >= h.startLine)) {\n shift += h.added - h.removed\n }\n }\n if (!overwritten && n + shift >= 1 && n + shift <= afterTotal) {\n next.add(n + shift)\n }\n }\n // Add every edited hunk's post-edit lines plus \u00B1contextLines window.\n let cumulativeDelta = 0\n for (const h of ordered) {\n const postStart = h.startLine + cumulativeDelta\n const from = Math.max(1, postStart - contextLines)\n const to = Math.min(afterTotal, postStart + Math.max(h.added, 1) - 1 + contextLines)\n for (let n = from; n <= to; n++) next.add(n)\n cumulativeDelta += h.added - h.removed\n }\n return next\n}\n\n/** Format a set of 1-based line numbers into compact `\"1-150, 200-230\"` ranges. */\nexport function formatRanges(lines: Iterable<number>): string {\n const sorted = [...lines].sort((a, b) => a - b)\n const parts: string[] = []\n for (let i = 0; i < sorted.length;) {\n let j = i\n while (j + 1 < sorted.length && sorted[j + 1] === sorted[j]! + 1) j++\n parts.push(sorted[i] === sorted[j] ? `${sorted[i]}` : `${sorted[i]}-${sorted[j]}`)\n i = j + 1\n }\n return parts.join(', ')\n}\n\n/** Model-facing refusal of an edit that touches lines outside the model's read window. */\nexport function unseenRejection(\n displayPath: string,\n missing: readonly number[],\n seen: ReadonlySet<number>,\n total: number,\n contextLines = 3,\n): string {\n const offset = Math.max(1, missing[0]! - contextLines)\n const shown = seen.size === 0 ? 'you have seen none of it' : `you have seen lines ${formatRanges(seen)}`\n const which = missing.length === 1 ? `line ${missing[0]} of ${displayPath} has` : `lines ${formatRanges(missing)} of ${displayPath} have`\n return `Your edit was NOT applied: ${which} not been shown to you `\n + `(the file has ${total} lines; ${shown}). `\n + `Read them first (read with offset=${offset}), then edit by the numbers you see.`\n}\n\n// --- Sandbox policy helper --------------------------------------------------\n\n/**\n * Resolve the calling session's sandbox policy (never the deployment cwd\n * fallback) before mutating via `ctx.fs`.\n */\nexport function sandboxPolicyFor(\n service: { resolve(request?: { session?: object }): unknown } | undefined,\n session: object | undefined,\n): unknown {\n if (service === undefined) return undefined\n return service.resolve(session === undefined ? {} : { session })\n}\n", "// Pure engine and specification for `editMode: 'tolerant'` (default).\n//\n// Keeps the standard `{ file_path, old_string, new_string }` contract unchanged\n// and resolves near-miss `old_string` regions through a strict-to-loose\n// uniqueness ladder:\n// 1. single-line leading-indent alignment (prevents partial-indent substring hits);\n// 2. Unicode/trailing-space fuzzy match;\n// 3. indentation-insensitive match;\n// 4. blank-line-insensitive match;\n// 5. inner-whitespace-insensitive match;\n// 6. unique close match (>= 90% bigram Dice similarity) guarded by dual\n// boundary anchors (>= 88% on both first and last lines + split-anchor\n// omitted-middle detection so shortened blocks never slide across\n// repetitive lines).\n//\n// Replacements are automatically re-indented to the file's indentation style,\n// and unchanged context lines keep the file's exact bytes so recall drift in\n// surrounding lines never reaches disk.\n\nimport type { EditModeSpec } from './literal.ts'\n\nexport const TOLERANT_EDIT_MODE: EditModeSpec = {\n id: 'tolerant',\n excludedTools: ['edit_lines'],\n mountsEditLinesPlugin: false,\n usesTolerantHook: true,\n}\n\nexport type MatchLevel = 'fuzzy' | 'indentation' | 'blank-lines' | 'whitespace' | 'similar'\n\nconst LEVEL_TEXT: Readonly<Record<MatchLevel, string>> = {\n fuzzy: 'after normalizing trailing whitespace/quotes',\n indentation: 'ignoring indentation',\n 'blank-lines': 'ignoring blank lines',\n whitespace: 'ignoring whitespace differences',\n similar: 'as the closest match',\n}\n\nexport interface RegionMatch {\n readonly level: MatchLevel\n /** Character offsets in the LF-normalized file. */\n readonly start: number\n readonly end: number\n /** 1-based inclusive line range. */\n readonly firstLine: number\n readonly lastLine: number\n /** Aligned [oldText line, file line] pairs of the matched lines. */\n readonly pairs: readonly (readonly [string, string])[]\n /** Blank lines in the file skipped between consecutive matched pairs. */\n readonly gaps?: readonly (readonly string[])[]\n readonly midStart?: boolean\n readonly midEnd?: boolean\n readonly similarity?: number\n}\n\nexport type RegionResult =\n | { readonly kind: 'match'; readonly match: RegionMatch }\n | { readonly kind: 'ambiguous'; readonly level: MatchLevel; readonly lines: readonly number[] }\n | { readonly kind: 'none'; readonly closest?: { readonly firstLine: number; readonly lastLine: number; readonly similarity: number } }\n\nexport type ResolvedTolerantEdit =\n | { readonly kind: 'exact' }\n | { readonly kind: 'repaired'; readonly oldString: string; readonly newString: string; readonly note: string }\n | { readonly kind: 'refused'; readonly message: string }\n\nexport const toLF = (text: string): string => text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\nconst indentOf = (line: string): string => /^[ \\t]*/.exec(line)![0]\nconst isBlank = (line: string): boolean => line.trim() === ''\nconst trimKey = (line: string): string => line.trim()\nconst spaceKey = (line: string): string => line.replace(/\\s+/g, ' ').trim()\n\nfunction normalizeFuzzyLine(line: string): string {\n return line\n .normalize('NFKC')\n .trimEnd()\n .replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n .replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n .replace(/[\\u2010-\\u2015\\u2212]/g, '-')\n .replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, ' ')\n}\n\nfunction bigrams(text: string): Map<string, number> {\n const map = new Map<string, number>()\n for (let i = 0; i < text.length - 1; i++) {\n const gram = text.slice(i, i + 2)\n map.set(gram, (map.get(gram) ?? 0) + 1)\n }\n return map\n}\n\n/** Dice coefficient over character bigrams. */\nexport function similarity(a: string, b: string): number {\n if (a === b) return 1\n if (a.length < 2 || b.length < 2) return 0\n const x = bigrams(a)\n const y = bigrams(b)\n let shared = 0\n for (const [gram, count] of x) shared += Math.min(count, y.get(gram) ?? 0)\n return (2 * shared) / (a.length - 1 + b.length - 1)\n}\n\ninterface Lines {\n readonly text: readonly string[]\n readonly starts: readonly number[]\n}\n\nfunction splitLines(content: string): Lines {\n const text = content.split('\\n')\n const starts: number[] = []\n let offset = 0\n for (const line of text) {\n starts.push(offset)\n offset += line.length + 1\n }\n return { text, starts }\n}\n\nfunction blankGaps(file: Lines, window: readonly number[]): string[][] {\n return window.map((line, t) => (t === 0 ? [] : file.text.slice(window[t - 1]! + 1, line) as string[]))\n}\n\n/**\n * Locate `oldText` in LF-normalized `content` under the strictest tolerance\n * level that finds a match. A level with multiple hits stops immediately as\n * `ambiguous` instead of falling through to looser matching.\n */\nexport function findRegion(content: string, oldText: string): RegionResult {\n const file = splitLines(content)\n const oldLF = toLF(oldText)\n const endsWithNewline = oldLF.endsWith('\\n')\n const old = (endsWithNewline ? oldLF.slice(0, -1) : oldLF).split('\\n')\n\n const levels: readonly {\n readonly level: MatchLevel\n readonly key: (line: string) => string\n readonly skipBlank: boolean\n readonly partial: boolean\n }[] = [\n { level: 'fuzzy', key: normalizeFuzzyLine, skipBlank: false, partial: false },\n { level: 'indentation', key: trimKey, skipBlank: false, partial: true },\n { level: 'blank-lines', key: trimKey, skipBlank: true, partial: true },\n { level: 'whitespace', key: spaceKey, skipBlank: true, partial: false },\n ]\n\n for (const { level, key, skipBlank, partial } of levels) {\n const oldIndex = old.map((_, i) => i).filter(i => !skipBlank || !isBlank(old[i]!))\n if (oldIndex.length === 0 || oldIndex.every(i => isBlank(old[i]!))) return { kind: 'none' }\n const pool = file.text.map((_, i) => i).filter(i => !skipBlank || !isBlank(file.text[i]!))\n const oldKeys = oldIndex.map(i => key(old[i]!))\n const found: RegionMatch[] = []\n\n for (let p = 0; p + oldIndex.length <= pool.length; p++) {\n const window = pool.slice(p, p + oldIndex.length)\n if (!skipBlank && window[window.length - 1]! - window[0]! !== oldIndex.length - 1) continue\n const fileKeys = window.map(i => key(file.text[i]!))\n const single = oldKeys.length === 1\n let ok = true\n for (let t = 0; t < oldKeys.length && ok; t++) {\n const fileKey = fileKeys[t]!\n const oldKey = oldKeys[t]!\n if (single) ok = partial ? oldKey.length > 0 && fileKey.includes(oldKey) : fileKey === oldKey\n else if (t === 0 && partial) ok = fileKey.endsWith(oldKey) && oldKey.length > 0\n else if (t === oldKeys.length - 1 && partial) ok = fileKey.startsWith(oldKey) && oldKey.length > 0\n else ok = fileKey === oldKey\n }\n if (!ok) continue\n\n const first = window[0]!\n const last = window[window.length - 1]!\n const firstLine = file.text[first]!\n const lastLine = file.text[last]!\n const oldFirst = old[oldIndex[0]!]!\n const oldLast = old[oldIndex[oldIndex.length - 1]!]!\n const pairs = oldIndex.map((i, t) => [old[i]!, file.text[window[t]!]!] as const)\n const gaps = skipBlank ? blankGaps(file, window) : undefined\n\n if (single && partial && key(firstLine) !== key(oldFirst)) {\n const needle = oldFirst.trim()\n for (let at = firstLine.indexOf(needle); at >= 0; at = firstLine.indexOf(needle, at + 1)) {\n let end = file.starts[first]! + at + needle.length\n if (endsWithNewline && at + needle.length === firstLine.length && first < file.text.length - 1) end += 1\n found.push({\n level,\n start: file.starts[first]! + at,\n end,\n firstLine: first + 1,\n lastLine: first + 1,\n pairs,\n midStart: true,\n midEnd: true,\n })\n }\n continue\n }\n\n const midStart = partial && key(firstLine) !== key(oldFirst)\n const start = midStart ? file.starts[first]! + firstLine.trimEnd().length - oldFirst.trim().length : file.starts[first]!\n const midEnd = partial && key(lastLine) !== key(oldLast)\n let end = midEnd ? file.starts[last]! + indentOf(lastLine).length + oldLast.trim().length : file.starts[last]! + lastLine.length\n if (!midEnd && endsWithNewline && last < file.text.length - 1) end += 1\n found.push({\n level,\n start,\n end,\n firstLine: first + 1,\n lastLine: last + 1,\n pairs,\n ...gaps ? { gaps } : {},\n ...midStart ? { midStart } : {},\n ...midEnd ? { midEnd } : {},\n })\n }\n\n if (found.length === 1) return { kind: 'match', match: found[0]! }\n if (found.length > 1) return { kind: 'ambiguous', level, lines: found.map(m => m.firstLine) }\n }\n\n return similarRegion(file, old)\n}\n\n/**\n * Unique non-blank region with >= 0.9 average per-line similarity, anchored on\n * both boundary lines (>= 0.88) and guarded against omitted-middle sliding.\n */\nfunction similarRegion(file: Lines, old: readonly string[]): RegionResult {\n const oldLines = old.filter(line => !isBlank(line))\n const pool = file.text.map((_, i) => i).filter(i => !isBlank(file.text[i]!))\n const n = oldLines.length\n if (n === 0 || pool.length < n) return { kind: 'none' }\n\n const oldKeys = oldLines.map(spaceKey)\n const fileKeys = pool.map(i => spaceKey(file.text[i]!))\n const firstScores = fileKeys.map(line => similarity(oldKeys[0]!, line))\n const lastScores = fileKeys.map(line => similarity(oldKeys[n - 1]!, line))\n\n const scored: { p: number; score: number }[] = []\n for (let p = 0; p + n <= pool.length; p++) {\n if (firstScores[p]! < 0.5 && lastScores[p + n - 1]! < 0.5) continue\n let total = 0\n for (let t = 0; t < n; t++) {\n total += t === 0 ? firstScores[p]! : t === n - 1 ? lastScores[p + t]! : similarity(oldKeys[t]!, fileKeys[p + t]!)\n }\n scored.push({ p, score: total / n })\n }\n scored.sort((a, b) => b.score - a.score)\n const best = scored[0]\n if (!best) return { kind: 'none' }\n\n const runner = scored.find(entry => Math.abs(entry.p - best.p) >= n)\n let first = pool[best.p]!\n let last = pool[best.p + n - 1]!\n\n // Omitted-middle sliding-window detection: if oldText's first line matches\n // strictly better earlier (or last line later) while the opposite end anchors\n // `best`, middle lines were left out of a repetitive block.\n let splitAnchor = false\n if (firstScores[best.p]! < 1) {\n for (let q = Math.max(0, best.p - n); q < best.p; q++) {\n if (firstScores[q]! >= 0.95 && firstScores[q]! > firstScores[best.p]! + 0.03) {\n first = pool[q]!\n splitAnchor = true\n break\n }\n }\n }\n if (lastScores[best.p + n - 1]! < 1) {\n for (let r = Math.min(pool.length - 1, best.p + 2 * n - 1); r > best.p + n - 1; r--) {\n if (lastScores[r]! >= 0.95 && lastScores[r]! > lastScores[best.p + n - 1]! + 0.03) {\n last = pool[r]!\n splitAnchor = true\n break\n }\n }\n }\n\n const anchorsOk = !splitAnchor && firstScores[best.p]! >= 0.88 && lastScores[best.p + n - 1]! >= 0.88\n const closest = { firstLine: first + 1, lastLine: last + 1, similarity: best.score }\n const singleLineHighConf = n === 1\n && oldKeys[0]!.length >= 36\n && best.score >= 0.95\n && (!runner || runner.score <= best.score - 0.14)\n const multiLineOk = n >= 2\n && best.score >= 0.9\n && anchorsOk\n && (!runner || runner.score <= best.score - (n >= 3 && best.score >= 0.96 ? 0.06 : 0.1))\n if (!singleLineHighConf && !multiLineOk) {\n return { kind: 'none', ...best.score >= 0.5 ? { closest } : {} }\n }\n\n return {\n kind: 'match',\n match: {\n level: 'similar',\n start: file.starts[first]!,\n end: file.starts[last]! + file.text[last]!.length,\n firstLine: first + 1,\n lastLine: last + 1,\n pairs: oldLines.map((line, t) => [line, file.text[pool[best.p + t]!]!] as const),\n gaps: blankGaps(file, pool.slice(best.p, best.p + n)),\n similarity: best.score,\n },\n }\n}\n\n/**\n * Re-indent `text` from the model's indentation to the file's indentation using\n * matched `[oldLine, fileLine]` pairs, converting spaces <-> tabs for deeper nesting.\n */\nexport function reindent(text: string, indents: readonly (readonly [string, string])[]): string {\n if (indents.every(([from, to]) => from === to)) return text\n const map = new Map<string, string>()\n for (const [from, to] of indents) if (!map.has(from)) map.set(from, to)\n let spacesPerTab = 0\n let tabToSpaces = 0\n for (const [from, to] of indents) {\n if (!spacesPerTab && /^ +$/.test(from) && /^\\t+$/.test(to) && from.length % to.length === 0) spacesPerTab = from.length / to.length\n if (!tabToSpaces && /^\\t+$/.test(from) && /^ +$/.test(to) && to.length % from.length === 0) tabToSpaces = to.length / from.length\n }\n return text.split('\\n').map(line => {\n if (isBlank(line)) return line\n const ws = indentOf(line)\n const mapped = map.get(ws)\n if (mapped !== undefined) return mapped + line.slice(ws.length)\n const from = [...map.keys()].filter(key => ws.startsWith(key)).sort((a, b) => b.length - a.length)[0]\n if (from === undefined) return line\n let rest = ws.slice(from.length)\n if (spacesPerTab) rest = rest.replace(new RegExp(` {${spacesPerTab}}`, 'g'), '\\t')\n if (tabToSpaces) rest = rest.replace(/\\t/g, ' '.repeat(tabToSpaces))\n return map.get(from)! + rest + line.slice(ws.length)\n }).join('\\n')\n}\n\n/**\n * Fit `newText` onto a matched region: re-indents whole lines to the file's\n * indentation and keeps unchanged context lines verbatim as the file has them.\n */\nexport function fitReplacement(\n newText: string,\n match: Pick<RegionMatch, 'pairs' | 'gaps' | 'midStart' | 'midEnd'>,\n): { text: string; reindented: boolean; kept: number } {\n const { pairs, gaps, midStart = false, midEnd = false } = match\n const lines = toLF(newText).split('\\n')\n const last = lines.length - 1\n if (midStart) {\n const lead = indentOf(pairs[0]![0])\n if (lines[0]!.startsWith(lead)) lines[0] = lines[0]!.slice(lead.length)\n }\n if (midEnd) {\n const trail = /[ \\t]*$/.exec(pairs[pairs.length - 1]![0])![0]\n if (trail && lines[last]!.endsWith(trail)) lines[last] = lines[last]!.slice(0, -trail.length)\n }\n const from = midStart ? 1 : 0\n const seen = new Map<string, number>()\n for (const [oldLine] of pairs) seen.set(oldLine, (seen.get(oldLine) ?? 0) + 1)\n const context = new Map<string, number>()\n pairs.forEach(([oldLine], t) => {\n if (t >= from && !(midEnd && t === pairs.length - 1) && !isBlank(oldLine) && seen.get(oldLine) === 1) {\n context.set(oldLine, t)\n }\n })\n const indents = pairs.slice(from).map(([oldLine, fileLine]) => [indentOf(oldLine), indentOf(fileLine)] as const)\n const reindented = indents.some(([a, b]) => a !== b)\n const body = lines.slice(from)\n const moved = [...lines.slice(0, from), ...(reindented ? reindent(body.join('\\n'), indents).split('\\n') : body)]\n let kept = 0\n let lastContext = -1\n const out: string[] = []\n moved.forEach((line, i) => {\n const t = i >= from && !(midEnd && i === last) ? context.get(lines[i]!) : undefined\n if (t === undefined) {\n out.push(line)\n return\n }\n if (out.length > 0 && !isBlank(out[out.length - 1]!) && t > lastContext) out.push(...(gaps?.[t] ?? []))\n const fileLine = pairs[t]![1]\n if (fileLine.trim() !== lines[i]!.trim()) kept++\n out.push(fileLine)\n lastContext = t\n })\n return { text: out.join('\\n'), reindented, kept }\n}\n\nconst lineAt = (content: string, offset: number): number => content.slice(0, offset).split('\\n').length\n\nconst numberedExcerpt = (content: string, first: number, last: number): string =>\n content.split('\\n').slice(first - 1, last).map((line, i) => `${first + i}: ${line}`).join('\\n')\n\nfunction isSingleIndentedLine(oldText: string, newText: string): boolean {\n const old = toLF(oldText)\n const body = old.endsWith('\\n') ? old.slice(0, -1) : old\n return /^[ \\t]/.test(body) && !body.includes('\\n') && (old !== body || toLF(newText).includes('\\n'))\n}\n\nfunction hasAllLineNumberPrefixes(text: string): boolean {\n const nonEmpty = text.split('\\n').filter(line => line !== '')\n return nonEmpty.length > 0\n && nonEmpty.every(line => /^\\s*\\d+: ?/.test(line))\n && nonEmpty.some(line => /^\\s*\\d+: /.test(line))\n}\n\nfunction stripLineNumberPrefixes(text: string): string {\n return text.split('\\n').map(line => (line === '' ? '' : line.replace(/^\\s*\\d+: ?/, ''))).join('\\n')\n}\n\n/**\n * Resolve a single `{ oldString, newString }` edit against `rawContent`,\n * preserving CRLF when present. Exact unique matches return `{ kind: 'exact' }`.\n */\nexport function resolveTolerantEdit(\n rawContent: string,\n oldString: string,\n newString: string,\n displayPath: string,\n): ResolvedTolerantEdit {\n if (oldString === '') return { kind: 'exact' }\n const eol = rawContent.includes('\\r\\n') ? '\\r\\n' : '\\n'\n const restoreEol = (lf: string): string => (eol === '\\r\\n' ? lf.replace(/\\n/g, '\\r\\n') : lf)\n const content = toLF(rawContent.startsWith('\\uFEFF') ? rawContent.slice(1) : rawContent)\n const oldLF = toLF(oldString)\n const newLF = toLF(newString)\n\n // Widen a single indented line whose leading whitespace drifted short, so a\n // multi-line replacement does not land under-indented inside the line's indent.\n if (isSingleIndentedLine(oldLF, newLF)) {\n const at = content.indexOf(oldLF)\n if (at >= 0 && content.indexOf(oldLF, at + 1) < 0) {\n const prefix = content.slice(content.lastIndexOf('\\n', at - 1) + 1, at)\n if (/^[ \\t]+$/.test(prefix)) {\n const line = oldLF.endsWith('\\n') ? oldLF.slice(0, -1) : oldLF\n const { text } = fitReplacement(newLF, { pairs: [[line, prefix + line]] })\n return {\n kind: 'repaired',\n oldString: restoreEol(prefix + oldLF),\n newString: restoreEol(text),\n note: `Matched the edit at line ${lineAt(content, at)} of ${displayPath} ignoring indentation; re-indented the replacement to the file.`,\n }\n }\n }\n }\n\n const exactAt = content.indexOf(oldLF)\n if (exactAt >= 0) {\n if (content.indexOf(oldLF, exactAt + 1) >= 0) {\n const hitLines: number[] = []\n let pos = exactAt\n while (pos >= 0 && hitLines.length < 16) {\n hitLines.push(lineAt(content, pos))\n pos = content.indexOf(oldLF, pos + Math.max(1, oldLF.length))\n }\n const shown = hitLines.slice(0, 8).join(', ')\n return {\n kind: 'refused',\n message: `Could not apply edit in ${displayPath}: old_string matched multiple places (lines ${shown}${hitLines.length > 8 ? ', ...' : ''}). `\n + 'Include surrounding lines in old_string so it matches uniquely, or set replace_all: true if every occurrence should change.',\n }\n }\n return eol === '\\r\\n' && (!oldString.includes('\\r\\n') || (newString.includes('\\n') && !newString.includes('\\r\\n')))\n ? {\n kind: 'repaired',\n oldString: restoreEol(oldLF),\n newString: restoreEol(newLF),\n note: `Matched the edit in ${displayPath} normalizing CRLF line endings.`,\n }\n : { kind: 'exact' }\n }\n\n // Strip accidental `123: ` line-number prefixes copied from `read` output.\n let effectiveOldLF = oldLF\n let effectiveNewLF = newLF\n let strippedPrefixes = false\n if (hasAllLineNumberPrefixes(oldLF) && !content.includes(oldLF)) {\n const candidateOld = stripLineNumberPrefixes(oldLF)\n if (candidateOld.trim() !== '') {\n effectiveOldLF = candidateOld\n strippedPrefixes = true\n if (hasAllLineNumberPrefixes(newLF)) {\n effectiveNewLF = stripLineNumberPrefixes(newLF)\n }\n const strippedAt = content.indexOf(effectiveOldLF)\n if (strippedAt >= 0 && content.indexOf(effectiveOldLF, strippedAt + 1) < 0) {\n if (effectiveOldLF === effectiveNewLF) {\n return {\n kind: 'refused',\n message: `Could not apply edit in ${displayPath}: old_string and new_string are identical after stripping line-number prefixes.`,\n }\n }\n return {\n kind: 'repaired',\n oldString: restoreEol(effectiveOldLF),\n newString: restoreEol(effectiveNewLF),\n note: `Matched the edit at line ${lineAt(content, strippedAt)} of ${displayPath} after stripping line-number prefixes.`,\n }\n }\n }\n }\n\n const result = findRegion(content, effectiveOldLF)\n if (result.kind === 'match') {\n const { match } = result\n const exact = content.slice(match.start, match.end)\n const fit = fitReplacement(effectiveNewLF, match)\n const range = match.firstLine === match.lastLine ? `line ${match.firstLine}` : `lines ${match.firstLine}-${match.lastLine}`\n if (fit.text === exact) {\n return {\n kind: 'refused',\n message: `Could not apply edit in ${displayPath}: old_string already contains the modified text instead of the current file text at ${range}. `\n + `Copy old_string from these exact lines:\\n${exact}`,\n }\n }\n let note = `Matched the edit at ${range} of ${displayPath} ${LEVEL_TEXT[match.level]}`\n if (strippedPrefixes) note += ' after stripping line-number prefixes'\n if (match.similarity !== undefined) note += ` (${Math.round(match.similarity * 100)}% similar)`\n if (fit.reindented) note += '; re-indented the replacement to the file'\n if (fit.kept > 0) note += `; kept ${fit.kept} unchanged line(s) as the file has them`\n note += '.'\n if (match.level === 'similar') note += ` Replaced text:\\n${exact}`\n return {\n kind: 'repaired',\n oldString: restoreEol(exact),\n newString: restoreEol(fit.text),\n note,\n }\n }\n\n if (result.kind === 'none' && result.closest && effectiveNewLF.trim().length >= 8) {\n const present = findRegion(content, effectiveNewLF)\n const { firstLine, lastLine } = result.closest\n if (present.kind === 'match' && present.match.level !== 'similar' && present.match.firstLine <= lastLine && present.match.lastLine >= firstLine) {\n return {\n kind: 'refused',\n message: `No edit needed in ${displayPath}: old_string is not in the file, and new_string is already present (line ${present.match.firstLine}). `\n + 'This change is already applied; do not repeat this edit. Continue with any remaining changes, or answer the user directly if all work is done.',\n }\n }\n }\n\n if (result.kind === 'ambiguous') {\n return {\n kind: 'refused',\n message: `Could not apply edit in ${displayPath}: when ${LEVEL_TEXT[result.level]}, old_string matches ${result.lines.length} places `\n + `(lines ${result.lines.slice(0, 8).join(', ')}). Include more surrounding lines so it matches uniquely.`,\n }\n }\n\n let message = `Could not find old_string in ${displayPath}.`\n if (result.closest) {\n const { firstLine, lastLine, similarity: score } = result.closest\n const totalLines = content.split('\\n').length\n const ctxFirst = Math.max(1, firstLine - 2)\n const ctxLast = Math.min(totalLines, lastLine + 2)\n message += ` The closest text is lines ${firstLine}-${lastLine} (${Math.round(score * 100)}% similar). `\n + `Current file around lines ${ctxFirst}-${ctxLast} (verify these are the intended lines before editing):\\n`\n + numberedExcerpt(content, ctxFirst, ctxLast)\n } else {\n message += ` Nothing similar was found; read ${displayPath} first to inspect its current content.`\n }\n return { kind: 'refused', message }\n}\n", "// Pure engine, wire mapping, and argument aliases for `editMode: 'line-edit'`\n// (Anchored Batch Line-Edit v2).\n//\n// Designed for RWKV-7's linear-state physics (empirically benchmarked on raw\n// rwkv7-g1l-7.2b):\n// - Semantic single-line anchors (`start_text`, optional `end_text`) achieve\n// ~100% recall across long windows + noise, whereas bare integer line\n// numbers drift by \u00B11..\u00B15 lines (~93.5% silent corruption without anchors)\n// and 2-hex hashline prefixes get 0% recall while destroying line tracking.\n// - 3-tier self-healing:\n// L1: exact `start_line` match (score >= 0.90)\n// L2: local \u00B115 line window unique relocation (exact >= 0.98 strictly\n// beats fuzzy runner-ups; >=2 local exact hits abort as ambiguous)\n// L3: whole-file unique fallback for non-trivial anchors (trimmed len >= 10)\n// - Atomic multi-hunk `edits[]`: all hunks resolved in pre-edit coordinates,\n// overlap-checked, applied bottom-up, and syntax-checked once before write.\n// - Defensive guards: auto-reindent on anchor indent drift, copied `N: ` line\n// prefix stripping, elision placeholder guard (`...`), no-op guard,\n// boundary duplication guard, and \u00B18 numbered context on error.\n// - 100% backward compatible with single-hunk `{ start_line, end_line, new_text }`.\n\nimport type { EditModeSpec } from './literal.ts'\nimport {\n joinDocumentLines,\n pluralLines,\n renderWindow,\n splitDocumentLines,\n type LineEdit,\n type LineEditResult,\n} from './shared.ts'\nimport { reindent, similarity } from './tolerant.ts'\n\n/** Empirically verified RWKV-7 line-number fidelity ceiling (95.7% \u00B15 recall <=200 lines; 0% at 320 lines). */\nexport const MAX_LINE_EDIT_READ_LINES = 200\n\nexport const LINE_EDIT_MODE: EditModeSpec = {\n id: 'line-edit',\n excludedTools: [],\n mountsEditLinesPlugin: true,\n maxReadLines: MAX_LINE_EDIT_READ_LINES,\n usesTolerantHook: false,\n}\n\nexport const LINE_EDIT_CONTEXT_LINES = 3\nconst ANCHOR_SEARCH_RADIUS = 15\nconst END_ANCHOR_SEARCH_RADIUS = 10\nconst ERROR_WINDOW_RADIUS = 8\nconst MIN_WHOLE_FILE_ANCHOR_LEN = 10\n\nconst PATH_ALIASES = ['file_path', 'filepath', 'file', 'filename', 'file_name'] as const\nconst NATIVE_PATH_ALIASES = ['path', 'filepath', 'file', 'filename', 'file_name'] as const\n\nexport const LINE_EDIT_WIRE_SCHEMA: Record<string, unknown> = {\n properties: {\n path: { type: 'string' },\n edits: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n start_line: { type: 'integer' },\n end_line: { type: 'integer' },\n start_text: { type: 'string' },\n end_text: { type: 'string' },\n new_text: { type: 'string' },\n },\n },\n },\n start_line: { type: 'integer' },\n end_line: { type: 'integer' },\n start_text: { type: 'string' },\n end_text: { type: 'string' },\n new_text: { type: 'string' },\n },\n}\n\n/**\n * Canonical flat placeholder rendered for `edit_lines` under `toolNames: 'dsh'`.\n * Keeps the nested `edits[]` hunk structure explicit instead of flattening it\n * into `\"optional array of object\"` via generic JSON-schema summarization.\n */\nexport const LINE_EDIT_DSH_WIRE_ARGUMENTS =\n '{\"file_path\":\"path to edit (read the file first)\",\"edits\":[{\"start_line\":\"1-based first line\",\"end_line\":\"1-based last line (start_line - 1 inserts)\",\"start_text\":\"original text at start_line without line number\",\"end_text\":\"optional original text at end_line\",\"new_text\":\"replacement lines without line numbers (empty deletes)\"}]}'\n\nexport const LINE_EDIT_TRAINED_ALIASES: Readonly<Record<string, readonly string[]>> = {\n path: PATH_ALIASES,\n start_line: ['startLine', 'line_start', 'from_line', 'start', 'line'],\n end_line: ['endLine', 'line_end', 'to_line', 'end'],\n start_text: ['startText', 'anchor', 'start_anchor', 'first_line'],\n end_text: ['endText', 'end_anchor', 'last_line'],\n new_text: ['newText', 'new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],\n}\n\nexport const LINE_EDIT_NATIVE_ALIASES: Readonly<Record<string, readonly string[]>> = {\n file_path: NATIVE_PATH_ALIASES,\n start_line: ['startLine', 'line_start', 'from_line', 'start', 'line', 'offset'],\n end_line: ['endLine', 'line_end', 'to_line', 'end'],\n start_text: ['startText', 'anchor', 'start_anchor', 'first_line'],\n end_text: ['endText', 'end_anchor', 'last_line'],\n new_text: ['newText', 'new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],\n}\n\nexport interface RawLineEditHunk {\n readonly start_line: number\n readonly end_line: number\n readonly start_text?: string\n readonly end_text?: string\n readonly new_text: string\n}\n\nexport interface ResolvedLineEdit {\n readonly index: number\n readonly requestedStart: number\n readonly requestedEnd: number\n readonly startLine: number\n readonly endLine: number\n readonly newLines: readonly string[]\n readonly removed: number\n readonly added: number\n readonly strippedLineNumbers: boolean\n readonly reindented: boolean\n readonly alignedNote?: string\n readonly anchorVerified: boolean\n readonly endAnchorVerified: boolean\n}\n\nexport interface BatchLineEditResult {\n readonly content: string\n readonly before: readonly string[]\n readonly after: readonly string[]\n readonly hunks: readonly ResolvedLineEdit[]\n readonly totalRemoved: number\n readonly totalAdded: number\n}\n\nexport interface ApplyLineEditsOptions {\n /** Enable \u00B115 local and whole-file unique `start_text` self-healing + indent alignment (default true). */\n readonly selfHeal?: boolean\n}\n\n// --- Normalization & anchor helpers -----------------------------------------\n\nconst TRIVIAL_ANCHORS = new Set([\n '{', '}', '(', ')', '[', ']', '},', '],', ');', '};',\n 'else:', 'else {', '} else {', 'try:', 'try {', 'finally:', 'finally {',\n 'pass', 'break', 'continue', 'return', 'return;', 'return None', 'return true', 'return false',\n 'end', 'fi', 'done', 'esac',\n])\n\nconst ELISION_LINE = /^\\s*(?:\\/\\/|#|\\/\\*|--|<!--)?\\s*(?:\\.\\.\\.|\u2026)\\s*(?:existing|unchanged|rest|remaining|omitted|same|code|lines|more|snip|truncated)?[^\\n]{0,40}(?:\\*\\/|-->)?\\s*$/i\n\nconst NUMBERED_PREFIX = /^(\\d+): ?(.*)$/\n\nfunction indentOf(line: string): string {\n return /^[ \\t]*/.exec(line)?.[0] ?? ''\n}\n\nfunction normalizeAnchorLine(line: string): string {\n return line\n .normalize('NFKC')\n .replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n .replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n .replace(/[\\u2010-\\u2015\\u2212]/g, '-')\n .replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nfunction stripOptionalLinePrefix(text: string): string {\n const m = /^\\s*\\d+:\\s?(.*)$/.exec(text)\n return m ? m[1]! : text\n}\n\n/** True when `anchor` carries enough semantic content to uniquely verify a target line. */\nexport function isNonTrivialAnchor(anchor: string | undefined, minLen = 8): boolean {\n if (typeof anchor !== 'string') return false\n const cleaned = normalizeAnchorLine(stripOptionalLinePrefix(anchor))\n if (cleaned.length < minLen) return false\n if (TRIVIAL_ANCHORS.has(cleaned)) return false\n return /[A-Za-z0-9_\\u4e00-\\u9fff]{3,}/.test(cleaned)\n}\n\nfunction lineAnchorScore(anchor: string, fileLine: string): number {\n const raw = stripOptionalLinePrefix(anchor)\n const a = normalizeAnchorLine(raw)\n const b = normalizeAnchorLine(fileLine)\n if (a === '' && b === '') return 1\n if (a === '' || b === '') return 0\n if (a === b) return 1\n // Allow truncated prefix anchors (model quoted first >= 16 chars of a long line).\n if (a.length >= 16 && b.startsWith(a)) return 0.96\n return similarity(a, b)\n}\n\nfunction newLinesOf(text: string): string[] {\n if (text === '') return []\n const normalized = text.replace(/\\r\\n/g, '\\n')\n return (normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized).split('\\n')\n}\n\n/**\n * Strip accidentally copied `N: ` line-number prefixes from `new_text` when\n * every non-empty line carries a sequential prefix near `startLine` and the\n * original file doesn't use literal `N: ` lines there.\n */\nfunction stripNumberedReplacement(\n newLines: readonly string[],\n startLine: number,\n before: readonly string[],\n): { readonly lines: string[]; readonly stripped: boolean } {\n if (newLines.length === 0) return { lines: [], stripped: false }\n const existingNear = before.slice(Math.max(0, startLine - 2), Math.min(before.length, startLine + 2))\n if (existingNear.some(line => NUMBERED_PREFIX.test(line))) {\n return { lines: [...newLines], stripped: false }\n }\n const out: string[] = []\n let expected: number | undefined\n let numberedCount = 0\n for (const line of newLines) {\n if (line === '') {\n out.push('')\n if (expected !== undefined) expected++\n continue\n }\n const m = NUMBERED_PREFIX.exec(line)\n if (!m) return { lines: [...newLines], stripped: false }\n const num = Number(m[1])\n if (expected === undefined) {\n if (Math.abs(num - startLine) > 20) return { lines: [...newLines], stripped: false }\n expected = num + 1\n } else {\n if (num !== expected) return { lines: [...newLines], stripped: false }\n expected++\n }\n numberedCount++\n out.push(m[2]!)\n }\n if (numberedCount === 0 || (numberedCount === 1 && newLines.length > 1)) {\n return { lines: [...newLines], stripped: false }\n }\n return { lines: out, stripped: true }\n}\n\nfunction pickUniqueAnchorHit(\n hits: readonly { readonly ln: number; readonly score: number }[],\n): { readonly kind: 'unique'; readonly ln: number } | { readonly kind: 'ambiguous'; readonly lines: readonly number[] } | { readonly kind: 'none' } {\n if (hits.length === 0) return { kind: 'none' }\n const exact = hits.filter(h => h.score >= 0.98)\n if (exact.length === 1) return { kind: 'unique', ln: exact[0]!.ln }\n if (exact.length > 1) return { kind: 'ambiguous', lines: exact.map(h => h.ln) }\n const sorted = [...hits].sort((a, b) => b.score - a.score)\n const best = sorted[0]!\n const runner = sorted[1]\n if (best.score >= 0.90 && (!runner || runner.score <= best.score - 0.08)) {\n return { kind: 'unique', ln: best.ln }\n }\n return { kind: 'ambiguous', lines: sorted.slice(0, 4).map(h => h.ln) }\n}\n\nfunction refineEndLineWithEndText(\n before: readonly string[],\n resolvedStart: number,\n resolvedEnd: number,\n endText: string,\n allowSelfHeal: boolean,\n): { readonly ok: true; readonly endLine: number; readonly note?: string } | { readonly ok: false } {\n if (resolvedEnd < resolvedStart || resolvedEnd > before.length) return { ok: false }\n if (lineAnchorScore(endText, before[resolvedEnd - 1]!) >= 0.90) {\n return { ok: true, endLine: resolvedEnd }\n }\n if (!allowSelfHeal) return { ok: false }\n const lo = Math.max(resolvedStart, resolvedEnd - END_ANCHOR_SEARCH_RADIUS)\n const hi = Math.min(before.length, resolvedEnd + END_ANCHOR_SEARCH_RADIUS)\n const hits: { ln: number; score: number }[] = []\n for (let ln = lo; ln <= hi; ln++) {\n const score = lineAnchorScore(endText, before[ln - 1]!)\n if (score >= 0.90) hits.push({ ln, score })\n }\n const picked = pickUniqueAnchorHit(hits)\n if (picked.kind === 'unique') {\n return {\n ok: true,\n endLine: picked.ln,\n note: `Auto-aligned edit end_line ${resolvedEnd} -> ${picked.ln} via end_text.`,\n }\n }\n return { ok: false }\n}\n\nfunction resolveSingleHunk(\n before: readonly string[],\n displayPath: string,\n edit: LineEdit,\n index: number,\n totalHunks: number,\n allowSelfHeal: boolean,\n): ResolvedLineEdit | string {\n const label = totalHunks > 1 ? `edit #${index + 1}` : 'edit'\n const { startLine: start, endLine: end } = edit\n const total = before.length\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {\n return `${label}: start_line and end_line must be whole numbers`\n }\n if (start < 1) return `${label}: start_line must be 1 or more (got ${start})`\n if (start > total + 1) return `${label}: start_line ${start} is past the end: ${displayPath} has ${total} lines`\n if (end > total) return `${label}: end_line ${end} is past the end: ${displayPath} has ${total} lines`\n if (end < start - 1) {\n return `${label}: end_line ${end} is before start_line ${start}; use end_line = start_line - 1 to insert without replacing`\n }\n\n const isInsert = end === start - 1\n const rawAnchor = typeof edit.startText === 'string' ? edit.startText : ''\n const hasAnchor = rawAnchor.trim() !== ''\n\n let resolvedStart = start\n let resolvedEnd = end\n let alignedNote: string | undefined\n let anchorVerified = false\n let endAnchorVerified = false\n let matchedAnchorLine: string | undefined\n\n if (hasAnchor && total > 0) {\n const anchorTargetLine = isInsert ? (start <= total ? start : total) : start\n const directLine = before[anchorTargetLine - 1]\n if (directLine !== undefined && lineAnchorScore(rawAnchor, directLine) >= 0.90) {\n anchorVerified = true\n matchedAnchorLine = directLine\n } else if (allowSelfHeal) {\n // Tier 2: local \u00B115 line window search.\n const lo = Math.max(1, anchorTargetLine - ANCHOR_SEARCH_RADIUS)\n const hi = Math.min(total, anchorTargetLine + ANCHOR_SEARCH_RADIUS)\n const localHits: { ln: number; score: number }[] = []\n for (let ln = lo; ln <= hi; ln++) {\n const score = lineAnchorScore(rawAnchor, before[ln - 1]!)\n if (score >= 0.90) localHits.push({ ln, score })\n }\n const localExactHits = localHits.filter(h => h.score >= 0.98)\n const localPick = pickUniqueAnchorHit(localHits)\n const localIsExact = localExactHits.length === 1 && localPick.kind === 'unique' && localPick.ln === localExactHits[0]!.ln\n\n if (localIsExact) {\n const shift = localPick.ln - anchorTargetLine\n const nextStart = start + shift\n const nextEnd = end + shift\n if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {\n resolvedStart = nextStart\n resolvedEnd = nextEnd\n anchorVerified = true\n matchedAnchorLine = before[localPick.ln - 1]\n alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via start_text.`\n }\n } else if (localExactHits.length > 1) {\n const win = renderWindow(displayPath, before, Math.max(1, anchorTargetLine - ERROR_WINDOW_RADIUS), Math.min(total, anchorTargetLine + ERROR_WINDOW_RADIUS))\n return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine}, and matched multiple nearby lines (${localExactHits.map(h => h.ln).join(', ')}).\\n\\nCurrent lines around line ${anchorTargetLine}:\\n${win}`\n }\n\n // Tier 3: whole-file unique fallback for non-trivial anchors (len >= 10) \u2014 exact file-wide match beats a fuzzy local hit.\n if (!anchorVerified && isNonTrivialAnchor(rawAnchor, MIN_WHOLE_FILE_ANCHOR_LEN)) {\n const globalHits: { ln: number; score: number }[] = []\n for (let ln = 1; ln <= total; ln++) {\n const score = lineAnchorScore(rawAnchor, before[ln - 1]!)\n if (score >= 0.92) globalHits.push({ ln, score })\n }\n const globalExact = globalHits.filter(h => h.score >= 0.98)\n const globalPick = pickUniqueAnchorHit(globalHits)\n if (globalPick.kind === 'unique' && (globalExact.length === 1 || localPick.kind !== 'unique')) {\n const shift = globalPick.ln - anchorTargetLine\n const nextStart = start + shift\n const nextEnd = end + shift\n if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {\n resolvedStart = nextStart\n resolvedEnd = nextEnd\n anchorVerified = true\n matchedAnchorLine = before[globalPick.ln - 1]\n alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via unique file-wide start_text.`\n }\n }\n }\n\n // Accept unique fuzzy local match if no exact file-wide match superseded it.\n if (!anchorVerified && localPick.kind === 'unique') {\n const shift = localPick.ln - anchorTargetLine\n const nextStart = start + shift\n const nextEnd = end + shift\n if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {\n resolvedStart = nextStart\n resolvedEnd = nextEnd\n anchorVerified = true\n matchedAnchorLine = before[localPick.ln - 1]\n alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via start_text.`\n }\n }\n\n if (!anchorVerified) {\n const win = renderWindow(displayPath, before, Math.max(1, anchorTargetLine - ERROR_WINDOW_RADIUS), Math.min(total, anchorTargetLine + ERROR_WINDOW_RADIUS))\n const extraMatches: string[] = []\n for (let ln = 1; ln <= total; ln++) {\n if (lineAnchorScore(rawAnchor, before[ln - 1]!) >= 0.80) {\n extraMatches.push(` ${ln}: ${before[ln - 1]!}`)\n if (extraMatches.length >= 4) break\n }\n }\n const candHint = extraMatches.length > 0\n ? `\\nMatching lines elsewhere in ${displayPath}:\\n${extraMatches.join('\\n')}`\n : ''\n return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine} (${JSON.stringify(before[anchorTargetLine - 1]?.trim() ?? '')}).${candHint}\\n\\nCurrent lines around line ${anchorTargetLine}:\\n${win}`\n }\n } else {\n const win = renderWindow(displayPath, before, Math.max(1, start - ERROR_WINDOW_RADIUS), Math.min(total, Math.max(end, start) + ERROR_WINDOW_RADIUS))\n return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine} (${JSON.stringify(before[anchorTargetLine - 1]?.trim() ?? '')}).\\n${win}`\n }\n }\n\n // Optional `end_text` verification & end-line drift auto-alignment for multi-line spans.\n if (!isInsert && typeof edit.endText === 'string' && edit.endText.trim() !== '') {\n const endCheck = refineEndLineWithEndText(before, resolvedStart, resolvedEnd, edit.endText, allowSelfHeal)\n if (!endCheck.ok) {\n const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 3), Math.min(total, resolvedEnd + ERROR_WINDOW_RADIUS))\n return `Your ${label} in ${displayPath} was NOT applied: end_text (${JSON.stringify(edit.endText.trim())}) did not match line ${resolvedEnd} (${JSON.stringify(before[resolvedEnd - 1]?.trim() ?? '')}).\\n\\nCurrent lines around line ${resolvedEnd}:\\n${win}`\n }\n resolvedEnd = endCheck.endLine\n endAnchorVerified = true\n if (endCheck.note) {\n alignedNote = alignedNote ? `${alignedNote} ${endCheck.note}` : endCheck.note\n }\n }\n\n const rawNewLines = newLinesOf(edit.newText)\n const { lines: strippedLines, stripped: strippedLineNumbers } = stripNumberedReplacement(rawNewLines, resolvedStart, before)\n let newLines = strippedLines\n let reindented = false\n\n // Auto-align base indentation only when `start_text` itself carried non-empty\n // leading whitespace (so trimmed anchors never push column-0 additions into an\n // indented block).\n if (allowSelfHeal && matchedAnchorLine !== undefined && newLines.length > 0 && hasAnchor) {\n const anchorWithoutPrefix = stripOptionalLinePrefix(rawAnchor)\n const oldIndent = indentOf(anchorWithoutPrefix)\n const fileIndent = indentOf(matchedAnchorLine)\n const firstNonBlank = newLines.find(line => line.trim() !== '')\n if (\n oldIndent !== fileIndent\n && firstNonBlank !== undefined\n && oldIndent.length > 0\n && firstNonBlank.startsWith(oldIndent)\n ) {\n const moved = reindent(newLines.join('\\n'), [[oldIndent, fileIndent]]).split('\\n')\n if (moved.join('\\n') !== newLines.join('\\n')) {\n newLines = moved\n reindented = true\n }\n }\n }\n\n const removedSlice = before.slice(resolvedStart - 1, resolvedEnd)\n const oldTrimmedSet = new Set(removedSlice.map(line => line.trim()))\n for (const nl of newLines) {\n if (ELISION_LINE.test(nl) && !oldTrimmedSet.has(nl.trim())) {\n return `Your ${label} in ${displayPath} was NOT applied: new_text contains an elision placeholder (${JSON.stringify(nl.trim())}), which would delete code. Narrow start_line..end_line to only the lines changing and write complete replacement code.`\n }\n }\n\n if (removedSlice.length === newLines.length && removedSlice.every((line, i) => line === newLines[i])) {\n const spanStr = resolvedStart === resolvedEnd ? `line ${resolvedStart}` : `lines ${resolvedStart}-${resolvedEnd}`\n return `No edit needed in ${displayPath}: new_text is the same as ${spanStr}; nothing changed.`\n }\n\n // Off-by-one boundary duplication guard: catches accidentally duplicating untouched line start-1 or end+1.\n if (newLines.length >= 2 && resolvedStart > 1) {\n const above = before[resolvedStart - 2]!.trim()\n if (above.length >= 8 && newLines[0]!.trim() === above && !oldTrimmedSet.has(above)) {\n const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 4), Math.min(total, Math.max(resolvedEnd, resolvedStart) + 4))\n return `Your ${label} in ${displayPath} was NOT applied: the first line of new_text duplicates line ${resolvedStart - 1} (${JSON.stringify(above)}) immediately above start_line=${resolvedStart}. Drop that unchanged line from new_text or adjust start_line.\\n\\n${win}`\n }\n }\n if (newLines.length >= 2 && resolvedEnd < total) {\n const below = before[resolvedEnd]!.trim()\n if (below.length >= 8 && newLines[newLines.length - 1]!.trim() === below && !oldTrimmedSet.has(below)) {\n const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 4), Math.min(total, Math.max(resolvedEnd, resolvedStart) + 4))\n return `Your ${label} in ${displayPath} was NOT applied: the last line of new_text duplicates line ${resolvedEnd + 1} (${JSON.stringify(below)}) immediately below end_line=${resolvedEnd}. Drop that unchanged line from new_text or adjust end_line.\\n\\n${win}`\n }\n }\n\n return {\n index,\n requestedStart: start,\n requestedEnd: end,\n startLine: resolvedStart,\n endLine: resolvedEnd,\n newLines,\n removed: removedSlice.length,\n added: newLines.length,\n strippedLineNumbers,\n reindented,\n ...(alignedNote ? { alignedNote } : {}),\n anchorVerified,\n endAnchorVerified,\n }\n}\n\nfunction hunksOverlap(a: ResolvedLineEdit, b: ResolvedLineEdit): boolean {\n const aInsert = a.endLine < a.startLine\n const bInsert = b.endLine < b.startLine\n if (aInsert && bInsert) return a.startLine === b.startLine\n if (aInsert) return a.startLine > b.startLine && a.startLine <= b.endLine\n if (bInsert) return b.startLine > a.startLine && b.startLine <= a.endLine\n return a.startLine <= b.endLine && b.startLine <= a.endLine\n}\n\n/**\n * Atomically resolve and apply one or more non-overlapping anchored line edits\n * against pre-edit file coordinates. Returns either the full batch result or a\n * model-facing error string.\n */\nexport function applyAnchoredLineEdits(\n text: string,\n displayPath: string,\n edits: readonly LineEdit[],\n options: ApplyLineEditsOptions = {},\n): BatchLineEditResult | string {\n if (edits.length === 0) return 'edits must contain at least one edit hunk'\n const allowSelfHeal = options.selfHeal !== false\n const { eol, trailingNewline, lines: before } = splitDocumentLines(text)\n\n const resolved: ResolvedLineEdit[] = []\n for (let i = 0; i < edits.length; i++) {\n const out = resolveSingleHunk(before, displayPath, edits[i]!, i, edits.length, allowSelfHeal)\n if (typeof out === 'string') return out\n resolved.push(out)\n }\n\n // Overlap check across all resolved pre-edit ranges.\n const sortedAsc = [...resolved].sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine)\n for (let i = 1; i < sortedAsc.length; i++) {\n if (hunksOverlap(sortedAsc[i - 1]!, sortedAsc[i]!)) {\n return `Your batch edit in ${displayPath} was NOT applied: edit #${sortedAsc[i - 1]!.index + 1} (lines ${sortedAsc[i - 1]!.startLine}-${sortedAsc[i - 1]!.endLine}) overlaps edit #${sortedAsc[i]!.index + 1} (lines ${sortedAsc[i]!.startLine}-${sortedAsc[i]!.endLine}). Combine overlapping edits into one range.`\n }\n }\n\n // Apply bottom-up so earlier pre-edit line numbers stay valid.\n const after = [...before]\n const sortedDesc = [...sortedAsc].reverse()\n for (const h of sortedDesc) {\n after.splice(h.startLine - 1, h.removed, ...h.newLines)\n }\n\n const content = joinDocumentLines(after, eol, trailingNewline, before.length === 0)\n const totalRemoved = resolved.reduce((acc, h) => acc + h.removed, 0)\n const totalAdded = resolved.reduce((acc, h) => acc + h.added, 0)\n return { content, before, after, hunks: sortedAsc, totalRemoved, totalAdded }\n}\n\n/** Backward-compatible single-hunk entry point (`applyLineEdit`). */\nexport function applyLineEdit(\n text: string,\n displayPath: string,\n edit: LineEdit,\n options: ApplyLineEditsOptions = {},\n): LineEditResult | string {\n const batch = applyAnchoredLineEdits(text, displayPath, [edit], options)\n if (typeof batch === 'string') return batch\n const h = batch.hunks[0]!\n return {\n content: batch.content,\n before: batch.before,\n after: batch.after,\n removed: h.removed,\n added: h.added,\n resolvedStart: h.startLine,\n resolvedEnd: h.endLine,\n ...(h.alignedNote ? { alignedNote: h.alignedNote } : {}),\n anchorVerified: h.anchorVerified,\n strippedLineNumbers: h.strippedLineNumbers,\n reindented: h.reindented,\n }\n}\n\n// --- Summaries & syntax-error messages --------------------------------------\n\nfunction resultWindow(displayPath: string, start: number, added: number, after: readonly string[]): string {\n return renderWindow(\n displayPath,\n after,\n start - LINE_EDIT_CONTEXT_LINES,\n start + Math.max(added, 1) - 1 + LINE_EDIT_CONTEXT_LINES,\n )\n}\n\n/** Model-facing result of an applied single coordinate line edit. */\nexport function editSummary(displayPath: string, edit: LineEdit, result: LineEditResult): string {\n const start = result.resolvedStart ?? edit.startLine\n const end = result.resolvedEnd ?? edit.endLine\n const { removed, added } = result\n let what: string\n if (removed === 0) what = start > 1 ? `Inserted ${pluralLines(added)} after line ${start - 1}` : `Inserted ${pluralLines(added)} at the start`\n else if (added === 0) what = `Deleted lines ${start}-${end}`\n else what = `Replaced lines ${start}-${end} with ${pluralLines(added)}`\n const parts = [`File updated. ${what}.`]\n if (result.alignedNote) parts.push(`(${result.alignedNote})`)\n if (result.strippedLineNumbers) parts.push('(Stripped copied line-number prefixes from new_text.)')\n if (result.reindented) parts.push('(Auto-aligned indentation to match the file.)')\n const delta = added - removed\n if (delta !== 0 && end < result.before.length) {\n parts.push(`Lines after it moved ${delta > 0 ? 'down' : 'up'} by ${Math.abs(delta)}: old line ${end + 1} is now line ${end + 1 + delta}.`)\n }\n parts.push('Review the change (correct indentation, no duplicate or missing lines) and edit again if necessary.')\n return `${parts.join(' ')}\\n${resultWindow(displayPath, start, added, result.after)}`\n}\n\n/** Model-facing result of an applied atomic multi-hunk (or single-hunk) edit. */\nexport function batchEditSummary(displayPath: string, batch: BatchLineEditResult): string {\n if (batch.hunks.length === 1) {\n const h = batch.hunks[0]!\n return editSummary(\n displayPath,\n { startLine: h.startLine, endLine: h.endLine, newText: h.newLines.join('\\n') },\n {\n content: batch.content,\n before: batch.before,\n after: batch.after,\n removed: h.removed,\n added: h.added,\n resolvedStart: h.startLine,\n resolvedEnd: h.endLine,\n ...(h.alignedNote ? { alignedNote: h.alignedNote } : {}),\n anchorVerified: h.anchorVerified,\n strippedLineNumbers: h.strippedLineNumbers,\n reindented: h.reindented,\n },\n )\n }\n const notes: string[] = []\n let cumulativeDelta = 0\n const windows: string[] = []\n for (const h of batch.hunks) {\n const postStart = h.startLine + cumulativeDelta\n if (h.alignedNote) notes.push(h.alignedNote)\n if (h.strippedLineNumbers) notes.push(`Stripped copied line-number prefixes in edit #${h.index + 1}.`)\n if (h.reindented) notes.push(`Auto-aligned indentation in edit #${h.index + 1}.`)\n windows.push(resultWindow(displayPath, postStart, h.added, batch.after))\n cumulativeDelta += h.added - h.removed\n }\n const parts = [`File updated with ${batch.hunks.length} atomic edits (${pluralLines(batch.totalRemoved)} removed, ${pluralLines(batch.totalAdded)} added).`]\n if (notes.length > 0) parts.push(`(${notes.join(' ')})`)\n parts.push('Review the updated windows below and edit again if necessary.')\n return `${parts.join(' ')}\\n${windows.join('\\n\\n')}`\n}\n\n/** Model-facing refusal of a single edit that would break the file's syntax (not applied). */\nexport function syntaxRejection(displayPath: string, edit: LineEdit, result: LineEditResult, error: string): string {\n const start = result.resolvedStart ?? edit.startLine\n const end = result.resolvedEnd ?? edit.endLine\n const original = renderWindow(displayPath, result.before, start - LINE_EDIT_CONTEXT_LINES, Math.max(end, start) + LINE_EDIT_CONTEXT_LINES)\n return [\n 'Your edit was NOT applied: it introduces a syntax error.',\n `ERROR: ${error}`,\n '',\n 'This is how the file would have looked:',\n resultWindow(displayPath, start, result.added, result.after),\n '',\n 'This is the original code before your edit:',\n original,\n '',\n 'Fix start_line/end_line or new_text (check the indentation) and try again. Do not repeat the same edit.',\n ].join('\\n')\n}\n\n/** Model-facing refusal of a batch edit that would break the file's syntax (not applied). */\nexport function batchSyntaxRejection(displayPath: string, batch: BatchLineEditResult, error: string): string {\n if (batch.hunks.length === 1) {\n const h = batch.hunks[0]!\n return syntaxRejection(\n displayPath,\n { startLine: h.startLine, endLine: h.endLine, newText: h.newLines.join('\\n') },\n {\n content: batch.content,\n before: batch.before,\n after: batch.after,\n removed: h.removed,\n added: h.added,\n resolvedStart: h.startLine,\n resolvedEnd: h.endLine,\n },\n error,\n )\n }\n const first = batch.hunks[0]!\n const last = batch.hunks[batch.hunks.length - 1]!\n const delta = batch.totalAdded - batch.totalRemoved\n const afterWin = renderWindow(displayPath, batch.after, first.startLine - LINE_EDIT_CONTEXT_LINES, last.endLine + delta + LINE_EDIT_CONTEXT_LINES)\n const beforeWin = renderWindow(displayPath, batch.before, first.startLine - LINE_EDIT_CONTEXT_LINES, last.endLine + LINE_EDIT_CONTEXT_LINES)\n return [\n `Your batch edit (${batch.hunks.length} hunks) was NOT applied: it introduces a syntax error.`,\n `ERROR: ${error}`,\n '',\n 'This is how the file would have looked:',\n afterWin,\n '',\n 'This is the original code before your edit:',\n beforeWin,\n '',\n 'Fix the affected hunk(s) and try again. Do not repeat the same edit.',\n ].join('\\n')\n}\n\n// --- Argument parsing & normalization (batch + single-hunk shorthand) -------\n\nfunction toSafeInt(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value)\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value.replace(/,/g, '').trim())\n if (Number.isFinite(parsed)) return Math.trunc(parsed)\n }\n return undefined\n}\n\nfunction normalizeRawHunk(raw: unknown): RawLineEditHunk | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const obj = raw as Record<string, unknown>\n const sl = toSafeInt(obj.start_line ?? obj.startLine ?? obj.line_start ?? obj.from_line ?? obj.start ?? obj.line)\n const el = toSafeInt(obj.end_line ?? obj.endLine ?? obj.line_end ?? obj.to_line ?? obj.end)\n const ntRaw = obj.new_text ?? obj.newText ?? obj.new_string ?? obj.new_str ?? obj.text ?? obj.content ?? obj.replacement ?? obj.lines\n if (sl === undefined || el === undefined || typeof ntRaw !== 'string') return undefined\n const stRaw = obj.start_text ?? obj.startText ?? obj.anchor ?? obj.start_anchor ?? obj.first_line\n const etRaw = obj.end_text ?? obj.endText ?? obj.end_anchor ?? obj.last_line\n return {\n start_line: sl,\n end_line: el,\n ...(typeof stRaw === 'string' ? { start_text: stRaw } : {}),\n ...(typeof etRaw === 'string' ? { end_text: etRaw } : {}),\n new_text: ntRaw,\n }\n}\n\n/**\n * Parse either canonical batch `edits[]` (array, single object, or JSON string)\n * or single-hunk top-level `{ start_line, end_line, start_text?, end_text?, new_text }`\n * into normalized `LineEdit[]` hunks.\n */\nexport function parseLineEditHunks(args: Record<string, unknown>): LineEdit[] | string {\n if (args.edits !== undefined) {\n let source: unknown = args.edits\n if (typeof source === 'string') {\n try {\n source = JSON.parse(source)\n } catch {\n return 'edits must be a valid JSON array of edit hunks'\n }\n }\n const items = Array.isArray(source) ? source : (typeof source === 'object' && source !== null ? [source] : undefined)\n if (!items || items.length === 0) return 'edits must be a non-empty array of { start_line, end_line, start_text?, new_text } hunks'\n const out: LineEdit[] = []\n for (let i = 0; i < items.length; i++) {\n const normalized = normalizeRawHunk(items[i])\n if (normalized === undefined) {\n return `edits[${i}] is missing required start_line, end_line, or new_text`\n }\n out.push({\n startLine: normalized.start_line,\n endLine: normalized.end_line,\n ...(normalized.start_text !== undefined ? { startText: normalized.start_text } : {}),\n ...(normalized.end_text !== undefined ? { endText: normalized.end_text } : {}),\n newText: normalized.new_text,\n })\n }\n return out\n }\n\n const single = normalizeRawHunk(args)\n if (single === undefined) {\n return 'Provide either edits: [{ start_line, end_line, start_text, new_text }] or single-hunk start_line, end_line, new_text'\n }\n return [{\n startLine: single.start_line,\n endLine: single.end_line,\n ...(single.start_text !== undefined ? { startText: single.start_text } : {}),\n ...(single.end_text !== undefined ? { endText: single.end_text } : {}),\n newText: single.new_text,\n }]\n}\n\n/** Normalize raw model arguments for `edit_lines` (`edits[]` or single-hunk shorthand) into clean wire/DSH args. */\nexport function normalizeLineEditArgs(args: Record<string, unknown>): Record<string, unknown> {\n if (args.edits === undefined) return args\n let source: unknown = args.edits\n if (typeof source === 'string') {\n try { source = JSON.parse(source) } catch { return args }\n }\n const items = Array.isArray(source) ? source : (typeof source === 'object' && source !== null ? [source] : undefined)\n if (!items || items.length === 0) return args\n const normalized = items.map(item => normalizeRawHunk(item) ?? item)\n return { ...args, edits: normalized }\n}\n", "// Per-session tracker of files whose earlier `read` or `write` output was\n// folded out of the active context window and has not yet been re-read.\n\nconst MAX_TRACKED_SESSIONS = 512\nconst foldedUnreadBySession = new Map<string, ReadonlySet<string>>()\n\nexport function setFoldedUnreadPaths(sessionId: string | undefined, paths: readonly string[]): void {\n if (sessionId === undefined || sessionId === '') return\n if (paths.length === 0) {\n foldedUnreadBySession.delete(sessionId)\n return\n }\n if (foldedUnreadBySession.has(sessionId)) foldedUnreadBySession.delete(sessionId)\n foldedUnreadBySession.set(sessionId, new Set(paths))\n while (foldedUnreadBySession.size > MAX_TRACKED_SESSIONS) {\n const oldest = foldedUnreadBySession.keys().next().value\n if (oldest === undefined) break\n foldedUnreadBySession.delete(oldest)\n }\n}\n\nexport function isFoldedUnreadPath(sessionId: string | undefined, candidates: readonly (string | undefined)[]): boolean {\n if (sessionId === undefined || sessionId === '') return false\n const blocked = foldedUnreadBySession.get(sessionId)\n if (blocked === undefined || blocked.size === 0) return false\n return candidates.some(candidate => candidate !== undefined && candidate !== '' && blocked.has(candidate))\n}\n\nexport function foldedUnreadErrorMessage(displayPath: string, toolName = 'edit'): string {\n return `The earlier read output for ${displayPath} was folded out of the active context window. `\n + `Call \\`read\\` on ${displayPath} again to inspect its current content before calling \\`${toolName}\\`.`\n}\n", "// Shared session file-version and visible-line observation store used by the\n// `line-edit` DSH tool plugin. Persists per-file versions and\n// seen line numbers in session plugin records (`plugin:rwkv-edit-lines/observed`)\n// so process-per-turn evaluators keep read state across resumed turns, while\n// enforcing `folded-read-guard` when earlier `read` outputs were folded out.\n\nimport { resolve } from 'node:path'\nimport { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'\nimport { addSeen, type SeenLines } from '../core/edit-modes/shared.ts'\nimport { ensureExecWorkingDir, sessionIdOfExec, type AgentLike } from '../dsh-host.ts'\nimport { READ_SHOWN_EVENT } from '../result-budget.ts'\nimport { foldedUnreadErrorMessage, isFoldedUnreadPath } from './folded-read-guard.ts'\n\nexport const EDIT_LINES_TOOL = 'edit_lines'\n\nexport interface FsTargetLike {\n readonly displayPath: string\n readonly targetKey: string\n}\n\nexport type Observation =\n | { readonly kind: 'present'; readonly version: unknown }\n | { readonly kind: 'absent' }\n\nexport interface FsLike {\n resolve(path: string, options: { cwd?: string; signal?: AbortSignal }): Promise<FsTargetLike>\n readText(target: FsTargetLike, signal?: AbortSignal): Promise<string>\n writeText(\n target: FsTargetLike,\n content: string,\n expected?: unknown,\n signal?: AbortSignal,\n sandboxPolicy?: unknown,\n ): Promise<{ version: unknown }>\n processPath(target: FsTargetLike): string\n}\n\nexport interface LineEditExecLike {\n readonly name?: string\n readonly agent?: AgentLike\n readonly signal?: AbortSignal\n}\n\nexport interface LineEditHostContext {\n readonly fs: FsLike\n readonly tools: { register(definition: unknown): () => void }\n on(event: 'fs/observed', listener: (target: FsTargetLike, observation: Observation, actor: LineEditExecLike | undefined) => void): () => void\n on(event: typeof READ_SHOWN_EVENT, listener: (exec: LineEditExecLike, window: { first: number; last: number }) => void): () => void\n emit(event: 'fs/observed', target: FsTargetLike, observation: Observation, actor: LineEditExecLike): void\n effect?(fn: () => () => void): void\n get(name: string): unknown\n}\n\ninterface Seen {\n readonly observation: Observation\n lines: SeenLines\n}\n\nconst OBSERVED_RECORD = 'plugin:rwkv-edit-lines/observed'\n\ninterface PersistedObservation {\n readonly targetKey: string\n readonly observation: Observation\n readonly lines: 'all' | readonly number[]\n}\n\ninterface DecodedObservation {\n readonly targetKey: string\n readonly observation: Observation\n readonly lines: SeenLines\n}\n\ninterface SessionLike {\n snapshotEvents?(): readonly unknown[]\n}\n\nconst appendRecord = appendPluginRecord as unknown as (session: object, type: string, data: unknown) => unknown\nconst recordOf = pluginRecordOf as unknown as (event: unknown) => { type: string; data: unknown } | undefined\n\nconst encodeLines = (lines: SeenLines): 'all' | number[] =>\n lines === 'all' ? 'all' : [...lines].sort((a, b) => a - b)\n\nconst decodeLines = (value: unknown): SeenLines | undefined => {\n if (value === 'all') return 'all'\n if (!Array.isArray(value) || !value.every(n => typeof n === 'number' && Number.isSafeInteger(n))) return undefined\n return new Set(value as number[])\n}\n\nconst decodeObservation = (data: unknown): DecodedObservation | undefined => {\n if (typeof data !== 'object' || data === null) return undefined\n const { targetKey, observation, lines } = data as Record<string, unknown>\n if (typeof targetKey !== 'string' || targetKey === '') return undefined\n if (typeof observation !== 'object' || observation === null) return undefined\n const kind = (observation as { kind?: unknown }).kind\n if (kind !== 'present' && kind !== 'absent') return undefined\n if (kind === 'present' && (observation as { version?: unknown }).version == null) return undefined\n const decoded = decodeLines(lines)\n if (decoded === undefined) return undefined\n return { targetKey, observation: observation as Observation, lines: decoded }\n}\n\nconst sameVersion = (a: Observation | undefined, b: Observation): boolean =>\n a?.kind === 'present' && b.kind === 'present' && JSON.stringify(a.version) === JSON.stringify(b.version)\n\nexport class Observations {\n private readonly bySession = new WeakMap<object, Map<string, Seen>>()\n private readonly hydrated = new WeakSet<object>()\n private readonly readTargets = new WeakMap<object, { session: object; targetKey: string; before: SeenLines }>()\n\n private mapFor(session: object): Map<string, Seen> {\n let byTarget = this.bySession.get(session)\n if (byTarget === undefined) this.bySession.set(session, byTarget = new Map())\n return byTarget\n }\n\n hydrate(session: object): void {\n if (this.hydrated.has(session)) return\n this.hydrated.add(session)\n const events = (session as SessionLike).snapshotEvents?.()\n if (events === undefined) return\n for (const event of events) {\n const record = recordOf(event)\n if (record?.type !== OBSERVED_RECORD) continue\n const entry = decodeObservation(record.data)\n if (entry !== undefined) {\n this.mapFor(session).set(entry.targetKey, { observation: entry.observation, lines: entry.lines })\n }\n }\n }\n\n private persist(session: object, targetKey: string, seen: Seen): void {\n const data: PersistedObservation = {\n targetKey,\n observation: seen.observation,\n lines: encodeLines(seen.lines),\n }\n try {\n appendRecord(session, OBSERVED_RECORD, data)\n } catch (error) {\n if (!(error instanceof Error) || !error.message.includes('reenter')) return\n setTimeout(() => {\n try { appendRecord(session, OBSERVED_RECORD, data) } catch { /* stays in memory */ }\n }, 0)\n }\n }\n\n record(actor: LineEditExecLike | undefined, target: FsTargetLike, observation: Observation): void {\n const session = actor?.agent?.session\n if (session === undefined) return\n this.hydrate(session)\n const byTarget = this.mapFor(session)\n const previous = byTarget.get(target.targetKey)\n const seen: Seen = { observation, lines: 'all' }\n byTarget.set(target.targetKey, seen)\n if (actor !== undefined && actor.name === 'read') {\n const before: SeenLines = previous !== undefined && sameVersion(previous.observation, observation) ? previous.lines : new Set()\n this.readTargets.set(actor, { session, targetKey: target.targetKey, before })\n } else if (actor?.name !== EDIT_LINES_TOOL) {\n this.persist(session, target.targetKey, seen)\n }\n }\n\n shown(exec: LineEditExecLike, first: number, last: number): void {\n const read = this.readTargets.get(exec)\n if (read === undefined) return\n this.readTargets.delete(exec)\n const seen = this.bySession.get(read.session)?.get(read.targetKey)\n if (seen === undefined) return\n seen.lines = addSeen(read.before, first, last)\n this.persist(read.session, read.targetKey, seen)\n }\n\n setLines(actor: LineEditExecLike, target: FsTargetLike, lines: SeenLines): void {\n const session = actor.agent?.session\n if (session === undefined) return\n this.hydrate(session)\n const seen = this.bySession.get(session)?.get(target.targetKey)\n if (seen === undefined) return\n seen.lines = lines\n this.persist(session, target.targetKey, seen)\n }\n\n guard(actor: LineEditExecLike, target: FsTargetLike): { kind: 'replaceIfVersion'; version: unknown; lines: SeenLines } | string {\n const session = actor.agent?.session\n if (session === undefined) return { kind: 'replaceIfVersion', version: undefined, lines: 'all' }\n this.hydrate(session)\n const seen = this.bySession.get(session)?.get(target.targetKey)\n if (seen === undefined) return `cannot modify \"${target.displayPath}\": file has not been read \u2014 read the file, then retry`\n if (seen.observation.kind === 'absent') return `cannot edit \"${target.displayPath}\": not found \u2014 use write to create it`\n return { kind: 'replaceIfVersion', version: seen.observation.version, lines: seen.lines }\n }\n}\n\nexport function attachObservations(host: LineEditHostContext): Observations {\n const observations = new Observations()\n host.on('fs/observed', (target, observation, actor) => observations.record(actor, target, observation))\n host.on(READ_SHOWN_EVENT, (exec, window) => observations.shown(exec, window.first, window.last))\n return observations\n}\n\nexport async function resolveTargetWithGuards(\n host: LineEditHostContext,\n observations: Observations,\n rawFilePath: string,\n exec: LineEditExecLike,\n options?: { readonly allowFolded?: boolean },\n): Promise<{\n readonly target: FsTargetLike\n readonly guard: { kind: 'replaceIfVersion'; version: unknown; lines: SeenLines }\n readonly folded: boolean\n}> {\n if (typeof rawFilePath !== 'string' || rawFilePath.trim() === '') {\n throw new Error('file_path must be a non-empty string')\n }\n const cwd = await ensureExecWorkingDir(host, exec)\n const resolveOpts = { ...cwd !== undefined ? { cwd } : {}, ...exec.signal ? { signal: exec.signal } : {} }\n const target = await host.fs.resolve(rawFilePath, resolveOpts)\n const folded = isFoldedUnreadPath(sessionIdOfExec(exec), [\n host.fs.processPath(target),\n target.displayPath,\n ...(cwd !== undefined ? [resolve(cwd, rawFilePath.trim())] : []),\n ])\n if (folded && !options?.allowFolded) {\n throw new Error(foldedUnreadErrorMessage(target.displayPath, EDIT_LINES_TOOL))\n }\n const guard = observations.guard(exec, target)\n if (typeof guard === 'string') throw new Error(guard)\n return { target, guard, folded }\n}\n\nexport function remediateStaleVersion(error: unknown): unknown {\n if ((error as { code?: unknown } | null)?.code !== 'FS_STALE_VERSION') return error\n return new Error(`${(error as Error).message} \u2014 its line numbers may have moved; re-read the file, then retry`, { cause: error })\n}\n", "// Structural DSH host interfaces shared across `tolerant-edit.ts`,\n// `result-budget.ts`, and `line-edit.ts`. Kept free of `@deepseek-ai/*` runtime\n// imports so `rwkv-agent-pipeline` plugins can import hooks directly when\n// `/opt/dsh-rwkv-plugin/node_modules` is an empty tmpfs inside Docker.\n\nexport interface SandboxPolicyLike {\n resolve(request?: { session?: object }): unknown\n}\n\nexport interface SessionHeaderLike {\n readonly header?: { readonly id?: string }\n requestHeader?(): { config?: { provider?: string } } | undefined\n}\n\nexport interface AgentLike {\n readonly session?: SessionHeaderLike & object\n readonly options?: { readonly provider?: string }\n}\n\nexport interface ToolExecLike {\n readonly name: string\n readonly callId?: string\n readonly arguments?: unknown\n readonly parent?: unknown\n readonly agent?: AgentLike\n readonly signal?: AbortSignal\n}\n\nexport interface WorkingDirectoryServiceLike {\n ensure(agent: unknown, signal?: AbortSignal): Promise<string>\n}\n\nexport function providerOfExec(exec: { readonly agent?: AgentLike }): string | undefined {\n return exec.agent?.session?.requestHeader?.()?.config?.provider ?? exec.agent?.options?.provider\n}\n\nexport function sessionIdOfExec(exec: { readonly agent?: AgentLike }): string | undefined {\n return exec.agent?.session?.header?.id\n}\n\nexport async function ensureExecWorkingDir(\n host: { get(name: string): unknown },\n exec: { readonly agent?: unknown; readonly signal?: AbortSignal },\n): Promise<string | undefined> {\n const workingDirectory = host.get('workingDirectory') as WorkingDirectoryServiceLike | undefined\n if (exec.agent === undefined || workingDirectory === undefined) return undefined\n return workingDirectory.ensure(exec.agent, exec.signal)\n}\n", "// Active stateful work list (`todo_plan` + `todo_update`): tool definitions,\n// lenient field parsing, per-turn item state transitions, and Desktop\n// `TodoPanel` projection. Kept separate from the passive/checkpoint folding\n// engine (`fold-pairs.ts`, `fold-window.ts`, `worklist.ts`).\n\nexport const TODO_PLAN_TOOL = 'todo_plan'\nexport const TODO_UPDATE_TOOL = 'todo_update'\n\nexport const TODO_PLAN_DESCRIPTION =\n 'Create or revise the ordered work list for multi-step tasks (touching multiple methods/files, code + docs/tests, or 3+ distinct subgoals). '\n + 'Skip this tool for casual chat, quick single-goal lookups (1-3 reads or searches), or a trivial one-spot edit. '\n + 'For multi-step changes, you may inspect 1-2 files first to understand the layout, then call todo_plan BEFORE making your first file edit \u2014 do not wait until after editing to plan. '\n + 'Calling todo_plan mid-turn keeps completed/dropped items and their notes intact and replaces only unfinished items.'\n\nexport const TODO_UPDATE_DESCRIPTION =\n 'Update one item in the current work list by id. '\n + 'As soon as an item is finished, mark it completed with a concise factual note (<= 120 words: exact /app/... file paths, updated line ranges, signatures, and test exit codes \u2014 never mark unexecuted work completed). '\n + 'Older exploratory tool outputs before the recent workspace actions are folded once note is saved, while your initial todo_plan and the latest workspace results stay visible. '\n + 'The next pending item becomes in_progress automatically; you may also checkpoint an in_progress item with an interim note before context fills up.'\n\nexport const WORKLIST_TOOLS: ReadonlySet<string> = new Set([TODO_PLAN_TOOL, TODO_UPDATE_TOOL])\n\nexport function isWorklistTool(name: string): boolean {\n return WORKLIST_TOOLS.has(name)\n}\n\nexport type WorklistStatus = 'pending' | 'in_progress' | 'completed' | 'dropped'\n\nexport interface WorklistItem {\n readonly id: number\n readonly content: string\n readonly status: WorklistStatus\n readonly note?: string\n}\n\nexport interface TodoUpdateInput {\n readonly id?: unknown\n readonly status?: unknown\n readonly note?: unknown\n readonly content?: unknown\n}\n\nconst WORKLIST_PROTOCOL_TAG = /<\\/?(?:think|tool_call|tool_response)(?:\\s[^>]*)?>/gi\nconst WORKLIST_LEADING_BULLET = /^\\s*(?:\\[\\d+\\]|\\d+[.)]|[-*\u2022])\\s*/\n\nexport function sanitizeWorklistField(text: string): string {\n return text.replace(WORKLIST_PROTOCOL_TAG, '').replace(/\\s*\\n+\\s*/g, ' | ').trim()\n}\n\nexport function parsePlanItems(raw: unknown): string[] | undefined {\n if (Array.isArray(raw)) {\n const out: string[] = []\n for (const entry of raw) {\n if (typeof entry === 'string') {\n const cleaned = sanitizeWorklistField(entry.replace(WORKLIST_LEADING_BULLET, ''))\n if (cleaned !== '') out.push(cleaned)\n } else if (typeof entry === 'object' && entry !== null) {\n const obj = entry as Record<string, unknown>\n const candidate = obj.content ?? obj.title ?? obj.text ?? obj.step\n if (typeof candidate === 'string') {\n const cleaned = sanitizeWorklistField(candidate.replace(WORKLIST_LEADING_BULLET, ''))\n if (cleaned !== '') out.push(cleaned)\n }\n } else {\n return undefined\n }\n }\n return out\n }\n if (typeof raw === 'string') {\n const lines = raw\n .split(/\\r?\\n/)\n .map(line => sanitizeWorklistField(line.replace(WORKLIST_LEADING_BULLET, '')))\n .filter(line => line !== '')\n return lines.length > 0 ? lines : undefined\n }\n return undefined\n}\n\nexport function normalizeWorklistStatus(raw: unknown): WorklistStatus | undefined {\n if (typeof raw !== 'string') return undefined\n const lower = raw.trim().toLowerCase()\n if (lower === 'pending' || lower === 'todo' || lower === 'not_started') return 'pending'\n if (lower === 'in_progress' || lower === 'in-progress' || lower === 'doing' || lower === 'active') return 'in_progress'\n if (lower === 'completed' || lower === 'complete' || lower === 'done' || lower === 'finished') return 'completed'\n if (lower === 'dropped' || lower === 'cancelled' || lower === 'canceled' || lower === 'skipped') return 'dropped'\n return undefined\n}\n\n/** Whether `item` is a `todo_update` call that wrote a non-empty `note`. */\nexport function isNotedTodoUpdateCall(item: { readonly kind: string; readonly name?: string; readonly args?: Record<string, unknown> }): boolean {\n if (item.kind !== 'call' || item.name !== TODO_UPDATE_TOOL || item.args === undefined) return false\n const note = item.args.note ?? item.args.notes ?? item.args.summary ?? item.args.findings ?? item.args.conclusion\n return typeof note === 'string' && sanitizeWorklistField(note) !== ''\n}\n\n/**\n * Apply `todo_plan` to the current turn's list. Completed and dropped items\n * (and their notes) are locked and kept at the top; `rawItems` replaces only\n * the remaining unfinished queue, activating the first unfinished item.\n */\nexport function applyTodoPlan(current: readonly WorklistItem[], rawItems: unknown): WorklistItem[] | string {\n const parsed = parsePlanItems(rawItems)\n if (parsed === undefined || parsed.length === 0) {\n return 'items must be a non-empty array of step strings'\n }\n const locked = current\n .filter(item => item.status === 'completed' || item.status === 'dropped')\n .map((item, idx) => ({ ...item, id: idx + 1 }))\n const lockedTitles = new Set(locked.map(item => item.content))\n // If the model re-sent already completed titles at the top of `items`, skip\n // duplicating them because `locked` already preserves them with their notes.\n const remaining = parsed.filter(title => !lockedTitles.has(title))\n if (locked.length === 0 && remaining.length < 2) {\n return 'todo_plan requires at least 2 steps; execute single-step tasks directly without todo_plan'\n }\n if (remaining.length === 0) {\n return 'todo_plan requires at least 1 new unfinished step after completed items'\n }\n if (locked.length + remaining.length > 12) {\n return `todo_plan accepts at most 12 total items (got ${locked.length + remaining.length}); group micro-actions into coarser subgoals`\n }\n const seen = new Set<string>()\n for (const [idx, title] of remaining.entries()) {\n if (seen.has(title)) {\n return `items[${idx}] duplicates ${JSON.stringify(title)}`\n }\n seen.add(title)\n }\n const tail: WorklistItem[] = remaining.map((content, idx) => ({\n id: locked.length + idx + 1,\n content,\n status: idx === 0 ? 'in_progress' : 'pending',\n }))\n return [...locked, ...tail]\n}\n\n/**\n * Apply `todo_update` to one item by 1-based `id`. Requires a non-empty `note`\n * when closing an item (`completed` or `dropped`), keeps at most one item\n * `in_progress`, and automatically advances the next `pending` item when the\n * active item finishes.\n */\nexport function applyTodoUpdate(\n current: readonly WorklistItem[],\n input: TodoUpdateInput,\n): { items: WorklistItem[]; noted: boolean } | string {\n if (current.length === 0) {\n return 'no active todo list in this turn; call todo_plan first if this task has multiple subgoals'\n }\n const rawId = typeof input.id === 'string' ? Number(input.id.trim()) : input.id\n if (typeof rawId !== 'number' || !Number.isInteger(rawId) || rawId < 1 || rawId > current.length) {\n return `id must be an integer between 1 and ${current.length} (got ${JSON.stringify(input.id)})`\n }\n const status = normalizeWorklistStatus(input.status)\n if (status === undefined || status === 'pending') {\n return 'status must be one of: in_progress, completed, dropped'\n }\n const target = current[rawId - 1]!\n const providedNote = typeof input.note === 'string' ? sanitizeWorklistField(input.note) : ''\n const effectiveNote = providedNote !== '' ? providedNote : target.note\n if ((status === 'completed' || status === 'dropped') && (!effectiveNote || effectiveNote === '')) {\n return 'note is required when status is completed or dropped: record concrete findings, exact file paths/lines, applied edits, or test results'\n }\n const updatedContent = typeof input.content === 'string' && sanitizeWorklistField(input.content) !== ''\n ? sanitizeWorklistField(input.content)\n : target.content\n\n const next = current.map((item, index): WorklistItem => {\n if (index === rawId - 1) {\n return {\n id: item.id,\n content: updatedContent,\n status,\n ...effectiveNote ? { note: effectiveNote } : {},\n }\n }\n // Single-active discipline: focusing a later item auto-completes an earlier\n // active item that already recorded a note, and demotes an unnoted/later one.\n if (status === 'in_progress' && item.status === 'in_progress') {\n const autoDone = index < rawId - 1 && Boolean(item.note && item.note.trim() !== '')\n return { ...item, status: autoDone ? 'completed' : 'pending' }\n }\n return item\n })\n\n // Auto-advance: when no item is active anymore, promote the next pending item.\n if (!next.some(item => item.status === 'in_progress')) {\n const afterIdx = next.findIndex((item, idx) => idx > rawId - 1 && item.status === 'pending')\n const promoteIdx = afterIdx >= 0 ? afterIdx : next.findIndex(item => item.status === 'pending')\n if (promoteIdx >= 0) {\n next[promoteIdx] = { ...next[promoteIdx]!, status: 'in_progress' }\n }\n }\n\n return { items: next, noted: providedNote !== '' }\n}\n\n/** Model-facing rendering returned as the tool output of `todo_plan` and `todo_update`. */\nexport function formatWorklist(items: readonly WorklistItem[]): string {\n const lines = ['Todo list:']\n for (const item of items) {\n lines.push(`[${item.id}] (${item.status}) ${item.content}`)\n if (item.note) lines.push(` note: ${item.note}`)\n }\n return lines.join('\\n')\n}\n\n/**\n * Clean single-line projection mirrored onto DSH's native `todo/write` event for\n * the Desktop `TodoPanel` dock (omits long technical notes, and settles lingering\n * `in_progress` spinners to `pending` once `turn/end` fires).\n */\nexport function projectNativeTodos(\n items: readonly WorklistItem[],\n options?: { readonly turnEnded?: boolean },\n): { content: string; status: 'pending' | 'in_progress' | 'completed' }[] {\n const settleActive = options?.turnEnded === true\n return items.map(item => ({\n content: item.status === 'dropped'\n ? `[${item.id}] [\u5DF2\u8DF3\u8FC7] ${item.content}`\n : `[${item.id}] ${item.content}`,\n status: item.status === 'dropped'\n ? 'completed'\n : (settleActive && item.status === 'in_progress' ? 'pending' : item.status),\n }))\n}\n", "// Built-in RWKV <-> DSH tool mappings (`agent-tool-v3` wire shapes and\n// bidirectional argument converters).\n\nimport {\n normalizeWorklistStatus,\n parsePlanItems,\n TODO_PLAN_DESCRIPTION,\n TODO_PLAN_TOOL,\n TODO_UPDATE_DESCRIPTION,\n TODO_UPDATE_TOOL,\n} from './todo-state.ts'\n\nexport interface DshToolSchema {\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n}\n\nexport type Args = Record<string, unknown>\n\nexport interface WireTool {\n /** Name the model sees and calls. */\n readonly name: string\n readonly description: string\n /** Flat placeholder JSON object (or JSON string) shown in the catalog. */\n readonly arguments: string\n /** DSH tool that executes the call. */\n readonly dshName: string\n /** JSON Schema used for lenient scalar coercion of model arguments. */\n readonly schema?: Record<string, unknown>\n /** Shown under its DSH name with DSH arguments (names: 'dsh'). */\n readonly native?: boolean\n toDsh(args: Args): Args\n fromDsh(args: Args): Args\n}\n\nexport interface ToolMapping {\n readonly wireName: string\n readonly description: string\n readonly arguments: string\n readonly schema: Record<string, unknown>\n toDsh(args: Args): Args\n fromDsh(args: Args): Args\n}\n\nexport const nonEmptyStr = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() !== '' ? value : undefined\n\nexport const finiteInt = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined\n\nfunction stripUndefined(args: Args): Args {\n return Object.fromEntries(Object.entries(args).filter(([, value]) => value !== undefined))\n}\n\n/** Workspace-relative path; models trained on a sandbox emit /workspace/... and fabricated home paths. */\nexport function workspacePath(value: unknown): string | undefined {\n const path = nonEmptyStr(value)\n if (path === undefined) return undefined\n const index = path.lastIndexOf('workspace/')\n if (path.startsWith('/') && index >= 0) return path.slice(index + 'workspace/'.length) || '.'\n if (path === '/workspace') return '.'\n return path\n}\n\nfunction escapeRegex(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction unescapeRegex(text: string): string {\n return text.replace(/\\\\([.*+?^${}()|[\\]\\\\])/g, '$1')\n}\n\n/**\n * Built-in mappings keyed by DSH tool name. Descriptions and placeholders are\n * the agent-tool-v3 strings the RWKV-Agent corpora were rendered with.\n */\nexport const BUILTIN_MAPPINGS: Readonly<Record<string, ToolMapping>> = {\n read: {\n wireName: 'read_file',\n description: 'Read a UTF-8 text file in the workspace. Lines come numbered. Without start_line/end_line it returns the start of the file.',\n arguments: '{\"path\":\"relative file path\",\"start_line\":\"optional integer >= 1\",\"end_line\":\"optional integer >= start_line\"}',\n schema: { properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' } } },\n toDsh(args) {\n const start = finiteInt(args.start_line)\n const end = finiteInt(args.end_line)\n return stripUndefined({\n file_path: workspacePath(args.path),\n offset: start,\n limit: end !== undefined ? Math.max(1, end - (start ?? 1) + 1) : undefined,\n })\n },\n fromDsh(args) {\n const offset = finiteInt(args.offset)\n const limit = finiteInt(args.limit)\n return stripUndefined({\n path: args.file_path,\n start_line: offset,\n end_line: limit !== undefined ? (offset ?? 1) + limit - 1 : undefined,\n })\n },\n },\n write: {\n wireName: 'write_file',\n description: 'Create or overwrite a workspace text file with the given content. The content becomes the whole file.',\n arguments: '{\"path\":\"relative file path\",\"content\":\"full file content\"}',\n schema: { properties: { path: { type: 'string' }, content: { type: 'string' } } },\n toDsh: args => ({ file_path: workspacePath(args.path), content: args.content ?? '' }),\n fromDsh: args => ({ path: args.file_path, content: args.content }),\n },\n edit: {\n wireName: 'edit_file',\n description: 'Replace one exact piece of text in a workspace text file. old_text must appear exactly once; copy it from read_file without the line numbers.',\n arguments: '{\"path\":\"relative file path\",\"old_text\":\"exact text to replace\",\"new_text\":\"replacement text\"}',\n schema: { properties: { path: { type: 'string' }, old_text: { type: 'string' }, new_text: { type: 'string' } } },\n toDsh: args => ({ file_path: workspacePath(args.path), old_string: args.old_text ?? '', new_string: args.new_text ?? '' }),\n fromDsh: args => ({ path: args.file_path, old_text: args.old_string, new_text: args.new_string }),\n },\n // Line-range edit (src/line-edit.ts); offered only where that plugin is mounted.\n edit_lines: {\n wireName: 'edit_lines',\n description: 'Replace a range of lines in a workspace text file, numbered as read_file shows them. end_line = start_line - 1 inserts before start_line.',\n arguments: '{\"path\":\"relative file path\",\"start_line\":\"first line to replace\",\"end_line\":\"last line to replace\",\"new_text\":\"replacement lines without line numbers\"}',\n schema: { properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' }, new_text: { type: 'string' } } },\n toDsh: args => ({ file_path: workspacePath(args.path), start_line: args.start_line, end_line: args.end_line, new_text: args.new_text ?? '' }),\n fromDsh: args => ({ path: args.file_path, start_line: args.start_line, end_line: args.end_line, new_text: args.new_text }),\n },\n glob: {\n wireName: 'list_files',\n description: 'List files below a workspace-relative path.',\n arguments: '{\"path\":\"optional relative directory\",\"pattern\":\"optional glob such as *.ts\"}',\n schema: { properties: { path: { type: 'string' }, pattern: { type: 'string' } } },\n toDsh: args => stripUndefined({ pattern: nonEmptyStr(args.pattern) ?? '*', path: workspacePath(args.path) }),\n fromDsh: args => stripUndefined({ path: args.path, pattern: args.pattern === '*' ? undefined : args.pattern }),\n },\n grep: {\n wireName: 'search_text',\n description: 'Search literal text in workspace files. Returns matching lines with line numbers.',\n arguments: '{\"query\":\"literal text\",\"path\":\"optional relative path\"}',\n schema: { properties: { query: { type: 'string' }, path: { type: 'string' } } },\n toDsh: args => stripUndefined({ pattern: escapeRegex(String(args.query ?? '')), path: workspacePath(args.path) }),\n fromDsh: args => stripUndefined({ query: unescapeRegex(String(args.pattern ?? '')), path: args.path }),\n },\n bash: {\n wireName: 'bash',\n description: 'Run a bash command in the workspace and return stdout and stderr. Each call starts in the workspace and does not keep cd or variables from earlier calls.',\n arguments: '{\"command\":\"bash command line\"}',\n schema: { properties: { command: { type: 'string' } } },\n toDsh(args) {\n const command = String(args.command ?? '')\n const firstLine = command.split('\\n')[0] ?? ''\n return { description: firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || 'Run command', command }\n },\n fromDsh: args => ({ command: args.command }),\n },\n web_search: {\n wireName: 'web_search',\n description: 'Search the public web and return titles, URLs, snippets, and source IDs.',\n arguments: '{\"query\":\"search query\"}',\n schema: { properties: { query: { type: 'string' } } },\n toDsh: args => ({ queries: [String(args.query ?? '')] }),\n fromDsh: args => ({ query: Array.isArray(args.queries) ? args.queries.join(' ') : args.queries }),\n },\n web_fetch: {\n wireName: 'web_fetch',\n description: 'Fetch the readable content of one public web page.',\n arguments: '{\"url\":\"https://example.com/page\"}',\n schema: { properties: { url: { type: 'string' } } },\n toDsh(args) {\n const url = nonEmptyStr(args.url) ?? (Array.isArray(args.urls) ? nonEmptyStr(args.urls[0]) : undefined)\n return { url: url ?? '' }\n },\n fromDsh: args => ({ url: args.url }),\n },\n // Stateful work list (src/todo.ts); offered when historyMode === 'worklist'.\n [TODO_PLAN_TOOL]: {\n wireName: TODO_PLAN_TOOL,\n description: TODO_PLAN_DESCRIPTION,\n arguments: '{\"items\":\"array of string\"}',\n schema: { properties: { items: { type: 'array', items: { type: 'string' } } } },\n toDsh: args => ({ items: parsePlanItems(args.items) ?? args.items }),\n fromDsh: args => ({ items: args.items }),\n },\n [TODO_UPDATE_TOOL]: {\n wireName: TODO_UPDATE_TOOL,\n description: TODO_UPDATE_DESCRIPTION,\n arguments: '{\"id\":\"integer\",\"status\":\"in_progress|completed|dropped\",\"note\":\"optional Concrete findings, exact file paths/lines, applied edits, or test outcomes\",\"content\":\"optional Refined title for this item if the initial wording was inaccurate\"}',\n schema: {\n properties: {\n id: { type: 'integer' },\n status: { type: 'string', enum: ['in_progress', 'completed', 'dropped'] },\n note: { type: 'string' },\n content: { type: 'string' },\n },\n },\n toDsh: args => stripUndefined({\n id: finiteInt(typeof args.id === 'string' ? Number(args.id.trim()) : args.id) ?? args.id,\n status: normalizeWorklistStatus(args.status) ?? args.status,\n note: nonEmptyStr(args.note),\n content: nonEmptyStr(args.content),\n }),\n fromDsh: args => stripUndefined({\n id: args.id,\n status: args.status,\n note: args.note,\n content: args.content,\n }),\n },\n}\n", "// Lenient tool-name resolution, argument key aliases, scalar coercion, and\n// DSH native value shape repairs for 7B outputs.\n\nimport { editLinesAliasesFor } from './edit-modes/index.ts'\nimport { normalizeLineEditArgs } from './edit-modes/line-edit.ts'\nimport {\n normalizeWorklistStatus,\n parsePlanItems,\n TODO_PLAN_TOOL,\n TODO_UPDATE_TOOL,\n} from './todo-state.ts'\nimport { BUILTIN_MAPPINGS, finiteInt, nonEmptyStr, type Args, type WireTool } from './tool-mappings.ts'\n\n/**\n * Other names the model uses for the wire tools: DSH's own names, Claude Code\n * / OpenAI-agent habits, and capitalised forms (\"Bash\"). Matched after an\n * exact, then a case-insensitive, lookup fails.\n */\nconst TOOL_NAME_ALIASES: Readonly<Record<string, string>> = {\n read: 'read_file', view: 'read_file', cat: 'read_file', open_file: 'read_file',\n write: 'write_file', create_file: 'write_file', save_file: 'write_file',\n edit: 'edit_file', str_replace: 'edit_file', replace: 'edit_file', replace_in_file: 'edit_file',\n glob: 'list_files', ls: 'list_files', list_dir: 'list_files', list_directory: 'list_files',\n grep: 'search_text', search: 'search_text', search_files: 'search_text',\n shell: 'bash', run: 'bash', terminal: 'bash', execute_command: 'bash', run_command: 'bash',\n fetch: 'web_fetch', webfetch: 'web_fetch', search_web: 'web_search', websearch: 'web_search',\n worklist_plan: TODO_PLAN_TOOL, plan_todo: TODO_PLAN_TOOL,\n worklist_update: TODO_UPDATE_TOOL, update_todo: TODO_UPDATE_TOOL,\n}\n\n/** The offered tool a model-written name refers to, and whether an alias was needed. */\nexport function resolveTool(tools: readonly WireTool[], name: string): { tool: WireTool; aliased: boolean } | undefined {\n const exact = tools.find(tool => tool.name === name)\n if (exact) return { tool: exact, aliased: false }\n const lower = name.trim().toLowerCase().replace(/^functions\\./, '')\n const target = tools.find(tool => tool.name.toLowerCase() === lower)\n ?? tools.find(tool => tool.name === TOOL_NAME_ALIASES[lower])\n ?? tools.find(tool => tool.dshName.toLowerCase() === lower)\n // DSH-named catalog: the trained names (read_file, ...) and their aliases.\n ?? tools.find(tool => BUILTIN_MAPPINGS[tool.dshName]?.wireName === (TOOL_NAME_ALIASES[lower] ?? lower))\n // Cross-harness compatibility: when `edit_lines` replaces `edit`, route `edit`/`edit_file` calls to `edit_lines`.\n ?? ((lower === 'edit' || lower === 'edit_file' || TOOL_NAME_ALIASES[lower] === 'edit_file')\n ? tools.find(tool => tool.dshName === 'edit_lines')\n : undefined)\n return target ? { tool: target, aliased: true } : undefined\n}\n\nconst PATH_ALIASES = ['file_path', 'filepath', 'file', 'filename', 'file_name']\nconst NATIVE_PATH_ALIASES = ['path', 'filepath', 'file', 'filename', 'file_name']\n\n/** Canonical argument key -> other keys the model writes for it, per wire tool. */\nconst ARGUMENT_ALIASES: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>> = {\n read_file: { path: PATH_ALIASES, start_line: ['line_start', 'from_line'], end_line: ['line_end', 'to_line'] },\n write_file: { path: PATH_ALIASES, content: ['text', 'file_text', 'contents', 'data', 'code'] },\n edit_file: {\n path: PATH_ALIASES,\n old_text: ['old_string', 'old_str', 'old', 'search', 'find', 'original'],\n new_text: ['new_string', 'new_str', 'new', 'replace', 'replacement', 'updated'],\n },\n edit_lines: {\n path: PATH_ALIASES,\n start_line: ['line_start', 'from_line', 'start', 'line'],\n end_line: ['line_end', 'to_line', 'end'],\n new_text: ['new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],\n },\n list_files: { path: ['directory', 'dir', 'folder', 'dir_path'], pattern: ['glob'] },\n search_text: { query: ['pattern', 'text', 'search', 'keyword', 'regex'], path: ['file_path', 'directory', 'dir'] },\n bash: { command: ['cmd', 'script', 'code', 'shell'] },\n web_fetch: { url: ['link', 'href', 'page'] },\n web_search: { query: ['q', 'keywords', 'search', 'search_query'] },\n [TODO_PLAN_TOOL]: { items: ['todos', 'tasks', 'steps', 'plan'] },\n [TODO_UPDATE_TOOL]: {\n id: ['index', 'item_id', 'task_id', 'step'],\n note: ['notes', 'summary', 'finding', 'findings', 'conclusion', 'result'],\n content: ['title', 'task', 'text', 'description'],\n },\n}\n\n/** The same table for DSH-named tools: trained and Claude-style keys -> DSH keys. */\nconst NATIVE_ARGUMENT_ALIASES: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>> = {\n read: { file_path: NATIVE_PATH_ALIASES, offset: ['start_line', 'line_start', 'from_line'] },\n write: { file_path: NATIVE_PATH_ALIASES, content: ['text', 'file_text', 'contents', 'data', 'code'] },\n edit: {\n file_path: NATIVE_PATH_ALIASES,\n old_string: ['old_text', 'old_str', 'old', 'search', 'find', 'original'],\n new_string: ['new_text', 'new_str', 'new', 'replace', 'replacement', 'updated'],\n },\n edit_lines: {\n file_path: NATIVE_PATH_ALIASES,\n start_line: ['line_start', 'from_line', 'start', 'line', 'offset'],\n end_line: ['line_end', 'to_line', 'end'],\n new_text: ['new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],\n },\n glob: { pattern: ['glob'], path: ['directory', 'dir', 'folder', 'dir_path'] },\n grep: { pattern: ['query', 'text', 'search', 'keyword', 'regex'], path: ['file_path', 'directory', 'dir'] },\n bash: { command: ['cmd', 'script', 'code', 'shell'] },\n web_fetch: { url: ['link', 'href', 'page'] },\n web_search: { queries: ['query', 'q', 'keywords', 'search', 'search_query'] },\n [TODO_PLAN_TOOL]: ARGUMENT_ALIASES[TODO_PLAN_TOOL]!,\n [TODO_UPDATE_TOOL]: ARGUMENT_ALIASES[TODO_UPDATE_TOOL]!,\n}\n\nfunction renameAliases(args: Args, aliases: Readonly<Record<string, readonly string[]>>): Args | undefined {\n let out: Args | undefined\n for (const [canonical, others] of Object.entries(aliases)) {\n if (args[canonical] !== undefined && args[canonical] !== '') continue\n const found = others.find(key => args[key] !== undefined && args[key] !== '')\n if (found === undefined) continue\n out ??= { ...args }\n out[canonical] = args[found]\n delete out[found]\n }\n return out\n}\n\nconst looseInt = (value: unknown) => finiteInt(typeof value === 'string' ? Number(value.trim()) : value)\n\n/** DSH-named tools: alias keys, end_line -> limit, a lone query string -> queries, a bash description. */\nfunction normalizeNativeArguments(tool: WireTool, args: Args): Args {\n const aliases = tool.dshName === 'edit_lines'\n ? editLinesAliasesFor({ native: true })\n : NATIVE_ARGUMENT_ALIASES[tool.dshName]\n if (aliases === undefined) return args\n let out = renameAliases(args, aliases)\n const current = out ?? args\n if (tool.dshName === 'edit_lines' && current.edits !== undefined) {\n out = normalizeLineEditArgs(current)\n }\n if (tool.dshName === 'read' && current.end_line !== undefined) {\n const start = looseInt(current.offset) ?? 1\n const end = looseInt(current.end_line)\n out ??= { ...args }\n delete out.end_line\n if (end !== undefined && current.limit === undefined) out.limit = Math.max(1, end - start + 1)\n }\n if (tool.dshName === 'web_search' && typeof current.queries === 'string') {\n out ??= { ...args }\n out.queries = [current.queries]\n }\n if (tool.dshName === 'bash' && nonEmptyStr(current.description) === undefined && nonEmptyStr(current.command) !== undefined) {\n const firstLine = String(current.command).split('\\n')[0] ?? ''\n out ??= { ...args }\n out.description = firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine\n }\n return out ?? args\n}\n\n/**\n * Renames alias keys to the tool's own keys when the own key is absent\n * (edit_file with Claude's old_string/new_string, read_file with file_path,\n * ...). read_file's DSH-style offset/limit become start_line/end_line.\n * Returns the args unchanged (same object) when nothing applied.\n */\nexport function normalizeArguments(tool: WireTool, args: Args): Args {\n if (tool.native === true) return normalizeNativeArguments(tool, args)\n const aliases = tool.name === 'edit_lines'\n ? editLinesAliasesFor({ native: false })\n : ARGUMENT_ALIASES[tool.name]\n if (aliases === undefined) return args\n let out = renameAliases(args, aliases)\n if (tool.name === 'edit_lines' && (out ?? args).edits !== undefined) {\n out = normalizeLineEditArgs(out ?? args)\n }\n if (tool.name === 'read_file' && args.start_line === undefined && args.offset !== undefined) {\n const start = looseInt(args.offset)\n const limit = looseInt(args.limit)\n out ??= { ...args }\n delete out.offset\n delete out.limit\n if (start !== undefined) out.start_line = start\n if (start !== undefined && limit !== undefined) out.end_line = start + limit - 1\n }\n return out ?? args\n}\n\n/**\n * Lenient scalars: \"10\" for an integer, \"true\" for a boolean, \"6,412\" with\n * thousands separators. Structural mismatches are left for the tool to reject.\n */\nexport function coerceArguments(args: Args, schema: Record<string, unknown> | undefined): Args {\n const properties = (schema?.properties ?? {}) as Record<string, Record<string, unknown>>\n const result: Args = {}\n for (const [key, value] of Object.entries(args)) {\n const type = properties[key]?.type\n if (value === null) continue\n if ((type === 'integer' || type === 'number') && typeof value === 'string') {\n const parsed = Number(value.replace(/,/g, '').trim())\n result[key] = value.trim() !== '' && Number.isFinite(parsed) ? parsed : value\n } else if (type === 'boolean' && typeof value === 'string' && /^(true|false)$/i.test(value.trim())) {\n result[key] = value.trim().toLowerCase() === 'true'\n } else if (type === 'string' && (typeof value === 'number' || typeof value === 'boolean')) {\n result[key] = String(value)\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n/**\n * DSH-named tools, after scalar coercion: value shapes 7B writes from other\n * harnesses' habits that DSH would reject. Keys outside the DSH schema\n * (Claude Code's grep output_mode, ...) are dropped; glob without a pattern\n * (list_files{path}) lists everything; read offset 0 (0-based habit) is line 1;\n * a pattern array becomes one pattern. The same object when nothing applied.\n */\nexport function repairNativeValues(tool: WireTool, args: Args): { args: Args; repairs: string[] } {\n if (tool.native !== true || tool.schema === undefined) return { args, repairs: [] }\n const properties = (tool.schema.properties ?? {}) as Record<string, unknown>\n const repairs: string[] = []\n let out: Args | undefined\n const edit = () => (out ??= { ...args })\n const unknown = Object.keys(args).filter(key => !(key in properties))\n if (unknown.length > 0) {\n for (const key of unknown) delete edit()[key]\n repairs.push('unknown_arguments_dropped')\n }\n const current = () => out ?? args\n if ((tool.dshName === 'grep' || tool.dshName === 'glob') && Array.isArray(current().pattern)) {\n const parts = (current().pattern as unknown[]).filter((part): part is string => typeof part === 'string' && part !== '')\n if (parts.length > 0) {\n edit().pattern = tool.dshName === 'grep' ? parts.join('|') : parts[0]\n repairs.push('pattern_array')\n }\n }\n if (tool.dshName === 'glob' && nonEmptyStr(current().pattern) === undefined) {\n edit().pattern = '*'\n repairs.push('glob_default_pattern')\n }\n if (tool.dshName === 'read') {\n for (const key of ['offset', 'limit']) {\n const value = current()[key]\n if (typeof value === 'number' && value < 1) {\n if (key === 'offset') edit().offset = 1\n else delete edit().limit\n repairs.push(`${key}_below_one`)\n }\n }\n }\n if (tool.dshName === TODO_PLAN_TOOL && current().items !== undefined) {\n const parsed = parsePlanItems(current().items)\n if (parsed !== undefined && JSON.stringify(parsed) !== JSON.stringify(current().items)) {\n edit().items = parsed\n repairs.push('plan_items_coerced')\n }\n }\n if (tool.dshName === TODO_UPDATE_TOOL && typeof current().status === 'string') {\n const normalized = normalizeWorklistStatus(current().status)\n if (normalized !== undefined && normalized !== current().status) {\n edit().status = normalized\n repairs.push('worklist_status_alias')\n }\n }\n return { args: out ?? args, repairs }\n}\n", "// Tool-result budget for RWKV sessions: the one place a long result is cut.\n//\n// RWKV reads a tool result once and cannot look back; past about 3000 tokens\n// a long result (a web page, a log) hurts more than it helps. DSH already\n// bounds results the same way for every model (spill-policy: head and tail\n// inline, the full text saved to a file whose path ends the result), but at\n// 12500 tokens. This hook does exactly that at RESULT_TOKEN_BUDGET, for\n// sessions served by the given providers, before DSH's own pass (which then\n// has nothing to do). So:\n// - every cut result names the file with the rest (the model can grep/read it);\n// - DSH records the result as the model saw it: no second cut when the\n// prompt is built, and training export reads the recorded text as is.\n//\n// read is not spilled (the file is on disk already): its window is shortened\n// at a line boundary with read's own \"Output capped ... Use offset=N\" footer.\n//\n// Tokens are exact RWKV World tokens (src/tokenizer.ts, the vendored\n// rwkv-tokenizer WASM). A result is measured as the <tool_response> the model\n// reads, JSON escaping included; the prompt's \"User: \" label and whitespace\n// cleanup are not counted (a few tokens, same as before). The budget is what\n// it says: 3000 RWKV tokens, not 3000 of an estimate.\n//\n// No DSH runtime imports: the pipeline's teacher plugin mounts the same hook.\n\nimport { toolResponse } from './core/prompt.ts'\nimport { providerOfExec, sessionIdOfExec, type AgentLike } from './dsh-host.ts'\nimport { countTokens } from './tokenizer.ts'\n\n/** RWKV tokens a tool result may take inline (as the model sees it, JSON-escaped). */\nexport const RESULT_TOKEN_BUDGET = 3000\n\n/** `text` as the prompt will carry it: `<tool_response>` + JSON payload. */\nexport type Wrap = (body: string) => string\n\n/** Exact RWKV tokens of one tool result as the model reads it. */\nexport function toolResultTokens(tool: string, body: string): number {\n return countTokens(toolResponse(tool, true, body))\n}\n\nconst GAP = '\\n\\n[...]\\n\\n'\n\n/**\n * Longest prefix (or suffix) of `text` whose wrapped token count stays within\n * `tokens`; whole code points. Token counts are not perfectly monotone in the\n * cut point (a cut can split a token), so this is a binary search that accepts\n * the largest tested prefix that fits.\n */\nfunction fit(text: string, tokens: number, fromEnd: boolean, wrap: Wrap): string {\n const chars = Array.from(text)\n const piece = (count: number): string =>\n fromEnd ? chars.slice(chars.length - count).join('') : chars.slice(0, count).join('')\n let low = 0\n let high = chars.length\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n if (countTokens(wrap(piece(middle))) <= tokens) low = middle\n else high = middle - 1\n }\n return piece(low)\n}\n\n/** DSH spill-policy's notice (notice.ts formatSpillNotice), so DSH and its UI recognise it. */\nexport function spillNotice(omittedBytes: number, locator: string, retrievalHint: string): string {\n return `(Omitted ${omittedBytes} bytes. Full formatted result stored at: ${locator}. ${retrievalHint})`\n}\n\n/**\n * `text` bounded to `budget` the way DSH spill-policy does it: half the room\n * for the head, half for the tail, the notice for the saved full text last.\n * `notice(omittedBytes)` renders that notice; `wrap` renders the bytes the\n * model actually reads (default: the body as is).\n */\nexport function spillText(text: string, budget: number, notice: (omittedBytes: number) => string, wrap: Wrap = body => body): string {\n if (countTokens(wrap(text)) <= budget) return text\n const totalBytes = Buffer.byteLength(text, 'utf8')\n const reserved = countTokens(wrap(`${GAP}\\n\\n${notice(totalBytes)}`))\n const room = Math.max(0, budget - reserved)\n const kept = fit(text, Math.ceil(room / 2), false, wrap)\n const rest = text.slice(kept.length)\n const end = fit(rest, Math.floor(room / 2), true, wrap)\n const omitted = Buffer.byteLength(rest.slice(0, rest.length - end.length), 'utf8')\n let bounded = kept.length + end.length === 0 ? notice(omitted) : `${kept}${GAP}${end}\\n\\n${notice(omitted)}`\n // Head and tail are fitted separately; the joined text can be a token or two\n // over. Drop whole lines from the tail until the real count fits.\n while (countTokens(wrap(bounded)) > budget && bounded.includes('\\n')) {\n const at = bounded.lastIndexOf('\\n')\n bounded = bounded.slice(0, at)\n }\n return bounded\n}\n\nconst READ_LINE = /^(\\d+): /\nconst READ_TOTAL = /^\\n\\n\\((?:End of file - total (\\d+) lines|Showing lines \\d+-\\d+ of (\\d+)\\.)/\n\n/** The file and the line numbers a DSH read result shows (as the model gets it), if it is one. */\nexport function readWindow(text: string): { first: number; last: number } | undefined {\n const open = text.indexOf('<content>\\n')\n const close = text.lastIndexOf('\\n</content>')\n if (open < 0 || close < open) return undefined\n const body = text.slice(open + '<content>\\n'.length, close)\n const footerAt = body.lastIndexOf('\\n\\n(')\n const lines = footerAt < 0 ? [] : body.slice(0, footerAt).split('\\n')\n const first = READ_LINE.exec(lines[0] ?? '')?.[1]\n const last = READ_LINE.exec(lines.at(-1) ?? '')?.[1]\n // Every shown line starts \"N: \", so the last \"\\n\\n(\" is the footer; none shown\n // (an empty file, an offset past the end) is the empty window 1-0.\n return first === undefined || last === undefined ? { first: 1, last: 0 } : { first: Number(first), last: Number(last) }\n}\n\n/**\n * Event carrying the lines a read showed the model, after this budget has cut\n * it: the line-edit plugin (src/line-edit.ts, a separate DSH plugin) keeps\n * which lines each session has seen and refuses edits outside them.\n */\nexport const READ_SHOWN_EVENT = 'rwkv/read-shown'\n\n/**\n * A DSH read result (`<content>` with \"N: text\" lines and a footer) shortened\n * to fit `budget` and optional `maxLines`, with read's own continuation footer;\n * undefined when it already fits or is not in that shape. At least one line is kept.\n */\nexport function capReadResult(\n text: string,\n budget: number,\n wrap: Wrap = body => body,\n maxLines?: number,\n): string | undefined {\n const open = text.indexOf('<content>\\n')\n const close = text.lastIndexOf('\\n</content>')\n if (open < 0 || close < open) return undefined\n const start = open + '<content>\\n'.length\n const body = text.slice(start, close)\n const footerAt = body.lastIndexOf('\\n\\n(')\n if (footerAt < 0) return undefined\n const lines = body.slice(0, footerAt).split('\\n')\n const overLineCap = maxLines !== undefined && maxLines > 0 && lines.length > maxLines\n if (!overLineCap && countTokens(wrap(text)) <= budget) return undefined\n const first = READ_LINE.exec(lines[0] ?? '')\n if (!first) return undefined\n // DSH's own footer knows the file's length unless read itself hit its byte cap.\n const total = READ_TOTAL.exec(body.slice(footerAt))?.[1] ?? READ_TOTAL.exec(body.slice(footerAt))?.[2]\n const render = (count: number) => {\n const last = Number(READ_LINE.exec(lines[count - 1] ?? '')?.[1] ?? first[1])\n // With the total, DSH's line-limit wording; without it, its byte-cap wording.\n const footer = total === undefined\n ? `(Output capped. Showing lines ${first[1]}-${last}. Use offset=${last + 1} to continue.)`\n : `(Showing lines ${first[1]}-${last} of ${total}. Use offset=${last + 1} to continue.)`\n return `${text.slice(0, start)}${lines.slice(0, count).join('\\n')}\\n\\n${footer}${text.slice(close)}`\n }\n let low = 1\n let high = overLineCap ? Math.min(lines.length, maxLines!) : lines.length\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n if (countTokens(wrap(render(middle))) <= budget) low = middle\n else high = middle - 1\n }\n return render(low)\n}\n\n// --- DSH wiring (structural types; see @deepseek-ai/dsh-tools, dsh-spill) ---\n\ninterface TextBlock { readonly type: string; readonly text?: string }\ninterface ExecLike { readonly name: string; readonly callId: string; readonly parent?: unknown; readonly agent?: AgentLike }\ninterface Decision { readonly kind: string; readonly content?: readonly TextBlock[]; readonly [key: string]: unknown }\ninterface SpillStoreLike {\n saveText(request: {\n owner: { sessionId: string }\n source: { kind: 'tool'; toolName: string; callId: string; label: 'result' }\n suggestedName: string\n content: string\n }): Promise<{ locator: string; retrievalHint: string }>\n}\n\nexport interface ResultBudgetOptions {\n /** Provider ids whose sessions get the budget (the RWKV plugin's routes, or the teacher's). */\n readonly providers: () => readonly string[]\n readonly budget?: number\n readonly maxReadLines?: () => number | undefined\n readonly log?: (message: string) => void\n}\n\n/** Mounts the budget on `tools/post-execute` (inside DSH's spill-policy, which runs outermost). */\nexport function applyResultBudget(ctx: unknown, options: ResultBudgetOptions): void {\n const budget = options.budget ?? RESULT_TOKEN_BUDGET\n const context = ctx as {\n on(event: string, listener: (exec: ExecLike, result: { content: readonly TextBlock[] }, next: () => Promise<Decision>) => Promise<Decision>): unknown\n emit(event: string, ...args: unknown[]): void\n get(name: string): unknown\n }\n context.on('tools/post-execute', async (exec, result, next) => {\n const decision = await next()\n if (decision.kind !== 'accept' || Object.hasOwn(decision, 'value') || exec.parent !== undefined) return decision\n const provider = providerOfExec(exec)\n if (provider === undefined || !options.providers().includes(provider)) return decision\n const content = decision.content ?? result.content\n if (!content.every(block => block.type === 'text')) return decision\n const text = content.map(block => block.text ?? '').join('')\n // Successful-frame bytes: for a failed result the wire says \"error\" instead\n // of \"result\", a token or two either way.\n const wrap: Wrap = body => toolResponse(exec.name, true, body)\n if (exec.name === 'read') {\n const lineCap = options.maxReadLines?.()\n const bounded = capReadResult(text, budget, wrap, lineCap)\n const finalText = bounded ?? text\n const window = readWindow(finalText)\n if (window !== undefined) context.emit(READ_SHOWN_EVENT, exec, window)\n return finalText === text ? decision : { ...decision, kind: 'accept', content: [{ type: 'text', text: finalText }] }\n }\n if (countTokens(wrap(text)) <= budget) return decision\n const store = context.get('spillStore') as SpillStoreLike | undefined\n const owner = sessionIdOfExec(exec)\n if (store === undefined || owner === undefined) {\n options.log?.(`result budget: no spill store or session for ${exec.name}; keeping the inline content`)\n return decision\n }\n const ref = await store.saveText({\n owner: { sessionId: owner },\n source: { kind: 'tool', toolName: exec.name, callId: exec.callId, label: 'result' },\n suggestedName: `${exec.name}.txt`,\n content: text,\n })\n const bounded = spillText(text, budget, bytes => spillNotice(bytes, ref.locator, ref.retrievalHint), wrap)\n return { ...decision, kind: 'accept', content: [{ type: 'text', text: bounded }] }\n })\n}\n", "// Pre-write incremental syntax check shared across `tolerant` and `line-edit`\n// edit modes. Uses checkers every DSH machine provides:\n// Python's compile() via python3, Node's stripTypeScriptTypes / --check,\n// bash -n, and JSON.parse. Unknown extensions or missing checkers pass through.\n\nimport { spawn } from 'node:child_process'\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport * as nodeModule from 'node:module'\nimport { tmpdir } from 'node:os'\nimport { extname, join } from 'node:path'\n\nconst stripTsTypes = (nodeModule as { stripTypeScriptTypes?: (code: string, options?: { mode?: string }) => string }).stripTypeScriptTypes\n\nconst TIMEOUT_MS = 10_000\n\nconst PYTHON_CHECK = String.raw`\nimport sys\nsource = sys.stdin.read()\ntry:\n compile(source, sys.argv[1], \"exec\", dont_inherit=True)\nexcept SyntaxError as error:\n print(f\"{type(error).__name__}: {error.msg} (line {error.lineno})\")\n sys.exit(1)\n`\n\nconst TOML_CHECK = String.raw`\nimport sys, tomllib\ntry:\n tomllib.loads(sys.stdin.read())\nexcept Exception as error:\n print(f\"TOML: {error}\")\n sys.exit(1)\n`\n\nconst YAML_CHECK = String.raw`\nimport sys\ntry:\n import yaml\nexcept ImportError:\n sys.exit(0)\ntry:\n list(yaml.safe_load_all(sys.stdin.read()))\nexcept Exception as error:\n first = str(error).splitlines()[0] if str(error) else type(error).__name__\n print(f\"YAML: {first}\")\n sys.exit(1)\n`\n\nconst JAVA_PARSE_ERROR_RE = /error:\\s*(?:';' expected|reached end of file while parsing|class, interface, enum, or record expected|illegal start of (?:expression|type)|unclosed (?:string|character) literal|unclosed comment|<identifier> expected|'[^']+' expected|(?:unnamed class|compact source file|implicitly declared class) should not have package declaration)/i\n\n/** stdout+stderr of a failed run; '' when it passed; undefined when it could not run. */\nfunction run(command: string, args: readonly string[], input: string): Promise<string | undefined> {\n return new Promise(resolve => {\n let output = ''\n let settled = false\n const done = (value: string | undefined) => {\n if (!settled) {\n settled = true\n resolve(value)\n }\n }\n let child\n try {\n // C locale: the same (English) message whatever the machine's language.\n child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], timeout: TIMEOUT_MS, env: { ...process.env, LC_ALL: 'C', LANG: 'C' } })\n } catch {\n done(undefined)\n return\n }\n child.stdout.on('data', chunk => { output += String(chunk) })\n child.stderr.on('data', chunk => { output += String(chunk) })\n child.on('error', () => done(undefined))\n child.on('close', (code, signal) => done(signal !== null ? undefined : code === 0 ? '' : output.trim() || `exit ${code}`))\n child.stdin.on('error', () => undefined)\n child.stdin.end(input)\n })\n}\n\nasync function nodeCheck(text: string, extension: string): Promise<string | undefined> {\n const dir = await mkdtemp(join(tmpdir(), 'rwkv-edit-check-'))\n try {\n const file = join(dir, `check${extension}`)\n await writeFile(file, text)\n const output = await run(process.execPath, ['--check', file], '')\n if (!output) return output\n const line = new RegExp(`${file.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}:(\\\\d+)`).exec(output)?.[1]\n const message = output.split('\\n').find(lineText => /^[A-Za-z]*Error: /.test(lineText)) ?? output.split('\\n')[0]!\n return line === undefined ? message : `${message} (line ${line})`\n } finally {\n await rm(dir, { recursive: true, force: true })\n }\n}\n\nfunction tsOrJsStripCheck(text: string): string | undefined {\n if (!stripTsTypes) return undefined\n try {\n stripTsTypes(text, { mode: 'strip' })\n return ''\n } catch (error) {\n // Non-erasable TS syntax (enum, namespace, parameter properties) is valid TS\n // but unsupported in strip mode; do not misreport it as a syntax error.\n if (error && typeof error === 'object' && 'code' in error && error.code === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX') {\n return undefined\n }\n const firstLine = (error instanceof Error ? error.message : String(error)).split('\\n')[0]!\n return `SyntaxError: ${firstLine}`\n }\n}\n\nasync function javaParseCheck(text: string): Promise<string | undefined> {\n const dir = await mkdtemp(join(tmpdir(), 'rwkv-java-check-'))\n try {\n const pubMatch = /\\bpublic\\s+(?:final\\s+|abstract\\s+)?(?:class|interface|enum|record)\\s+([A-Za-z_$][A-Za-z0-9_$]*)/.exec(text)\n const fileName = `${pubMatch?.[1] ?? 'Check'}.java`\n const file = join(dir, fileName)\n await writeFile(file, text)\n const output = await run('javac', ['-J-Duser.language=en', '-J-Duser.country=US', '-encoding', 'UTF-8', '-XDcompilePolicy=simple', '-proc:none', '-d', dir, file], '')\n if (!output) return output\n const parseLine = output.split('\\n').find(line => JAVA_PARSE_ERROR_RE.test(line))\n if (!parseLine) return '' // Only type/symbol resolution errors -> syntax & brace structure is valid.\n return parseLine.replace(file, fileName).trim()\n } finally {\n await rm(dir, { recursive: true, force: true })\n }\n}\n\nfunction parseCsvRows(text: string): string[][] | string {\n const rows: string[][] = []\n let row: string[] = []\n let field = ''\n let inQuotes = false\n const s = text.replace(/\\r\\n/g, '\\n')\n for (let i = 0; i < s.length; i++) {\n const ch = s[i]!\n if (inQuotes) {\n if (ch === '\"') {\n if (s[i + 1] === '\"') { field += '\"'; i++ }\n else inQuotes = false\n } else {\n field += ch\n }\n } else if (ch === '\"') {\n if (field === '') inQuotes = true\n else field += ch\n } else if (ch === ',') {\n row.push(field)\n field = ''\n } else if (ch === '\\n') {\n row.push(field)\n field = ''\n if (!(row.length === 1 && row[0] === '')) rows.push(row)\n row = []\n } else {\n field += ch\n }\n }\n if (inQuotes) return 'CSV: unclosed double-quoted field'\n if (field !== '' || row.length > 0) {\n row.push(field)\n if (!(row.length === 1 && row[0] === '')) rows.push(row)\n }\n return rows\n}\n\nfunction csvStructureError(text: string): string {\n if (text.trim() === '') return ''\n const parsed = parseCsvRows(text)\n if (typeof parsed === 'string') return parsed\n if (parsed.length < 2) return ''\n const headerCols = parsed[0]!.length\n if (headerCols < 2) return ''\n for (let r = 1; r < parsed.length; r++) {\n if (parsed[r]!.length !== headerCols) {\n return `CSV column count mismatch at row ${r + 1}: expected ${headerCols} columns (matching header \"${parsed[0]!.slice(0, 4).join(',')}\"), got ${parsed[r]!.length}`\n }\n }\n return ''\n}\n\n/** The first syntax error in `text` as a file named `path`, '' when it parses, undefined when unchecked. */\nexport async function syntaxError(text: string, path: string): Promise<string | undefined> {\n const extension = extname(path).toLowerCase()\n switch (extension) {\n case '.py':\n return run('python3', ['-c', PYTHON_CHECK, path], text)\n case '.go':\n return run('gofmt', ['-e'], text)\n case '.java':\n return javaParseCheck(text)\n case '.ts':\n case '.mts':\n case '.cts':\n return tsOrJsStripCheck(text)\n case '.js':\n case '.mjs':\n case '.cjs':\n return nodeCheck(text, extension)\n case '.sh':\n case '.bash':\n return run('bash', ['-n'], text)\n case '.toml':\n return run('python3', ['-c', TOML_CHECK], text)\n case '.yaml':\n case '.yml':\n return run('python3', ['-c', YAML_CHECK], text)\n case '.csv':\n return csvStructureError(text)\n case '.json':\n if (text.trim() === '') return ''\n try {\n JSON.parse(text)\n return ''\n } catch (error) {\n return `JSON: ${(error as Error).message}`\n }\n default:\n return undefined\n }\n}\n\n/** The error an edit introduces: the new text fails while the old one parsed. */\nexport async function introducedSyntaxError(before: string, after: string, path: string): Promise<string | undefined> {\n const now = await syntaxError(after, path)\n if (!now) return undefined\n return await syntaxError(before, path) === '' ? now : undefined\n}\n", "// DSH plugin entry `dsh-rwkv-plugin/line-edit`: mounts the Anchored Batch\n// `edit_lines` tool (`src/edit-modes/line-edit.ts`).\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { applyLineEditPlugin } from './edit-modes/line-edit.ts'\nimport { EDIT_LINES_TOOL } from './edit-modes/observations.ts'\n\nexport { EDIT_LINES_TOOL }\n\nexport const name = 'rwkv-edit-lines'\nexport const inject = ['tools', 'fs']\n\nexport function apply(ctx: Context): void {\n applyLineEditPlugin(ctx)\n}\n"],
5
+ "mappings": ";AAYA,SAAS,kBAAkB;;;ACsBpB,IAAM,cAAc,CAAC,UAA0B,GAAG,KAAK,QAAQ,UAAU,IAAI,KAAK,GAAG;AAGrF,SAAS,mBAAmB,MAIjC;AACA,QAAM,MAAM,KAAK,SAAS,MAAM,IAAI,SAAS;AAC7C,QAAM,aAAa,QAAQ,SAAS,KAAK,QAAQ,SAAS,IAAI,IAAI;AAClE,QAAM,kBAAkB,WAAW,SAAS,IAAI;AAChD,QAAM,QAAQ,eAAe,KAAK,CAAC,KAAK,kBAAkB,WAAW,MAAM,GAAG,EAAE,IAAI,YAAY,MAAM,IAAI;AAC1G,SAAO,EAAE,KAAK,iBAAiB,MAAM;AACvC;AAGO,SAAS,kBACd,OACA,KACA,iBACA,UACQ;AACR,QAAM,cAAc,mBAAoB,YAAY,MAAM,SAAS;AACnE,QAAM,SAAS,MAAM,KAAK,IAAI,KAAK,eAAe,MAAM,SAAS,IAAI,OAAO;AAC5E,SAAO,QAAQ,SAAS,OAAO,QAAQ,OAAO,MAAM,IAAI;AAC1D;AAOO,SAAS,aAAa,aAAqB,OAA0B,MAAc,IAAoB;AAC5G,MAAI,MAAM,WAAW,EAAG,QAAO,OAAO,WAAW;AACjD,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,MAAM,QAAQ,IAAI,CAAC;AACtD,QAAM,OAAO,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,QAAQ,EAAE,CAAC;AACvD,QAAM,MAAM,CAAC,OAAO,WAAW,WAAW,KAAK,IAAI,IAAI,OAAO,MAAM,MAAM,OAAO;AACjF,MAAI,QAAQ,EAAG,KAAI,KAAK,IAAI,YAAY,QAAQ,CAAC,CAAC,SAAS;AAC3D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