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,107 @@
|
|
|
1
|
+
// Checks the vendored tokenizer (src/tokenizer.ts) against rwkv-tokenizer-go on
|
|
2
|
+
// real tool results as the model reads them (inside <tool_response>,
|
|
3
|
+
// JSON-escaped). Both must produce the same ids: the Go binary is the
|
|
4
|
+
// reference every training-pack and evaluation token count was taken with.
|
|
5
|
+
//
|
|
6
|
+
// node scripts/tokenizer-parity.ts [--tokenizer BIN] [--limit N] SOURCE...
|
|
7
|
+
//
|
|
8
|
+
// SOURCE: DSH --json event logs (events-*.jsonl: tool_result events), files
|
|
9
|
+
// holding one <tool_response>...</tool_response> segment, or directories of
|
|
10
|
+
// either. Results shorter than 300 characters are skipped; duplicates once.
|
|
11
|
+
// Exits non-zero when any sample differs, printing the first few.
|
|
12
|
+
|
|
13
|
+
import { spawnSync } from 'node:child_process'
|
|
14
|
+
import { createHash } from 'node:crypto'
|
|
15
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
16
|
+
import { homedir } from 'node:os'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
import { parseArgs } from 'node:util'
|
|
19
|
+
import { toolResponse } from '../src/core/prompt.ts'
|
|
20
|
+
import { countTokens } from '../src/tokenizer.ts'
|
|
21
|
+
|
|
22
|
+
const { values, positionals } = parseArgs({
|
|
23
|
+
allowPositionals: true,
|
|
24
|
+
options: {
|
|
25
|
+
tokenizer: { type: 'string', default: join(homedir(), 'Projects/rwkv-tokenizer-go/bin/rwkv-tokenizer') },
|
|
26
|
+
limit: { type: 'string', default: '400' },
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
const limit = Number(values.limit)
|
|
30
|
+
|
|
31
|
+
interface Sample { tool: string; text: string }
|
|
32
|
+
const samples: Sample[] = []
|
|
33
|
+
const seen = new Set<string>()
|
|
34
|
+
const perTool = new Map<string, number>()
|
|
35
|
+
|
|
36
|
+
function add(tool: string, text: string): void {
|
|
37
|
+
if (text.length < 300) return
|
|
38
|
+
const hash = createHash('md5').update(text).digest('hex')
|
|
39
|
+
if (seen.has(hash)) return
|
|
40
|
+
seen.add(hash)
|
|
41
|
+
const count = (perTool.get(tool) ?? 0) + 1
|
|
42
|
+
perTool.set(tool, count)
|
|
43
|
+
if (count <= limit) samples.push({ tool, text })
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function readSource(path: string): void {
|
|
47
|
+
let stat
|
|
48
|
+
try {
|
|
49
|
+
stat = statSync(path)
|
|
50
|
+
} catch {
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
if (stat.isDirectory()) {
|
|
54
|
+
for (const name of readdirSync(path)) readSource(join(path, name))
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
const content = readFileSync(path, 'utf8')
|
|
58
|
+
if (content.startsWith('<tool_response>')) {
|
|
59
|
+
const payload = JSON.parse(content.slice('<tool_response>'.length, -'</tool_response>'.length)) as { tool?: string; result?: unknown; error?: unknown }
|
|
60
|
+
const value = payload.result ?? payload.error
|
|
61
|
+
add(String(payload.tool ?? 'tool'), typeof value === 'string' ? value : JSON.stringify(value))
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
if (!path.endsWith('.jsonl')) return
|
|
65
|
+
const calls = new Map<string, string>()
|
|
66
|
+
for (const line of content.split('\n')) {
|
|
67
|
+
let event: { type?: string; callId?: string; tool?: string; result?: unknown; error?: unknown }
|
|
68
|
+
try {
|
|
69
|
+
event = JSON.parse(line)
|
|
70
|
+
} catch {
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
if (event.type === 'tool_call' && event.callId) calls.set(event.callId, String(event.tool))
|
|
74
|
+
else if (event.type === 'tool_result' && event.callId && calls.has(event.callId)) {
|
|
75
|
+
const value = event.result ?? event.error
|
|
76
|
+
if (typeof value === 'string') add(calls.get(event.callId)!, value)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
for (const source of positionals) readSource(source)
|
|
82
|
+
if (samples.length === 0) {
|
|
83
|
+
console.error('usage: node scripts/tokenizer-parity.ts [--tokenizer BIN] [--limit N] SOURCE...')
|
|
84
|
+
process.exit(2)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function goTokens(text: string): number {
|
|
88
|
+
const run = spawnSync(values.tokenizer!, ['encode'], { input: text, encoding: 'utf8', maxBuffer: 1 << 28 })
|
|
89
|
+
if (run.status !== 0) throw new Error(`tokenizer failed: ${run.stderr}`)
|
|
90
|
+
return run.stdout.split(/\s+/).filter(Boolean).length
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The tool response the model reads. */
|
|
94
|
+
const wire = (tool: string, text: string) => toolResponse(tool, true, text)
|
|
95
|
+
|
|
96
|
+
let identical = 0
|
|
97
|
+
const different: { tool: string; wasm: number; go: number; preview: string }[] = []
|
|
98
|
+
for (const { tool, text } of samples) {
|
|
99
|
+
const body = wire(tool, text)
|
|
100
|
+
const wasm = countTokens(body)
|
|
101
|
+
const go = goTokens(body)
|
|
102
|
+
if (wasm === go) identical++
|
|
103
|
+
else if (different.length < 10) different.push({ tool, wasm, go, preview: text.slice(0, 120) })
|
|
104
|
+
}
|
|
105
|
+
console.log(`samples ${samples.length} identical ${identical} different ${samples.length - identical}`)
|
|
106
|
+
for (const row of different) console.log(JSON.stringify(row))
|
|
107
|
+
if (different.length > 0) process.exit(1)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Raw output quality from trace JSONL: how often the model's own output was
|
|
2
|
+
// used as written, versus how often the plugin had to repair or intervene.
|
|
3
|
+
// The same numbers as the developer section of the settings page.
|
|
4
|
+
//
|
|
5
|
+
// node scripts/trace-stats.ts <traceDir or .jsonl files...>
|
|
6
|
+
|
|
7
|
+
import { readdirSync, statSync } from 'node:fs'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
import { readTrace, traceStats } from '../src/traces.ts'
|
|
10
|
+
|
|
11
|
+
const args = process.argv.slice(2)
|
|
12
|
+
if (args.length === 0) {
|
|
13
|
+
console.error('usage: node scripts/trace-stats.ts <traceDir or .jsonl files...>')
|
|
14
|
+
process.exit(1)
|
|
15
|
+
}
|
|
16
|
+
const files = args.flatMap(path => statSync(path).isDirectory()
|
|
17
|
+
? readdirSync(path).filter(name => name.endsWith('.jsonl')).map(name => join(path, name))
|
|
18
|
+
: [path])
|
|
19
|
+
|
|
20
|
+
const percent = (part: number, whole: number) => whole === 0 ? '-' : `${(100 * part / whole).toFixed(1)}%`
|
|
21
|
+
const sorted = (counts: Record<string, number>) => Object.entries(counts).sort((a, b) => b[1] - a[1])
|
|
22
|
+
for (const stats of traceStats(files.flatMap(readTrace))) {
|
|
23
|
+
console.log(`## ${stats.model}`)
|
|
24
|
+
console.log(`clean generations: ${stats.clean}/${stats.generations} (${percent(stats.clean, stats.generations)}) — used as written, no repair, no re-ask`)
|
|
25
|
+
console.log(`requests decided on the first try, no repair: ${stats.cleanSteps}/${stats.steps} (${percent(stats.cleanSteps, stats.steps)})`)
|
|
26
|
+
console.log('outcomes:')
|
|
27
|
+
for (const [key, count] of sorted(stats.outcomes)) console.log(` ${key.padEnd(24)} ${count} (${percent(count, stats.generations)})`)
|
|
28
|
+
if (Object.keys(stats.repairs).length > 0) {
|
|
29
|
+
console.log('repairs (per generation):')
|
|
30
|
+
for (const [key, count] of sorted(stats.repairs)) console.log(` ${key.padEnd(24)} ${count} (${percent(count, stats.generations)})`)
|
|
31
|
+
}
|
|
32
|
+
console.log()
|
|
33
|
+
}
|
package/src/adapter.ts
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { brandString } from '@deepseek-ai/dsh-brand'
|
|
3
|
+
import {
|
|
4
|
+
LlmAdapter,
|
|
5
|
+
LlmError,
|
|
6
|
+
type GenerateOptions,
|
|
7
|
+
type LlmModelInfo,
|
|
8
|
+
type LlmResolvedModelInfo,
|
|
9
|
+
type StreamChunk,
|
|
10
|
+
type ToolCallId,
|
|
11
|
+
} from '@deepseek-ai/dsh-llm'
|
|
12
|
+
import { BackendError, type Generator } from './backend/generator.ts'
|
|
13
|
+
import { IRWKVClient } from './backend/irwkv.ts'
|
|
14
|
+
import { LightningClient } from './backend/lightning.ts'
|
|
15
|
+
import { decideStep, type GenerationTrace, type HarnessConfig } from './core/agent.ts'
|
|
16
|
+
import type { EditMode } from './core/defaults.ts'
|
|
17
|
+
import { dshSystemSections } from './core/dsh-prompt.ts'
|
|
18
|
+
import { currentDateLine } from './core/prompt.ts'
|
|
19
|
+
import type { RelayOptions } from './core/relay.ts'
|
|
20
|
+
import { buildCatalog, type ToolMode, type ToolNames, type ToolOverride } from './core/tools.ts'
|
|
21
|
+
import type { WorklistOptions } from './core/worklist.ts'
|
|
22
|
+
import { setFoldedUnreadPaths } from './folded-read-guard.ts'
|
|
23
|
+
import { historyFromMessages, systemText } from './history.ts'
|
|
24
|
+
import { liveWire } from './live-wire.ts'
|
|
25
|
+
import { repairToolPaths, runtimeCwd } from './paths.ts'
|
|
26
|
+
import { RelayCardStore } from './relay-store.ts'
|
|
27
|
+
import { buildExcludedTools } from './session-setup.ts'
|
|
28
|
+
import {
|
|
29
|
+
appendSessionTrace,
|
|
30
|
+
argumentChanges,
|
|
31
|
+
clipArguments,
|
|
32
|
+
TraceLocation,
|
|
33
|
+
type ArgumentChange,
|
|
34
|
+
type TraceRecord,
|
|
35
|
+
} from './traces.ts'
|
|
36
|
+
|
|
37
|
+
/** Route model id that resolves to the first configured model. */
|
|
38
|
+
export const DEFAULT_MODEL_ID = 'default'
|
|
39
|
+
|
|
40
|
+
export interface ModelConfig {
|
|
41
|
+
readonly id: string
|
|
42
|
+
readonly name?: string
|
|
43
|
+
readonly backend: 'lightning' | 'irwkv'
|
|
44
|
+
readonly baseURL: string
|
|
45
|
+
/** Upstream model id. */
|
|
46
|
+
readonly model: string
|
|
47
|
+
/** iRWKV bearer key or rwkv_lightning password. */
|
|
48
|
+
readonly apiKey?: string
|
|
49
|
+
/** Extra request headers, e.g. Cloudflare Access service-token headers. */
|
|
50
|
+
readonly headers?: Record<string, string>
|
|
51
|
+
readonly contextWindow?: number
|
|
52
|
+
/** rwkv_lightning only: initial state uploaded through /v1/state/upload. */
|
|
53
|
+
readonly stateId?: string
|
|
54
|
+
/** rwkv_lightning only: adapter id for request-level adaptation. */
|
|
55
|
+
readonly adapterId?: string
|
|
56
|
+
/** Legacy (pre-94b3734) form of adapterId; only its id is read. */
|
|
57
|
+
readonly adapter?: { readonly id?: string }
|
|
58
|
+
/** Per-model harness overrides (e.g. thinking: off for a non-thinking checkpoint). */
|
|
59
|
+
readonly thinking?: 'off' | 'full'
|
|
60
|
+
/** agent-wire-think-v2.0 history for think-sft checkpoints. */
|
|
61
|
+
readonly historyEmptyThink?: boolean
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface AdapterSettings {
|
|
65
|
+
readonly models: readonly ModelConfig[]
|
|
66
|
+
readonly harness: HarnessConfig
|
|
67
|
+
readonly toolMode: ToolMode
|
|
68
|
+
readonly toolNames: ToolNames
|
|
69
|
+
readonly editMode?: EditMode
|
|
70
|
+
readonly excludeTools: readonly string[]
|
|
71
|
+
readonly toolOverrides?: Readonly<Record<string, ToolOverride>>
|
|
72
|
+
readonly includeDeveloper: boolean
|
|
73
|
+
readonly currentDate?: boolean
|
|
74
|
+
readonly timeZone?: string
|
|
75
|
+
readonly loopGuard: boolean
|
|
76
|
+
readonly traces?: TraceLocation
|
|
77
|
+
readonly relay?: RelayOptions
|
|
78
|
+
readonly worklist?: WorklistOptions
|
|
79
|
+
readonly onFoldEvent?: (sessionId: string, fold: { readonly kind: string; readonly beforeTokens: number; readonly afterTokens: number; readonly foldedTools: number }) => void
|
|
80
|
+
readonly log?: (message: string) => void
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function llmError(error: unknown): LlmError {
|
|
84
|
+
if (error instanceof LlmError) return error
|
|
85
|
+
if (error instanceof BackendError) {
|
|
86
|
+
return new LlmError(`rwkv: ${error.message}`, error.code, error.status === undefined ? undefined : { status: error.status })
|
|
87
|
+
}
|
|
88
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
89
|
+
return new LlmError(`rwkv: ${message || 'request failed'}`, 'PROVIDER_NETWORK_ERROR')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export class RwkvAdapter extends LlmAdapter {
|
|
93
|
+
private readonly current: () => AdapterSettings
|
|
94
|
+
private readonly clients = new Map<string, Generator>()
|
|
95
|
+
private readonly relayCards = new RelayCardStore()
|
|
96
|
+
|
|
97
|
+
constructor(settings: () => AdapterSettings) {
|
|
98
|
+
super()
|
|
99
|
+
this.current = settings
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private get settings(): AdapterSettings {
|
|
103
|
+
return this.current()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
override providerInfo(provider: string) {
|
|
107
|
+
return { id: provider, name: 'RWKV' }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
|
|
111
|
+
return Promise.resolve(this.settings.models.map(model => {
|
|
112
|
+
const adapterId = model.adapterId ?? model.adapter?.id
|
|
113
|
+
return {
|
|
114
|
+
provider,
|
|
115
|
+
id: model.id,
|
|
116
|
+
name: model.name ?? model.id,
|
|
117
|
+
description: `${model.backend === 'irwkv' ? 'iRWKV' : 'rwkv_lightning'} · ${model.model}${model.stateId ? ` · state ${model.stateId}` : ''}${adapterId ? ` · adapter ${adapterId}` : ''}`,
|
|
118
|
+
inputModalities: ['text'] as const,
|
|
119
|
+
}
|
|
120
|
+
}))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
|
|
124
|
+
const config = this.model(model)
|
|
125
|
+
return Promise.resolve({
|
|
126
|
+
provider,
|
|
127
|
+
id: model,
|
|
128
|
+
name: config.name ?? config.id,
|
|
129
|
+
inputModalities: ['text'] as const,
|
|
130
|
+
context: { contextWindow: config.contextWindow ?? 32768 },
|
|
131
|
+
defaultMaxTokens: this.settings.harness.answerMaxTokens,
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private model(id: string): ModelConfig {
|
|
136
|
+
const models = this.settings.models
|
|
137
|
+
const config = id === DEFAULT_MODEL_ID && !models.some(model => model.id === id) ? models[0] : models.find(model => model.id === id)
|
|
138
|
+
if (config === undefined) {
|
|
139
|
+
throw new LlmError(`rwkv: unknown model "${id}"; configured: ${this.settings.models.map(model => model.id).join(', ') || 'none'}`, 'MODEL_NOT_FOUND')
|
|
140
|
+
}
|
|
141
|
+
return config
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
client(config: ModelConfig): Generator {
|
|
145
|
+
const key = JSON.stringify([config, this.settings.loopGuard])
|
|
146
|
+
let client = this.clients.get(key)
|
|
147
|
+
if (client !== undefined) return client
|
|
148
|
+
const adapterId = config.adapterId ?? config.adapter?.id
|
|
149
|
+
if (config.backend === 'irwkv') {
|
|
150
|
+
if (config.stateId || adapterId) {
|
|
151
|
+
throw new LlmError(`rwkv: model "${config.id}" sets adapter/stateId, which iRWKV does not support`, 'INVALID_MODEL_CONFIG')
|
|
152
|
+
}
|
|
153
|
+
client = new IRWKVClient({
|
|
154
|
+
baseURL: config.baseURL,
|
|
155
|
+
model: config.model,
|
|
156
|
+
...config.apiKey ? { apiKey: config.apiKey } : {},
|
|
157
|
+
...config.headers ? { headers: config.headers } : {},
|
|
158
|
+
loopGuard: this.settings.loopGuard,
|
|
159
|
+
})
|
|
160
|
+
} else {
|
|
161
|
+
client = new LightningClient({
|
|
162
|
+
baseURL: config.baseURL,
|
|
163
|
+
model: config.model,
|
|
164
|
+
...config.apiKey ? { password: config.apiKey } : {},
|
|
165
|
+
...config.stateId ? { stateId: config.stateId } : {},
|
|
166
|
+
...adapterId ? { adapterId } : {},
|
|
167
|
+
...config.headers ? { headers: config.headers } : {},
|
|
168
|
+
loopGuard: this.settings.loopGuard,
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
this.clients.set(key, client)
|
|
172
|
+
return client
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
|
|
176
|
+
const config = this.model(options.model)
|
|
177
|
+
if (options.stop !== undefined && options.stop.length > 0) {
|
|
178
|
+
throw new LlmError('rwkv: custom stop sequences are not supported; the harness owns the RWKV stops', 'UNSUPPORTED_OPTION')
|
|
179
|
+
}
|
|
180
|
+
const harness: HarnessConfig = {
|
|
181
|
+
...this.settings.harness,
|
|
182
|
+
...config.thinking ? { thinking: config.thinking } : {},
|
|
183
|
+
...config.historyEmptyThink === undefined ? {} : { historyEmptyThink: config.historyEmptyThink },
|
|
184
|
+
...options.temperature === undefined ? {} : { sampling: { ...this.settings.harness.sampling, temperature: options.temperature } },
|
|
185
|
+
...options.maxTokens === undefined ? {} : {
|
|
186
|
+
decisionMaxTokens: Math.min(this.settings.harness.decisionMaxTokens, options.maxTokens),
|
|
187
|
+
answerMaxTokens: Math.min(this.settings.harness.answerMaxTokens, options.maxTokens),
|
|
188
|
+
},
|
|
189
|
+
...this.settings.currentDate ? { dateLine: currentDateLine(Date.now(), this.settings.timeZone) } : {},
|
|
190
|
+
...this.settings.relay === undefined ? {} : { relay: this.settings.relay },
|
|
191
|
+
...this.settings.worklist === undefined ? {} : { worklist: this.settings.worklist },
|
|
192
|
+
}
|
|
193
|
+
const names = this.settings.toolNames
|
|
194
|
+
const exclude = buildExcludedTools({
|
|
195
|
+
excludeTools: this.settings.excludeTools,
|
|
196
|
+
editMode: this.settings.editMode,
|
|
197
|
+
worklist: this.settings.worklist,
|
|
198
|
+
})
|
|
199
|
+
const catalog = buildCatalog(options.tools ?? [], { mode: this.settings.toolMode, names, exclude, overrides: this.settings.toolOverrides })
|
|
200
|
+
const history = historyFromMessages(options.messages, catalog, {
|
|
201
|
+
includeDeveloper: this.settings.includeDeveloper,
|
|
202
|
+
names,
|
|
203
|
+
dropTimeContext: this.settings.currentDate === true,
|
|
204
|
+
})
|
|
205
|
+
const systemHead = names === 'dsh' ? dshSystemSections(options.system ?? systemText(options.messages)) : undefined
|
|
206
|
+
|
|
207
|
+
const queue: StreamChunk[] = []
|
|
208
|
+
let wake: (() => void) | undefined
|
|
209
|
+
const push = (chunk: StreamChunk) => {
|
|
210
|
+
queue.push(chunk)
|
|
211
|
+
wake?.()
|
|
212
|
+
}
|
|
213
|
+
let reasoningOpen = false
|
|
214
|
+
let reasoning = ''
|
|
215
|
+
let textOpen = false
|
|
216
|
+
let textIndex = 0
|
|
217
|
+
let streamedText = ''
|
|
218
|
+
let nextIndex = 0
|
|
219
|
+
let attempts = 0
|
|
220
|
+
const closeReasoning = () => {
|
|
221
|
+
if (!reasoningOpen) return
|
|
222
|
+
push({ type: 'block-end', index: 0, block: { type: 'reasoning', text: reasoning } })
|
|
223
|
+
reasoningOpen = false
|
|
224
|
+
nextIndex = Math.max(nextIndex, 1)
|
|
225
|
+
}
|
|
226
|
+
const reasoningDelta = (text: string) => {
|
|
227
|
+
if (textOpen) return
|
|
228
|
+
if (!reasoningOpen) {
|
|
229
|
+
push({ type: 'block-start', index: 0, blockType: 'reasoning' })
|
|
230
|
+
reasoningOpen = true
|
|
231
|
+
nextIndex = 1
|
|
232
|
+
}
|
|
233
|
+
reasoning += text
|
|
234
|
+
push({ type: 'reasoning-delta', index: 0, text })
|
|
235
|
+
}
|
|
236
|
+
const textDelta = (text: string) => {
|
|
237
|
+
if (text === '') return
|
|
238
|
+
if (!textOpen) {
|
|
239
|
+
closeReasoning()
|
|
240
|
+
textIndex = nextIndex++
|
|
241
|
+
push({ type: 'block-start', index: textIndex, blockType: 'text' })
|
|
242
|
+
textOpen = true
|
|
243
|
+
}
|
|
244
|
+
streamedText += text
|
|
245
|
+
push({ type: 'text-delta', index: textIndex, text })
|
|
246
|
+
}
|
|
247
|
+
const sessionId = options.sessionId === undefined ? undefined : String(options.sessionId)
|
|
248
|
+
const cwd = runtimeCwd(history)
|
|
249
|
+
const location = this.settings.traces
|
|
250
|
+
const writeLine = (fields: Record<string, unknown>) => {
|
|
251
|
+
const record = { at: new Date().toISOString(), model: config.id, purpose: options.purpose, ...fields } as TraceRecord
|
|
252
|
+
appendSessionTrace(sessionId, location, record)
|
|
253
|
+
}
|
|
254
|
+
const writeTrace = (trace: GenerationTrace) => writeLine({ ...trace })
|
|
255
|
+
|
|
256
|
+
let settled = false
|
|
257
|
+
const work = (async () => {
|
|
258
|
+
const relayLocation = location ?? new TraceLocation()
|
|
259
|
+
return decideStep({
|
|
260
|
+
history,
|
|
261
|
+
tools: catalog,
|
|
262
|
+
config: harness,
|
|
263
|
+
generator: this.client(config),
|
|
264
|
+
...systemHead ? { systemHead } : {},
|
|
265
|
+
...options.signal ? { signal: options.signal } : {},
|
|
266
|
+
...sessionId ? { sessionId } : {},
|
|
267
|
+
...cwd !== undefined ? { cwd } : {},
|
|
268
|
+
...this.settings.relay === undefined || sessionId === undefined ? {} : {
|
|
269
|
+
relay: {
|
|
270
|
+
cards: this.relayCards.load(relayLocation, sessionId),
|
|
271
|
+
save: card => this.relayCards.append(relayLocation, sessionId, card),
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
hooks: {
|
|
275
|
+
...harness.thinking === 'full' ? { reasoning: reasoningDelta } : {},
|
|
276
|
+
text: textDelta,
|
|
277
|
+
attempt: label => {
|
|
278
|
+
if (attempts++ > 0 && reasoningOpen) reasoningDelta(`\n\n[harness: ${label}]\n\n`)
|
|
279
|
+
},
|
|
280
|
+
trace: writeTrace,
|
|
281
|
+
...(sessionId !== undefined && options.purpose === undefined ? {
|
|
282
|
+
wireStart: info => liveWire.start(sessionId, { model: config.id, ...info }),
|
|
283
|
+
wireDelta: delta => liveWire.delta(sessionId, delta),
|
|
284
|
+
wireEnd: info => liveWire.finish(sessionId, info),
|
|
285
|
+
} : {}),
|
|
286
|
+
},
|
|
287
|
+
})
|
|
288
|
+
})().finally(() => {
|
|
289
|
+
settled = true
|
|
290
|
+
wake?.()
|
|
291
|
+
})
|
|
292
|
+
work.catch(() => {})
|
|
293
|
+
|
|
294
|
+
while (!settled || queue.length > 0) {
|
|
295
|
+
if (queue.length === 0) {
|
|
296
|
+
await new Promise<void>(resolve => {
|
|
297
|
+
wake = resolve
|
|
298
|
+
})
|
|
299
|
+
wake = undefined
|
|
300
|
+
continue
|
|
301
|
+
}
|
|
302
|
+
yield queue.shift()!
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
let step
|
|
306
|
+
try {
|
|
307
|
+
step = await work
|
|
308
|
+
} catch (error) {
|
|
309
|
+
if (reasoningOpen) yield { type: 'block-end', index: 0, block: { type: 'reasoning', text: reasoning } }
|
|
310
|
+
if (textOpen) yield { type: 'block-end', index: textIndex, block: { type: 'text', text: streamedText } }
|
|
311
|
+
if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {
|
|
312
|
+
yield { type: 'finish', reason: { kind: 'aborted', failure: { message: 'rwkv: request aborted', code: 'ABORTED' } } }
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
throw llmError(error)
|
|
316
|
+
}
|
|
317
|
+
setFoldedUnreadPaths(sessionId, step.foldedUnread ?? [])
|
|
318
|
+
if (sessionId !== undefined && step.foldEvent !== undefined && options.purpose === undefined) {
|
|
319
|
+
this.settings.onFoldEvent?.(sessionId, step.foldEvent)
|
|
320
|
+
}
|
|
321
|
+
if (reasoningOpen) {
|
|
322
|
+
yield { type: 'block-end', index: 0, block: { type: 'reasoning', text: reasoning } }
|
|
323
|
+
reasoningOpen = false
|
|
324
|
+
nextIndex = Math.max(nextIndex, 1)
|
|
325
|
+
}
|
|
326
|
+
const { decision } = step
|
|
327
|
+
const repairs = decision.type === 'tool' ? [...decision.repairs] : []
|
|
328
|
+
let handed: { args: Record<string, unknown>; changes: ArgumentChange[] } | undefined
|
|
329
|
+
if (decision.type === 'final') {
|
|
330
|
+
if (textOpen) {
|
|
331
|
+
if (decision.text.startsWith(streamedText)) {
|
|
332
|
+
const rest = decision.text.slice(streamedText.length)
|
|
333
|
+
if (rest !== '') {
|
|
334
|
+
streamedText += rest
|
|
335
|
+
yield { type: 'text-delta', index: textIndex, text: rest }
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
yield { type: 'block-end', index: textIndex, block: { type: 'text', text: streamedText || decision.text } }
|
|
339
|
+
} else {
|
|
340
|
+
const index = nextIndex++
|
|
341
|
+
yield { type: 'block-start', index, blockType: 'text' }
|
|
342
|
+
yield { type: 'text-delta', index, text: decision.text }
|
|
343
|
+
yield { type: 'block-end', index, block: { type: 'text', text: decision.text } }
|
|
344
|
+
}
|
|
345
|
+
} else {
|
|
346
|
+
if (textOpen) {
|
|
347
|
+
yield { type: 'block-end', index: textIndex, block: { type: 'text', text: streamedText } }
|
|
348
|
+
textOpen = false
|
|
349
|
+
}
|
|
350
|
+
const index = nextIndex++
|
|
351
|
+
const id = brandString<ToolCallId>(`call_${randomUUID().replace(/-/g, '').slice(0, 24)}`)
|
|
352
|
+
const dshArgs = decision.tool.toDsh(decision.args)
|
|
353
|
+
const pathed = harness.outputRepairs ? repairToolPaths(decision.tool.dshName, dshArgs, cwd) : dshArgs
|
|
354
|
+
if (pathed !== dshArgs) repairs.push('path_repaired')
|
|
355
|
+
const argumentsText = JSON.stringify(pathed)
|
|
356
|
+
handed = {
|
|
357
|
+
args: clipArguments(pathed),
|
|
358
|
+
changes: [...argumentChanges(decision.rawArgs, decision.args), ...argumentChanges(dshArgs, pathed)].map(change => ({
|
|
359
|
+
...change,
|
|
360
|
+
...'before' in change ? { before: clipArguments({ value: change.before }, 200).value } : {},
|
|
361
|
+
...'after' in change ? { after: clipArguments({ value: change.after }, 200).value } : {},
|
|
362
|
+
})),
|
|
363
|
+
}
|
|
364
|
+
yield { type: 'block-start', index, blockType: 'tool-call' }
|
|
365
|
+
yield { type: 'tool-call-delta', index, id, name: decision.tool.dshName, argumentsDelta: argumentsText }
|
|
366
|
+
yield { type: 'block-end', index, block: { type: 'tool-call', id, name: decision.tool.dshName, arguments: argumentsText } }
|
|
367
|
+
}
|
|
368
|
+
writeLine({
|
|
369
|
+
stage: 'step',
|
|
370
|
+
decision: decision.type === 'tool' ? `tool ${decision.tool.dshName}` : `final ${decision.via}`,
|
|
371
|
+
repairs,
|
|
372
|
+
...handed ? { args: handed.args, changes: handed.changes } : {},
|
|
373
|
+
generations: step.generations,
|
|
374
|
+
attempts,
|
|
375
|
+
outputRepairs: harness.outputRepairs,
|
|
376
|
+
guards: harness.guards,
|
|
377
|
+
})
|
|
378
|
+
yield {
|
|
379
|
+
type: 'usage',
|
|
380
|
+
usage: {
|
|
381
|
+
inputTokens: step.promptTokens,
|
|
382
|
+
outputTokens: step.completionTokens,
|
|
383
|
+
totalTokens: step.promptTokens + step.completionTokens,
|
|
384
|
+
},
|
|
385
|
+
}
|
|
386
|
+
yield { type: 'finish', reason: decision.type === 'tool' ? { kind: 'tool-calls' } : { kind: 'stop' } }
|
|
387
|
+
}
|
|
388
|
+
}
|