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,225 @@
|
|
|
1
|
+
// Tool-result budget for RWKV sessions: the one place a long result is cut.
|
|
2
|
+
//
|
|
3
|
+
// RWKV reads a tool result once and cannot look back; past about 3000 tokens
|
|
4
|
+
// a long result (a web page, a log) hurts more than it helps. DSH already
|
|
5
|
+
// bounds results the same way for every model (spill-policy: head and tail
|
|
6
|
+
// inline, the full text saved to a file whose path ends the result), but at
|
|
7
|
+
// 12500 tokens. This hook does exactly that at RESULT_TOKEN_BUDGET, for
|
|
8
|
+
// sessions served by the given providers, before DSH's own pass (which then
|
|
9
|
+
// has nothing to do). So:
|
|
10
|
+
// - every cut result names the file with the rest (the model can grep/read it);
|
|
11
|
+
// - DSH records the result as the model saw it: no second cut when the
|
|
12
|
+
// prompt is built, and training export reads the recorded text as is.
|
|
13
|
+
//
|
|
14
|
+
// read is not spilled (the file is on disk already): its window is shortened
|
|
15
|
+
// at a line boundary with read's own "Output capped ... Use offset=N" footer.
|
|
16
|
+
//
|
|
17
|
+
// Tokens are exact RWKV World tokens (src/tokenizer.ts, the vendored
|
|
18
|
+
// rwkv-tokenizer WASM). A result is measured as the <tool_response> the model
|
|
19
|
+
// reads, JSON escaping included; the prompt's "User: " label and whitespace
|
|
20
|
+
// cleanup are not counted (a few tokens, same as before). The budget is what
|
|
21
|
+
// it says: 3000 RWKV tokens, not 3000 of an estimate.
|
|
22
|
+
//
|
|
23
|
+
// No DSH runtime imports: the pipeline's teacher plugin mounts the same hook.
|
|
24
|
+
|
|
25
|
+
import { toolResponse } from './core/prompt.ts'
|
|
26
|
+
import { providerOfExec, sessionIdOfExec, type AgentLike } from './dsh-host.ts'
|
|
27
|
+
import { countTokens } from './tokenizer.ts'
|
|
28
|
+
|
|
29
|
+
/** RWKV tokens a tool result may take inline (as the model sees it, JSON-escaped). */
|
|
30
|
+
export const RESULT_TOKEN_BUDGET = 3000
|
|
31
|
+
|
|
32
|
+
/** `text` as the prompt will carry it: `<tool_response>` + JSON payload. */
|
|
33
|
+
export type Wrap = (body: string) => string
|
|
34
|
+
|
|
35
|
+
/** Exact RWKV tokens of one tool result as the model reads it. */
|
|
36
|
+
export function toolResultTokens(tool: string, body: string): number {
|
|
37
|
+
return countTokens(toolResponse(tool, true, body))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const GAP = '\n\n[...]\n\n'
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Longest prefix (or suffix) of `text` whose wrapped token count stays within
|
|
44
|
+
* `tokens`; whole code points. Token counts are not perfectly monotone in the
|
|
45
|
+
* cut point (a cut can split a token), so this is a binary search that accepts
|
|
46
|
+
* the largest tested prefix that fits.
|
|
47
|
+
*/
|
|
48
|
+
function fit(text: string, tokens: number, fromEnd: boolean, wrap: Wrap): string {
|
|
49
|
+
const chars = Array.from(text)
|
|
50
|
+
const piece = (count: number): string =>
|
|
51
|
+
fromEnd ? chars.slice(chars.length - count).join('') : chars.slice(0, count).join('')
|
|
52
|
+
let low = 0
|
|
53
|
+
let high = chars.length
|
|
54
|
+
while (low < high) {
|
|
55
|
+
const middle = Math.ceil((low + high) / 2)
|
|
56
|
+
if (countTokens(wrap(piece(middle))) <= tokens) low = middle
|
|
57
|
+
else high = middle - 1
|
|
58
|
+
}
|
|
59
|
+
return piece(low)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** DSH spill-policy's notice (notice.ts formatSpillNotice), so DSH and its UI recognise it. */
|
|
63
|
+
export function spillNotice(omittedBytes: number, locator: string, retrievalHint: string): string {
|
|
64
|
+
return `(Omitted ${omittedBytes} bytes. Full formatted result stored at: ${locator}. ${retrievalHint})`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* `text` bounded to `budget` the way DSH spill-policy does it: half the room
|
|
69
|
+
* for the head, half for the tail, the notice for the saved full text last.
|
|
70
|
+
* `notice(omittedBytes)` renders that notice; `wrap` renders the bytes the
|
|
71
|
+
* model actually reads (default: the body as is).
|
|
72
|
+
*/
|
|
73
|
+
export function spillText(text: string, budget: number, notice: (omittedBytes: number) => string, wrap: Wrap = body => body): string {
|
|
74
|
+
if (countTokens(wrap(text)) <= budget) return text
|
|
75
|
+
const totalBytes = Buffer.byteLength(text, 'utf8')
|
|
76
|
+
const reserved = countTokens(wrap(`${GAP}\n\n${notice(totalBytes)}`))
|
|
77
|
+
const room = Math.max(0, budget - reserved)
|
|
78
|
+
const kept = fit(text, Math.ceil(room / 2), false, wrap)
|
|
79
|
+
const rest = text.slice(kept.length)
|
|
80
|
+
const end = fit(rest, Math.floor(room / 2), true, wrap)
|
|
81
|
+
const omitted = Buffer.byteLength(rest.slice(0, rest.length - end.length), 'utf8')
|
|
82
|
+
let bounded = kept.length + end.length === 0 ? notice(omitted) : `${kept}${GAP}${end}\n\n${notice(omitted)}`
|
|
83
|
+
// Head and tail are fitted separately; the joined text can be a token or two
|
|
84
|
+
// over. Drop whole lines from the tail until the real count fits.
|
|
85
|
+
while (countTokens(wrap(bounded)) > budget && bounded.includes('\n')) {
|
|
86
|
+
const at = bounded.lastIndexOf('\n')
|
|
87
|
+
bounded = bounded.slice(0, at)
|
|
88
|
+
}
|
|
89
|
+
return bounded
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const READ_LINE = /^(\d+): /
|
|
93
|
+
const READ_TOTAL = /^\n\n\((?:End of file - total (\d+) lines|Showing lines \d+-\d+ of (\d+)\.)/
|
|
94
|
+
|
|
95
|
+
/** The file and the line numbers a DSH read result shows (as the model gets it), if it is one. */
|
|
96
|
+
export function readWindow(text: string): { first: number; last: number } | undefined {
|
|
97
|
+
const open = text.indexOf('<content>\n')
|
|
98
|
+
const close = text.lastIndexOf('\n</content>')
|
|
99
|
+
if (open < 0 || close < open) return undefined
|
|
100
|
+
const body = text.slice(open + '<content>\n'.length, close)
|
|
101
|
+
const footerAt = body.lastIndexOf('\n\n(')
|
|
102
|
+
const lines = footerAt < 0 ? [] : body.slice(0, footerAt).split('\n')
|
|
103
|
+
const first = READ_LINE.exec(lines[0] ?? '')?.[1]
|
|
104
|
+
const last = READ_LINE.exec(lines.at(-1) ?? '')?.[1]
|
|
105
|
+
// Every shown line starts "N: ", so the last "\n\n(" is the footer; none shown
|
|
106
|
+
// (an empty file, an offset past the end) is the empty window 1-0.
|
|
107
|
+
return first === undefined || last === undefined ? { first: 1, last: 0 } : { first: Number(first), last: Number(last) }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Event carrying the lines a read showed the model, after this budget has cut
|
|
112
|
+
* it: the line-edit plugin (src/line-edit.ts, a separate DSH plugin) keeps
|
|
113
|
+
* which lines each session has seen and refuses edits outside them.
|
|
114
|
+
*/
|
|
115
|
+
export const READ_SHOWN_EVENT = 'rwkv/read-shown'
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A DSH read result (`<content>` with "N: text" lines and a footer) shortened
|
|
119
|
+
* to fit `budget` and optional `maxLines`, with read's own continuation footer;
|
|
120
|
+
* undefined when it already fits or is not in that shape. At least one line is kept.
|
|
121
|
+
*/
|
|
122
|
+
export function capReadResult(
|
|
123
|
+
text: string,
|
|
124
|
+
budget: number,
|
|
125
|
+
wrap: Wrap = body => body,
|
|
126
|
+
maxLines?: number,
|
|
127
|
+
): string | undefined {
|
|
128
|
+
const open = text.indexOf('<content>\n')
|
|
129
|
+
const close = text.lastIndexOf('\n</content>')
|
|
130
|
+
if (open < 0 || close < open) return undefined
|
|
131
|
+
const start = open + '<content>\n'.length
|
|
132
|
+
const body = text.slice(start, close)
|
|
133
|
+
const footerAt = body.lastIndexOf('\n\n(')
|
|
134
|
+
if (footerAt < 0) return undefined
|
|
135
|
+
const lines = body.slice(0, footerAt).split('\n')
|
|
136
|
+
const overLineCap = maxLines !== undefined && maxLines > 0 && lines.length > maxLines
|
|
137
|
+
if (!overLineCap && countTokens(wrap(text)) <= budget) return undefined
|
|
138
|
+
const first = READ_LINE.exec(lines[0] ?? '')
|
|
139
|
+
if (!first) return undefined
|
|
140
|
+
// DSH's own footer knows the file's length unless read itself hit its byte cap.
|
|
141
|
+
const total = READ_TOTAL.exec(body.slice(footerAt))?.[1] ?? READ_TOTAL.exec(body.slice(footerAt))?.[2]
|
|
142
|
+
const render = (count: number) => {
|
|
143
|
+
const last = Number(READ_LINE.exec(lines[count - 1] ?? '')?.[1] ?? first[1])
|
|
144
|
+
// With the total, DSH's line-limit wording; without it, its byte-cap wording.
|
|
145
|
+
const footer = total === undefined
|
|
146
|
+
? `(Output capped. Showing lines ${first[1]}-${last}. Use offset=${last + 1} to continue.)`
|
|
147
|
+
: `(Showing lines ${first[1]}-${last} of ${total}. Use offset=${last + 1} to continue.)`
|
|
148
|
+
return `${text.slice(0, start)}${lines.slice(0, count).join('\n')}\n\n${footer}${text.slice(close)}`
|
|
149
|
+
}
|
|
150
|
+
let low = 1
|
|
151
|
+
let high = overLineCap ? Math.min(lines.length, maxLines!) : lines.length
|
|
152
|
+
while (low < high) {
|
|
153
|
+
const middle = Math.ceil((low + high) / 2)
|
|
154
|
+
if (countTokens(wrap(render(middle))) <= budget) low = middle
|
|
155
|
+
else high = middle - 1
|
|
156
|
+
}
|
|
157
|
+
return render(low)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// --- DSH wiring (structural types; see @deepseek-ai/dsh-tools, dsh-spill) ---
|
|
161
|
+
|
|
162
|
+
interface TextBlock { readonly type: string; readonly text?: string }
|
|
163
|
+
interface ExecLike { readonly name: string; readonly callId: string; readonly parent?: unknown; readonly agent?: AgentLike }
|
|
164
|
+
interface Decision { readonly kind: string; readonly content?: readonly TextBlock[]; readonly [key: string]: unknown }
|
|
165
|
+
interface SpillStoreLike {
|
|
166
|
+
saveText(request: {
|
|
167
|
+
owner: { sessionId: string }
|
|
168
|
+
source: { kind: 'tool'; toolName: string; callId: string; label: 'result' }
|
|
169
|
+
suggestedName: string
|
|
170
|
+
content: string
|
|
171
|
+
}): Promise<{ locator: string; retrievalHint: string }>
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export interface ResultBudgetOptions {
|
|
175
|
+
/** Provider ids whose sessions get the budget (the RWKV plugin's routes, or the teacher's). */
|
|
176
|
+
readonly providers: () => readonly string[]
|
|
177
|
+
readonly budget?: number
|
|
178
|
+
readonly maxReadLines?: () => number | undefined
|
|
179
|
+
readonly log?: (message: string) => void
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Mounts the budget on `tools/post-execute` (inside DSH's spill-policy, which runs outermost). */
|
|
183
|
+
export function applyResultBudget(ctx: unknown, options: ResultBudgetOptions): void {
|
|
184
|
+
const budget = options.budget ?? RESULT_TOKEN_BUDGET
|
|
185
|
+
const context = ctx as {
|
|
186
|
+
on(event: string, listener: (exec: ExecLike, result: { content: readonly TextBlock[] }, next: () => Promise<Decision>) => Promise<Decision>): unknown
|
|
187
|
+
emit(event: string, ...args: unknown[]): void
|
|
188
|
+
get(name: string): unknown
|
|
189
|
+
}
|
|
190
|
+
context.on('tools/post-execute', async (exec, result, next) => {
|
|
191
|
+
const decision = await next()
|
|
192
|
+
if (decision.kind !== 'accept' || Object.hasOwn(decision, 'value') || exec.parent !== undefined) return decision
|
|
193
|
+
const provider = providerOfExec(exec)
|
|
194
|
+
if (provider === undefined || !options.providers().includes(provider)) return decision
|
|
195
|
+
const content = decision.content ?? result.content
|
|
196
|
+
if (!content.every(block => block.type === 'text')) return decision
|
|
197
|
+
const text = content.map(block => block.text ?? '').join('')
|
|
198
|
+
// Successful-frame bytes: for a failed result the wire says "error" instead
|
|
199
|
+
// of "result", a token or two either way.
|
|
200
|
+
const wrap: Wrap = body => toolResponse(exec.name, true, body)
|
|
201
|
+
if (exec.name === 'read') {
|
|
202
|
+
const lineCap = options.maxReadLines?.()
|
|
203
|
+
const bounded = capReadResult(text, budget, wrap, lineCap)
|
|
204
|
+
const finalText = bounded ?? text
|
|
205
|
+
const window = readWindow(finalText)
|
|
206
|
+
if (window !== undefined) context.emit(READ_SHOWN_EVENT, exec, window)
|
|
207
|
+
return finalText === text ? decision : { ...decision, kind: 'accept', content: [{ type: 'text', text: finalText }] }
|
|
208
|
+
}
|
|
209
|
+
if (countTokens(wrap(text)) <= budget) return decision
|
|
210
|
+
const store = context.get('spillStore') as SpillStoreLike | undefined
|
|
211
|
+
const owner = sessionIdOfExec(exec)
|
|
212
|
+
if (store === undefined || owner === undefined) {
|
|
213
|
+
options.log?.(`result budget: no spill store or session for ${exec.name}; keeping the inline content`)
|
|
214
|
+
return decision
|
|
215
|
+
}
|
|
216
|
+
const ref = await store.saveText({
|
|
217
|
+
owner: { sessionId: owner },
|
|
218
|
+
source: { kind: 'tool', toolName: exec.name, callId: exec.callId, label: 'result' },
|
|
219
|
+
suggestedName: `${exec.name}.txt`,
|
|
220
|
+
content: text,
|
|
221
|
+
})
|
|
222
|
+
const bounded = spillText(text, budget, bytes => spillNotice(bytes, ref.locator, ref.retrievalHint), wrap)
|
|
223
|
+
return { ...decision, kind: 'accept', content: [{ type: 'text', text: bounded }] }
|
|
224
|
+
})
|
|
225
|
+
}
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// Host routes behind the authenticated /api bridge for the settings page:
|
|
2
|
+
// the models a server lists (to prefill the upstream model id) and the
|
|
3
|
+
// rwkv_lightning initial states (list / upload / delete). The browser cannot
|
|
4
|
+
// reach the inference server (other origin, often a Tailscale address), so
|
|
5
|
+
// the Host relays for it. Handlers run on the `connection/request` waterfall,
|
|
6
|
+
// i.e. only after client-connection admitted the request with the same
|
|
7
|
+
// cookie and origin checks as every DSH API call.
|
|
8
|
+
|
|
9
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
10
|
+
import { BackendError, listModels } from './backend/generator.ts'
|
|
11
|
+
import { LightningClient, MAX_ADAPTER_UPLOAD_BYTES, MAX_STATE_UPLOAD_BYTES } from './backend/lightning.ts'
|
|
12
|
+
import { countWireBlockTokens, liveWire, type LiveWireSnapshot } from './live-wire.ts'
|
|
13
|
+
import { countTokens } from './tokenizer.ts'
|
|
14
|
+
import { allSessions, deleteTrace, exportTask, sessionRecords, traceStats, transcriptWithThinks, type TraceLocation } from './traces.ts'
|
|
15
|
+
|
|
16
|
+
function extractThinkText(output: string): string {
|
|
17
|
+
const close = output.indexOf('</think>')
|
|
18
|
+
if (close < 0) return ''
|
|
19
|
+
const open = output.indexOf('<think')
|
|
20
|
+
if (open < 0 || open > close) return ''
|
|
21
|
+
const bodyStart = output.indexOf('>', open)
|
|
22
|
+
if (bodyStart < 0 || bodyStart > close) return ''
|
|
23
|
+
return output.slice(bodyStart + 1, close).trim()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const MODEL_ROUTE = '/api/rwkv/models'
|
|
27
|
+
export const STATE_ROUTE = '/api/rwkv/states'
|
|
28
|
+
export const ADAPTER_ROUTE = '/api/rwkv/adapters'
|
|
29
|
+
|
|
30
|
+
/** The draft model's connection, sent by the page so unsaved edits can be listed against. */
|
|
31
|
+
interface Connection {
|
|
32
|
+
baseURL: string
|
|
33
|
+
apiKey?: string
|
|
34
|
+
headers?: Record<string, string>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function connectionOf(request: IncomingMessage): Connection {
|
|
38
|
+
const raw = request.headers['x-rwkv-connection']
|
|
39
|
+
if (typeof raw !== 'string' || raw === '') throw new BackendError('missing x-rwkv-connection header', 'BAD_REQUEST', 400)
|
|
40
|
+
const parsed = JSON.parse(Buffer.from(raw, 'base64').toString('utf8')) as Connection
|
|
41
|
+
if (typeof parsed.baseURL !== 'string' || !/^https?:\/\//.test(parsed.baseURL)) {
|
|
42
|
+
throw new BackendError('baseURL must be an http(s) URL', 'BAD_REQUEST', 400)
|
|
43
|
+
}
|
|
44
|
+
return parsed
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function clientFor(connection: Connection): LightningClient {
|
|
48
|
+
return new LightningClient({
|
|
49
|
+
baseURL: connection.baseURL,
|
|
50
|
+
model: '',
|
|
51
|
+
...connection.apiKey ? { password: connection.apiKey } : {},
|
|
52
|
+
...connection.headers ? { headers: connection.headers } : {},
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Reads an upload, stopping at `limit` bytes (checked against content-length first, then while streaming). */
|
|
57
|
+
async function readBody(request: IncomingMessage, limit = MAX_STATE_UPLOAD_BYTES, what = 'state'): Promise<Buffer> {
|
|
58
|
+
const tooLarge = () => new BackendError(`${what} file is over ${limit >> 20} MB`, 'PAYLOAD_TOO_LARGE', 413)
|
|
59
|
+
if (Number(request.headers['content-length']) > limit) throw tooLarge()
|
|
60
|
+
const chunks: Buffer[] = []
|
|
61
|
+
let size = 0
|
|
62
|
+
for await (const chunk of request) {
|
|
63
|
+
size += (chunk as Buffer).length
|
|
64
|
+
if (size > limit) throw tooLarge()
|
|
65
|
+
chunks.push(chunk as Buffer)
|
|
66
|
+
}
|
|
67
|
+
return Buffer.concat(chunks)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function send(response: ServerResponse, status: number, body: unknown): void {
|
|
71
|
+
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
72
|
+
response.end(JSON.stringify(body))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function failure(response: ServerResponse, error: unknown): void {
|
|
76
|
+
const status = error instanceof BackendError
|
|
77
|
+
? (error.code === 'STATES_UNSUPPORTED' || error.code === 'ADAPTERS_UNSUPPORTED') ? 404 : error.status && error.status < 500 ? error.status : 502
|
|
78
|
+
: 502
|
|
79
|
+
const message = error instanceof BackendError && error.code === 'STATES_UNSUPPORTED'
|
|
80
|
+
? '这个服务不支持上传 state(没有 /v1/state 接口)'
|
|
81
|
+
: error instanceof BackendError && error.code === 'ADAPTERS_UNSUPPORTED'
|
|
82
|
+
? '这个服务不支持 adapter(没有 /v1/adapters 接口)'
|
|
83
|
+
: error instanceof Error ? error.message : String(error)
|
|
84
|
+
if (!response.headersSent) send(response, status, { error: message })
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Serves one request when it belongs to {@link MODEL_ROUTE}, {@link STATE_ROUTE}
|
|
89
|
+
* or {@link ADAPTER_ROUTE}; returns false for any other path so the waterfall continues.
|
|
90
|
+
* GET /api/rwkv/models { models: string[] }
|
|
91
|
+
* GET /api/rwkv/states { states: StateInfo[] }
|
|
92
|
+
* PUT /api/rwkv/states?name=FILE body = file bytes → { state: StateInfo }
|
|
93
|
+
* DELETE /api/rwkv/states/<state id>
|
|
94
|
+
* GET /api/rwkv/adapters { adapters: ServerAdapter[] }
|
|
95
|
+
* PUT /api/rwkv/adapters/<id>?name= body = file bytes → { id, version }
|
|
96
|
+
* DELETE /api/rwkv/adapters/<id>
|
|
97
|
+
*/
|
|
98
|
+
export async function handleServerRoute(request: IncomingMessage, response: ServerResponse): Promise<boolean> {
|
|
99
|
+
const url = new URL(request.url ?? '/', 'http://host')
|
|
100
|
+
const isModels = url.pathname === MODEL_ROUTE
|
|
101
|
+
const isStates = url.pathname === STATE_ROUTE || url.pathname.startsWith(`${STATE_ROUTE}/`)
|
|
102
|
+
const isAdapters = url.pathname === ADAPTER_ROUTE || url.pathname.startsWith(`${ADAPTER_ROUTE}/`)
|
|
103
|
+
if (!isModels && !isStates && !isAdapters) return false
|
|
104
|
+
try {
|
|
105
|
+
const connection = connectionOf(request)
|
|
106
|
+
if (isModels) {
|
|
107
|
+
if (request.method !== 'GET') {
|
|
108
|
+
send(response, 405, { error: 'method not allowed' })
|
|
109
|
+
return true
|
|
110
|
+
}
|
|
111
|
+
const models = await listModels(connection.baseURL, {
|
|
112
|
+
...connection.apiKey ? { apiKey: connection.apiKey } : {},
|
|
113
|
+
...connection.headers ? { headers: connection.headers } : {},
|
|
114
|
+
})
|
|
115
|
+
send(response, 200, { models })
|
|
116
|
+
return true
|
|
117
|
+
}
|
|
118
|
+
if (isAdapters) {
|
|
119
|
+
const id = decodeURIComponent(url.pathname.slice(ADAPTER_ROUTE.length + 1))
|
|
120
|
+
const client = clientFor(connection)
|
|
121
|
+
if (request.method === 'GET' && id === '') {
|
|
122
|
+
const adapters = await client.listAdapters()
|
|
123
|
+
send(response, 200, {
|
|
124
|
+
adapters: adapters.map(adapter => {
|
|
125
|
+
const manifest = (adapter.manifest ?? {}) as Record<string, unknown>
|
|
126
|
+
return {
|
|
127
|
+
id: adapter.id,
|
|
128
|
+
method: typeof manifest.method === 'string' ? manifest.method : '',
|
|
129
|
+
rank: typeof manifest.rank === 'number' ? manifest.rank : undefined,
|
|
130
|
+
version: String(adapter.version ?? manifest.content_version ?? ''),
|
|
131
|
+
}
|
|
132
|
+
}),
|
|
133
|
+
})
|
|
134
|
+
} else if (request.method === 'PUT' && id !== '') {
|
|
135
|
+
const body = await readBody(request, MAX_ADAPTER_UPLOAD_BYTES, 'adapter')
|
|
136
|
+
const name = url.searchParams.get('name') || `${id}.pth`
|
|
137
|
+
const version = await client.uploadAdapterBlob(id, new Blob([new Uint8Array(body)]), name)
|
|
138
|
+
send(response, 200, { id, version })
|
|
139
|
+
} else if (request.method === 'DELETE' && id !== '') {
|
|
140
|
+
await client.deleteAdapter(id)
|
|
141
|
+
send(response, 200, { id })
|
|
142
|
+
} else {
|
|
143
|
+
send(response, 405, { error: 'method not allowed' })
|
|
144
|
+
}
|
|
145
|
+
return true
|
|
146
|
+
}
|
|
147
|
+
const id = decodeURIComponent(url.pathname.slice(STATE_ROUTE.length + 1))
|
|
148
|
+
const client = clientFor(connection)
|
|
149
|
+
if (request.method === 'GET' && id === '') {
|
|
150
|
+
send(response, 200, { states: await client.listStates() })
|
|
151
|
+
} else if (request.method === 'PUT' && id === '') {
|
|
152
|
+
const body = await readBody(request)
|
|
153
|
+
const name = url.searchParams.get('name') || 'state.pth'
|
|
154
|
+
send(response, 200, { state: await client.uploadStateBlob(new Blob([new Uint8Array(body)]), name) })
|
|
155
|
+
} else if (request.method === 'DELETE' && id !== '') {
|
|
156
|
+
await client.deleteState(id)
|
|
157
|
+
send(response, 200, { id })
|
|
158
|
+
} else {
|
|
159
|
+
send(response, 405, { error: 'method not allowed' })
|
|
160
|
+
}
|
|
161
|
+
} catch (error) {
|
|
162
|
+
failure(response, error)
|
|
163
|
+
}
|
|
164
|
+
return true
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export const TRACE_ROUTE = '/api/rwkv/traces'
|
|
168
|
+
export const TRACE_EXPORT_ROUTE = '/api/rwkv/trace-export'
|
|
169
|
+
export const LIVE_WIRE_ROUTE = '/api/rwkv/live'
|
|
170
|
+
|
|
171
|
+
function fallbackLiveSnapshot(location: TraceLocation, session: string): LiveWireSnapshot | undefined {
|
|
172
|
+
const records = sessionRecords(location, session)
|
|
173
|
+
for (let i = records.length - 1; i >= 0; i--) {
|
|
174
|
+
const rec = records[i]!
|
|
175
|
+
if (rec.purpose !== undefined) continue
|
|
176
|
+
if (rec.stage !== 'decision' && rec.stage !== 'answer' && rec.stage !== 'card') continue
|
|
177
|
+
if (typeof rec.prompt !== 'string') continue
|
|
178
|
+
const rawOutput = rec.output ?? ''
|
|
179
|
+
const strippedOutput = rec.prompt.endsWith('<think') && rawOutput.startsWith('<think')
|
|
180
|
+
? rawOutput.slice('<think'.length)
|
|
181
|
+
: rawOutput
|
|
182
|
+
const pastThinks: string[] = []
|
|
183
|
+
for (let j = 0; j < i; j++) {
|
|
184
|
+
const prev = records[j]!
|
|
185
|
+
if (prev.purpose !== undefined) continue
|
|
186
|
+
if (prev.stage !== 'decision' && prev.stage !== 'answer') continue
|
|
187
|
+
if (prev.outcome !== 'run' && prev.outcome !== 'final') continue
|
|
188
|
+
pastThinks.push(extractThinkText(prev.output ?? ''))
|
|
189
|
+
}
|
|
190
|
+
const fullPrompt = transcriptWithThinks(records.slice(0, i + 1)) || undefined
|
|
191
|
+
return {
|
|
192
|
+
sessionId: session,
|
|
193
|
+
model: rec.model ?? '',
|
|
194
|
+
stage: rec.stage,
|
|
195
|
+
streaming: false,
|
|
196
|
+
prompt: rec.prompt,
|
|
197
|
+
...(fullPrompt === undefined ? {} : { fullPrompt }),
|
|
198
|
+
promptTokens: rec.promptTokens ?? rec.worklist?.promptTokens ?? 0,
|
|
199
|
+
blockTokens: countWireBlockTokens(rec.prompt),
|
|
200
|
+
...(fullPrompt === undefined ? {} : { fullBlockTokens: countWireBlockTokens(fullPrompt) }),
|
|
201
|
+
...(pastThinks.some(t => t !== '') ? { pastThinks } : {}),
|
|
202
|
+
output: strippedOutput,
|
|
203
|
+
outputTokens: countTokens(strippedOutput),
|
|
204
|
+
...(rec.fold === undefined ? {} : {
|
|
205
|
+
fold: {
|
|
206
|
+
kind: rec.fold.kind as 'in-place' | 'stage-archive' | 'prior-turn' | 'worklist' | 'relay',
|
|
207
|
+
beforeTokens: rec.fold.beforeTokens,
|
|
208
|
+
afterTokens: rec.fold.afterTokens,
|
|
209
|
+
foldedTools: rec.fold.foldedTools,
|
|
210
|
+
},
|
|
211
|
+
}),
|
|
212
|
+
updatedAt: rec.at ?? new Date().toISOString(),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return undefined
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export interface TraceRouteSettings {
|
|
219
|
+
/** Where trace files are (next to DSH's session logs, or a custom directory). */
|
|
220
|
+
readonly location: TraceLocation
|
|
221
|
+
/** Whether new traces are also written to disk (they are always kept in memory). */
|
|
222
|
+
readonly recording: boolean
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Developer tools over the traces (memory and disk):
|
|
227
|
+
* /api/rwkv/traces session list + statistics over all sessions
|
|
228
|
+
* /api/rwkv/traces/<session> the session's records, prompts left out (promptChars instead)
|
|
229
|
+
* /api/rwkv/traces/<session>?index=N one record with its prompt
|
|
230
|
+
* DELETE /api/rwkv/traces/<session> remove the session's RWKV trace (never DSH's own session log)
|
|
231
|
+
* /api/rwkv/trace-export?sessions=a,b whole tasks as JSONL (all sessions when the list is empty)
|
|
232
|
+
*/
|
|
233
|
+
export function handleTraceRoute(request: IncomingMessage, response: ServerResponse, settings: () => TraceRouteSettings): boolean {
|
|
234
|
+
const url = new URL(request.url ?? '/', 'http://host')
|
|
235
|
+
if (url.pathname.startsWith(`${LIVE_WIRE_ROUTE}/`)) {
|
|
236
|
+
if (request.method !== 'GET') {
|
|
237
|
+
send(response, 405, { error: 'method not allowed' })
|
|
238
|
+
return true
|
|
239
|
+
}
|
|
240
|
+
const session = decodeURIComponent(url.pathname.slice(LIVE_WIRE_ROUTE.length + 1))
|
|
241
|
+
const { location } = settings()
|
|
242
|
+
response.writeHead(200, {
|
|
243
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
244
|
+
'cache-control': 'no-cache, no-transform',
|
|
245
|
+
'connection': 'keep-alive',
|
|
246
|
+
'x-accel-buffering': 'no',
|
|
247
|
+
})
|
|
248
|
+
const writeEvent = (event: string, data: unknown) => {
|
|
249
|
+
if (response.writableEnded) return
|
|
250
|
+
response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
|
|
251
|
+
}
|
|
252
|
+
const initial = liveWire.get(session) ?? fallbackLiveSnapshot(location, session)
|
|
253
|
+
if (initial !== undefined) writeEvent('snapshot', initial)
|
|
254
|
+
else writeEvent('empty', { sessionId: session })
|
|
255
|
+
const unsubscribe = liveWire.subscribe(session, event => {
|
|
256
|
+
if (event.type === 'snapshot') writeEvent('snapshot', event.state)
|
|
257
|
+
else if (event.type === 'delta') writeEvent('delta', { text: event.text })
|
|
258
|
+
else writeEvent('done', { output: event.output, outputTokens: event.outputTokens, updatedAt: event.updatedAt })
|
|
259
|
+
})
|
|
260
|
+
const heartbeat = setInterval(() => {
|
|
261
|
+
if (!response.writableEnded) response.write(': ping\n\n')
|
|
262
|
+
}, 25_000)
|
|
263
|
+
request.on('close', () => {
|
|
264
|
+
clearInterval(heartbeat)
|
|
265
|
+
unsubscribe()
|
|
266
|
+
})
|
|
267
|
+
return true
|
|
268
|
+
}
|
|
269
|
+
const isList = url.pathname === TRACE_ROUTE || url.pathname.startsWith(`${TRACE_ROUTE}/`)
|
|
270
|
+
if (!isList && url.pathname !== TRACE_EXPORT_ROUTE) return false
|
|
271
|
+
const { location, recording } = settings()
|
|
272
|
+
const dir = location.describe()
|
|
273
|
+
const deleting = request.method === 'DELETE' && isList && url.pathname.length > TRACE_ROUTE.length + 1
|
|
274
|
+
if (request.method !== 'GET' && !deleting) {
|
|
275
|
+
send(response, 405, { error: 'method not allowed' })
|
|
276
|
+
return true
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
if (deleting) {
|
|
280
|
+
const session = decodeURIComponent(url.pathname.slice(TRACE_ROUTE.length + 1))
|
|
281
|
+
send(response, 200, { session, deleted: deleteTrace(location, session) })
|
|
282
|
+
return true
|
|
283
|
+
}
|
|
284
|
+
if (url.pathname === TRACE_EXPORT_ROUTE) {
|
|
285
|
+
const wanted = (url.searchParams.get('sessions') ?? '').split(',').map(item => item.trim()).filter(Boolean)
|
|
286
|
+
const sessions = wanted.length > 0 ? wanted : allSessions(location).map(item => item.session)
|
|
287
|
+
response.writeHead(200, {
|
|
288
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
289
|
+
'content-disposition': `attachment; filename="rwkv-traces-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '')}.jsonl"`,
|
|
290
|
+
'cache-control': 'no-store',
|
|
291
|
+
})
|
|
292
|
+
for (const session of sessions) {
|
|
293
|
+
const records = sessionRecords(location, session)
|
|
294
|
+
if (records.length === 0) continue
|
|
295
|
+
response.write(`${JSON.stringify(exportTask(session, records))}\n`)
|
|
296
|
+
}
|
|
297
|
+
response.end()
|
|
298
|
+
return true
|
|
299
|
+
}
|
|
300
|
+
const session = decodeURIComponent(url.pathname.slice(TRACE_ROUTE.length + 1))
|
|
301
|
+
if (session === '') {
|
|
302
|
+
const sessions = allSessions(location)
|
|
303
|
+
const records = sessions.flatMap(item => sessionRecords(location, item.session))
|
|
304
|
+
send(response, 200, { dir, recording, sessions, stats: traceStats(records) })
|
|
305
|
+
return true
|
|
306
|
+
}
|
|
307
|
+
const records = sessionRecords(location, session)
|
|
308
|
+
const index = url.searchParams.get('index')
|
|
309
|
+
if (index !== null) {
|
|
310
|
+
const record = records[Number(index)]
|
|
311
|
+
if (record === undefined) send(response, 404, { error: 'no such record' })
|
|
312
|
+
else send(response, 200, { record })
|
|
313
|
+
return true
|
|
314
|
+
}
|
|
315
|
+
send(response, 200, {
|
|
316
|
+
dir, recording, session,
|
|
317
|
+
records: records.map(({ prompt, ...rest }) => prompt === undefined ? rest : { ...rest, promptChars: prompt.length }),
|
|
318
|
+
})
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (!response.headersSent) send(response, 500, { error: error instanceof Error ? error.message : String(error) })
|
|
321
|
+
else response.end()
|
|
322
|
+
}
|
|
323
|
+
return true
|
|
324
|
+
}
|