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
|
+
// Pure statistics, session summaries, past-think transcript reconstruction,
|
|
2
|
+
// and argument diff helpers over `TraceRecord` streams.
|
|
3
|
+
|
|
4
|
+
export interface TraceRecord {
|
|
5
|
+
readonly at?: string
|
|
6
|
+
readonly model?: string
|
|
7
|
+
/** DSH request purpose; absent for the agent itself, e.g. "session-title" for side requests. */
|
|
8
|
+
readonly purpose?: string
|
|
9
|
+
readonly stage?: string
|
|
10
|
+
readonly prompt?: string
|
|
11
|
+
readonly promptTokens?: number
|
|
12
|
+
readonly output?: string
|
|
13
|
+
readonly finish?: string
|
|
14
|
+
readonly stop?: string
|
|
15
|
+
readonly action?: string
|
|
16
|
+
readonly outcome?: string
|
|
17
|
+
readonly repairs?: readonly string[]
|
|
18
|
+
readonly decision?: string
|
|
19
|
+
readonly attempts?: number
|
|
20
|
+
readonly generations?: number
|
|
21
|
+
readonly outputRepairs?: boolean
|
|
22
|
+
readonly guards?: boolean
|
|
23
|
+
/** Card records only: the history range this handoff card replaced. */
|
|
24
|
+
readonly relay?: { readonly from: number; readonly to: number; readonly turn: number; readonly fallback: boolean; readonly card: string }
|
|
25
|
+
/** Decision records in worklist mode: token budget state and active checkpoint index. */
|
|
26
|
+
readonly worklist?: { readonly promptTokens: number; readonly budgetTokens: number; readonly checkpointAt?: number; readonly nudged: boolean }
|
|
27
|
+
/** Context fold triggered on this step (auto-fold in-place mask, stage archive, prior-turn, or relay). */
|
|
28
|
+
readonly fold?: { readonly kind: string; readonly beforeTokens: number; readonly afterTokens: number; readonly foldedTools: number }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const isGeneration = (record: TraceRecord) => record.stage === 'decision' || record.stage === 'answer'
|
|
32
|
+
const isAgent = (record: TraceRecord) => record.purpose === undefined
|
|
33
|
+
|
|
34
|
+
/** Clean = the model's output was used as written: no repair, no re-ask, no gate. */
|
|
35
|
+
export function cleanGeneration(record: TraceRecord): boolean {
|
|
36
|
+
return (record.outcome === 'run' || record.outcome === 'final') && (record.repairs ?? []).length === 0
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Clean request = decided on the first try, no repair, by the model's own call or answer. */
|
|
40
|
+
export function cleanStep(record: TraceRecord): boolean {
|
|
41
|
+
const decision = record.decision ?? ''
|
|
42
|
+
return (record.repairs ?? []).length === 0 && record.attempts === 1
|
|
43
|
+
&& (decision.startsWith('tool ') || decision === 'final model' || decision === 'final exit')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ModelStats {
|
|
47
|
+
readonly model: string
|
|
48
|
+
generations: number
|
|
49
|
+
clean: number
|
|
50
|
+
steps: number
|
|
51
|
+
cleanSteps: number
|
|
52
|
+
readonly outcomes: Record<string, number>
|
|
53
|
+
readonly repairs: Record<string, number>
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Per-model counts over agent requests (side requests such as session titles are left out). */
|
|
57
|
+
export function traceStats(records: Iterable<TraceRecord>): ModelStats[] {
|
|
58
|
+
const byModel = new Map<string, ModelStats>()
|
|
59
|
+
const entry = (model: string) => {
|
|
60
|
+
let stats = byModel.get(model)
|
|
61
|
+
if (stats === undefined) {
|
|
62
|
+
stats = { model, generations: 0, clean: 0, steps: 0, cleanSteps: 0, outcomes: {}, repairs: {} }
|
|
63
|
+
byModel.set(model, stats)
|
|
64
|
+
}
|
|
65
|
+
return stats
|
|
66
|
+
}
|
|
67
|
+
for (const record of records) {
|
|
68
|
+
if (!isAgent(record)) continue
|
|
69
|
+
const stats = entry(record.model ?? '?')
|
|
70
|
+
if (record.stage === 'step') {
|
|
71
|
+
stats.steps++
|
|
72
|
+
if (cleanStep(record)) stats.cleanSteps++
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
if (!isGeneration(record) || record.outcome === undefined) continue
|
|
76
|
+
stats.generations++
|
|
77
|
+
stats.outcomes[record.outcome] = (stats.outcomes[record.outcome] ?? 0) + 1
|
|
78
|
+
for (const repair of record.repairs ?? []) stats.repairs[repair] = (stats.repairs[repair] ?? 0) + 1
|
|
79
|
+
if (cleanGeneration(record)) stats.clean++
|
|
80
|
+
}
|
|
81
|
+
return [...byModel.values()]
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** First user message of the agent's first prompt, as a list preview. */
|
|
85
|
+
function taskPreview(records: readonly TraceRecord[]): string {
|
|
86
|
+
const prompt = records.find(record => isAgent(record) && isGeneration(record))?.prompt ?? ''
|
|
87
|
+
const match = /\n\nUser: ([\s\S]*?)(?:\n\n(?:User|Assistant):|$)/.exec(prompt)
|
|
88
|
+
return (match?.[1] ?? '').trim().slice(0, 200)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface SessionSummary {
|
|
92
|
+
readonly session: string
|
|
93
|
+
readonly modified: string
|
|
94
|
+
readonly bytes: number
|
|
95
|
+
/** A file in the trace directory exists for it (otherwise memory only). */
|
|
96
|
+
readonly persisted: boolean
|
|
97
|
+
readonly task: string
|
|
98
|
+
readonly models: readonly string[]
|
|
99
|
+
readonly generations: number
|
|
100
|
+
readonly steps: number
|
|
101
|
+
/** Generations / requests the plugin had to touch (repair, re-ask, gate). */
|
|
102
|
+
readonly touchedGenerations: number
|
|
103
|
+
readonly touchedSteps: number
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function summarizeSession(
|
|
107
|
+
session: string,
|
|
108
|
+
records: readonly TraceRecord[],
|
|
109
|
+
modified: string,
|
|
110
|
+
bytes: number,
|
|
111
|
+
persisted: boolean,
|
|
112
|
+
): SessionSummary {
|
|
113
|
+
const agent = records.filter(isAgent)
|
|
114
|
+
const generations = agent.filter(isGeneration)
|
|
115
|
+
const steps = agent.filter(record => record.stage === 'step')
|
|
116
|
+
return {
|
|
117
|
+
session,
|
|
118
|
+
modified,
|
|
119
|
+
bytes,
|
|
120
|
+
persisted,
|
|
121
|
+
task: taskPreview(records),
|
|
122
|
+
models: [...new Set(agent.map(record => record.model ?? '?'))],
|
|
123
|
+
generations: generations.length,
|
|
124
|
+
steps: steps.length,
|
|
125
|
+
touchedGenerations: generations.filter(record => record.outcome !== undefined && !cleanGeneration(record)).length,
|
|
126
|
+
touchedSteps: steps.filter(record => !cleanStep(record)).length,
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const WITHHELD_THINK = '<think'
|
|
131
|
+
const EMPTY_THINK = 'Assistant: <think></think>'
|
|
132
|
+
|
|
133
|
+
/** prompt + output as one text: the withheld "<think" generation point is not doubled. */
|
|
134
|
+
export function joinGeneration(prompt: string, output: string): string {
|
|
135
|
+
return prompt.endsWith(WITHHELD_THINK) && output.startsWith(WITHHELD_THINK)
|
|
136
|
+
? prompt.slice(0, -WITHHELD_THINK.length) + output
|
|
137
|
+
: prompt + output
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function thinkOf(output: string): string | undefined {
|
|
141
|
+
const match = /^\s*<think>([\s\S]*?)<\/think>/.exec(output)
|
|
142
|
+
return match?.[1]
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The agent's last generation as one RWKV text, with each past step's empty
|
|
147
|
+
* think replaced by the think the model really wrote at that step.
|
|
148
|
+
*/
|
|
149
|
+
export function transcriptWithThinks(records: readonly TraceRecord[]): string | undefined {
|
|
150
|
+
const agent = records.filter(isAgent)
|
|
151
|
+
const last = [...agent].reverse().find(isGeneration)
|
|
152
|
+
if (last?.prompt === undefined || last.output === undefined) return undefined
|
|
153
|
+
const thinks: (string | undefined)[] = []
|
|
154
|
+
let accepted: TraceRecord | undefined
|
|
155
|
+
for (const record of agent) {
|
|
156
|
+
if (record.stage === 'step') {
|
|
157
|
+
thinks.push(accepted?.output === undefined ? undefined : thinkOf(accepted.output))
|
|
158
|
+
accepted = undefined
|
|
159
|
+
} else if (isGeneration(record) && (record.outcome === 'run' || record.outcome === 'final' || record.outcome === 'raw')) {
|
|
160
|
+
accepted = record
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const parts = last.prompt.split(EMPTY_THINK)
|
|
164
|
+
if (thinks.length !== parts.length) return undefined
|
|
165
|
+
let text = parts[0]!
|
|
166
|
+
for (let index = 1; index < parts.length; index++) {
|
|
167
|
+
const think = thinks[index - 1]
|
|
168
|
+
text += (think === undefined ? EMPTY_THINK : `Assistant: <think>${think}</think>`) + parts[index]
|
|
169
|
+
}
|
|
170
|
+
return joinGeneration(text, last.output)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** One exported task: every record as written, plus the RWKV texts derived from them. */
|
|
174
|
+
export function exportTask(session: string, records: readonly TraceRecord[]): Record<string, unknown> {
|
|
175
|
+
const agent = records.filter(isAgent)
|
|
176
|
+
const last = [...agent].reverse().find(isGeneration)
|
|
177
|
+
const transcript = transcriptWithThinks(records)
|
|
178
|
+
return {
|
|
179
|
+
session,
|
|
180
|
+
models: [...new Set(agent.map(record => record.model ?? '?'))],
|
|
181
|
+
stats: traceStats(records),
|
|
182
|
+
...last?.prompt !== undefined && last.output !== undefined ? { text: joinGeneration(last.prompt, last.output) } : {},
|
|
183
|
+
...transcript !== undefined ? { textWithThinks: transcript } : {},
|
|
184
|
+
records,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** One argument difference between what the model wrote and what DSH received. */
|
|
189
|
+
export interface ArgumentChange {
|
|
190
|
+
readonly key: string
|
|
191
|
+
readonly kind: 'changed' | 'added' | 'removed' | 'renamed'
|
|
192
|
+
/** For renamed: the key the model wrote. */
|
|
193
|
+
readonly from?: string
|
|
194
|
+
readonly before?: unknown
|
|
195
|
+
readonly after?: unknown
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const sameValue = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
|
199
|
+
|
|
200
|
+
/** Field-level differences, with a removed + added pair of equal values reported as one rename. */
|
|
201
|
+
export function argumentChanges(before: Record<string, unknown>, after: Record<string, unknown>): ArgumentChange[] {
|
|
202
|
+
const changes: ArgumentChange[] = []
|
|
203
|
+
const removed = Object.keys(before).filter(key => !(key in after))
|
|
204
|
+
const added = Object.keys(after).filter(key => !(key in before))
|
|
205
|
+
for (const key of Object.keys(after)) {
|
|
206
|
+
if (key in before && !sameValue(before[key], after[key])) changes.push({ key, kind: 'changed', before: before[key], after: after[key] })
|
|
207
|
+
}
|
|
208
|
+
for (const key of added) {
|
|
209
|
+
const source = removed.find(old => sameValue(before[old], after[key]))
|
|
210
|
+
if (source !== undefined) {
|
|
211
|
+
removed.splice(removed.indexOf(source), 1)
|
|
212
|
+
changes.push({ key, kind: 'renamed', from: source, after: after[key] })
|
|
213
|
+
} else {
|
|
214
|
+
changes.push({ key, kind: 'added', after: after[key] })
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const key of removed) changes.push({ key, kind: 'removed', before: before[key] })
|
|
218
|
+
return changes
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Arguments for a trace record: long strings (file content) cut so memory and files stay small. */
|
|
222
|
+
export function clipArguments(args: Record<string, unknown>, limit = 2000): Record<string, unknown> {
|
|
223
|
+
return Object.fromEntries(Object.entries(args).map(([key, value]) =>
|
|
224
|
+
[key, typeof value === 'string' && value.length > limit ? `${value.slice(0, limit)}…(共 ${value.length} 字符)` : value]))
|
|
225
|
+
}
|
package/src/traces.ts
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// RWKV trace storage and I/O: session directory discovery, bounded in-memory
|
|
2
|
+
// ring, ordered async JSONL append, readback, and deletion. Pure statistics
|
|
3
|
+
// and export helpers live in `trace-stats.ts` and are re-exported here.
|
|
4
|
+
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
|
|
6
|
+
import { appendFile, mkdir } from 'node:fs/promises'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
import { basename, dirname, join } from 'node:path'
|
|
9
|
+
import { summarizeSession, type SessionSummary, type TraceRecord } from './trace-stats.ts'
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
argumentChanges,
|
|
13
|
+
cleanGeneration,
|
|
14
|
+
cleanStep,
|
|
15
|
+
clipArguments,
|
|
16
|
+
exportTask,
|
|
17
|
+
joinGeneration,
|
|
18
|
+
summarizeSession,
|
|
19
|
+
traceStats,
|
|
20
|
+
transcriptWithThinks,
|
|
21
|
+
type ArgumentChange,
|
|
22
|
+
type ModelStats,
|
|
23
|
+
type SessionSummary,
|
|
24
|
+
type TraceRecord,
|
|
25
|
+
} from './trace-stats.ts'
|
|
26
|
+
|
|
27
|
+
export function dshHome(): string {
|
|
28
|
+
return process.env.DSH_HOME?.trim() || join(homedir(), '.dsh')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** File name of the RWKV trace inside a DSH session directory. */
|
|
32
|
+
export const SESSION_TRACE_FILE = 'rwkv-trace.jsonl'
|
|
33
|
+
|
|
34
|
+
/** File name of the relay handoff cards inside a DSH session directory. */
|
|
35
|
+
export const RELAY_CARD_FILE = 'rwkv-relay.jsonl'
|
|
36
|
+
|
|
37
|
+
const SESSION_ID = /^[\w.-]+$/
|
|
38
|
+
const SESSION_FILE = /^[\w.-]+\.jsonl$/
|
|
39
|
+
const validSession = (session: string) => SESSION_ID.test(session) && !session.includes('..')
|
|
40
|
+
|
|
41
|
+
/** Session id -> its DSH session directory; found once by scanning the workspace directories. */
|
|
42
|
+
const sessionDirs = new Map<string, string>()
|
|
43
|
+
|
|
44
|
+
/** Pending appends per trace file, so records keep their order. */
|
|
45
|
+
const traceWrites = new Map<string, Promise<void>>()
|
|
46
|
+
/** Trace files this process has started writing; the first write also flushes what memory held before. */
|
|
47
|
+
const traceStarted = new Set<string>()
|
|
48
|
+
|
|
49
|
+
function findSessionDir(root: string, session: string): string | undefined {
|
|
50
|
+
const cached = sessionDirs.get(session)
|
|
51
|
+
if (cached !== undefined && existsSync(cached)) return cached
|
|
52
|
+
let workspaces: string[]
|
|
53
|
+
try {
|
|
54
|
+
workspaces = readdirSync(root)
|
|
55
|
+
} catch {
|
|
56
|
+
return undefined
|
|
57
|
+
}
|
|
58
|
+
for (const workspace of workspaces) {
|
|
59
|
+
const dir = join(root, workspace, session)
|
|
60
|
+
if (existsSync(dir)) {
|
|
61
|
+
sessionDirs.set(session, dir)
|
|
62
|
+
return dir
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Where trace files are: next to the DSH session logs, or in a custom directory. */
|
|
69
|
+
export class TraceLocation {
|
|
70
|
+
readonly customDir: string | undefined
|
|
71
|
+
readonly sessionsRoot: string
|
|
72
|
+
|
|
73
|
+
constructor(customDir?: string, sessionsRoot = join(dshHome(), 'sessions')) {
|
|
74
|
+
this.customDir = customDir?.trim() || undefined
|
|
75
|
+
this.sessionsRoot = sessionsRoot
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Human-readable place, for the settings page. */
|
|
79
|
+
describe(): string {
|
|
80
|
+
const place = this.customDir ?? `${this.sessionsRoot}/<工作区>/<会话>/${SESSION_TRACE_FILE}`
|
|
81
|
+
const home = homedir()
|
|
82
|
+
return place.startsWith(`${home}/`) ? `~${place.slice(home.length)}` : place
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The session's trace file; undefined while its DSH session directory does not exist yet. */
|
|
86
|
+
path(session: string): string | undefined {
|
|
87
|
+
if (!validSession(session)) return undefined
|
|
88
|
+
if (this.customDir !== undefined) return join(this.customDir, `${session}.jsonl`)
|
|
89
|
+
const dir = findSessionDir(this.sessionsRoot, session)
|
|
90
|
+
return dir === undefined ? undefined : join(dir, SESSION_TRACE_FILE)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The session's relay-card file: same place as the trace, different name. */
|
|
94
|
+
relayPath(session: string): string | undefined {
|
|
95
|
+
if (!validSession(session)) return undefined
|
|
96
|
+
if (this.customDir !== undefined) return join(this.customDir, `${session}.relay.jsonl`)
|
|
97
|
+
const dir = findSessionDir(this.sessionsRoot, session)
|
|
98
|
+
return dir === undefined ? undefined : join(dir, RELAY_CARD_FILE)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Every existing trace file. */
|
|
102
|
+
list(): { session: string; path: string }[] {
|
|
103
|
+
const found: { session: string; path: string }[] = []
|
|
104
|
+
if (this.customDir !== undefined) {
|
|
105
|
+
try {
|
|
106
|
+
for (const name of readdirSync(this.customDir)) {
|
|
107
|
+
if (SESSION_FILE.test(name)) found.push({ session: basename(name, '.jsonl'), path: join(this.customDir, name) })
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
// No directory yet.
|
|
111
|
+
}
|
|
112
|
+
return found
|
|
113
|
+
}
|
|
114
|
+
let workspaces: string[] = []
|
|
115
|
+
try {
|
|
116
|
+
workspaces = readdirSync(this.sessionsRoot)
|
|
117
|
+
} catch {
|
|
118
|
+
return found
|
|
119
|
+
}
|
|
120
|
+
for (const workspace of workspaces) {
|
|
121
|
+
let sessions: string[] = []
|
|
122
|
+
try {
|
|
123
|
+
sessions = readdirSync(join(this.sessionsRoot, workspace))
|
|
124
|
+
} catch {
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
for (const session of sessions) {
|
|
128
|
+
const path = join(this.sessionsRoot, workspace, session, SESSION_TRACE_FILE)
|
|
129
|
+
if (existsSync(path)) {
|
|
130
|
+
sessionDirs.set(session, join(this.sessionsRoot, workspace, session))
|
|
131
|
+
found.push({ session, path })
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return found
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function readTrace(path: string): TraceRecord[] {
|
|
140
|
+
const records: TraceRecord[] = []
|
|
141
|
+
for (const line of readFileSync(path, 'utf8').split('\n')) {
|
|
142
|
+
if (line.trim() === '') continue
|
|
143
|
+
try {
|
|
144
|
+
records.push(JSON.parse(line) as TraceRecord)
|
|
145
|
+
} catch {
|
|
146
|
+
// A line cut by a crash mid-append: skip it, keep the rest.
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return records
|
|
150
|
+
.map((record, index) => ({ record, index }))
|
|
151
|
+
.sort((a, b) => (a.record.at ?? '').localeCompare(b.record.at ?? '') || a.index - b.index)
|
|
152
|
+
.map(item => item.record)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Sessions on disk only. */
|
|
156
|
+
export function listSessions(location: TraceLocation): SessionSummary[] {
|
|
157
|
+
return location.list()
|
|
158
|
+
.map(({ session, path }) => {
|
|
159
|
+
const info = statSync(path)
|
|
160
|
+
return summarizeSession(session, readTrace(path), info.mtime.toISOString(), info.size, true)
|
|
161
|
+
})
|
|
162
|
+
.sort((a, b) => b.modified.localeCompare(a.modified))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Traces of this DSH process, kept in memory whether or not they are written
|
|
167
|
+
* to disk, so the RWKV tab works without recording.
|
|
168
|
+
*/
|
|
169
|
+
export class MemoryTraces {
|
|
170
|
+
private readonly sessions = new Map<string, { records: TraceRecord[]; chars: number; modified: string }>()
|
|
171
|
+
private total = 0
|
|
172
|
+
private readonly maxSessions: number
|
|
173
|
+
private readonly maxChars: number
|
|
174
|
+
|
|
175
|
+
constructor(maxSessions = 100, maxChars = 100_000_000) {
|
|
176
|
+
this.maxSessions = maxSessions
|
|
177
|
+
this.maxChars = maxChars
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
add(session: string, record: TraceRecord): void {
|
|
181
|
+
const chars = JSON.stringify(record).length
|
|
182
|
+
const entry = this.sessions.get(session) ?? { records: [], chars: 0, modified: '' }
|
|
183
|
+
this.sessions.delete(session)
|
|
184
|
+
entry.records.push(record)
|
|
185
|
+
entry.chars += chars
|
|
186
|
+
entry.modified = record.at ?? new Date().toISOString()
|
|
187
|
+
this.sessions.set(session, entry)
|
|
188
|
+
this.total += chars
|
|
189
|
+
for (const [key, oldest] of this.sessions) {
|
|
190
|
+
if (this.sessions.size <= 1 || (this.sessions.size <= this.maxSessions && this.total <= this.maxChars)) break
|
|
191
|
+
this.sessions.delete(key)
|
|
192
|
+
this.total -= oldest.chars
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
get(session: string): TraceRecord[] | undefined {
|
|
197
|
+
return this.sessions.get(session)?.records
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
delete(session: string): void {
|
|
201
|
+
const entry = this.sessions.get(session)
|
|
202
|
+
if (entry === undefined) return
|
|
203
|
+
this.sessions.delete(session)
|
|
204
|
+
this.total -= entry.chars
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
list(): SessionSummary[] {
|
|
208
|
+
return [...this.sessions].map(([session, entry]) => summarizeSession(session, entry.records, entry.modified, entry.chars, false))
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export const memoryTraces = new MemoryTraces()
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Record one trace entry into `memory` and, when `location` resolves a file for
|
|
216
|
+
* `sessionId`, serialize writes per file so step summaries always follow their
|
|
217
|
+
* generations.
|
|
218
|
+
*/
|
|
219
|
+
export function appendSessionTrace(
|
|
220
|
+
sessionId: string | undefined,
|
|
221
|
+
location: TraceLocation | undefined,
|
|
222
|
+
record: TraceRecord,
|
|
223
|
+
memory: MemoryTraces = memoryTraces,
|
|
224
|
+
): void {
|
|
225
|
+
const memoryKey = sessionId ?? 'no-session'
|
|
226
|
+
memory.add(memoryKey, record)
|
|
227
|
+
const traceFile = sessionId === undefined ? undefined : location?.path(sessionId)
|
|
228
|
+
if (traceFile === undefined) return
|
|
229
|
+
const traceDir = dirname(traceFile)
|
|
230
|
+
let records: readonly unknown[] = [record]
|
|
231
|
+
if (!traceStarted.has(traceFile)) {
|
|
232
|
+
traceStarted.add(traceFile)
|
|
233
|
+
if (!existsSync(traceFile)) records = memory.get(memoryKey) ?? [record]
|
|
234
|
+
}
|
|
235
|
+
const line = records.map(item => `${JSON.stringify(item)}\n`).join('')
|
|
236
|
+
const previous = traceWrites.get(traceFile) ?? Promise.resolve()
|
|
237
|
+
const next = previous.then(() => mkdir(traceDir, { recursive: true })).then(() => appendFile(traceFile, line)).catch(() => {})
|
|
238
|
+
traceWrites.set(traceFile, next)
|
|
239
|
+
void next.then(() => { if (traceWrites.get(traceFile) === next) traceWrites.delete(traceFile) })
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Flush all pending async trace appends and drop a closed session's in-memory
|
|
244
|
+
* trace copy so multi-session daemon processes stay flat in RSS.
|
|
245
|
+
*/
|
|
246
|
+
export async function flushAndEvictSessionTrace(sessionId: string, memory: MemoryTraces = memoryTraces): Promise<void> {
|
|
247
|
+
if (!sessionId) return
|
|
248
|
+
if (traceWrites.size > 0) {
|
|
249
|
+
await Promise.allSettled([...traceWrites.values()])
|
|
250
|
+
}
|
|
251
|
+
for (const file of [...traceStarted]) {
|
|
252
|
+
if (basename(file) === `${sessionId}.jsonl` || basename(dirname(file)) === sessionId) {
|
|
253
|
+
traceStarted.delete(file)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
sessionDirs.delete(sessionId)
|
|
257
|
+
memory.delete(sessionId)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** One session's records: from disk or memory, whichever holds more. */
|
|
261
|
+
export function sessionRecords(location: TraceLocation, session: string, memory: MemoryTraces = memoryTraces): TraceRecord[] {
|
|
262
|
+
const path = location.path(session)
|
|
263
|
+
const disk = path !== undefined && existsSync(path) ? readTrace(path) : []
|
|
264
|
+
const live = memory.get(session) ?? []
|
|
265
|
+
return live.length > disk.length ? [...live] : disk
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Removes a session's RWKV trace (the file and the memory copy); DSH's own session log is not touched. */
|
|
269
|
+
export function deleteTrace(location: TraceLocation, session: string, memory: MemoryTraces = memoryTraces): boolean {
|
|
270
|
+
if (!validSession(session)) return false
|
|
271
|
+
const path = location.path(session)
|
|
272
|
+
const existed = path !== undefined && existsSync(path)
|
|
273
|
+
if (existed) rmSync(path)
|
|
274
|
+
const inMemory = memory.get(session) !== undefined
|
|
275
|
+
memory.delete(session)
|
|
276
|
+
return existed || inMemory
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Disk and memory sessions together, newest first. */
|
|
280
|
+
export function allSessions(location: TraceLocation, memory: MemoryTraces = memoryTraces): SessionSummary[] {
|
|
281
|
+
const byId = new Map(listSessions(location).map(item => [item.session, item]))
|
|
282
|
+
for (const item of memory.list()) {
|
|
283
|
+
const disk = byId.get(item.session)
|
|
284
|
+
if (disk === undefined || item.generations + item.steps > disk.generations + disk.steps) {
|
|
285
|
+
byId.set(item.session, { ...item, persisted: disk !== undefined })
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return [...byId.values()].sort((a, b) => b.modified.localeCompare(a.modified))
|
|
289
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# rwkv-tokenizer (vendored)
|
|
2
|
+
|
|
3
|
+
Exact RWKV World token counts without a network install: the published npm
|
|
4
|
+
package `rwkv-tokenizer@0.3.3` (2025-07-08), copied verbatim.
|
|
5
|
+
|
|
6
|
+
- Source: https://github.com/cahya-wirawan/rwkv-tokenizer (npm tarball
|
|
7
|
+
`https://registry.npmjs.org/rwkv-tokenizer/-/rwkv-tokenizer-0.3.3.tgz`)
|
|
8
|
+
- License: MIT OR Apache-2.0 (as declared in the package's `package.json`; the
|
|
9
|
+
tarball ships no license file)
|
|
10
|
+
- Vocabulary: 65,530 entries, the RWKV World vocabulary (`rwkv_vocab_v20230424`)
|
|
11
|
+
used by `rwkv-tokenizer-go`, the reference for every token count in this
|
|
12
|
+
workbench. Verified identical on 442 real tool results and on the fixtures in
|
|
13
|
+
`test/edit-budget.test.ts`.
|
|
14
|
+
|
|
15
|
+
`rwkv_tokenizer.js` is a wasm-bindgen (CommonJS) glue file and reads
|
|
16
|
+
`rwkv_tokenizer_bg.wasm` from its own directory at require time; both files
|
|
17
|
+
must stay together. Do not edit either file. Re-vendoring means replacing both
|
|
18
|
+
and re-running `scripts/tokenizer-parity.ts`.
|
|
19
|
+
|
|
20
|
+
SHA-256:
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
d3583b3b4abe520e1820d27e66db393676bd00eacffeb109face0ff0818cc86c rwkv_tokenizer.js
|
|
24
|
+
956b97490bb811b47886b9ec32c4b4ba6ae2d4b5b915bce03c7a32a8f9853ae2 rwkv_tokenizer_bg.wasm
|
|
25
|
+
4feb9d0cfade4b614c27266fc625a9270e5d046e52e22683ca4ac010b05eb10e rwkv_tokenizer.d.ts
|
|
26
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
export class WorldTokenizer {
|
|
4
|
+
free(): void;
|
|
5
|
+
constructor();
|
|
6
|
+
encode(word: string): Uint16Array;
|
|
7
|
+
encode_batch(word_list: string[]): Array<any>;
|
|
8
|
+
decode(vec: Uint16Array): string;
|
|
9
|
+
vocab_size(): number;
|
|
10
|
+
get_vocab_as_json(): any;
|
|
11
|
+
}
|