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,26 @@
1
+ // Unified host-side installer for edit-mode hooks (`tolerant` / `literal`).
2
+ // Kept free of `@deepseek-ai/*` runtime imports so both `src/index.ts` and
3
+ // container teacher overlays can mount it.
4
+
5
+ import type { EditMode } from '../core/defaults.ts'
6
+ import { usesTolerantEditHook } from '../core/edit-modes/index.ts'
7
+ import { applyLiteralEditMode } from './literal.ts'
8
+ import { applyTolerantEdit } from './tolerant.ts'
9
+
10
+ export interface EditModeHostHooksOptions {
11
+ readonly providers: () => readonly string[]
12
+ readonly editMode: () => EditMode
13
+ readonly outputRepairs: () => boolean
14
+ readonly guards: () => boolean
15
+ }
16
+
17
+ export function installEditModeHooks(ctx: unknown, options: EditModeHostHooksOptions): void {
18
+ applyLiteralEditMode()
19
+ applyTolerantEdit(ctx, {
20
+ providers: options.providers,
21
+ enabled: () => usesTolerantEditHook(options.editMode()),
22
+ outputRepairs: options.outputRepairs,
23
+ syntaxGuard: options.guards,
24
+ foldedReadGuard: options.guards,
25
+ })
26
+ }
@@ -0,0 +1,154 @@
1
+ // Host DSH tool implementation for `editMode: 'line-edit'`
2
+ // (Anchored Batch Line-Edit v2).
3
+ //
4
+ // Registers `edit_lines` supporting both canonical atomic multi-hunk batches
5
+ // (`{ file_path, edits: [{ start_line, end_line, start_text, end_text?, new_text }] }`)
6
+ // and backward-compatible single-hunk shorthand
7
+ // (`{ file_path, start_line, end_line, start_text?, end_text?, new_text }`),
8
+ // guarded by session read observations, file-version lock, visible-line window,
9
+ // folded-read guard (with verified-anchor bypass on observed file versions),
10
+ // and pre-write incremental syntax check.
11
+
12
+ import type { Context } from '@deepseek-ai/cordis'
13
+ import { defineTool } from '@deepseek-ai/dsh-tools'
14
+ import {
15
+ applyAnchoredLineEdits,
16
+ batchEditSummary,
17
+ batchSyntaxRejection,
18
+ isNonTrivialAnchor,
19
+ LINE_EDIT_CONTEXT_LINES,
20
+ parseLineEditHunks,
21
+ type RawLineEditHunk,
22
+ } from '../core/edit-modes/line-edit.ts'
23
+ import {
24
+ sandboxPolicyFor,
25
+ seenAfterBatchEdit,
26
+ unseenLines,
27
+ unseenRejection,
28
+ } from '../core/edit-modes/shared.ts'
29
+ import type { SandboxPolicyLike } from '../dsh-host.ts'
30
+ import { foldedUnreadErrorMessage } from './folded-read-guard.ts'
31
+ import {
32
+ attachObservations,
33
+ EDIT_LINES_TOOL,
34
+ remediateStaleVersion,
35
+ resolveTargetWithGuards,
36
+ type LineEditExecLike,
37
+ type LineEditHostContext,
38
+ type Observations,
39
+ } from './observations.ts'
40
+ import { introducedSyntaxError } from './syntax-check.ts'
41
+
42
+ export interface AnchoredLineEditArgs {
43
+ file_path: string
44
+ edits?: RawLineEditHunk[] | string
45
+ start_line?: number
46
+ end_line?: number
47
+ start_text?: string
48
+ end_text?: string
49
+ new_text?: string
50
+ }
51
+
52
+ export function createLineEditToolDefinition(
53
+ host: LineEditHostContext,
54
+ observations: Observations,
55
+ ): unknown {
56
+ return defineTool({
57
+ name: EDIT_LINES_TOOL,
58
+ description:
59
+ 'Atomically apply one or more non-overlapping anchored line-range edits to an existing UTF-8 text file. '
60
+ + '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). '
61
+ + '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.',
62
+ parameters: {
63
+ file_path: { type: 'string', required: true, description: 'Path to edit, resolved by the filesystem backend. Read the file first.' },
64
+ edits: {
65
+ type: 'array',
66
+ description: 'One or more non-overlapping anchored edits evaluated against pre-edit 1-based line numbers.',
67
+ items: {
68
+ type: 'object',
69
+ additionalProperties: false,
70
+ properties: {
71
+ start_line: { type: 'number', required: true, description: '1-based first line to replace (from read output).' },
72
+ end_line: { type: 'number', required: true, description: '1-based last line to replace (start_line - 1 inserts before start_line).' },
73
+ start_text: { type: 'string', description: 'Original text of line start_line without line-number prefix (verifies and auto-aligns line drift).' },
74
+ end_text: { type: 'string', description: 'Optional original text of line end_line for multi-line spans.' },
75
+ new_text: { type: 'string', required: true, description: 'Replacement lines without line-number prefixes (empty string deletes).' },
76
+ },
77
+ },
78
+ },
79
+ start_line: { type: 'number', description: 'Single-hunk shorthand: 1-based first line to replace.' },
80
+ end_line: { type: 'number', description: 'Single-hunk shorthand: 1-based last line to replace (start_line - 1 inserts).' },
81
+ start_text: { type: 'string', description: 'Single-hunk shorthand: original text of line start_line without line-number prefix.' },
82
+ end_text: { type: 'string', description: 'Single-hunk shorthand: optional original text of line end_line.' },
83
+ new_text: { type: 'string', description: 'Single-hunk shorthand: replacement lines without line numbers.' },
84
+ },
85
+ output: {
86
+ schema: {
87
+ type: 'object',
88
+ additionalProperties: false,
89
+ properties: {
90
+ path: { type: 'string', required: true, description: 'Canonical absolute path in the filesystem execution world.' },
91
+ summary: { type: 'string', required: true },
92
+ },
93
+ },
94
+ render: (_args: unknown, value: { summary: string }) => [{ type: 'text', text: value.summary }],
95
+ },
96
+ async execute(args: AnchoredLineEditArgs, exec: LineEditExecLike) {
97
+ const hunks = parseLineEditHunks(args as unknown as Record<string, unknown>)
98
+ if (typeof hunks === 'string') throw new Error(hunks)
99
+ const allNonTrivialAnchored = hunks.every(h => isNonTrivialAnchor(h.startText, 8))
100
+ const { target, guard, folded } = await resolveTargetWithGuards(
101
+ host,
102
+ observations,
103
+ args.file_path,
104
+ exec,
105
+ { allowFolded: allNonTrivialAnchored },
106
+ )
107
+ try {
108
+ const text = await host.fs.readText(target, exec.signal)
109
+ const edited = applyAnchoredLineEdits(text, target.displayPath, hunks)
110
+ if (typeof edited === 'string') throw new Error(edited)
111
+
112
+ const allVerified = allNonTrivialAnchored && edited.hunks.every(h => h.anchorVerified)
113
+ if (folded && !allVerified) {
114
+ throw new Error(foldedUnreadErrorMessage(target.displayPath, EDIT_LINES_TOOL))
115
+ }
116
+
117
+ if (guard.lines !== 'all' && !folded) {
118
+ for (const h of edited.hunks) {
119
+ const rawHunk = hunks[h.index]
120
+ const startAnchored = h.anchorVerified && isNonTrivialAnchor(rawHunk?.startText, 8)
121
+ const endAnchored = h.endAnchorVerified && isNonTrivialAnchor(rawHunk?.endText, 4)
122
+ if (startAnchored && (h.endLine <= h.startLine || endAnchored)) continue
123
+ const missing = unseenLines(guard.lines, h, edited.before.length)
124
+ if (missing.length > 0) {
125
+ throw new Error(unseenRejection(target.displayPath, missing, guard.lines, edited.before.length, LINE_EDIT_CONTEXT_LINES))
126
+ }
127
+ }
128
+ }
129
+
130
+ const broken = await introducedSyntaxError(text, edited.content, target.displayPath)
131
+ if (broken !== undefined) throw new Error(batchSyntaxRejection(target.displayPath, edited, broken))
132
+
133
+ const expected = guard.version === undefined ? undefined : { kind: guard.kind, version: guard.version }
134
+ const policy = sandboxPolicyFor(host.get('sandboxPolicy') as SandboxPolicyLike | undefined, exec.agent?.session)
135
+ const outcome = await host.fs.writeText(target, edited.content, expected, exec.signal, policy)
136
+ host.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec)
137
+ observations.setLines(
138
+ exec,
139
+ target,
140
+ seenAfterBatchEdit(guard.lines, edited.hunks, edited.after.length, LINE_EDIT_CONTEXT_LINES),
141
+ )
142
+ return { path: host.fs.processPath(target), summary: batchEditSummary(target.displayPath, edited) }
143
+ } catch (error: unknown) {
144
+ throw remediateStaleVersion(error)
145
+ }
146
+ },
147
+ } as never)
148
+ }
149
+
150
+ export function applyLineEditPlugin(ctx: Context): void {
151
+ const host = ctx as unknown as LineEditHostContext
152
+ const observations = attachObservations(host)
153
+ host.tools.register(createLineEditToolDefinition(host, observations))
154
+ }
@@ -0,0 +1,9 @@
1
+ // Host handler for `editMode: 'literal'`.
2
+ //
3
+ // In `literal` mode, `edit_lines` is excluded from the model catalog and the
4
+ // `tolerant` hook is inactive, so calls to `edit` delegate straight to DSH's
5
+ // built-in `@deepseek-ai/dsh-tool-fs` literal replacement implementation.
6
+
7
+ export function applyLiteralEditMode(): void {
8
+ // Intentional pass-through to stock `@deepseek-ai/dsh-tool-fs` `edit`.
9
+ }
@@ -0,0 +1,234 @@
1
+ // Shared session file-version and visible-line observation store used by the
2
+ // `line-edit` DSH tool plugin. Persists per-file versions and
3
+ // seen line numbers in session plugin records (`plugin:rwkv-edit-lines/observed`)
4
+ // so process-per-turn evaluators keep read state across resumed turns, while
5
+ // enforcing `folded-read-guard` when earlier `read` outputs were folded out.
6
+
7
+ import { resolve } from 'node:path'
8
+ import { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'
9
+ import { addSeen, type SeenLines } from '../core/edit-modes/shared.ts'
10
+ import { ensureExecWorkingDir, sessionIdOfExec, type AgentLike } from '../dsh-host.ts'
11
+ import { READ_SHOWN_EVENT } from '../result-budget.ts'
12
+ import { foldedUnreadErrorMessage, isFoldedUnreadPath } from './folded-read-guard.ts'
13
+
14
+ export const EDIT_LINES_TOOL = 'edit_lines'
15
+
16
+ export interface FsTargetLike {
17
+ readonly displayPath: string
18
+ readonly targetKey: string
19
+ }
20
+
21
+ export type Observation =
22
+ | { readonly kind: 'present'; readonly version: unknown }
23
+ | { readonly kind: 'absent' }
24
+
25
+ export interface FsLike {
26
+ resolve(path: string, options: { cwd?: string; signal?: AbortSignal }): Promise<FsTargetLike>
27
+ readText(target: FsTargetLike, signal?: AbortSignal): Promise<string>
28
+ writeText(
29
+ target: FsTargetLike,
30
+ content: string,
31
+ expected?: unknown,
32
+ signal?: AbortSignal,
33
+ sandboxPolicy?: unknown,
34
+ ): Promise<{ version: unknown }>
35
+ processPath(target: FsTargetLike): string
36
+ }
37
+
38
+ export interface LineEditExecLike {
39
+ readonly name?: string
40
+ readonly agent?: AgentLike
41
+ readonly signal?: AbortSignal
42
+ }
43
+
44
+ export interface LineEditHostContext {
45
+ readonly fs: FsLike
46
+ readonly tools: { register(definition: unknown): () => void }
47
+ on(event: 'fs/observed', listener: (target: FsTargetLike, observation: Observation, actor: LineEditExecLike | undefined) => void): () => void
48
+ on(event: typeof READ_SHOWN_EVENT, listener: (exec: LineEditExecLike, window: { first: number; last: number }) => void): () => void
49
+ emit(event: 'fs/observed', target: FsTargetLike, observation: Observation, actor: LineEditExecLike): void
50
+ effect?(fn: () => () => void): void
51
+ get(name: string): unknown
52
+ }
53
+
54
+ interface Seen {
55
+ readonly observation: Observation
56
+ lines: SeenLines
57
+ }
58
+
59
+ const OBSERVED_RECORD = 'plugin:rwkv-edit-lines/observed'
60
+
61
+ interface PersistedObservation {
62
+ readonly targetKey: string
63
+ readonly observation: Observation
64
+ readonly lines: 'all' | readonly number[]
65
+ }
66
+
67
+ interface DecodedObservation {
68
+ readonly targetKey: string
69
+ readonly observation: Observation
70
+ readonly lines: SeenLines
71
+ }
72
+
73
+ interface SessionLike {
74
+ snapshotEvents?(): readonly unknown[]
75
+ }
76
+
77
+ const appendRecord = appendPluginRecord as unknown as (session: object, type: string, data: unknown) => unknown
78
+ const recordOf = pluginRecordOf as unknown as (event: unknown) => { type: string; data: unknown } | undefined
79
+
80
+ const encodeLines = (lines: SeenLines): 'all' | number[] =>
81
+ lines === 'all' ? 'all' : [...lines].sort((a, b) => a - b)
82
+
83
+ const decodeLines = (value: unknown): SeenLines | undefined => {
84
+ if (value === 'all') return 'all'
85
+ if (!Array.isArray(value) || !value.every(n => typeof n === 'number' && Number.isSafeInteger(n))) return undefined
86
+ return new Set(value as number[])
87
+ }
88
+
89
+ const decodeObservation = (data: unknown): DecodedObservation | undefined => {
90
+ if (typeof data !== 'object' || data === null) return undefined
91
+ const { targetKey, observation, lines } = data as Record<string, unknown>
92
+ if (typeof targetKey !== 'string' || targetKey === '') return undefined
93
+ if (typeof observation !== 'object' || observation === null) return undefined
94
+ const kind = (observation as { kind?: unknown }).kind
95
+ if (kind !== 'present' && kind !== 'absent') return undefined
96
+ if (kind === 'present' && (observation as { version?: unknown }).version == null) return undefined
97
+ const decoded = decodeLines(lines)
98
+ if (decoded === undefined) return undefined
99
+ return { targetKey, observation: observation as Observation, lines: decoded }
100
+ }
101
+
102
+ const sameVersion = (a: Observation | undefined, b: Observation): boolean =>
103
+ a?.kind === 'present' && b.kind === 'present' && JSON.stringify(a.version) === JSON.stringify(b.version)
104
+
105
+ export class Observations {
106
+ private readonly bySession = new WeakMap<object, Map<string, Seen>>()
107
+ private readonly hydrated = new WeakSet<object>()
108
+ private readonly readTargets = new WeakMap<object, { session: object; targetKey: string; before: SeenLines }>()
109
+
110
+ private mapFor(session: object): Map<string, Seen> {
111
+ let byTarget = this.bySession.get(session)
112
+ if (byTarget === undefined) this.bySession.set(session, byTarget = new Map())
113
+ return byTarget
114
+ }
115
+
116
+ hydrate(session: object): void {
117
+ if (this.hydrated.has(session)) return
118
+ this.hydrated.add(session)
119
+ const events = (session as SessionLike).snapshotEvents?.()
120
+ if (events === undefined) return
121
+ for (const event of events) {
122
+ const record = recordOf(event)
123
+ if (record?.type !== OBSERVED_RECORD) continue
124
+ const entry = decodeObservation(record.data)
125
+ if (entry !== undefined) {
126
+ this.mapFor(session).set(entry.targetKey, { observation: entry.observation, lines: entry.lines })
127
+ }
128
+ }
129
+ }
130
+
131
+ private persist(session: object, targetKey: string, seen: Seen): void {
132
+ const data: PersistedObservation = {
133
+ targetKey,
134
+ observation: seen.observation,
135
+ lines: encodeLines(seen.lines),
136
+ }
137
+ try {
138
+ appendRecord(session, OBSERVED_RECORD, data)
139
+ } catch (error) {
140
+ if (!(error instanceof Error) || !error.message.includes('reenter')) return
141
+ setTimeout(() => {
142
+ try { appendRecord(session, OBSERVED_RECORD, data) } catch { /* stays in memory */ }
143
+ }, 0)
144
+ }
145
+ }
146
+
147
+ record(actor: LineEditExecLike | undefined, target: FsTargetLike, observation: Observation): void {
148
+ const session = actor?.agent?.session
149
+ if (session === undefined) return
150
+ this.hydrate(session)
151
+ const byTarget = this.mapFor(session)
152
+ const previous = byTarget.get(target.targetKey)
153
+ const seen: Seen = { observation, lines: 'all' }
154
+ byTarget.set(target.targetKey, seen)
155
+ if (actor !== undefined && actor.name === 'read') {
156
+ const before: SeenLines = previous !== undefined && sameVersion(previous.observation, observation) ? previous.lines : new Set()
157
+ this.readTargets.set(actor, { session, targetKey: target.targetKey, before })
158
+ } else if (actor?.name !== EDIT_LINES_TOOL) {
159
+ this.persist(session, target.targetKey, seen)
160
+ }
161
+ }
162
+
163
+ shown(exec: LineEditExecLike, first: number, last: number): void {
164
+ const read = this.readTargets.get(exec)
165
+ if (read === undefined) return
166
+ this.readTargets.delete(exec)
167
+ const seen = this.bySession.get(read.session)?.get(read.targetKey)
168
+ if (seen === undefined) return
169
+ seen.lines = addSeen(read.before, first, last)
170
+ this.persist(read.session, read.targetKey, seen)
171
+ }
172
+
173
+ setLines(actor: LineEditExecLike, target: FsTargetLike, lines: SeenLines): void {
174
+ const session = actor.agent?.session
175
+ if (session === undefined) return
176
+ this.hydrate(session)
177
+ const seen = this.bySession.get(session)?.get(target.targetKey)
178
+ if (seen === undefined) return
179
+ seen.lines = lines
180
+ this.persist(session, target.targetKey, seen)
181
+ }
182
+
183
+ guard(actor: LineEditExecLike, target: FsTargetLike): { kind: 'replaceIfVersion'; version: unknown; lines: SeenLines } | string {
184
+ const session = actor.agent?.session
185
+ if (session === undefined) return { kind: 'replaceIfVersion', version: undefined, lines: 'all' }
186
+ this.hydrate(session)
187
+ const seen = this.bySession.get(session)?.get(target.targetKey)
188
+ if (seen === undefined) return `cannot modify "${target.displayPath}": file has not been read — read the file, then retry`
189
+ if (seen.observation.kind === 'absent') return `cannot edit "${target.displayPath}": not found — use write to create it`
190
+ return { kind: 'replaceIfVersion', version: seen.observation.version, lines: seen.lines }
191
+ }
192
+ }
193
+
194
+ export function attachObservations(host: LineEditHostContext): Observations {
195
+ const observations = new Observations()
196
+ host.on('fs/observed', (target, observation, actor) => observations.record(actor, target, observation))
197
+ host.on(READ_SHOWN_EVENT, (exec, window) => observations.shown(exec, window.first, window.last))
198
+ return observations
199
+ }
200
+
201
+ export async function resolveTargetWithGuards(
202
+ host: LineEditHostContext,
203
+ observations: Observations,
204
+ rawFilePath: string,
205
+ exec: LineEditExecLike,
206
+ options?: { readonly allowFolded?: boolean },
207
+ ): Promise<{
208
+ readonly target: FsTargetLike
209
+ readonly guard: { kind: 'replaceIfVersion'; version: unknown; lines: SeenLines }
210
+ readonly folded: boolean
211
+ }> {
212
+ if (typeof rawFilePath !== 'string' || rawFilePath.trim() === '') {
213
+ throw new Error('file_path must be a non-empty string')
214
+ }
215
+ const cwd = await ensureExecWorkingDir(host, exec)
216
+ const resolveOpts = { ...cwd !== undefined ? { cwd } : {}, ...exec.signal ? { signal: exec.signal } : {} }
217
+ const target = await host.fs.resolve(rawFilePath, resolveOpts)
218
+ const folded = isFoldedUnreadPath(sessionIdOfExec(exec), [
219
+ host.fs.processPath(target),
220
+ target.displayPath,
221
+ ...(cwd !== undefined ? [resolve(cwd, rawFilePath.trim())] : []),
222
+ ])
223
+ if (folded && !options?.allowFolded) {
224
+ throw new Error(foldedUnreadErrorMessage(target.displayPath, EDIT_LINES_TOOL))
225
+ }
226
+ const guard = observations.guard(exec, target)
227
+ if (typeof guard === 'string') throw new Error(guard)
228
+ return { target, guard, folded }
229
+ }
230
+
231
+ export function remediateStaleVersion(error: unknown): unknown {
232
+ if ((error as { code?: unknown } | null)?.code !== 'FS_STALE_VERSION') return error
233
+ return new Error(`${(error as Error).message} — its line numbers may have moved; re-read the file, then retry`, { cause: error })
234
+ }
@@ -0,0 +1,226 @@
1
+ // Pre-write incremental syntax check shared across `tolerant` and `line-edit`
2
+ // edit modes. Uses checkers every DSH machine provides:
3
+ // Python's compile() via python3, Node's stripTypeScriptTypes / --check,
4
+ // bash -n, and JSON.parse. Unknown extensions or missing checkers pass through.
5
+
6
+ import { spawn } from 'node:child_process'
7
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
8
+ import * as nodeModule from 'node:module'
9
+ import { tmpdir } from 'node:os'
10
+ import { extname, join } from 'node:path'
11
+
12
+ const stripTsTypes = (nodeModule as { stripTypeScriptTypes?: (code: string, options?: { mode?: string }) => string }).stripTypeScriptTypes
13
+
14
+ const TIMEOUT_MS = 10_000
15
+
16
+ const PYTHON_CHECK = String.raw`
17
+ import sys
18
+ source = sys.stdin.read()
19
+ try:
20
+ compile(source, sys.argv[1], "exec", dont_inherit=True)
21
+ except SyntaxError as error:
22
+ print(f"{type(error).__name__}: {error.msg} (line {error.lineno})")
23
+ sys.exit(1)
24
+ `
25
+
26
+ const TOML_CHECK = String.raw`
27
+ import sys, tomllib
28
+ try:
29
+ tomllib.loads(sys.stdin.read())
30
+ except Exception as error:
31
+ print(f"TOML: {error}")
32
+ sys.exit(1)
33
+ `
34
+
35
+ const YAML_CHECK = String.raw`
36
+ import sys
37
+ try:
38
+ import yaml
39
+ except ImportError:
40
+ sys.exit(0)
41
+ try:
42
+ list(yaml.safe_load_all(sys.stdin.read()))
43
+ except Exception as error:
44
+ first = str(error).splitlines()[0] if str(error) else type(error).__name__
45
+ print(f"YAML: {first}")
46
+ sys.exit(1)
47
+ `
48
+
49
+ const 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
50
+
51
+ /** stdout+stderr of a failed run; '' when it passed; undefined when it could not run. */
52
+ function run(command: string, args: readonly string[], input: string): Promise<string | undefined> {
53
+ return new Promise(resolve => {
54
+ let output = ''
55
+ let settled = false
56
+ const done = (value: string | undefined) => {
57
+ if (!settled) {
58
+ settled = true
59
+ resolve(value)
60
+ }
61
+ }
62
+ let child
63
+ try {
64
+ // C locale: the same (English) message whatever the machine's language.
65
+ child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], timeout: TIMEOUT_MS, env: { ...process.env, LC_ALL: 'C', LANG: 'C' } })
66
+ } catch {
67
+ done(undefined)
68
+ return
69
+ }
70
+ child.stdout.on('data', chunk => { output += String(chunk) })
71
+ child.stderr.on('data', chunk => { output += String(chunk) })
72
+ child.on('error', () => done(undefined))
73
+ child.on('close', (code, signal) => done(signal !== null ? undefined : code === 0 ? '' : output.trim() || `exit ${code}`))
74
+ child.stdin.on('error', () => undefined)
75
+ child.stdin.end(input)
76
+ })
77
+ }
78
+
79
+ async function nodeCheck(text: string, extension: string): Promise<string | undefined> {
80
+ const dir = await mkdtemp(join(tmpdir(), 'rwkv-edit-check-'))
81
+ try {
82
+ const file = join(dir, `check${extension}`)
83
+ await writeFile(file, text)
84
+ const output = await run(process.execPath, ['--check', file], '')
85
+ if (!output) return output
86
+ const line = new RegExp(`${file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:(\\d+)`).exec(output)?.[1]
87
+ const message = output.split('\n').find(lineText => /^[A-Za-z]*Error: /.test(lineText)) ?? output.split('\n')[0]!
88
+ return line === undefined ? message : `${message} (line ${line})`
89
+ } finally {
90
+ await rm(dir, { recursive: true, force: true })
91
+ }
92
+ }
93
+
94
+ function tsOrJsStripCheck(text: string): string | undefined {
95
+ if (!stripTsTypes) return undefined
96
+ try {
97
+ stripTsTypes(text, { mode: 'strip' })
98
+ return ''
99
+ } catch (error) {
100
+ // Non-erasable TS syntax (enum, namespace, parameter properties) is valid TS
101
+ // but unsupported in strip mode; do not misreport it as a syntax error.
102
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX') {
103
+ return undefined
104
+ }
105
+ const firstLine = (error instanceof Error ? error.message : String(error)).split('\n')[0]!
106
+ return `SyntaxError: ${firstLine}`
107
+ }
108
+ }
109
+
110
+ async function javaParseCheck(text: string): Promise<string | undefined> {
111
+ const dir = await mkdtemp(join(tmpdir(), 'rwkv-java-check-'))
112
+ try {
113
+ const pubMatch = /\bpublic\s+(?:final\s+|abstract\s+)?(?:class|interface|enum|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)/.exec(text)
114
+ const fileName = `${pubMatch?.[1] ?? 'Check'}.java`
115
+ const file = join(dir, fileName)
116
+ await writeFile(file, text)
117
+ const output = await run('javac', ['-J-Duser.language=en', '-J-Duser.country=US', '-encoding', 'UTF-8', '-XDcompilePolicy=simple', '-proc:none', '-d', dir, file], '')
118
+ if (!output) return output
119
+ const parseLine = output.split('\n').find(line => JAVA_PARSE_ERROR_RE.test(line))
120
+ if (!parseLine) return '' // Only type/symbol resolution errors -> syntax & brace structure is valid.
121
+ return parseLine.replace(file, fileName).trim()
122
+ } finally {
123
+ await rm(dir, { recursive: true, force: true })
124
+ }
125
+ }
126
+
127
+ function parseCsvRows(text: string): string[][] | string {
128
+ const rows: string[][] = []
129
+ let row: string[] = []
130
+ let field = ''
131
+ let inQuotes = false
132
+ const s = text.replace(/\r\n/g, '\n')
133
+ for (let i = 0; i < s.length; i++) {
134
+ const ch = s[i]!
135
+ if (inQuotes) {
136
+ if (ch === '"') {
137
+ if (s[i + 1] === '"') { field += '"'; i++ }
138
+ else inQuotes = false
139
+ } else {
140
+ field += ch
141
+ }
142
+ } else if (ch === '"') {
143
+ if (field === '') inQuotes = true
144
+ else field += ch
145
+ } else if (ch === ',') {
146
+ row.push(field)
147
+ field = ''
148
+ } else if (ch === '\n') {
149
+ row.push(field)
150
+ field = ''
151
+ if (!(row.length === 1 && row[0] === '')) rows.push(row)
152
+ row = []
153
+ } else {
154
+ field += ch
155
+ }
156
+ }
157
+ if (inQuotes) return 'CSV: unclosed double-quoted field'
158
+ if (field !== '' || row.length > 0) {
159
+ row.push(field)
160
+ if (!(row.length === 1 && row[0] === '')) rows.push(row)
161
+ }
162
+ return rows
163
+ }
164
+
165
+ function csvStructureError(text: string): string {
166
+ if (text.trim() === '') return ''
167
+ const parsed = parseCsvRows(text)
168
+ if (typeof parsed === 'string') return parsed
169
+ if (parsed.length < 2) return ''
170
+ const headerCols = parsed[0]!.length
171
+ if (headerCols < 2) return ''
172
+ for (let r = 1; r < parsed.length; r++) {
173
+ if (parsed[r]!.length !== headerCols) {
174
+ return `CSV column count mismatch at row ${r + 1}: expected ${headerCols} columns (matching header "${parsed[0]!.slice(0, 4).join(',')}"), got ${parsed[r]!.length}`
175
+ }
176
+ }
177
+ return ''
178
+ }
179
+
180
+ /** The first syntax error in `text` as a file named `path`, '' when it parses, undefined when unchecked. */
181
+ export async function syntaxError(text: string, path: string): Promise<string | undefined> {
182
+ const extension = extname(path).toLowerCase()
183
+ switch (extension) {
184
+ case '.py':
185
+ return run('python3', ['-c', PYTHON_CHECK, path], text)
186
+ case '.go':
187
+ return run('gofmt', ['-e'], text)
188
+ case '.java':
189
+ return javaParseCheck(text)
190
+ case '.ts':
191
+ case '.mts':
192
+ case '.cts':
193
+ return tsOrJsStripCheck(text)
194
+ case '.js':
195
+ case '.mjs':
196
+ case '.cjs':
197
+ return nodeCheck(text, extension)
198
+ case '.sh':
199
+ case '.bash':
200
+ return run('bash', ['-n'], text)
201
+ case '.toml':
202
+ return run('python3', ['-c', TOML_CHECK], text)
203
+ case '.yaml':
204
+ case '.yml':
205
+ return run('python3', ['-c', YAML_CHECK], text)
206
+ case '.csv':
207
+ return csvStructureError(text)
208
+ case '.json':
209
+ if (text.trim() === '') return ''
210
+ try {
211
+ JSON.parse(text)
212
+ return ''
213
+ } catch (error) {
214
+ return `JSON: ${(error as Error).message}`
215
+ }
216
+ default:
217
+ return undefined
218
+ }
219
+ }
220
+
221
+ /** The error an edit introduces: the new text fails while the old one parsed. */
222
+ export async function introducedSyntaxError(before: string, after: string, path: string): Promise<string | undefined> {
223
+ const now = await syntaxError(after, path)
224
+ if (!now) return undefined
225
+ return await syntaxError(before, path) === '' ? now : undefined
226
+ }