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,232 @@
1
+ // Host `tools/execute` wrapper for `editMode: 'tolerant'`.
2
+ //
3
+ // Combines `src/core/edit-modes/tolerant.ts` (content-anchored recall tolerance +
4
+ // auto-reindent + dual-anchor sliding-window guard), `folded-read-guard.ts`, and
5
+ // `syntax-check.ts` (pre-write incremental syntax validation) on standard `edit`.
6
+
7
+ import { resolve } from 'node:path'
8
+ import { sandboxPolicyFor } from '../core/edit-modes/shared.ts'
9
+ import { resolveTolerantEdit } from '../core/edit-modes/tolerant.ts'
10
+ import {
11
+ ensureExecWorkingDir,
12
+ providerOfExec,
13
+ sessionIdOfExec,
14
+ type AgentLike,
15
+ type SandboxPolicyLike,
16
+ } from '../dsh-host.ts'
17
+ import { foldedUnreadErrorMessage, isFoldedUnreadPath } from './folded-read-guard.ts'
18
+ import { introducedSyntaxError, syntaxError } from './syntax-check.ts'
19
+
20
+ interface FsTargetLike { readonly displayPath: string }
21
+ interface FsLike {
22
+ resolve(path: string, options: { cwd?: string; signal?: AbortSignal }): Promise<FsTargetLike>
23
+ readText(target: FsTargetLike, signal?: AbortSignal): Promise<string>
24
+ editText(
25
+ target: FsTargetLike,
26
+ edit: { oldString: string; newString: string; replaceAll: boolean },
27
+ expected?: unknown,
28
+ signal?: AbortSignal,
29
+ sandboxPolicy?: unknown,
30
+ ): Promise<{ version: unknown; before: string; after: string }>
31
+ processPath(target: FsTargetLike): string
32
+ }
33
+
34
+ interface ExecLike {
35
+ readonly name: string
36
+ readonly arguments: unknown
37
+ readonly parent?: unknown
38
+ readonly agent?: AgentLike
39
+ readonly signal?: AbortSignal
40
+ }
41
+
42
+ interface ToolResultLike {
43
+ readonly content: readonly { readonly type: string; readonly text?: string }[]
44
+ readonly isError: boolean
45
+ readonly value?: unknown
46
+ readonly error?: { readonly message: string }
47
+ }
48
+
49
+ export interface TolerantEditOptions {
50
+ readonly providers: () => readonly string[]
51
+ readonly enabled: () => boolean
52
+ readonly outputRepairs: () => boolean
53
+ readonly syntaxGuard: () => boolean
54
+ readonly foldedReadGuard?: () => boolean
55
+ }
56
+
57
+ function errorResult(message: string): ToolResultLike {
58
+ return {
59
+ content: [{ type: 'text', text: `Error: ${message}` }],
60
+ isError: true,
61
+ error: { message },
62
+ }
63
+ }
64
+
65
+ function previewSingleEdit(before: string, oldString: string, newString: string): string | undefined {
66
+ if (oldString === '') return undefined
67
+ const at = before.indexOf(oldString)
68
+ if (at < 0 || before.indexOf(oldString, at + 1) >= 0) return undefined
69
+ return before.slice(0, at) + newString + before.slice(at + oldString.length)
70
+ }
71
+
72
+ export function applyTolerantEdit(ctx: unknown, options: TolerantEditOptions): void {
73
+ const host = ctx as {
74
+ on(event: 'tools/execute', listener: (exec: ExecLike, next: () => Promise<ToolResultLike>) => Promise<ToolResultLike>): unknown
75
+ waterfall?(event: 'fs/edit-intent', target: FsTargetLike, exec: ExecLike, fallback: () => undefined): Promise<unknown>
76
+ emit(event: 'fs/observed', target: FsTargetLike, observation: { kind: 'present'; version: unknown }, actor: ExecLike): void
77
+ get(name: string): unknown
78
+ }
79
+
80
+ host.on('tools/execute', async (exec, next) => {
81
+ if ((exec.name !== 'edit' && exec.name !== 'write') || exec.parent !== undefined || !options.enabled()) return next()
82
+ const provider = providerOfExec(exec)
83
+ if (provider === undefined || !options.providers().includes(provider)) return next()
84
+ const fs = host.get('fs') as FsLike | undefined
85
+ if (fs === undefined || typeof exec.arguments !== 'object' || exec.arguments === null) return next()
86
+
87
+ if (exec.name === 'write') {
88
+ const wargs = exec.arguments as { file_path?: unknown; content?: unknown }
89
+ if (typeof wargs.file_path !== 'string' || wargs.file_path.trim() === '' || typeof wargs.content !== 'string') {
90
+ return next()
91
+ }
92
+ const cwd = await ensureExecWorkingDir(host, exec)
93
+ const resolveOpts = { ...cwd !== undefined ? { cwd } : {}, ...exec.signal ? { signal: exec.signal } : {} }
94
+ let target: FsTargetLike
95
+ try {
96
+ target = await fs.resolve(wargs.file_path, resolveOpts)
97
+ } catch {
98
+ return next()
99
+ }
100
+ if ((options.foldedReadGuard?.() ?? true) && isFoldedUnreadPath(sessionIdOfExec(exec), [
101
+ fs.processPath(target),
102
+ target.displayPath,
103
+ ...(cwd !== undefined ? [resolve(cwd, wargs.file_path.trim())] : []),
104
+ ])) {
105
+ return errorResult(foldedUnreadErrorMessage(target.displayPath, 'write'))
106
+ }
107
+ let existingBefore: string | undefined
108
+ try {
109
+ existingBefore = await fs.readText(target, exec.signal)
110
+ } catch {
111
+ existingBefore = undefined
112
+ }
113
+ if (existingBefore !== undefined) {
114
+ const beforeLines = existingBefore.split('\n').length
115
+ const afterLines = wargs.content.split('\n').length
116
+ if (beforeLines >= 30 && afterLines < Math.max(5, Math.floor(beforeLines * 0.25))) {
117
+ return errorResult(
118
+ `Refusing to overwrite ${beforeLines}-line file ${target.displayPath} with only ${afterLines} lines via write; `
119
+ + 'use edit to modify or append rows without losing existing content.',
120
+ )
121
+ }
122
+ }
123
+ if (options.syntaxGuard()) {
124
+ const broken = existingBefore !== undefined
125
+ ? await introducedSyntaxError(existingBefore, wargs.content, target.displayPath)
126
+ : (await syntaxError(wargs.content, target.displayPath)) || undefined
127
+ if (broken !== undefined) {
128
+ return errorResult(
129
+ `Your write to ${target.displayPath} was NOT applied: it contains a syntax error (${broken}). `
130
+ + 'Fix content (check parentheses, braces, quotes, indentation, and column structure) and try again.',
131
+ )
132
+ }
133
+ }
134
+ return next()
135
+ }
136
+
137
+ const args = exec.arguments as {
138
+ file_path?: unknown
139
+ old_string?: unknown
140
+ new_string?: unknown
141
+ replace_all?: unknown
142
+ }
143
+ if (typeof args.file_path !== 'string' || args.file_path.trim() === '') return next()
144
+
145
+ const cwd = await ensureExecWorkingDir(host, exec)
146
+ const resolveOpts = { ...cwd !== undefined ? { cwd } : {}, ...exec.signal ? { signal: exec.signal } : {} }
147
+
148
+ let target: FsTargetLike
149
+ let before: string
150
+ try {
151
+ target = await fs.resolve(args.file_path, resolveOpts)
152
+ if ((options.foldedReadGuard?.() ?? true) && isFoldedUnreadPath(sessionIdOfExec(exec), [
153
+ fs.processPath(target),
154
+ target.displayPath,
155
+ ...(cwd !== undefined ? [resolve(cwd, args.file_path.trim())] : []),
156
+ ])) {
157
+ return errorResult(foldedUnreadErrorMessage(target.displayPath, 'edit'))
158
+ }
159
+ if (
160
+ typeof args.old_string !== 'string' || args.old_string === '' ||
161
+ typeof args.new_string !== 'string' ||
162
+ args.old_string === args.new_string
163
+ ) {
164
+ return next()
165
+ }
166
+ before = await fs.readText(target, exec.signal)
167
+ if (args.replace_all === true) {
168
+ if (options.syntaxGuard() && before.includes(args.old_string)) {
169
+ const afterAll = before.split(args.old_string).join(args.new_string)
170
+ const broken = await introducedSyntaxError(before, afterAll, target.displayPath)
171
+ if (broken !== undefined) {
172
+ return errorResult(
173
+ `Your edit to ${target.displayPath} was NOT applied: it introduces a syntax error (${broken}). `
174
+ + 'Fix new_string and try again.',
175
+ )
176
+ }
177
+ }
178
+ return next()
179
+ }
180
+ } catch {
181
+ return next()
182
+ }
183
+
184
+ const resolved = options.outputRepairs()
185
+ ? resolveTolerantEdit(before, args.old_string, args.new_string, target.displayPath)
186
+ : { kind: 'exact' as const }
187
+
188
+ if (resolved.kind === 'refused') return errorResult(resolved.message)
189
+
190
+ const effectiveOld = resolved.kind === 'repaired' ? resolved.oldString : args.old_string
191
+ const effectiveNew = resolved.kind === 'repaired' ? resolved.newString : args.new_string
192
+
193
+ if (options.syntaxGuard()) {
194
+ const afterPreview = previewSingleEdit(before, effectiveOld, effectiveNew)
195
+ if (afterPreview !== undefined) {
196
+ const broken = await introducedSyntaxError(before, afterPreview, target.displayPath)
197
+ if (broken !== undefined) {
198
+ return errorResult(
199
+ `Your edit to ${target.displayPath} was NOT applied: it introduces a syntax error (${broken}). `
200
+ + 'Fix new_string (check parentheses, braces, quotes, and indentation) and try again.',
201
+ )
202
+ }
203
+ }
204
+ }
205
+
206
+ if (resolved.kind === 'exact') return next()
207
+
208
+ try {
209
+ const intent = host.waterfall
210
+ ? await host.waterfall('fs/edit-intent', target, exec, () => undefined)
211
+ : undefined
212
+ const policy = sandboxPolicyFor(host.get('sandboxPolicy') as SandboxPolicyLike | undefined, exec.agent?.session)
213
+ const outcome = await fs.editText(
214
+ target,
215
+ { oldString: effectiveOld, newString: effectiveNew, replaceAll: false },
216
+ intent,
217
+ exec.signal,
218
+ policy,
219
+ )
220
+ const canonicalPath = fs.processPath(target)
221
+ host.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec)
222
+ return {
223
+ content: [{ type: 'text', text: `The file ${canonicalPath} has been updated successfully.\n${resolved.note}` }],
224
+ isError: false,
225
+ value: { path: canonicalPath, before: outcome.before, after: outcome.after },
226
+ }
227
+ } catch (error) {
228
+ const msg = error instanceof Error ? error.message : String(error)
229
+ return errorResult(msg)
230
+ }
231
+ })
232
+ }
@@ -0,0 +1,6 @@
1
+ // Re-export shim: folded-read guard now lives in `src/edit-modes/folded-read-guard.ts`.
2
+ export {
3
+ foldedUnreadErrorMessage,
4
+ isFoldedUnreadPath,
5
+ setFoldedUnreadPaths,
6
+ } from './edit-modes/folded-read-guard.ts'
package/src/history.ts ADDED
@@ -0,0 +1,163 @@
1
+ // DSH request messages → the harness history. Kept free of DSH runtime
2
+ // imports (types only) so it can be tested without a DSH checkout.
3
+
4
+ import type { RequestMessage } from '@deepseek-ai/dsh-llm'
5
+ import type { HistoryItem } from './core/policy.ts'
6
+ import type { Args, ToolNames, WireTool } from './core/tools.ts'
7
+ import { BUILTIN_MAPPINGS } from './core/tools.ts'
8
+
9
+ interface BlockLike {
10
+ readonly type: string
11
+ readonly text?: string
12
+ readonly id?: string
13
+ readonly name?: string
14
+ readonly arguments?: string
15
+ }
16
+
17
+ function textOf(content: readonly BlockLike[]): string {
18
+ const parts: string[] = []
19
+ for (const block of content) {
20
+ if (block.type === 'text' && block.text) parts.push(block.text)
21
+ else if (block.type === 'image') parts.push('[image]')
22
+ else if (block.type === 'file') parts.push('[file]')
23
+ }
24
+ return parts.join('\n').trim()
25
+ }
26
+
27
+ function reasoningOf(content: readonly BlockLike[]): string {
28
+ const parts: string[] = []
29
+ for (const block of content) {
30
+ if (block.type === 'reasoning' && block.text) parts.push(block.text)
31
+ }
32
+ return parts.join('\n').trim()
33
+ }
34
+
35
+ function parseArgs(raw: string | undefined): Args {
36
+ if (!raw) return {}
37
+ try {
38
+ const value: unknown = JSON.parse(raw)
39
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Args : {}
40
+ } catch {
41
+ return {}
42
+ }
43
+ }
44
+
45
+ interface RuntimeSource {
46
+ readonly kind?: string
47
+ readonly form?: string
48
+ readonly sections?: readonly { readonly name: string; readonly text: string }[]
49
+ }
50
+
51
+ /**
52
+ * Runtime-context sections shown to RWKV: the working directory (path repair
53
+ * reads it too) and the file sandbox policy. Approval policy, the DSH checkout
54
+ * and the Web GUI URL are dropped.
55
+ */
56
+ export const RUNTIME_CONTEXT_KEPT: readonly string[] = ['working-directory:current', 'sandbox:policy']
57
+
58
+ const TIME_SAMPLE = /^Time sampled while preparing turn \d+, step \d+: (\S+)/
59
+
60
+ /**
61
+ * DSH's time-context reading (`@deepseek-ai/dsh-time-context`) as RWKV sees it:
62
+ * the timestamp only. The browser time-zone line (which asks the model to
63
+ * query the user when no browser zone is known) and the elapsed-time line are
64
+ * dropped. Unrecognised text is kept whole.
65
+ */
66
+ export function timeNote(text: string): string {
67
+ const match = TIME_SAMPLE.exec(text)
68
+ return match ? `Current time: ${match[1]}.` : text
69
+ }
70
+
71
+ export interface HistoryOptions {
72
+ /** Include developer messages (DSH context snapshots, instructions) as user notes. */
73
+ readonly includeDeveloper: boolean
74
+ /** Name tools outside the catalog by their trained (default) or DSH names. */
75
+ readonly names?: ToolNames
76
+ /** Drop DSH time-context readings (the date is in the system prompt instead). */
77
+ readonly dropTimeContext?: boolean
78
+ }
79
+
80
+ /** The leading system message DSH assembled for this request ('' when absent). */
81
+ export function systemText(messages: readonly RequestMessage[]): string {
82
+ const first = messages[0]
83
+ return first?.role === 'system' ? textOf(first.content as readonly BlockLike[]) : ''
84
+ }
85
+
86
+ /**
87
+ * Converts the provider-neutral DSH history. Tool calls made under DSH names
88
+ * are shown to the model under their RWKV names (the catalog's reverse
89
+ * mapping), so a session switched from another model reads naturally.
90
+ */
91
+ export function historyFromMessages(
92
+ messages: readonly RequestMessage[],
93
+ catalog: readonly WireTool[],
94
+ options: HistoryOptions,
95
+ ): HistoryItem[] {
96
+ const items: HistoryItem[] = []
97
+ const callNames = new Map<string, string>()
98
+ const byDsh = new Map(catalog.map(tool => [tool.dshName, tool]))
99
+ for (const message of messages) {
100
+ const content = message.content as readonly BlockLike[]
101
+ switch (message.role) {
102
+ case 'system':
103
+ break
104
+ case 'developer': {
105
+ const text = textOf(content)
106
+ if (options.includeDeveloper && text) items.push({ kind: 'note', text })
107
+ break
108
+ }
109
+ case 'user': {
110
+ const text = textOf(content)
111
+ if (!text) break
112
+ const source = 'source' in message ? message.source as RuntimeSource | undefined : undefined
113
+ if (source?.kind === 'runtime-context') {
114
+ // DSH's runtime-context snapshot: a note, never the task, and only
115
+ // the sections RWKV can use (the cleared marker has none).
116
+ const kept = (source.sections ?? []).filter(section => RUNTIME_CONTEXT_KEPT.includes(section.name))
117
+ if (kept.length > 0) items.push({ kind: 'note', text: kept.map(section => section.text).join('\n') })
118
+ break
119
+ }
120
+ if (source?.kind === 'time-context') {
121
+ // A clock reading appended before a step: a note, never a new user turn.
122
+ if (!options.dropTimeContext) items.push({ kind: 'note', text: timeNote(text) })
123
+ break
124
+ }
125
+ items.push({ kind: source?.form === 'notice' ? 'note' : 'user', text })
126
+ break
127
+ }
128
+ case 'assistant': {
129
+ const calls = content.filter(block => block.type === 'tool-call')
130
+ const reasoning = reasoningOf(content)
131
+ if (calls.length === 0) {
132
+ const text = textOf(content)
133
+ if (text) items.push({ kind: 'assistant', text, ...(reasoning ? { reasoning } : {}) })
134
+ break
135
+ }
136
+ calls.forEach((call, callIdx) => {
137
+ const dshName = call.name ?? ''
138
+ const args = parseArgs(call.arguments)
139
+ const wire = byDsh.get(dshName)
140
+ const mapping = options.names === 'dsh' ? undefined : BUILTIN_MAPPINGS[dshName]
141
+ const name = wire?.name ?? mapping?.wireName ?? dshName
142
+ const wireArgs = wire ? wire.fromDsh(args) : mapping ? mapping.fromDsh(args) : args
143
+ const id = call.id ?? `call-${items.length}`
144
+ callNames.set(id, name)
145
+ items.push({ kind: 'call', id, name, args: wireArgs, ...(callIdx === 0 && reasoning ? { reasoning } : {}) })
146
+ })
147
+ break
148
+ }
149
+ case 'tool': {
150
+ const id = String(message.toolCallId)
151
+ items.push({
152
+ kind: 'result',
153
+ id,
154
+ name: callNames.get(id) ?? 'tool',
155
+ ok: message.isError !== true,
156
+ text: textOf(content),
157
+ })
158
+ break
159
+ }
160
+ }
161
+ }
162
+ return items
163
+ }