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.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/cordis.patch.yml +59 -0
- package/lib/client.js +3148 -0
- package/lib/client.js.map +7 -0
- package/lib/index.js +6294 -0
- package/lib/index.js.map +7 -0
- package/lib/line-edit.js +1423 -0
- package/lib/line-edit.js.map +7 -0
- package/lib/todo.js +610 -0
- package/lib/todo.js.map +7 -0
- package/package.json +72 -4
- package/scripts/build.mjs +77 -0
- package/scripts/headless.ts +279 -0
- package/scripts/link-dsh.sh +31 -0
- package/scripts/relay-e2e.mjs +157 -0
- package/scripts/smoke.ts +116 -0
- package/scripts/state.ts +39 -0
- package/scripts/tokenizer-parity.ts +107 -0
- package/scripts/trace-stats.ts +33 -0
- package/src/adapter.ts +388 -0
- package/src/backend/generator.ts +221 -0
- package/src/backend/irwkv.ts +117 -0
- package/src/backend/lightning.ts +228 -0
- package/src/backend/stream.ts +97 -0
- package/src/client/AdapterPicker.tsx +264 -0
- package/src/client/DeveloperPanel.tsx +403 -0
- package/src/client/FoldNode.tsx +82 -0
- package/src/client/ModelCard.tsx +230 -0
- package/src/client/RwkvSettings.tsx +265 -0
- package/src/client/Segment.tsx +15 -0
- package/src/client/StatePicker.tsx +248 -0
- package/src/client/TraceFrames.tsx +462 -0
- package/src/client/TraceView.tsx +77 -0
- package/src/client/WirePanel.tsx +566 -0
- package/src/client/fields.tsx +362 -0
- package/src/client/index.tsx +109 -0
- package/src/client/styles.ts +277 -0
- package/src/client/traces-api.ts +222 -0
- package/src/client/url.ts +20 -0
- package/src/core/agent.ts +586 -0
- package/src/core/defaults.ts +51 -0
- package/src/core/dsh-prompt.ts +32 -0
- package/src/core/edit-modes/index.ts +108 -0
- package/src/core/edit-modes/line-edit.ts +793 -0
- package/src/core/edit-modes/literal.ts +26 -0
- package/src/core/edit-modes/shared.ts +213 -0
- package/src/core/edit-modes/tolerant.ts +558 -0
- package/src/core/fold-pairs.ts +407 -0
- package/src/core/fold-window.ts +563 -0
- package/src/core/line-edit.ts +33 -0
- package/src/core/parse.ts +290 -0
- package/src/core/policy.ts +500 -0
- package/src/core/prompt.ts +220 -0
- package/src/core/relay.ts +400 -0
- package/src/core/step-gates.ts +371 -0
- package/src/core/time-zone.ts +32 -0
- package/src/core/todo-state.ts +227 -0
- package/src/core/tolerant-edit.ts +14 -0
- package/src/core/tool-mappings.ts +209 -0
- package/src/core/tool-repairs.ts +255 -0
- package/src/core/tools.ts +162 -0
- package/src/core/worklist.ts +606 -0
- package/src/dsh-host.ts +48 -0
- package/src/edit-modes/folded-read-guard.ts +32 -0
- package/src/edit-modes/index.ts +26 -0
- package/src/edit-modes/line-edit.ts +154 -0
- package/src/edit-modes/literal.ts +9 -0
- package/src/edit-modes/observations.ts +234 -0
- package/src/edit-modes/syntax-check.ts +226 -0
- package/src/edit-modes/tolerant.ts +232 -0
- package/src/folded-read-guard.ts +6 -0
- package/src/history.ts +163 -0
- package/src/index.ts +287 -0
- package/src/line-edit.ts +15 -0
- package/src/live-wire.ts +133 -0
- package/src/paths.ts +91 -0
- package/src/relay-store.ts +59 -0
- package/src/result-budget.ts +225 -0
- package/src/routes.ts +324 -0
- package/src/session-setup.ts +150 -0
- package/src/syntax-check.ts +2 -0
- package/src/todo.ts +328 -0
- package/src/tokenizer.ts +48 -0
- package/src/tolerant-edit.ts +2 -0
- package/src/trace-stats.ts +225 -0
- package/src/traces.ts +289 -0
- package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
- package/vendor/rwkv-tokenizer/package.json +5 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// DSH plugin: registers RWKV-7 G1 continuation models as an LLM provider.
|
|
2
|
+
// Select it for the main agent (agent-default-model) or for a delegation tool
|
|
3
|
+
// (tool-subagent agentOptions); see README.md and cordis.patch.yml.
|
|
4
|
+
|
|
5
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
6
|
+
import type { Context, Volatile } from '@deepseek-ai/cordis'
|
|
7
|
+
import { appendPluginRecord } from '@deepseek-ai/dsh-session'
|
|
8
|
+
import z from '@deepseek-ai/schemastery'
|
|
9
|
+
import { RwkvAdapter, type AdapterSettings, type ModelConfig } from './adapter.ts'
|
|
10
|
+
import { DEFAULT_HARNESS } from './core/agent.ts'
|
|
11
|
+
import {
|
|
12
|
+
DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS,
|
|
13
|
+
DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS,
|
|
14
|
+
DEFAULT_RELAY_BUDGET_TOKENS,
|
|
15
|
+
DEFAULT_RELAY_CARD_MAX_TOKENS,
|
|
16
|
+
DEFAULT_WORKLIST_BUDGET_TOKENS,
|
|
17
|
+
DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS,
|
|
18
|
+
DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS,
|
|
19
|
+
DEFAULT_WORKLIST_MIN_FOLD_TOKENS,
|
|
20
|
+
type EditMode,
|
|
21
|
+
type HistoryMode,
|
|
22
|
+
} from './core/defaults.ts'
|
|
23
|
+
import { maxReadLinesForEditMode } from './core/edit-modes/index.ts'
|
|
24
|
+
import type { ToolMode, ToolNames } from './core/tools.ts'
|
|
25
|
+
import { setFoldedUnreadPaths } from './edit-modes/folded-read-guard.ts'
|
|
26
|
+
import { installEditModeHooks } from './edit-modes/index.ts'
|
|
27
|
+
import { applyResultBudget } from './result-budget.ts'
|
|
28
|
+
import { handleServerRoute, handleTraceRoute } from './routes.ts'
|
|
29
|
+
import { resolveHistoryModeConfig } from './session-setup.ts'
|
|
30
|
+
import { flushAndEvictSessionTrace, TraceLocation } from './traces.ts'
|
|
31
|
+
|
|
32
|
+
export const name = 'rwkv-llm'
|
|
33
|
+
export const inject = ['llm']
|
|
34
|
+
|
|
35
|
+
/** Plain field values; the plugin receives each one as a live reference. */
|
|
36
|
+
export interface Settings {
|
|
37
|
+
models: ModelConfig[]
|
|
38
|
+
thinking: 'off' | 'full'
|
|
39
|
+
historyEmptyThink: boolean
|
|
40
|
+
maxSteps: number
|
|
41
|
+
maxConsecutiveFailures: number
|
|
42
|
+
protocolRetries: number
|
|
43
|
+
decisionMaxTokens: number
|
|
44
|
+
answerMaxTokens: number
|
|
45
|
+
sampling: {
|
|
46
|
+
temperature: number
|
|
47
|
+
topK: number
|
|
48
|
+
topP: number
|
|
49
|
+
presencePenalty: number
|
|
50
|
+
frequencyPenalty: number
|
|
51
|
+
penaltyDecay: number
|
|
52
|
+
}
|
|
53
|
+
taskContract: string
|
|
54
|
+
toolMode: ToolMode
|
|
55
|
+
toolNames: ToolNames
|
|
56
|
+
excludeTools: string[]
|
|
57
|
+
toolOverrides: Record<string, { description?: string, arguments?: Record<string, string> }>
|
|
58
|
+
includeDeveloper: boolean
|
|
59
|
+
currentDate: boolean
|
|
60
|
+
timeZone: string
|
|
61
|
+
loopGuard: boolean
|
|
62
|
+
outputRepairs: boolean
|
|
63
|
+
guards: boolean
|
|
64
|
+
duplicateGateMode: 'epoch' | 'bounded' | 'adjacent' | 'off'
|
|
65
|
+
answerOpenerMode: 'default' | 'zh-only' | 'none'
|
|
66
|
+
fallbackSummary: boolean
|
|
67
|
+
editMode: EditMode
|
|
68
|
+
historyMode: HistoryMode
|
|
69
|
+
relayBudgetTokens: number
|
|
70
|
+
relayCardMaxTokens: number
|
|
71
|
+
worklistMinFoldTokens: number
|
|
72
|
+
worklistBudgetTokens: number
|
|
73
|
+
worklistKeepRecentPairs: number
|
|
74
|
+
worklistEpochTargetTokens: number
|
|
75
|
+
worklistExemptResultTokens: number
|
|
76
|
+
worklistBackboneMaxTokens: number
|
|
77
|
+
worklistHardCapTokens: number
|
|
78
|
+
worklistImmediatePriorFold: boolean
|
|
79
|
+
worklistInPlaceMask: boolean
|
|
80
|
+
worklistPinUneditedRead: boolean
|
|
81
|
+
recordTraces: boolean
|
|
82
|
+
traceDir: string
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Every field but the provider routes is volatile: only volatile fields are
|
|
87
|
+
* served to the Settings page (settings.describe skips plugins without any),
|
|
88
|
+
* and the adapter reads them per request, so a save applies without a reload.
|
|
89
|
+
*/
|
|
90
|
+
export type Config = { providers: string[] } & { [K in keyof Settings]: Volatile<Settings[K]> }
|
|
91
|
+
|
|
92
|
+
const Model = z.object({
|
|
93
|
+
id: z.string().required().description('Model id selected in DSH (provider/model route).'),
|
|
94
|
+
name: z.string().description('Display name.'),
|
|
95
|
+
backend: z.union(['lightning', 'irwkv']).required().description('lightning = rwkv_lightning CUDA /v1/batch/completions; irwkv = iRWKV /v1/completions.'),
|
|
96
|
+
baseURL: z.string().required().description('Server root, e.g. http://100.64.0.5:8103 or https://api-7b.rwkvos.com.'),
|
|
97
|
+
model: z.string().required().description('Upstream model id.'),
|
|
98
|
+
apiKey: z.string().description('iRWKV bearer key or rwkv_lightning password.'),
|
|
99
|
+
headers: z.dict(z.string()).description('Extra request headers (Cloudflare Access service token).'),
|
|
100
|
+
contextWindow: z.natural().description('Context window advertised to DSH.'),
|
|
101
|
+
stateId: z.string().description('rwkv_lightning: initial state id from /v1/state/upload; empty = zero state.'),
|
|
102
|
+
adapterId: z.string().description('rwkv_lightning: adapter id for request-level adaptation; empty = no adapter.'),
|
|
103
|
+
// Configs saved before 94b3734 carry `adapter: { id, file, serverPath }`;
|
|
104
|
+
// schemastery passes unknown keys through, the adapter still reads
|
|
105
|
+
// adapter.id, and the settings page rewrites it as adapterId on save.
|
|
106
|
+
thinking: z.union(['off', 'full']).description('Overrides the global wire for this model.'),
|
|
107
|
+
historyEmptyThink: z.boolean().description('Overrides historyEmptyThink for this model.'),
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
export const Config = z.object({
|
|
111
|
+
providers: z.array(z.string()).default(['rwkv']).description('Provider routes this adapter serves.'),
|
|
112
|
+
models: z.array(Model).default([]).volatile(),
|
|
113
|
+
thinking: z.union(['off', 'full']).default(DEFAULT_HARNESS.thinking)
|
|
114
|
+
.description('full = agent-wire-think-v1.0 (prompt ends with "Assistant: <think"); off = agent-wire-v1.0.').volatile(),
|
|
115
|
+
historyEmptyThink: z.boolean().default(DEFAULT_HARNESS.historyEmptyThink)
|
|
116
|
+
.description('true (default): empty <think></think> before past assistant steps; false: keep full past-step thinking in history.').volatile(),
|
|
117
|
+
maxSteps: z.natural().default(DEFAULT_HARNESS.maxSteps).description('Tool calls per user turn before the forced closeout.').volatile(),
|
|
118
|
+
maxConsecutiveFailures: z.natural().default(DEFAULT_HARNESS.maxConsecutiveFailures).volatile(),
|
|
119
|
+
protocolRetries: z.natural().default(DEFAULT_HARNESS.protocolRetries).volatile(),
|
|
120
|
+
decisionMaxTokens: z.natural().default(DEFAULT_HARNESS.decisionMaxTokens).volatile(),
|
|
121
|
+
answerMaxTokens: z.natural().default(DEFAULT_HARNESS.answerMaxTokens).volatile(),
|
|
122
|
+
sampling: z.object({
|
|
123
|
+
temperature: z.number().default(DEFAULT_HARNESS.sampling.temperature),
|
|
124
|
+
topK: z.natural().default(DEFAULT_HARNESS.sampling.topK),
|
|
125
|
+
topP: z.number().default(DEFAULT_HARNESS.sampling.topP),
|
|
126
|
+
presencePenalty: z.number().default(DEFAULT_HARNESS.sampling.presencePenalty),
|
|
127
|
+
frequencyPenalty: z.number().default(DEFAULT_HARNESS.sampling.frequencyPenalty),
|
|
128
|
+
penaltyDecay: z.number().default(DEFAULT_HARNESS.sampling.penaltyDecay),
|
|
129
|
+
}).default(DEFAULT_HARNESS.sampling).description('Defaults are the agent-fast preset.').volatile(),
|
|
130
|
+
taskContract: z.string().default('').description('Appended to the RWKV system prompt as "Task-specific contract".').volatile(),
|
|
131
|
+
toolMode: z.union(['mapped', 'passthrough']).default('mapped')
|
|
132
|
+
.description('mapped: only DSH tools with an RWKV-trained counterpart (read/write/edit/glob/grep/bash/web); passthrough: all offered tools.').volatile(),
|
|
133
|
+
toolNames: z.union(['dsh', 'trained']).default('dsh')
|
|
134
|
+
.description('dsh: DSH tool names (read, glob, ...) and DSH\'s system prompt without the sections for tools the RWKV preset does not mount; trained: the agent-tool-v3 names (read_file, ...) and the Go-aligned prompt.').volatile(),
|
|
135
|
+
excludeTools: z.array(z.string()).default([]).description('Tool names (DSH or RWKV) hidden from the model.').volatile(),
|
|
136
|
+
toolOverrides: z.dict(z.object({ description: z.string(), arguments: z.dict(z.string()) })).default({})
|
|
137
|
+
.description('Experiment only: replace tool descriptions / argument placeholders by tool name. Anything set here breaks parity with the training data.').volatile(),
|
|
138
|
+
includeDeveloper: z.boolean().default(false).description('Show DSH developer/context messages to the model as user notes.').volatile(),
|
|
139
|
+
currentDate: z.boolean().default(true)
|
|
140
|
+
.description('End the system prompt with "Current date: YYYY-MM-DD (zone, UTC±hh:mm)." for this machine\'s time zone; DSH time-context readings are then left out of the history. Off: no date line; readings appear as "Current time: ..." notes.').volatile(),
|
|
141
|
+
timeZone: z.string().default('')
|
|
142
|
+
.description('IANA time zone for the date line (e.g. Asia/Shanghai). Empty: this machine\'s zone.').volatile(),
|
|
143
|
+
loopGuard: z.boolean().default(true).description('Client-side repetition cut-off.').volatile(),
|
|
144
|
+
outputRepairs: z.boolean().default(DEFAULT_HARNESS.outputRepairs)
|
|
145
|
+
.description('Fix near-miss output: parser repairs, tool name / argument aliases, scalar coercion, DSH value repairs, path repair. Off: exact protocol form only, arguments reach DSH as written.').volatile(),
|
|
146
|
+
guards: z.boolean().default(DEFAULT_HARNESS.guards)
|
|
147
|
+
.description('Harness interventions: format re-asks, duplicate / failure gates, over-budget think close, answer-stage re-asks and fallbacks. Off: the model\'s output stands.').volatile(),
|
|
148
|
+
duplicateGateMode: z.union(['epoch', 'bounded', 'adjacent', 'off']).default('bounded')
|
|
149
|
+
.description('Duplicate gate mode when guards is true: bounded (default), epoch, adjacent (only consecutive identical calls), or off.').volatile(),
|
|
150
|
+
answerOpenerMode: z.union(['default', 'zh-only', 'none']).default('zh-only')
|
|
151
|
+
.description('Attempt-2 answer prefill mode: zh-only (default, avoids English opener collision), default, or none.').volatile(),
|
|
152
|
+
fallbackSummary: z.boolean().default(false)
|
|
153
|
+
.description('When answerStage fails, replace empty prose with "I looked up..." summary instead of salvaging reasoning/prose.').volatile(),
|
|
154
|
+
editMode: z.union(['tolerant', 'line-edit', 'literal']).default('tolerant')
|
|
155
|
+
.description('tolerant (default): recall-tolerant `edit` + syntax guard. line-edit: anchored batch `edit_lines` (`start_text` self-healing + atomic `edits[]` + <=200-line read cap). literal: exact `edit`.').volatile(),
|
|
156
|
+
historyMode: z.union(['auto-fold', 'full', 'relay', 'worklist']).default('auto-fold')
|
|
157
|
+
.description('auto-fold (default): immediate <=2k prior-turn compaction + 13.5k->9k batch in-place observation masking (<250 tok exempt, recent 3 pairs kept, 14.5k stage archive). full: renders the whole conversation. worklist: active `todo_plan` + `todo_update`. relay: model-written handoff cards.').volatile(),
|
|
158
|
+
relayBudgetTokens: z.natural().default(DEFAULT_RELAY_BUDGET_TOKENS)
|
|
159
|
+
.description('relay: exact RWKV token budget for the part of the leg that gets carded; the latest call/result pair is always kept.').volatile(),
|
|
160
|
+
relayCardMaxTokens: z.natural().default(DEFAULT_RELAY_CARD_MAX_TOKENS)
|
|
161
|
+
.description('relay: output cap of one handoff recap.').volatile(),
|
|
162
|
+
worklistMinFoldTokens: z.natural().default(DEFAULT_WORKLIST_MIN_FOLD_TOKENS)
|
|
163
|
+
.description('worklist: minimum RWKV prompt tokens (low watermark) before a noted `todo_update` folds earlier tool outputs.').volatile(),
|
|
164
|
+
worklistBudgetTokens: z.natural().default(DEFAULT_WORKLIST_BUDGET_TOKENS)
|
|
165
|
+
.description('auto-fold/worklist: total RWKV prompt token high watermark (13500 default in auto-fold v2).').volatile(),
|
|
166
|
+
worklistKeepRecentPairs: z.natural().default(DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS)
|
|
167
|
+
.description('auto-fold/worklist: recent workspace call/result pairs kept unmasked across a fold (3 default in auto-fold v2).').volatile(),
|
|
168
|
+
worklistEpochTargetTokens: z.natural().default(DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS)
|
|
169
|
+
.description('auto-fold: low-watermark target tokens on batch fold (9000 default in auto-fold v2; 0 disables epoch jump).').volatile(),
|
|
170
|
+
worklistExemptResultTokens: z.natural().default(DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS)
|
|
171
|
+
.description('auto-fold: tool results shorter than this RWKV token count are exempt from in-place masking (250 default).').volatile(),
|
|
172
|
+
worklistBackboneMaxTokens: z.natural().default(DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS)
|
|
173
|
+
.description('auto-fold/worklist: maximum RWKV tokens kept for completed prior turns (2000 default in auto-fold v2).').volatile(),
|
|
174
|
+
worklistHardCapTokens: z.natural().default(0)
|
|
175
|
+
.description('auto-fold/worklist: hard RWKV token safety ceiling (0 = auto: budgetTokens + 1000 = 14500 in auto-fold v2).').volatile(),
|
|
176
|
+
worklistImmediatePriorFold: z.boolean().default(true)
|
|
177
|
+
.description('auto-fold: immediately compact completed prior turns on turn boundary instead of waiting for minFoldTokens mid-turn.').volatile(),
|
|
178
|
+
worklistInPlaceMask: z.boolean().default(true)
|
|
179
|
+
.description('auto-fold: mask old tool results in-place while keeping assistant tool-call arguments untouched.').volatile(),
|
|
180
|
+
worklistPinUneditedRead: z.boolean().default(false)
|
|
181
|
+
.description('auto-fold/worklist: pin up to one latest unedited read (<= 2400 tokens) across a fold boundary when it fits inside budgetTokens.').volatile(),
|
|
182
|
+
recordTraces: z.boolean().default(true)
|
|
183
|
+
.description('Write RWKV traces (prompt bytes + raw output, outcome, repairs) to disk: rwkv-trace.jsonl next to each DSH session log, or traceDir. They are always kept in memory for the RWKV tab.').volatile(),
|
|
184
|
+
traceDir: z.string().default('').description('Custom trace directory (<session>.jsonl per session); empty = next to the DSH session logs.').volatile(),
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
function traceLocationOf(config: Config): TraceLocation {
|
|
188
|
+
return new TraceLocation(config.traceDir.get())
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const CONTEXT_FOLD_RECORD = 'plugin:rwkv-llm/context-fold'
|
|
192
|
+
const appendRecord = appendPluginRecord as unknown as (session: object, type: string, data: unknown) => unknown
|
|
193
|
+
|
|
194
|
+
function settingsOf(config: Config, ctx: Context): AdapterSettings {
|
|
195
|
+
const editMode = config.editMode.get()
|
|
196
|
+
const emitFold = (sessionId: string, fold: { readonly kind: string; readonly beforeTokens: number; readonly afterTokens: number; readonly foldedTools: number }) => {
|
|
197
|
+
try {
|
|
198
|
+
const sessions = (ctx as unknown as { get?(name: string): unknown }).get?.('sessions') as { get?(id: string): object | undefined } | undefined
|
|
199
|
+
const session = sessions?.get?.(sessionId)
|
|
200
|
+
if (session !== undefined) appendRecord(session, CONTEXT_FOLD_RECORD, fold)
|
|
201
|
+
} catch {
|
|
202
|
+
// Session log unavailable in minimal compositions: ignore cleanly.
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
models: config.models.get(),
|
|
207
|
+
harness: {
|
|
208
|
+
thinking: config.thinking.get(),
|
|
209
|
+
historyEmptyThink: config.historyEmptyThink.get(),
|
|
210
|
+
maxSteps: config.maxSteps.get(),
|
|
211
|
+
maxConsecutiveFailures: config.maxConsecutiveFailures.get(),
|
|
212
|
+
protocolRetries: config.protocolRetries.get(),
|
|
213
|
+
decisionMaxTokens: config.decisionMaxTokens.get(),
|
|
214
|
+
answerMaxTokens: config.answerMaxTokens.get(),
|
|
215
|
+
sampling: config.sampling.get(),
|
|
216
|
+
outputRepairs: config.outputRepairs.get(),
|
|
217
|
+
guards: config.guards.get(),
|
|
218
|
+
duplicateGateMode: config.duplicateGateMode.get(),
|
|
219
|
+
answerOpenerMode: config.answerOpenerMode.get(),
|
|
220
|
+
fallbackSummary: config.fallbackSummary.get(),
|
|
221
|
+
...config.taskContract.get() ? { taskContract: config.taskContract.get() } : {},
|
|
222
|
+
},
|
|
223
|
+
toolMode: config.toolMode.get(),
|
|
224
|
+
toolNames: config.toolNames.get(),
|
|
225
|
+
editMode,
|
|
226
|
+
excludeTools: config.excludeTools.get(),
|
|
227
|
+
...Object.keys(config.toolOverrides.get()).length ? { toolOverrides: config.toolOverrides.get() } : {},
|
|
228
|
+
includeDeveloper: config.includeDeveloper.get(),
|
|
229
|
+
currentDate: config.currentDate.get(),
|
|
230
|
+
...config.timeZone.get() ? { timeZone: config.timeZone.get() } : {},
|
|
231
|
+
loopGuard: config.loopGuard.get(),
|
|
232
|
+
...resolveHistoryModeConfig({
|
|
233
|
+
historyMode: config.historyMode.get(),
|
|
234
|
+
relayBudgetTokens: config.relayBudgetTokens.get(),
|
|
235
|
+
relayCardMaxTokens: config.relayCardMaxTokens.get(),
|
|
236
|
+
worklistMinFoldTokens: config.worklistMinFoldTokens.get(),
|
|
237
|
+
worklistBudgetTokens: config.worklistBudgetTokens.get(),
|
|
238
|
+
worklistKeepRecentPairs: config.worklistKeepRecentPairs.get(),
|
|
239
|
+
worklistEpochTargetTokens: config.worklistEpochTargetTokens.get(),
|
|
240
|
+
worklistExemptResultTokens: config.worklistExemptResultTokens.get(),
|
|
241
|
+
worklistBackboneMaxTokens: config.worklistBackboneMaxTokens.get(),
|
|
242
|
+
worklistHardCapTokens: config.worklistHardCapTokens.get(),
|
|
243
|
+
worklistImmediatePriorFold: config.worklistImmediatePriorFold.get(),
|
|
244
|
+
worklistInPlaceMask: config.worklistInPlaceMask.get(),
|
|
245
|
+
worklistPinUneditedRead: config.worklistPinUneditedRead.get(),
|
|
246
|
+
}),
|
|
247
|
+
...config.recordTraces.get() ? { traces: traceLocationOf(config) } : {},
|
|
248
|
+
onFoldEvent: emitFold,
|
|
249
|
+
log: message => console.log(`[rwkv-llm] ${message}`),
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function apply(ctx: Context, config: Config): void {
|
|
254
|
+
const adapter = new RwkvAdapter(() => settingsOf(config, ctx))
|
|
255
|
+
ctx.llm.registerAdapter(config.providers, adapter)
|
|
256
|
+
;(ctx as unknown as { provide: (service: string, value: unknown) => void }).provide(
|
|
257
|
+
'rwkvSessionCleanup',
|
|
258
|
+
async (sessionId: string): Promise<void> => {
|
|
259
|
+
setFoldedUnreadPaths(sessionId, [])
|
|
260
|
+
await flushAndEvictSessionTrace(sessionId)
|
|
261
|
+
},
|
|
262
|
+
)
|
|
263
|
+
// Long tool results in RWKV sessions: cut once when the tool runs, the rest saved to a file.
|
|
264
|
+
applyResultBudget(ctx, {
|
|
265
|
+
providers: () => config.providers,
|
|
266
|
+
maxReadLines: () => maxReadLinesForEditMode(config.editMode.get()),
|
|
267
|
+
log: message => console.log(`[rwkv-llm] ${message}`),
|
|
268
|
+
})
|
|
269
|
+
// Edit-mode host hooks (`tolerant` / `literal` + live `editMode` sync).
|
|
270
|
+
installEditModeHooks(ctx, {
|
|
271
|
+
providers: () => config.providers,
|
|
272
|
+
editMode: () => config.editMode.get(),
|
|
273
|
+
outputRepairs: () => config.outputRepairs.get(),
|
|
274
|
+
guards: () => config.guards.get(),
|
|
275
|
+
})
|
|
276
|
+
// Server model list and state list / upload / delete for the settings page, behind the /api
|
|
277
|
+
// bridge's authentication (client-connection runs this waterfall only for
|
|
278
|
+
// admitted requests). Absent in compositions without a Web connection.
|
|
279
|
+
const on = ctx.on as unknown as (
|
|
280
|
+
event: string,
|
|
281
|
+
listener: (request: IncomingMessage, response: ServerResponse, next: () => Promise<void>) => Promise<void>,
|
|
282
|
+
) => () => void
|
|
283
|
+
on.call(ctx, 'connection/request', async (request, response, next) => {
|
|
284
|
+
if (handleTraceRoute(request, response, () => ({ location: traceLocationOf(config), recording: config.recordTraces.get() }))) return
|
|
285
|
+
if (!await handleServerRoute(request, response)) await next()
|
|
286
|
+
})
|
|
287
|
+
}
|
package/src/line-edit.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// DSH plugin entry `dsh-rwkv-plugin/line-edit`: mounts the Anchored Batch
|
|
2
|
+
// `edit_lines` tool (`src/edit-modes/line-edit.ts`).
|
|
3
|
+
|
|
4
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
5
|
+
import { applyLineEditPlugin } from './edit-modes/line-edit.ts'
|
|
6
|
+
import { EDIT_LINES_TOOL } from './edit-modes/observations.ts'
|
|
7
|
+
|
|
8
|
+
export { EDIT_LINES_TOOL }
|
|
9
|
+
|
|
10
|
+
export const name = 'rwkv-edit-lines'
|
|
11
|
+
export const inject = ['tools', 'fs']
|
|
12
|
+
|
|
13
|
+
export function apply(ctx: Context): void {
|
|
14
|
+
applyLineEditPlugin(ctx)
|
|
15
|
+
}
|
package/src/live-wire.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// In-memory live RWKV wire state + pub/sub for real-time SSE streaming to the
|
|
2
|
+
// right-sidebar "RWKV 实时上下文" panel (`/api/rwkv/live/<session>`).
|
|
3
|
+
|
|
4
|
+
import type { ContextFoldEvent } from './core/fold-window.ts'
|
|
5
|
+
import { countTokens } from './tokenizer.ts'
|
|
6
|
+
|
|
7
|
+
const WIRE_SPLIT_RE = /(?=\n\n(?:System:|User:|Assistant:|Tool:))/g
|
|
8
|
+
|
|
9
|
+
/** Exact RWKV token count per role block (matches `WirePanel.tsx` block splitting). */
|
|
10
|
+
export function countWireBlockTokens(raw: string): number[] {
|
|
11
|
+
if (raw === '') return []
|
|
12
|
+
return raw.split(WIRE_SPLIT_RE).map(part => countTokens(part.replace(/^\n+/, '')))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface LiveWireSnapshot {
|
|
16
|
+
readonly sessionId: string
|
|
17
|
+
readonly model: string
|
|
18
|
+
readonly stage: 'decision' | 'answer' | 'card' | 'idle'
|
|
19
|
+
readonly streaming: boolean
|
|
20
|
+
readonly prompt: string
|
|
21
|
+
readonly fullPrompt?: string
|
|
22
|
+
readonly promptTokens: number
|
|
23
|
+
readonly blockTokens?: readonly number[]
|
|
24
|
+
readonly fullBlockTokens?: readonly number[]
|
|
25
|
+
readonly pastThinks?: readonly string[]
|
|
26
|
+
readonly output: string
|
|
27
|
+
readonly outputTokens: number
|
|
28
|
+
readonly fold?: ContextFoldEvent
|
|
29
|
+
readonly updatedAt: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type LiveWireEvent =
|
|
33
|
+
| { readonly type: 'snapshot'; readonly state: LiveWireSnapshot }
|
|
34
|
+
| { readonly type: 'delta'; readonly text: string }
|
|
35
|
+
| { readonly type: 'done'; readonly output: string; readonly outputTokens: number; readonly updatedAt: string }
|
|
36
|
+
|
|
37
|
+
type Listener = (event: LiveWireEvent) => void
|
|
38
|
+
|
|
39
|
+
class LiveWireHub {
|
|
40
|
+
private readonly states = new Map<string, LiveWireSnapshot>()
|
|
41
|
+
private readonly listeners = new Map<string, Set<Listener>>()
|
|
42
|
+
private readonly maxSessions = 50
|
|
43
|
+
|
|
44
|
+
get(sessionId: string): LiveWireSnapshot | undefined {
|
|
45
|
+
return this.states.get(sessionId)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
start(
|
|
49
|
+
sessionId: string,
|
|
50
|
+
info: {
|
|
51
|
+
readonly model: string
|
|
52
|
+
readonly stage: 'decision' | 'answer' | 'card'
|
|
53
|
+
readonly prompt: string
|
|
54
|
+
readonly fullPrompt?: string
|
|
55
|
+
readonly promptTokens: number
|
|
56
|
+
readonly pastThinks?: readonly string[]
|
|
57
|
+
readonly fold?: ContextFoldEvent
|
|
58
|
+
},
|
|
59
|
+
): void {
|
|
60
|
+
const state: LiveWireSnapshot = {
|
|
61
|
+
sessionId,
|
|
62
|
+
model: info.model,
|
|
63
|
+
stage: info.stage,
|
|
64
|
+
streaming: true,
|
|
65
|
+
prompt: info.prompt,
|
|
66
|
+
...(info.fullPrompt === undefined ? {} : { fullPrompt: info.fullPrompt }),
|
|
67
|
+
promptTokens: info.promptTokens,
|
|
68
|
+
blockTokens: countWireBlockTokens(info.prompt),
|
|
69
|
+
...(info.fullPrompt === undefined ? {} : { fullBlockTokens: countWireBlockTokens(info.fullPrompt) }),
|
|
70
|
+
...(info.pastThinks === undefined ? {} : { pastThinks: info.pastThinks }),
|
|
71
|
+
output: '',
|
|
72
|
+
outputTokens: 0,
|
|
73
|
+
...(info.fold === undefined ? {} : { fold: info.fold }),
|
|
74
|
+
updatedAt: new Date().toISOString(),
|
|
75
|
+
}
|
|
76
|
+
this.states.delete(sessionId)
|
|
77
|
+
this.states.set(sessionId, state)
|
|
78
|
+
for (const key of this.states.keys()) {
|
|
79
|
+
if (this.states.size <= this.maxSessions) break
|
|
80
|
+
if (!this.listeners.has(key)) this.states.delete(key)
|
|
81
|
+
}
|
|
82
|
+
this.emit(sessionId, { type: 'snapshot', state })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
delta(sessionId: string, text: string): void {
|
|
86
|
+
if (text === '') return
|
|
87
|
+
const current = this.states.get(sessionId)
|
|
88
|
+
if (current === undefined) return
|
|
89
|
+
this.states.set(sessionId, { ...current, output: current.output + text })
|
|
90
|
+
this.emit(sessionId, { type: 'delta', text })
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
finish(sessionId: string, info: { readonly output: string; readonly outputTokens: number }): void {
|
|
94
|
+
const current = this.states.get(sessionId)
|
|
95
|
+
if (current === undefined) return
|
|
96
|
+
const updatedAt = new Date().toISOString()
|
|
97
|
+
this.states.set(sessionId, {
|
|
98
|
+
...current,
|
|
99
|
+
streaming: false,
|
|
100
|
+
output: info.output,
|
|
101
|
+
outputTokens: info.outputTokens,
|
|
102
|
+
updatedAt,
|
|
103
|
+
})
|
|
104
|
+
this.emit(sessionId, { type: 'done', output: info.output, outputTokens: info.outputTokens, updatedAt })
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
subscribe(sessionId: string, listener: Listener): () => void {
|
|
108
|
+
let set = this.listeners.get(sessionId)
|
|
109
|
+
if (set === undefined) {
|
|
110
|
+
set = new Set()
|
|
111
|
+
this.listeners.set(sessionId, set)
|
|
112
|
+
}
|
|
113
|
+
set.add(listener)
|
|
114
|
+
return () => {
|
|
115
|
+
set.delete(listener)
|
|
116
|
+
if (set.size === 0) this.listeners.delete(sessionId)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private emit(sessionId: string, event: LiveWireEvent): void {
|
|
121
|
+
const set = this.listeners.get(sessionId)
|
|
122
|
+
if (set === undefined) return
|
|
123
|
+
for (const listener of set) {
|
|
124
|
+
try {
|
|
125
|
+
listener(event)
|
|
126
|
+
} catch {
|
|
127
|
+
// Ignore broken subscriber streams.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export const liveWire = new LiveWireHub()
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Path repair for file tool calls. G1 copies the long absolute working
|
|
2
|
+
// directory from the runtime context and often drops its last component
|
|
3
|
+
// (".../task/ws/a.py" written as ".../task/a.py"). A path is rewritten only
|
|
4
|
+
// when it does not exist and the repaired path does, so a correct path, a new
|
|
5
|
+
// file, or a deliberate path outside the workspace is passed through as is.
|
|
6
|
+
|
|
7
|
+
import { existsSync } from 'node:fs'
|
|
8
|
+
import { tmpdir } from 'node:os'
|
|
9
|
+
import { basename, dirname, isAbsolute, join } from 'node:path'
|
|
10
|
+
import type { HistoryItem } from './core/policy.ts'
|
|
11
|
+
|
|
12
|
+
const CWD_PATTERN = /Current working directory: "([^"]+)"/
|
|
13
|
+
|
|
14
|
+
/** The working directory DSH last announced in its runtime-context message. */
|
|
15
|
+
export function runtimeCwd(history: readonly HistoryItem[]): string | undefined {
|
|
16
|
+
for (let index = history.length - 1; index >= 0; index--) {
|
|
17
|
+
const item = history[index]!
|
|
18
|
+
if (item.kind !== 'user' && item.kind !== 'note') continue
|
|
19
|
+
const match = CWD_PATTERN.exec(item.text)
|
|
20
|
+
if (match) return match[1]
|
|
21
|
+
}
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const GHOST_WORKSPACE_ROOTS = [
|
|
26
|
+
'/home/user/project',
|
|
27
|
+
'/home/user',
|
|
28
|
+
'/workspace',
|
|
29
|
+
'/home/agent',
|
|
30
|
+
'/app',
|
|
31
|
+
] as const
|
|
32
|
+
|
|
33
|
+
const SPILL_SUFFIX_PATTERN = /\/(dsh-spill-[^/]+(?:\/.*)?)$/i
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* macOS spill-path self-healing: models trained in Linux containers often
|
|
37
|
+
* rewrite `/var/folders/.../T/dsh-spill-...` as `/tmp/dsh-spill-...` (or
|
|
38
|
+
* mangle the random macOS tmpdir prefix). Remap to the real OS tmpdir only
|
|
39
|
+
* when the original path does not exist and the remapped spill path does.
|
|
40
|
+
*/
|
|
41
|
+
function repairSpillPath(path: string, tempDir: string): string | undefined {
|
|
42
|
+
if (!isAbsolute(path) || existsSync(path)) return undefined
|
|
43
|
+
const match = SPILL_SUFFIX_PATTERN.exec(path)
|
|
44
|
+
if (!match) return undefined
|
|
45
|
+
const suffix = match[1]!
|
|
46
|
+
const normalized = suffix.replace(/^dsh-spill-/i, 'dsh-spill-')
|
|
47
|
+
const candidates = normalized === suffix
|
|
48
|
+
? [join(tempDir, normalized)]
|
|
49
|
+
: [join(tempDir, normalized), join(tempDir, suffix)]
|
|
50
|
+
return candidates.find(candidate => existsSync(candidate))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function repairPath(path: string, cwd: string): string {
|
|
54
|
+
if (!isAbsolute(path) || existsSync(path)) return path
|
|
55
|
+
const parent = dirname(cwd)
|
|
56
|
+
const candidates: string[] = []
|
|
57
|
+
if (path.startsWith(`${parent}/`) && !path.startsWith(`${cwd}/`)) candidates.push(join(cwd, path.slice(parent.length + 1)))
|
|
58
|
+
for (const root of GHOST_WORKSPACE_ROOTS) {
|
|
59
|
+
if (path === root) {
|
|
60
|
+
candidates.push(cwd)
|
|
61
|
+
} else if (path.startsWith(`${root}/`) && cwd !== root && !cwd.startsWith(`${root}/`)) {
|
|
62
|
+
candidates.push(join(cwd, path.slice(root.length + 1)))
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
candidates.push(join(cwd, basename(path)))
|
|
66
|
+
return candidates.find(candidate => existsSync(candidate)) ?? path
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const FILE_TOOLS = new Set(['read', 'write', 'edit', 'edit_lines', 'glob', 'grep'])
|
|
70
|
+
|
|
71
|
+
/** DSH-side arguments with file_path / path repaired; the same object when nothing changed. */
|
|
72
|
+
export function repairToolPaths(
|
|
73
|
+
dshName: string,
|
|
74
|
+
args: Record<string, unknown>,
|
|
75
|
+
cwd: string | undefined,
|
|
76
|
+
tempDir: string = tmpdir(),
|
|
77
|
+
): Record<string, unknown> {
|
|
78
|
+
if (!FILE_TOOLS.has(dshName)) return args
|
|
79
|
+
const hasCwd = cwd !== undefined && existsSync(cwd)
|
|
80
|
+
let out: Record<string, unknown> | undefined
|
|
81
|
+
for (const key of ['file_path', 'path']) {
|
|
82
|
+
const value = args[key]
|
|
83
|
+
if (typeof value !== 'string') continue
|
|
84
|
+
const repaired = repairSpillPath(value, tempDir) ?? (hasCwd ? repairPath(value, cwd) : value)
|
|
85
|
+
if (repaired !== value) {
|
|
86
|
+
out ??= { ...args }
|
|
87
|
+
out[key] = repaired
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out ?? args
|
|
91
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Handoff cards of RWKV relay sessions: one JSON line per card, stored next to
|
|
2
|
+
// the session's trace file. The evaluators run one DSH process per user turn,
|
|
3
|
+
// so a resumed session rebuilds its cards from here instead of regenerating
|
|
4
|
+
// them (a model-written card is not reproducible).
|
|
5
|
+
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { dirname } from 'node:path'
|
|
8
|
+
import type { RelayCard } from './core/relay.ts'
|
|
9
|
+
import type { TraceLocation } from './traces.ts'
|
|
10
|
+
|
|
11
|
+
function decode(line: string): RelayCard | undefined {
|
|
12
|
+
let value: unknown
|
|
13
|
+
try {
|
|
14
|
+
value = JSON.parse(line)
|
|
15
|
+
} catch {
|
|
16
|
+
return undefined
|
|
17
|
+
}
|
|
18
|
+
if (typeof value !== 'object' || value === null) return undefined
|
|
19
|
+
const card = value as Partial<RelayCard>
|
|
20
|
+
if (!Number.isInteger(card.at) || typeof card.turn !== 'number' || typeof card.task !== 'string'
|
|
21
|
+
|| typeof card.text !== 'string' || typeof card.hash !== 'string') return undefined
|
|
22
|
+
return { at: card.at!, turn: card.turn, task: card.task, text: card.text, hash: card.hash }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Per-session card lists; reads the file once, then follows appends in memory. */
|
|
26
|
+
export class RelayCardStore {
|
|
27
|
+
private readonly bySession = new Map<string, RelayCard[]>()
|
|
28
|
+
|
|
29
|
+
/** Cards of `session`, oldest first; empty when nothing is stored yet. */
|
|
30
|
+
load(location: TraceLocation, session: string): readonly RelayCard[] {
|
|
31
|
+
const cached = this.bySession.get(session)
|
|
32
|
+
if (cached !== undefined) return cached
|
|
33
|
+
const file = location.relayPath(session)
|
|
34
|
+
const cards: RelayCard[] = []
|
|
35
|
+
if (file !== undefined && existsSync(file)) {
|
|
36
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
37
|
+
if (line.trim() === '') continue
|
|
38
|
+
const card = decode(line)
|
|
39
|
+
if (card !== undefined) cards.push(card)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
this.bySession.set(session, cards)
|
|
43
|
+
return cards
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Append one card; the file is created on demand. Failures leave the card in memory only. */
|
|
47
|
+
append(location: TraceLocation, session: string, card: RelayCard): void {
|
|
48
|
+
const cards = this.bySession.get(session)
|
|
49
|
+
if (cards !== undefined) cards.push(card)
|
|
50
|
+
const file = location.relayPath(session)
|
|
51
|
+
if (file === undefined) return
|
|
52
|
+
try {
|
|
53
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
54
|
+
appendFileSync(file, `${JSON.stringify(card)}\n`)
|
|
55
|
+
} catch {
|
|
56
|
+
// The session keeps the card in memory; a resumed process regenerates it.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|