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
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// Shared continuation contract for the RWKV backends, ported from RWKV-Agent
|
|
2
|
+
// internal/continuation (continuation.go, loopguard.go, httputil).
|
|
3
|
+
|
|
4
|
+
import { AGENT_FAST_SAMPLING, type SamplingDefaults } from '../core/defaults.ts'
|
|
5
|
+
import type { FinishReason } from '../core/parse.ts'
|
|
6
|
+
|
|
7
|
+
export type Sampling = SamplingDefaults
|
|
8
|
+
|
|
9
|
+
/** agent-fast: default RWKV-7 G1 multi-step agent sampling preset. */
|
|
10
|
+
export const AGENT_FAST: Sampling = AGENT_FAST_SAMPLING
|
|
11
|
+
|
|
12
|
+
export interface GenerateRequest {
|
|
13
|
+
readonly prompt: string
|
|
14
|
+
readonly maxTokens: number
|
|
15
|
+
/** Decoded-text stops, matched on the client. */
|
|
16
|
+
readonly stops: readonly string[]
|
|
17
|
+
readonly sampling: Sampling
|
|
18
|
+
readonly signal?: AbortSignal
|
|
19
|
+
/** Sticks a multi-card gateway to one card so the prefix cache hits across steps. */
|
|
20
|
+
readonly sessionId?: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface GenerateResult {
|
|
24
|
+
readonly text: string
|
|
25
|
+
readonly finish: FinishReason
|
|
26
|
+
/** The client stop string that ended the generation, consumed from text. */
|
|
27
|
+
readonly stop?: string
|
|
28
|
+
readonly promptTokens?: number
|
|
29
|
+
readonly completionTokens?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Generator {
|
|
33
|
+
generate(request: GenerateRequest, onDelta?: (text: string) => void): Promise<GenerateResult>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class BackendError extends Error {
|
|
37
|
+
readonly code: string
|
|
38
|
+
readonly status?: number
|
|
39
|
+
|
|
40
|
+
constructor(message: string, code: string, status?: number) {
|
|
41
|
+
super(message)
|
|
42
|
+
this.name = 'BackendError'
|
|
43
|
+
this.code = code
|
|
44
|
+
if (status !== undefined) this.status = status
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Splits pending text at the earliest stop. Without a stop, the longest tail
|
|
50
|
+
* that could still begin a stop is held back so a stop split across chunks is
|
|
51
|
+
* never emitted.
|
|
52
|
+
*/
|
|
53
|
+
export function splitAtStop(pending: string, stops: readonly string[]): { safe: string; tail: string; stop?: string } {
|
|
54
|
+
let best = -1
|
|
55
|
+
let bestStop = ''
|
|
56
|
+
for (const stop of stops) {
|
|
57
|
+
if (stop === '') continue
|
|
58
|
+
const index = pending.indexOf(stop)
|
|
59
|
+
if (index >= 0 && (best < 0 || index < best)) {
|
|
60
|
+
best = index
|
|
61
|
+
bestStop = stop
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (best >= 0) return { safe: pending.slice(0, best), tail: '', stop: bestStop }
|
|
65
|
+
let hold = 0
|
|
66
|
+
for (const stop of stops) {
|
|
67
|
+
for (let length = Math.min(stop.length - 1, pending.length); length > hold; length--) {
|
|
68
|
+
if (pending.endsWith(stop.slice(0, length))) {
|
|
69
|
+
hold = length
|
|
70
|
+
break
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { safe: pending.slice(0, pending.length - hold), tail: pending.slice(pending.length - hold) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const GRAM = 24
|
|
78
|
+
const WINDOW = 768
|
|
79
|
+
const FRESH_PERMILLE = 50
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Streaming repetition detector calibrated on 7000+ RWKV outputs with no false
|
|
83
|
+
* positive: over the last 768 24-char windows, fewer than 5% seen for the
|
|
84
|
+
* first time means the model is looping.
|
|
85
|
+
*/
|
|
86
|
+
export class LoopGuard {
|
|
87
|
+
private readonly seen = new Set<string>()
|
|
88
|
+
private readonly fresh: boolean[] = new Array<boolean>(WINDOW).fill(false)
|
|
89
|
+
private runes: string[] = []
|
|
90
|
+
private grams = 0
|
|
91
|
+
private next = 0
|
|
92
|
+
private freshCount = 0
|
|
93
|
+
tripped = false
|
|
94
|
+
|
|
95
|
+
write(text: string): boolean {
|
|
96
|
+
if (this.tripped) return true
|
|
97
|
+
for (const char of text) {
|
|
98
|
+
this.runes.push(char)
|
|
99
|
+
if (this.runes.length > GRAM * 4) this.runes = this.runes.slice(-GRAM)
|
|
100
|
+
if (this.runes.length < GRAM) continue
|
|
101
|
+
const gram = this.runes.slice(-GRAM).join('')
|
|
102
|
+
const isNew = !this.seen.has(gram)
|
|
103
|
+
if (isNew) this.seen.add(gram)
|
|
104
|
+
if (this.grams >= WINDOW && this.fresh[this.next]) this.freshCount--
|
|
105
|
+
this.fresh[this.next] = isNew
|
|
106
|
+
if (isNew) this.freshCount++
|
|
107
|
+
this.next = (this.next + 1) % WINDOW
|
|
108
|
+
this.grams++
|
|
109
|
+
if (this.grams >= WINDOW && this.freshCount * 1000 < WINDOW * FRESH_PERMILLE) {
|
|
110
|
+
this.tripped = true
|
|
111
|
+
return true
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Yields the data payloads of an SSE body until [DONE]. */
|
|
119
|
+
export async function* sseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
120
|
+
const decoder = new TextDecoder()
|
|
121
|
+
let buffer = ''
|
|
122
|
+
for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {
|
|
123
|
+
buffer += decoder.decode(chunk, { stream: true })
|
|
124
|
+
let newline: number
|
|
125
|
+
while ((newline = buffer.indexOf('\n')) >= 0) {
|
|
126
|
+
const line = buffer.slice(0, newline).trim()
|
|
127
|
+
buffer = buffer.slice(newline + 1)
|
|
128
|
+
if (!line.startsWith('data:')) continue
|
|
129
|
+
const data = line.slice(5).trim()
|
|
130
|
+
if (data === '[DONE]') return
|
|
131
|
+
if (data !== '') yield data
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const last = buffer.trim()
|
|
135
|
+
if (last.startsWith('data:') && last.slice(5).trim() !== '[DONE]') yield last.slice(5).trim()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface StreamState {
|
|
139
|
+
text: string
|
|
140
|
+
pending: string
|
|
141
|
+
stop?: string
|
|
142
|
+
guard?: LoopGuard
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Feeds one decoded delta through client stops and the loop guard. Returns
|
|
147
|
+
* 'stop' or 'length' when the generation must end now.
|
|
148
|
+
*/
|
|
149
|
+
export function feedDelta(
|
|
150
|
+
state: StreamState,
|
|
151
|
+
delta: string,
|
|
152
|
+
stops: readonly string[],
|
|
153
|
+
onDelta?: (text: string) => void,
|
|
154
|
+
): 'stop' | 'length' | undefined {
|
|
155
|
+
state.pending += delta
|
|
156
|
+
const { safe, tail, stop } = splitAtStop(state.pending, stops)
|
|
157
|
+
state.pending = tail
|
|
158
|
+
if (safe !== '') {
|
|
159
|
+
state.text += safe
|
|
160
|
+
onDelta?.(safe)
|
|
161
|
+
}
|
|
162
|
+
if (stop !== undefined) {
|
|
163
|
+
state.stop = stop
|
|
164
|
+
return 'stop'
|
|
165
|
+
}
|
|
166
|
+
if (state.guard?.write(safe)) return 'length'
|
|
167
|
+
return undefined
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function flushPending(state: StreamState, onDelta?: (text: string) => void): void {
|
|
171
|
+
if (state.pending !== '') {
|
|
172
|
+
state.text += state.pending
|
|
173
|
+
onDelta?.(state.pending)
|
|
174
|
+
state.pending = ''
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function responseError(response: Response, secret?: string): Promise<BackendError> {
|
|
179
|
+
let body = ''
|
|
180
|
+
try {
|
|
181
|
+
body = (await response.text()).slice(0, 500)
|
|
182
|
+
} catch {
|
|
183
|
+
// The status alone still identifies the failure.
|
|
184
|
+
}
|
|
185
|
+
if (secret) body = body.split(secret).join('[REDACTED]')
|
|
186
|
+
const code = response.status === 413 ? 'PAYLOAD_TOO_LARGE' : response.status >= 500 ? 'PROVIDER_UNAVAILABLE' : 'PROVIDER_HTTP_ERROR'
|
|
187
|
+
return new BackendError(`HTTP ${response.status}: ${body || response.statusText}`, code, response.status)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Normalizes a configured base URL to its /v1 root. */
|
|
191
|
+
export function v1Root(baseURL: string): string {
|
|
192
|
+
const url = new URL(baseURL.trim())
|
|
193
|
+
let path = url.pathname.replace(/\/+$/, '')
|
|
194
|
+
for (const suffix of ['/batch/completions', '/chat/completions', '/completions', '/models']) {
|
|
195
|
+
if (path.endsWith(suffix)) {
|
|
196
|
+
path = path.slice(0, -suffix.length)
|
|
197
|
+
break
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (!path.endsWith('/v1')) path += '/v1'
|
|
201
|
+
url.pathname = path
|
|
202
|
+
url.search = ''
|
|
203
|
+
return url.toString().replace(/\/+$/, '')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Model ids the server lists (`GET /v1/models`; OpenAI shape). rwkv_lightning
|
|
208
|
+
* does not check the password there; iRWKV takes the bearer key.
|
|
209
|
+
*/
|
|
210
|
+
export async function listModels(baseURL: string, options: { apiKey?: string; headers?: Readonly<Record<string, string>> } = {}): Promise<string[]> {
|
|
211
|
+
const response = await fetch(`${v1Root(baseURL)}/models`, {
|
|
212
|
+
headers: { ...options.headers, ...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {} },
|
|
213
|
+
signal: AbortSignal.timeout(10_000),
|
|
214
|
+
})
|
|
215
|
+
if (!response.ok) throw await responseError(response, options.apiKey)
|
|
216
|
+
const body = await response.json() as { data?: { id?: unknown; status?: unknown }[]; loaded?: unknown }
|
|
217
|
+
const ids = (body.data ?? []).flatMap(item => typeof item.id === 'string' ? [item.id] : [])
|
|
218
|
+
// Dynamic-loading servers mark the resident model; list it first.
|
|
219
|
+
const loaded = typeof body.loaded === 'string' ? body.loaded : undefined
|
|
220
|
+
return loaded && ids.includes(loaded) ? [loaded, ...ids.filter(id => id !== loaded)] : ids
|
|
221
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// iRWKV (vLLM fork) raw continuation: POST /v1/completions with the RWKV
|
|
2
|
+
// sampling fields. No state or adapter support; the server prepends token 0,
|
|
3
|
+
// so add_special_tokens stays false. Ported from RWKV-Agent
|
|
4
|
+
// internal/continuation/irwkv.
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
responseError,
|
|
8
|
+
v1Root,
|
|
9
|
+
type GenerateRequest,
|
|
10
|
+
type GenerateResult,
|
|
11
|
+
type Generator,
|
|
12
|
+
} from './generator.ts'
|
|
13
|
+
import { readCompletionStream } from './stream.ts'
|
|
14
|
+
|
|
15
|
+
export interface IRWKVConfig {
|
|
16
|
+
readonly baseURL: string
|
|
17
|
+
readonly model: string
|
|
18
|
+
readonly apiKey?: string
|
|
19
|
+
/** Token-id stops; 24281 (bare "User") is never forwarded, see LightningConfig.stopTokens. */
|
|
20
|
+
readonly stopTokenIds?: readonly number[]
|
|
21
|
+
readonly headers?: Readonly<Record<string, string>>
|
|
22
|
+
readonly loopGuard?: boolean
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Caps server-side `stop` sequences to OpenAI/vLLM's 4-item limit while client
|
|
27
|
+
* stream matching still enforces all `request.stops`.
|
|
28
|
+
*/
|
|
29
|
+
export function capServerStops(stops: readonly string[], maxItems = 4): readonly string[] {
|
|
30
|
+
if (stops.length <= maxItems) return stops
|
|
31
|
+
// Drop superstrings already covered by a shorter non-empty prefix stop (e.g. "<tool_call>" vs "<tool_call").
|
|
32
|
+
const deduped = stops.filter(
|
|
33
|
+
s => s !== '' && !stops.some(other => other !== '' && other !== s && s.startsWith(other)),
|
|
34
|
+
)
|
|
35
|
+
if (deduped.length <= maxItems) return deduped
|
|
36
|
+
// Prefer dropping rare "\nSystem:" server-side first (client-side stream matcher still enforces all stops).
|
|
37
|
+
const withoutSystem = deduped.filter(s => s !== '\nSystem:')
|
|
38
|
+
if (withoutSystem.length <= maxItems) return withoutSystem
|
|
39
|
+
// Keep extra tail stops (like "<tool_call") plus earliest core stops.
|
|
40
|
+
const tailCount = Math.min(maxItems - 1, Math.max(1, withoutSystem.length - 3))
|
|
41
|
+
return [...withoutSystem.slice(0, maxItems - tailCount), ...withoutSystem.slice(-tailCount)]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class IRWKVClient implements Generator {
|
|
45
|
+
private readonly config: IRWKVConfig
|
|
46
|
+
private readonly root: string
|
|
47
|
+
|
|
48
|
+
constructor(config: IRWKVConfig) {
|
|
49
|
+
this.config = config
|
|
50
|
+
this.root = v1Root(config.baseURL)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async generate(request: GenerateRequest, onDelta?: (text: string) => void): Promise<GenerateResult> {
|
|
54
|
+
const controller = new AbortController()
|
|
55
|
+
const signal = request.signal ? AbortSignal.any([request.signal, controller.signal]) : controller.signal
|
|
56
|
+
const stopTokenIds = (this.config.stopTokenIds ?? []).filter(id => id !== 24281)
|
|
57
|
+
const body = {
|
|
58
|
+
model: this.config.model,
|
|
59
|
+
prompt: request.prompt,
|
|
60
|
+
max_tokens: request.maxTokens,
|
|
61
|
+
temperature: request.sampling.temperature,
|
|
62
|
+
top_k: request.sampling.topK,
|
|
63
|
+
top_p: request.sampling.topP,
|
|
64
|
+
presence_penalty: request.sampling.presencePenalty,
|
|
65
|
+
frequency_penalty: request.sampling.frequencyPenalty,
|
|
66
|
+
penalty_decay: request.sampling.penaltyDecay,
|
|
67
|
+
stop: capServerStops(request.stops),
|
|
68
|
+
...stopTokenIds.length > 0 ? { stop_token_ids: stopTokenIds } : {},
|
|
69
|
+
add_special_tokens: false,
|
|
70
|
+
stream: true,
|
|
71
|
+
stream_options: { include_usage: true },
|
|
72
|
+
}
|
|
73
|
+
const response = await fetch(`${this.root}/completions`, {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
headers: {
|
|
76
|
+
...this.config.headers,
|
|
77
|
+
'content-type': 'application/json',
|
|
78
|
+
...this.config.apiKey ? { authorization: `Bearer ${this.config.apiKey}` } : {},
|
|
79
|
+
...request.sessionId ? { 'x-rwkv-session-id': request.sessionId } : {},
|
|
80
|
+
},
|
|
81
|
+
body: JSON.stringify(body),
|
|
82
|
+
signal,
|
|
83
|
+
})
|
|
84
|
+
if (!response.ok || response.body === null) throw await responseError(response, this.config.apiKey)
|
|
85
|
+
try {
|
|
86
|
+
return await readCompletionStream(response.body, data => {
|
|
87
|
+
const chunk = data as {
|
|
88
|
+
choices?: { index?: number; text?: string; finish_reason?: string | null; stop_reason?: unknown }[]
|
|
89
|
+
usage?: { prompt_tokens?: number; completion_tokens?: number } | null
|
|
90
|
+
error?: unknown
|
|
91
|
+
object?: string
|
|
92
|
+
message?: string
|
|
93
|
+
}
|
|
94
|
+
const choice = chunk.choices?.find(item => (item.index ?? 0) === 0)
|
|
95
|
+
const error = chunk.error ? JSON.stringify(chunk.error) : chunk.object === 'error' ? chunk.message ?? 'error' : undefined
|
|
96
|
+
return {
|
|
97
|
+
delta: choice?.text ?? '',
|
|
98
|
+
...choice?.finish_reason ? { finish: choice.finish_reason } : {},
|
|
99
|
+
...typeof choice?.stop_reason === 'string' ? { stop: choice.stop_reason } : {},
|
|
100
|
+
...chunk.usage?.prompt_tokens ? { promptTokens: chunk.usage.prompt_tokens } : {},
|
|
101
|
+
...chunk.usage?.completion_tokens ? { completionTokens: chunk.usage.completion_tokens } : {},
|
|
102
|
+
...error ? { error } : {},
|
|
103
|
+
}
|
|
104
|
+
}, {
|
|
105
|
+
// The server already matched the text stops; matching again catches split variants.
|
|
106
|
+
stops: request.stops,
|
|
107
|
+
maxTokens: request.maxTokens,
|
|
108
|
+
loopGuard: this.config.loopGuard ?? true,
|
|
109
|
+
...onDelta ? { onDelta } : {},
|
|
110
|
+
abort: () => controller.abort(),
|
|
111
|
+
})
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (request.signal?.aborted) return { text: '', finish: 'cancelled' }
|
|
114
|
+
throw error
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// rwkv_lightning CUDA raw continuation: POST /v1/batch/completions with
|
|
2
|
+
// `contents`, integer stop_tokens, optional uploaded state_id or adapter_id.
|
|
3
|
+
// Ported from RWKV-Agent internal/continuation/rwkvlightning.
|
|
4
|
+
|
|
5
|
+
import { openAsBlob } from 'node:fs'
|
|
6
|
+
import { basename } from 'node:path'
|
|
7
|
+
import {
|
|
8
|
+
BackendError,
|
|
9
|
+
responseError,
|
|
10
|
+
v1Root,
|
|
11
|
+
type GenerateRequest,
|
|
12
|
+
type GenerateResult,
|
|
13
|
+
type Generator,
|
|
14
|
+
} from './generator.ts'
|
|
15
|
+
import { readCompletionStream } from './stream.ts'
|
|
16
|
+
|
|
17
|
+
/** rwkv_lightning_cuda rejects state uploads over 512 MiB. */
|
|
18
|
+
export const MAX_STATE_UPLOAD_BYTES = 512 << 20
|
|
19
|
+
/**
|
|
20
|
+
* The server's request-body cap is the state limit plus 1 MiB of form overhead,
|
|
21
|
+
* and adapter registration goes through the same cap. Cloudflare-fronted
|
|
22
|
+
* endpoints stop at 100 MB earlier; their 413 is explained in registeredAdapter.
|
|
23
|
+
*/
|
|
24
|
+
export const MAX_ADAPTER_UPLOAD_BYTES = MAX_STATE_UPLOAD_BYTES
|
|
25
|
+
|
|
26
|
+
export interface LightningConfig {
|
|
27
|
+
readonly baseURL: string
|
|
28
|
+
readonly model: string
|
|
29
|
+
readonly password?: string
|
|
30
|
+
readonly adapterId?: string
|
|
31
|
+
readonly stateId?: string
|
|
32
|
+
/** EOS only: 24281 (bare "User") also cuts "User(...)" inside thinking and code. */
|
|
33
|
+
readonly stopTokens?: readonly number[]
|
|
34
|
+
readonly headers?: Readonly<Record<string, string>>
|
|
35
|
+
readonly loopGuard?: boolean
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface AdapterInfo {
|
|
39
|
+
readonly id: string
|
|
40
|
+
readonly version?: string
|
|
41
|
+
readonly manifest?: Record<string, unknown>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** One entry of `GET /v1/state/list` (and the upload response). */
|
|
45
|
+
export interface StateInfo {
|
|
46
|
+
readonly state_id: string
|
|
47
|
+
readonly filename?: string
|
|
48
|
+
readonly original_filename?: string
|
|
49
|
+
readonly size_bytes?: number
|
|
50
|
+
readonly layers?: number
|
|
51
|
+
readonly heads?: number
|
|
52
|
+
readonly head_size?: number
|
|
53
|
+
readonly created_ms?: number
|
|
54
|
+
readonly uploaded_at?: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class LightningClient implements Generator {
|
|
58
|
+
private readonly config: LightningConfig
|
|
59
|
+
private readonly root: string
|
|
60
|
+
|
|
61
|
+
constructor(config: LightningConfig) {
|
|
62
|
+
this.config = config
|
|
63
|
+
this.root = v1Root(config.baseURL)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private headers(extra: Record<string, string> = {}): Record<string, string> {
|
|
67
|
+
// Ask for uncompressed JSON so rwkv_router gateways do not trip over gzipped backend adapter lists.
|
|
68
|
+
const merged = { ...this.config.headers, ...extra }
|
|
69
|
+
const hasAcceptEncoding = Object.keys(merged).some(key => key.toLowerCase() === 'accept-encoding')
|
|
70
|
+
return hasAcceptEncoding ? merged : { 'accept-encoding': 'identity', ...merged }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async generate(request: GenerateRequest, onDelta?: (text: string) => void): Promise<GenerateResult> {
|
|
74
|
+
const controller = new AbortController()
|
|
75
|
+
const signal = request.signal ? AbortSignal.any([request.signal, controller.signal]) : controller.signal
|
|
76
|
+
const body = {
|
|
77
|
+
model: this.config.model,
|
|
78
|
+
contents: [request.prompt],
|
|
79
|
+
max_tokens: request.maxTokens,
|
|
80
|
+
stop_tokens: this.config.stopTokens ?? [0],
|
|
81
|
+
temperature: request.sampling.temperature,
|
|
82
|
+
top_k: request.sampling.topK,
|
|
83
|
+
top_p: request.sampling.topP,
|
|
84
|
+
alpha_presence: request.sampling.presencePenalty,
|
|
85
|
+
alpha_frequency: request.sampling.frequencyPenalty,
|
|
86
|
+
alpha_decay: request.sampling.penaltyDecay,
|
|
87
|
+
stream: true,
|
|
88
|
+
chunk_size: 1,
|
|
89
|
+
...this.config.stateId ? { state_id: this.config.stateId } : {},
|
|
90
|
+
...this.config.adapterId ? { adapter_id: this.config.adapterId } : {},
|
|
91
|
+
...this.config.password ? { password: this.config.password } : {},
|
|
92
|
+
}
|
|
93
|
+
const response = await fetch(`${this.root}/batch/completions`, {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers: this.headers({
|
|
96
|
+
'content-type': 'application/json',
|
|
97
|
+
...request.sessionId ? { 'x-rwkv-session-id': request.sessionId } : {},
|
|
98
|
+
}),
|
|
99
|
+
body: JSON.stringify(body),
|
|
100
|
+
signal,
|
|
101
|
+
})
|
|
102
|
+
if (!response.ok || response.body === null) throw await responseError(response, this.config.password)
|
|
103
|
+
try {
|
|
104
|
+
return await readCompletionStream(response.body, data => {
|
|
105
|
+
const chunk = data as {
|
|
106
|
+
choices?: { index?: number; delta?: { content?: string }; finish_reason?: string }[]
|
|
107
|
+
usage?: { prompt_tokens?: number; completion_tokens?: number }
|
|
108
|
+
error?: unknown
|
|
109
|
+
}
|
|
110
|
+
const choice = chunk.choices?.find(item => (item.index ?? 0) === 0)
|
|
111
|
+
return {
|
|
112
|
+
delta: choice?.delta?.content ?? '',
|
|
113
|
+
...choice?.finish_reason ? { finish: choice.finish_reason } : {},
|
|
114
|
+
...chunk.usage?.prompt_tokens ? { promptTokens: chunk.usage.prompt_tokens } : {},
|
|
115
|
+
...chunk.error ? { error: JSON.stringify(chunk.error) } : {},
|
|
116
|
+
}
|
|
117
|
+
}, {
|
|
118
|
+
stops: request.stops,
|
|
119
|
+
maxTokens: request.maxTokens,
|
|
120
|
+
loopGuard: this.config.loopGuard ?? true,
|
|
121
|
+
...onDelta ? { onDelta } : {},
|
|
122
|
+
abort: () => controller.abort(),
|
|
123
|
+
})
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (request.signal?.aborted) return { text: '', finish: 'cancelled' }
|
|
126
|
+
throw error
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Initial states uploaded to the server (`GET /v1/state/list`), newest first. */
|
|
131
|
+
async listStates(): Promise<StateInfo[]> {
|
|
132
|
+
const response = await fetch(`${this.root}/state/list`, { headers: this.headers(this.auth()) })
|
|
133
|
+
if (response.status === 404 || response.status === 405) {
|
|
134
|
+
throw new BackendError(`deployment has no /v1/state/list route (HTTP ${response.status})`, 'STATES_UNSUPPORTED', response.status)
|
|
135
|
+
}
|
|
136
|
+
if (!response.ok) throw await responseError(response, this.config.password)
|
|
137
|
+
const body = await response.json() as { data?: StateInfo[] }
|
|
138
|
+
return body.data ?? []
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Uploads a local state file (`.pth`). Returns the server's entry; its `state_id` is the file stem plus a UUID. */
|
|
142
|
+
async uploadState(file: string): Promise<StateInfo> {
|
|
143
|
+
return this.uploadStateBlob(await openAsBlob(file), basename(file))
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Uploads state bytes already in memory (the settings page sends the browser's file through the Host). */
|
|
147
|
+
async uploadStateBlob(blob: Blob, fileName: string): Promise<StateInfo> {
|
|
148
|
+
if (blob.size > MAX_STATE_UPLOAD_BYTES) {
|
|
149
|
+
throw new BackendError(`state file is ${blob.size >> 20} MB, over the server's ${MAX_STATE_UPLOAD_BYTES >> 20} MB upload limit`, 'PAYLOAD_TOO_LARGE')
|
|
150
|
+
}
|
|
151
|
+
const form = new FormData()
|
|
152
|
+
form.set('file', blob, fileName)
|
|
153
|
+
const response = await fetch(`${this.root}/state/upload`, { method: 'POST', headers: this.headers(this.auth()), body: form })
|
|
154
|
+
if (response.status === 404 || response.status === 405) {
|
|
155
|
+
throw new BackendError(`deployment has no /v1/state/upload route (HTTP ${response.status})`, 'STATES_UNSUPPORTED', response.status)
|
|
156
|
+
}
|
|
157
|
+
if (!response.ok) throw await responseError(response, this.config.password)
|
|
158
|
+
const body = await response.json() as StateInfo
|
|
159
|
+
if (!body.state_id) throw new BackendError('upload response has no state_id', 'PROVIDER_PROTOCOL_ERROR')
|
|
160
|
+
return body
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async deleteState(stateId: string): Promise<void> {
|
|
164
|
+
const response = await fetch(`${this.root}/state/delete`, {
|
|
165
|
+
method: 'DELETE',
|
|
166
|
+
headers: this.headers({ 'content-type': 'application/json', ...this.auth() }),
|
|
167
|
+
body: JSON.stringify({ state_id: stateId }),
|
|
168
|
+
})
|
|
169
|
+
if (!response.ok) throw await responseError(response, this.config.password)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async listAdapters(): Promise<AdapterInfo[]> {
|
|
173
|
+
const response = await fetch(`${this.root}/adapters`, { headers: this.headers(this.auth()) })
|
|
174
|
+
if (response.status === 404 || response.status === 405) {
|
|
175
|
+
throw new BackendError(`deployment has no /v1/adapters route (HTTP ${response.status})`, 'ADAPTERS_UNSUPPORTED', response.status)
|
|
176
|
+
}
|
|
177
|
+
if (!response.ok) throw await responseError(response, this.config.password)
|
|
178
|
+
const body = await response.json() as { data?: AdapterInfo[] }
|
|
179
|
+
return body.data ?? []
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Uploads adapter bytes already in memory (the settings page sends the browser's file through the Host). */
|
|
183
|
+
async uploadAdapterBlob(adapterId: string, blob: Blob, fileName: string): Promise<string> {
|
|
184
|
+
if (blob.size > MAX_ADAPTER_UPLOAD_BYTES) {
|
|
185
|
+
throw new BackendError(
|
|
186
|
+
`adapter file is ${blob.size >> 20} MB, over the server's ${MAX_ADAPTER_UPLOAD_BYTES >> 20} MB request limit; upload adapter-final.pth, not a full training checkpoint`,
|
|
187
|
+
'PAYLOAD_TOO_LARGE',
|
|
188
|
+
413,
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
const form = new FormData()
|
|
192
|
+
form.set('adapter_id', adapterId)
|
|
193
|
+
form.set('file', blob, fileName)
|
|
194
|
+
const response = await fetch(`${this.root}/adapters`, { method: 'POST', headers: this.headers(this.auth()), body: form })
|
|
195
|
+
return this.registeredAdapter(response)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async deleteAdapter(adapterId: string, version?: string): Promise<void> {
|
|
199
|
+
const response = await fetch(`${this.root}/adapters`, {
|
|
200
|
+
method: 'DELETE',
|
|
201
|
+
headers: this.headers({ 'content-type': 'application/json', ...this.auth() }),
|
|
202
|
+
body: JSON.stringify({ adapter_id: adapterId, ...version ? { adapter_version: version } : {} }),
|
|
203
|
+
})
|
|
204
|
+
if (!response.ok) throw await responseError(response, this.config.password)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private async registeredAdapter(response: Response): Promise<string> {
|
|
208
|
+
if (response.status === 404 || response.status === 405) {
|
|
209
|
+
throw new BackendError(`deployment has no /v1/adapters route (HTTP ${response.status})`, 'ADAPTERS_UNSUPPORTED', response.status)
|
|
210
|
+
}
|
|
211
|
+
if (response.status === 413) {
|
|
212
|
+
throw new BackendError(
|
|
213
|
+
'HTTP 413: request body too large; Cloudflare-fronted endpoints cap uploads at 100 MB, so register adapters larger than that through the server address directly',
|
|
214
|
+
'PAYLOAD_TOO_LARGE',
|
|
215
|
+
413,
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
if (!response.ok) throw await responseError(response, this.config.password)
|
|
219
|
+
const body = await response.json() as { version?: string }
|
|
220
|
+
if (!body.version) throw new BackendError('register response has no version', 'PROVIDER_PROTOCOL_ERROR')
|
|
221
|
+
return body.version
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The password as a bearer token, for routes that take no JSON body (multipart upload, list). */
|
|
225
|
+
private auth(): Record<string, string> {
|
|
226
|
+
return this.config.password ? { authorization: `Bearer ${this.config.password}` } : {}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BackendError,
|
|
3
|
+
flushPending,
|
|
4
|
+
feedDelta,
|
|
5
|
+
LoopGuard,
|
|
6
|
+
sseData,
|
|
7
|
+
type GenerateResult,
|
|
8
|
+
type StreamState,
|
|
9
|
+
} from './generator.ts'
|
|
10
|
+
import type { FinishReason } from '../core/parse.ts'
|
|
11
|
+
|
|
12
|
+
export interface StreamChunkView {
|
|
13
|
+
readonly delta: string
|
|
14
|
+
readonly finish?: string
|
|
15
|
+
/** Stop string the server matched (iRWKV stop_reason). */
|
|
16
|
+
readonly stop?: string
|
|
17
|
+
readonly promptTokens?: number
|
|
18
|
+
readonly completionTokens?: number
|
|
19
|
+
readonly error?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ReadStreamOptions {
|
|
23
|
+
readonly stops: readonly string[]
|
|
24
|
+
readonly maxTokens: number
|
|
25
|
+
readonly loopGuard: boolean
|
|
26
|
+
readonly onDelta?: (text: string) => void
|
|
27
|
+
/** Ends the upstream request once a client stop or the loop guard fires. */
|
|
28
|
+
readonly abort: () => void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function finishOf(value: string | undefined): FinishReason {
|
|
32
|
+
switch (value) {
|
|
33
|
+
case 'stop':
|
|
34
|
+
return 'stop'
|
|
35
|
+
case 'length':
|
|
36
|
+
return 'length'
|
|
37
|
+
case 'abort':
|
|
38
|
+
return 'cancelled'
|
|
39
|
+
default:
|
|
40
|
+
return 'unknown'
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Reads an OpenAI-style SSE completion stream with client-side stops and the loop guard. */
|
|
45
|
+
export async function readCompletionStream(
|
|
46
|
+
body: ReadableStream<Uint8Array>,
|
|
47
|
+
view: (data: unknown) => StreamChunkView,
|
|
48
|
+
options: ReadStreamOptions,
|
|
49
|
+
): Promise<GenerateResult> {
|
|
50
|
+
const state: StreamState = { text: '', pending: '' }
|
|
51
|
+
if (options.loopGuard) state.guard = new LoopGuard()
|
|
52
|
+
let finish: FinishReason = 'unknown'
|
|
53
|
+
let deltas = 0
|
|
54
|
+
let promptTokens: number | undefined
|
|
55
|
+
let completionTokens: number | undefined
|
|
56
|
+
let serverStop: string | undefined
|
|
57
|
+
const result = (reason: FinishReason): GenerateResult => {
|
|
58
|
+
// rwkv_lightning may report "stop" after running into max_tokens.
|
|
59
|
+
const generated = completionTokens ?? deltas
|
|
60
|
+
const capped = reason !== 'cancelled' && options.maxTokens > 0 && generated >= options.maxTokens * 0.98
|
|
61
|
+
&& state.stop === undefined && serverStop === undefined
|
|
62
|
+
return {
|
|
63
|
+
text: state.text,
|
|
64
|
+
finish: capped ? 'length' : reason,
|
|
65
|
+
...(state.stop ?? serverStop) === undefined ? {} : { stop: state.stop ?? serverStop },
|
|
66
|
+
...promptTokens === undefined ? {} : { promptTokens },
|
|
67
|
+
completionTokens: completionTokens ?? deltas,
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
let ended: 'stop' | 'length' | undefined
|
|
71
|
+
for await (const data of sseData(body)) {
|
|
72
|
+
let parsed: unknown
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(data)
|
|
75
|
+
} catch {
|
|
76
|
+
throw new BackendError(`undecodable stream chunk: ${data.slice(0, 200)}`, 'PROVIDER_PROTOCOL_ERROR')
|
|
77
|
+
}
|
|
78
|
+
const chunk = view(parsed)
|
|
79
|
+
if (chunk.error) throw new BackendError(`stream error: ${chunk.error}`, 'PROVIDER_STREAM_ERROR')
|
|
80
|
+
if (chunk.promptTokens) promptTokens = chunk.promptTokens
|
|
81
|
+
if (chunk.completionTokens) completionTokens = chunk.completionTokens
|
|
82
|
+
if (chunk.finish) finish = finishOf(chunk.finish)
|
|
83
|
+
if (chunk.stop) serverStop = chunk.stop
|
|
84
|
+
if (chunk.delta === '') continue
|
|
85
|
+
deltas++
|
|
86
|
+
ended = feedDelta(state, chunk.delta, options.stops, options.onDelta)
|
|
87
|
+
// Leave the loop first: its iterator cancels the body cleanly, while an
|
|
88
|
+
// abort issued inside it would surface as this request's error.
|
|
89
|
+
if (ended !== undefined) break
|
|
90
|
+
}
|
|
91
|
+
if (ended !== undefined) {
|
|
92
|
+
options.abort()
|
|
93
|
+
return result(ended)
|
|
94
|
+
}
|
|
95
|
+
flushPending(state, options.onDelta)
|
|
96
|
+
return result(finish)
|
|
97
|
+
}
|