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,586 @@
|
|
|
1
|
+
// One DSH model request = one RWKV agent step. DSH owns the outer loop (it
|
|
2
|
+
// executes the tool and calls again), so this decides one action from the
|
|
3
|
+
// history, running the RWKV-Agent harness inside the request: protocol
|
|
4
|
+
// re-asks, duplicate and failure gates, the forced closeout, and the answer
|
|
5
|
+
// stage fallbacks (runner_turn.go, runner_tool_step.go, think_stop.go).
|
|
6
|
+
|
|
7
|
+
import type { GenerateRequest, GenerateResult, Generator, Sampling } from '../backend/generator.ts'
|
|
8
|
+
import { countTokens } from '../tokenizer.ts'
|
|
9
|
+
import {
|
|
10
|
+
AGENT_FAST_SAMPLING,
|
|
11
|
+
DEFAULT_ANSWER_MAX_TOKENS,
|
|
12
|
+
DEFAULT_DECISION_MAX_TOKENS,
|
|
13
|
+
DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
14
|
+
DEFAULT_MAX_STEPS,
|
|
15
|
+
DEFAULT_PROTOCOL_RETRIES,
|
|
16
|
+
DEFAULT_RELAY_CARD_MAX_TOKENS,
|
|
17
|
+
} from './defaults.ts'
|
|
18
|
+
import {
|
|
19
|
+
cleanFinalText,
|
|
20
|
+
endsWithCompleteCall,
|
|
21
|
+
parseAction,
|
|
22
|
+
thinkOpen,
|
|
23
|
+
type Action,
|
|
24
|
+
} from './parse.ts'
|
|
25
|
+
import {
|
|
26
|
+
analyzeTurn,
|
|
27
|
+
ANSWER_STAGE_REASK,
|
|
28
|
+
answerFallbackSummary,
|
|
29
|
+
answerOpener,
|
|
30
|
+
correction,
|
|
31
|
+
EMPTY_EXIT_REASK,
|
|
32
|
+
extractThinkInner,
|
|
33
|
+
hasPlanningMarker,
|
|
34
|
+
isChinese,
|
|
35
|
+
oneStageAnswerInstruction,
|
|
36
|
+
POST_TOOL_REMINDER,
|
|
37
|
+
POST_TOOL_REMINDER_THINK,
|
|
38
|
+
salvageAnswerProse,
|
|
39
|
+
salvageLastResortAnswer,
|
|
40
|
+
transcriptEntries,
|
|
41
|
+
type HistoryItem,
|
|
42
|
+
} from './policy.ts'
|
|
43
|
+
import { reconstructOutput, renderPrompt, systemPrompt, type Entry, type ThinkingMode } from './prompt.ts'
|
|
44
|
+
import {
|
|
45
|
+
cleanCardText,
|
|
46
|
+
fallbackCard,
|
|
47
|
+
makeCard,
|
|
48
|
+
planRelay,
|
|
49
|
+
recapEntries,
|
|
50
|
+
relayEntries,
|
|
51
|
+
type RelayCard,
|
|
52
|
+
type RelayNeed,
|
|
53
|
+
type RelayOptions,
|
|
54
|
+
} from './relay.ts'
|
|
55
|
+
import {
|
|
56
|
+
describeAction,
|
|
57
|
+
gateToolCall,
|
|
58
|
+
rawFinal,
|
|
59
|
+
ThinkSplitter,
|
|
60
|
+
type Decision,
|
|
61
|
+
type DuplicateGateMode,
|
|
62
|
+
type FinalVia,
|
|
63
|
+
} from './step-gates.ts'
|
|
64
|
+
import type { WireTool } from './tools.ts'
|
|
65
|
+
import { worklistEntries, type ContextFoldEvent, type WorklistOptions } from './worklist.ts'
|
|
66
|
+
|
|
67
|
+
export type { ContextFoldEvent, Decision, FinalVia }
|
|
68
|
+
|
|
69
|
+
export const DECISION_STOPS = ['</tool_call>', '\nUser:', '\nSystem:', '\nTool:'] as const
|
|
70
|
+
|
|
71
|
+
export interface HarnessConfig {
|
|
72
|
+
readonly thinking: ThinkingMode
|
|
73
|
+
readonly historyEmptyThink: boolean
|
|
74
|
+
/** Tool calls DSH may execute in one user turn before the forced closeout. */
|
|
75
|
+
readonly maxSteps: number
|
|
76
|
+
/** Consecutive failures of one tool before a further call of it is blocked. */
|
|
77
|
+
readonly maxConsecutiveFailures: number
|
|
78
|
+
/** Re-asks after unparseable output within one request. */
|
|
79
|
+
readonly protocolRetries: number
|
|
80
|
+
readonly decisionMaxTokens: number
|
|
81
|
+
readonly answerMaxTokens: number
|
|
82
|
+
readonly sampling: Sampling
|
|
83
|
+
readonly taskContract?: string
|
|
84
|
+
/** Appended as the system prompt's last line (currentDateLine); absent: no date. */
|
|
85
|
+
readonly dateLine?: string
|
|
86
|
+
/**
|
|
87
|
+
* Fixes applied to the model's output: parser near-miss repairs, tool name
|
|
88
|
+
* and argument aliases, scalar coercion, DSH value repairs, path repair.
|
|
89
|
+
*/
|
|
90
|
+
readonly outputRepairs: boolean
|
|
91
|
+
/**
|
|
92
|
+
* Harness interventions: format re-asks, the duplicate and failure gates,
|
|
93
|
+
* closing an over-budget think, answer-stage re-asks and the salvage /
|
|
94
|
+
* summary fallbacks.
|
|
95
|
+
*/
|
|
96
|
+
readonly guards: boolean
|
|
97
|
+
/** Duplicate gate mode when `guards` is true: 'epoch' (default), 'bounded', 'adjacent', or 'off'. */
|
|
98
|
+
readonly duplicateGateMode?: DuplicateGateMode
|
|
99
|
+
/** Attempt-2 answer prefill mode: 'default', 'zh-only' (avoids English opener collision), or 'none'. */
|
|
100
|
+
readonly answerOpenerMode?: 'default' | 'zh-only' | 'none'
|
|
101
|
+
/** Whether answer-stage failure replaces empty outputs with "I looked up..." summary (default true). */
|
|
102
|
+
readonly fallbackSummary?: boolean
|
|
103
|
+
/** Turn-relay context: finished legs are replaced by model-written handoff cards. */
|
|
104
|
+
readonly relay?: RelayOptions
|
|
105
|
+
/** Stateful work list or passive auto-fold context. */
|
|
106
|
+
readonly worklist?: WorklistOptions
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const DEFAULT_HARNESS: HarnessConfig = {
|
|
110
|
+
thinking: 'full',
|
|
111
|
+
historyEmptyThink: true,
|
|
112
|
+
maxSteps: DEFAULT_MAX_STEPS,
|
|
113
|
+
maxConsecutiveFailures: DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
114
|
+
protocolRetries: DEFAULT_PROTOCOL_RETRIES,
|
|
115
|
+
decisionMaxTokens: DEFAULT_DECISION_MAX_TOKENS,
|
|
116
|
+
answerMaxTokens: DEFAULT_ANSWER_MAX_TOKENS,
|
|
117
|
+
outputRepairs: true,
|
|
118
|
+
guards: true,
|
|
119
|
+
sampling: AGENT_FAST_SAMPLING,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface GenerationTrace {
|
|
123
|
+
readonly stage: 'decision' | 'answer' | 'card'
|
|
124
|
+
readonly prompt: string
|
|
125
|
+
readonly promptTokens?: number
|
|
126
|
+
readonly output: string
|
|
127
|
+
readonly finish: string
|
|
128
|
+
readonly stop?: string
|
|
129
|
+
readonly action: string
|
|
130
|
+
readonly outcome: string
|
|
131
|
+
readonly repairs: readonly string[]
|
|
132
|
+
readonly relay?: RelayTrace
|
|
133
|
+
readonly worklist?: WorklistTrace
|
|
134
|
+
readonly fold?: ContextFoldEvent
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface WorklistTrace {
|
|
138
|
+
readonly promptTokens: number
|
|
139
|
+
readonly budgetTokens: number
|
|
140
|
+
readonly checkpointAt?: number
|
|
141
|
+
readonly nudged: boolean
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface RelayTrace {
|
|
145
|
+
readonly from: number
|
|
146
|
+
readonly to: number
|
|
147
|
+
readonly turn: number
|
|
148
|
+
readonly fallback: boolean
|
|
149
|
+
readonly card: string
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface StepHooks {
|
|
153
|
+
reasoning?(delta: string): void
|
|
154
|
+
text?(delta: string): void
|
|
155
|
+
attempt?(label: string): void
|
|
156
|
+
trace?(trace: GenerationTrace): void
|
|
157
|
+
wireStart?(info: {
|
|
158
|
+
readonly stage: 'decision' | 'answer' | 'card'
|
|
159
|
+
readonly prompt: string
|
|
160
|
+
readonly fullPrompt?: string
|
|
161
|
+
readonly promptTokens: number
|
|
162
|
+
readonly pastThinks?: readonly string[]
|
|
163
|
+
readonly fold?: ContextFoldEvent
|
|
164
|
+
}): void
|
|
165
|
+
wireDelta?(delta: string): void
|
|
166
|
+
wireEnd?(info: { readonly output: string; readonly outputTokens: number }): void
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface StepInput {
|
|
170
|
+
readonly history: readonly HistoryItem[]
|
|
171
|
+
readonly tools: readonly WireTool[]
|
|
172
|
+
readonly config: HarnessConfig
|
|
173
|
+
readonly generator: Generator
|
|
174
|
+
readonly signal?: AbortSignal
|
|
175
|
+
readonly sessionId?: string
|
|
176
|
+
readonly cwd?: string
|
|
177
|
+
readonly hooks?: StepHooks
|
|
178
|
+
readonly systemHead?: string
|
|
179
|
+
readonly relay?: {
|
|
180
|
+
readonly cards: readonly RelayCard[]
|
|
181
|
+
readonly save?: (card: RelayCard) => void
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface StepResult {
|
|
186
|
+
readonly decision: Decision
|
|
187
|
+
readonly promptTokens: number
|
|
188
|
+
readonly completionTokens: number
|
|
189
|
+
readonly generations: number
|
|
190
|
+
readonly foldedUnread?: readonly string[]
|
|
191
|
+
readonly foldEvent?: ContextFoldEvent
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const MAX_THINK_STOP_RESUMES = 4
|
|
195
|
+
const THINK_CLOSE_TOKENS = 1024
|
|
196
|
+
const CARD_FINISH_TOKENS = 384
|
|
197
|
+
|
|
198
|
+
export async function decideStep(input: StepInput): Promise<StepResult> {
|
|
199
|
+
const { config, tools, hooks } = input
|
|
200
|
+
const reminder = config.thinking === 'full' ? POST_TOOL_REMINDER_THINK : POST_TOOL_REMINDER
|
|
201
|
+
const worklistGuidance = config.worklist?.passive === true ? false : config.worklist?.systemGuidance
|
|
202
|
+
const system = systemPrompt(
|
|
203
|
+
tools,
|
|
204
|
+
config.thinking,
|
|
205
|
+
config.taskContract,
|
|
206
|
+
input.systemHead,
|
|
207
|
+
config.dateLine,
|
|
208
|
+
worklistGuidance === undefined ? undefined : { worklistGuidance },
|
|
209
|
+
)
|
|
210
|
+
let promptTokens = 0
|
|
211
|
+
let completionTokens = 0
|
|
212
|
+
let generations = 0
|
|
213
|
+
|
|
214
|
+
let worklistTrace: WorklistTrace | undefined
|
|
215
|
+
let stepFoldEvent: ContextFoldEvent | undefined
|
|
216
|
+
let foldTraced = false
|
|
217
|
+
|
|
218
|
+
const generate = async (
|
|
219
|
+
entries: readonly Entry[],
|
|
220
|
+
stage: 'decision' | 'answer' | 'card',
|
|
221
|
+
label: string,
|
|
222
|
+
prefill?: string,
|
|
223
|
+
options?: { readonly rawAssistantPrefix?: string; readonly extraStops?: readonly string[] },
|
|
224
|
+
): Promise<{ output: string; result: GenerateResult; prompt: string; promptTokens: number }> => {
|
|
225
|
+
const rawPrefix = options?.rawAssistantPrefix
|
|
226
|
+
const prompt = renderPrompt(entries, {
|
|
227
|
+
thinking: config.thinking,
|
|
228
|
+
historyEmptyThink: config.historyEmptyThink,
|
|
229
|
+
...prefill === undefined ? {} : { prefill },
|
|
230
|
+
...rawPrefix === undefined ? {} : { rawAssistantPrefix: rawPrefix },
|
|
231
|
+
})
|
|
232
|
+
hooks?.attempt?.(label)
|
|
233
|
+
if (hooks?.wireStart !== undefined) {
|
|
234
|
+
const pastThinks = config.thinking === 'full' && config.historyEmptyThink
|
|
235
|
+
? entries.filter(entry => entry.role === 'assistant').map(entry => entry.reasoning ?? '')
|
|
236
|
+
: undefined
|
|
237
|
+
const fullEntries: Entry[] = [
|
|
238
|
+
{ role: 'system', text: system },
|
|
239
|
+
...transcriptEntries(input.history, { tools, postToolReminder: reminder }),
|
|
240
|
+
]
|
|
241
|
+
const fullPrompt = renderPrompt(fullEntries, {
|
|
242
|
+
thinking: config.thinking,
|
|
243
|
+
historyEmptyThink: false,
|
|
244
|
+
...prefill === undefined ? {} : { prefill },
|
|
245
|
+
...rawPrefix === undefined ? {} : { rawAssistantPrefix: rawPrefix },
|
|
246
|
+
})
|
|
247
|
+
hooks.wireStart({
|
|
248
|
+
stage,
|
|
249
|
+
prompt,
|
|
250
|
+
fullPrompt,
|
|
251
|
+
promptTokens: countTokens(prompt),
|
|
252
|
+
...(pastThinks !== undefined && pastThinks.some(t => t !== '') ? { pastThinks } : {}),
|
|
253
|
+
...(stage !== 'card' && stepFoldEvent !== undefined ? { fold: stepFoldEvent } : {}),
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
const hasOpenThink = config.thinking === 'full' && prefill === undefined && rawPrefix === undefined
|
|
257
|
+
const streamText = stage !== 'card' && prefill === undefined ? hooks?.text : undefined
|
|
258
|
+
const splitter = hasOpenThink && (hooks?.reasoning || streamText)
|
|
259
|
+
? new ThinkSplitter(hooks?.reasoning, streamText, false)
|
|
260
|
+
: !hasOpenThink && streamText
|
|
261
|
+
? new ThinkSplitter(undefined, streamText, true)
|
|
262
|
+
: undefined
|
|
263
|
+
const stops = options?.extraStops ? [...DECISION_STOPS, ...options.extraStops] : [...DECISION_STOPS]
|
|
264
|
+
const request: GenerateRequest = {
|
|
265
|
+
prompt,
|
|
266
|
+
maxTokens: stage === 'answer' ? config.answerMaxTokens
|
|
267
|
+
: stage === 'card' ? config.relay?.cardMaxTokens ?? DEFAULT_RELAY_CARD_MAX_TOKENS
|
|
268
|
+
: config.decisionMaxTokens,
|
|
269
|
+
stops,
|
|
270
|
+
sampling: config.sampling,
|
|
271
|
+
...input.signal ? { signal: input.signal } : {},
|
|
272
|
+
...input.sessionId ? { sessionId: input.sessionId } : {},
|
|
273
|
+
}
|
|
274
|
+
const onDelta = splitter || hooks?.wireDelta
|
|
275
|
+
? (text: string) => {
|
|
276
|
+
splitter?.feed(text)
|
|
277
|
+
hooks?.wireDelta?.(text)
|
|
278
|
+
}
|
|
279
|
+
: undefined
|
|
280
|
+
let result = await input.generator.generate(request, onDelta)
|
|
281
|
+
generations++
|
|
282
|
+
let text = result.text
|
|
283
|
+
let spent = result.completionTokens ?? countTokens(text)
|
|
284
|
+
const stepPromptTokens = result.promptTokens ?? countTokens(prompt)
|
|
285
|
+
promptTokens += stepPromptTokens
|
|
286
|
+
|
|
287
|
+
const opening = hasOpenThink ? '<think' : ''
|
|
288
|
+
for (let resume = 0; resume < MAX_THINK_STOP_RESUMES; resume++) {
|
|
289
|
+
if (result.finish !== 'stop' || result.stop !== '</tool_call>' || !thinkOpen(opening + text) || endsWithCompleteCall(text)) break
|
|
290
|
+
text += '</tool_call>'
|
|
291
|
+
onDelta?.('</tool_call>')
|
|
292
|
+
const remaining = request.maxTokens - spent
|
|
293
|
+
if (remaining <= 0) {
|
|
294
|
+
result = { ...result, finish: 'length' }
|
|
295
|
+
break
|
|
296
|
+
}
|
|
297
|
+
const next = await input.generator.generate({ ...request, prompt: prompt + text, maxTokens: remaining }, onDelta)
|
|
298
|
+
generations++
|
|
299
|
+
text += next.text
|
|
300
|
+
spent += next.completionTokens ?? countTokens(next.text)
|
|
301
|
+
result = { ...next, text }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (config.guards && result.finish === 'length' && opening !== '' && thinkOpen(opening + text)) {
|
|
305
|
+
const closed = `${text.trimEnd()}\n</think>\n`
|
|
306
|
+
onDelta?.('\n</think>\n')
|
|
307
|
+
const next = await input.generator.generate({ ...request, prompt: prompt + closed, maxTokens: THINK_CLOSE_TOKENS }, onDelta)
|
|
308
|
+
generations++
|
|
309
|
+
text = closed + next.text
|
|
310
|
+
spent += next.completionTokens ?? countTokens(next.text)
|
|
311
|
+
result = { ...next, text }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (stage === 'card' && config.guards && result.finish === 'length' && (!opening || !thinkOpen(opening + text))) {
|
|
315
|
+
const next = await input.generator.generate({ ...request, prompt: prompt + text, maxTokens: CARD_FINISH_TOKENS }, onDelta)
|
|
316
|
+
generations++
|
|
317
|
+
text += next.text
|
|
318
|
+
spent += next.completionTokens ?? countTokens(next.text)
|
|
319
|
+
result = { ...next, text }
|
|
320
|
+
}
|
|
321
|
+
completionTokens += spent
|
|
322
|
+
hooks?.wireEnd?.({ output: text, outputTokens: spent })
|
|
323
|
+
const output = rawPrefix !== undefined
|
|
324
|
+
? `${rawPrefix.trimStart()}${text}`
|
|
325
|
+
: hasOpenThink ? reconstructOutput(text, config.thinking) : text
|
|
326
|
+
return { output, result: { ...result, text }, prompt, promptTokens: stepPromptTokens }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const traced = (
|
|
330
|
+
stage: 'decision' | 'answer' | 'card', prompt: string, output: string, result: GenerateResult, action: Action,
|
|
331
|
+
outcome: string, gateRepairs: readonly string[] = [], relay?: RelayTrace, stepPromptTokens?: number,
|
|
332
|
+
) => {
|
|
333
|
+
const parsed = action.type === 'tool' || action.type === 'exit' ? action.repairs : []
|
|
334
|
+
const attachFold = !foldTraced && stage !== 'card' && stepFoldEvent !== undefined ? stepFoldEvent : undefined
|
|
335
|
+
if (attachFold !== undefined) foldTraced = true
|
|
336
|
+
hooks?.trace?.({
|
|
337
|
+
stage, prompt, output, finish: result.finish, action: describeAction(action), outcome,
|
|
338
|
+
repairs: [...parsed, ...gateRepairs],
|
|
339
|
+
...stepPromptTokens === undefined ? {} : { promptTokens: stepPromptTokens },
|
|
340
|
+
...result.stop === undefined ? {} : { stop: result.stop },
|
|
341
|
+
...relay === undefined ? {} : { relay },
|
|
342
|
+
...stage === 'decision' && worklistTrace !== undefined ? { worklist: worklistTrace } : {},
|
|
343
|
+
...attachFold === undefined ? {} : { fold: attachFold },
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
const parseOptions = { strict: !config.outputRepairs }
|
|
347
|
+
|
|
348
|
+
let foldedUnread: readonly string[] | undefined
|
|
349
|
+
const done = (decision: Decision): StepResult => ({
|
|
350
|
+
decision,
|
|
351
|
+
promptTokens,
|
|
352
|
+
completionTokens,
|
|
353
|
+
generations,
|
|
354
|
+
...(foldedUnread !== undefined ? { foldedUnread } : {}),
|
|
355
|
+
...(stepFoldEvent !== undefined ? { foldEvent: stepFoldEvent } : {}),
|
|
356
|
+
})
|
|
357
|
+
|
|
358
|
+
const writeCard = async (need: RelayNeed, cards: readonly RelayCard[]): Promise<RelayCard> => {
|
|
359
|
+
let text = ''
|
|
360
|
+
let pending: { output: string; result: GenerateResult; prompt: string; promptTokens: number } | undefined
|
|
361
|
+
try {
|
|
362
|
+
const entries: Entry[] = [
|
|
363
|
+
{ role: 'system', text: system },
|
|
364
|
+
...recapEntries(input.history, cards, need, { tools, postToolReminder: '' }),
|
|
365
|
+
]
|
|
366
|
+
const { output, result, prompt, promptTokens: cardPromptTokens } = await generate(entries, 'card', 'handoff recap')
|
|
367
|
+
text = cleanCardText(output)
|
|
368
|
+
pending = { output, result, prompt, promptTokens: cardPromptTokens }
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (error instanceof Error && error.name === 'AbortError') throw error
|
|
371
|
+
}
|
|
372
|
+
const budget = Math.min(500, config.relay?.cardMaxTokens ?? DEFAULT_RELAY_CARD_MAX_TOKENS)
|
|
373
|
+
const card = makeCard(input.history, need, text !== '' ? text : fallbackCard(input.history, need, budget))
|
|
374
|
+
const relay: RelayTrace = { from: need.start, to: need.end, turn: need.turn, fallback: text === '', card: card.text }
|
|
375
|
+
if (pending !== undefined) {
|
|
376
|
+
traced('card', pending.prompt, pending.output, pending.result, { type: 'final', text }, text === '' ? 'card-empty' : 'card', [], relay, pending.promptTokens)
|
|
377
|
+
} else if (hooks?.trace !== undefined) {
|
|
378
|
+
hooks.trace({
|
|
379
|
+
stage: 'card', prompt: '', output: '', finish: 'error', action: 'card', outcome: 'card-failed', repairs: [], relay,
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
input.relay?.save?.(card)
|
|
383
|
+
return card
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
let state = analyzeTurn(input.history)
|
|
387
|
+
let base: Entry[]
|
|
388
|
+
let liveWorklistNudge: string | undefined
|
|
389
|
+
if (config.worklist !== undefined) {
|
|
390
|
+
const { entries, fold } = worklistEntries(input.history, {
|
|
391
|
+
tools,
|
|
392
|
+
postToolReminder: reminder,
|
|
393
|
+
systemTokens: countTokens(system),
|
|
394
|
+
historyEmptyThink: config.historyEmptyThink,
|
|
395
|
+
...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
|
|
396
|
+
...config.worklist,
|
|
397
|
+
})
|
|
398
|
+
foldedUnread = fold.foldedUnread
|
|
399
|
+
stepFoldEvent = fold.foldEvent
|
|
400
|
+
liveWorklistNudge = fold.nudge
|
|
401
|
+
worklistTrace = {
|
|
402
|
+
promptTokens: fold.promptTokens,
|
|
403
|
+
budgetTokens: config.worklist.budgetTokens,
|
|
404
|
+
...(fold.checkpointAt === undefined ? {} : { checkpointAt: fold.checkpointAt }),
|
|
405
|
+
nudged: fold.nudge !== undefined,
|
|
406
|
+
}
|
|
407
|
+
state = analyzeTurn(input.history, {
|
|
408
|
+
duplicateFrom: fold.duplicateFrom,
|
|
409
|
+
...(fold.maskedCallIds !== undefined ? { maskedCallIds: fold.maskedCallIds } : {}),
|
|
410
|
+
})
|
|
411
|
+
base = [{ role: 'system', text: system }, ...entries]
|
|
412
|
+
} else if (config.relay === undefined) {
|
|
413
|
+
base = [
|
|
414
|
+
{ role: 'system', text: system },
|
|
415
|
+
...transcriptEntries(input.history, { tools, postToolReminder: reminder }),
|
|
416
|
+
]
|
|
417
|
+
} else {
|
|
418
|
+
const plan = planRelay(input.history, input.relay?.cards ?? [], config.relay)
|
|
419
|
+
let cards = plan.cards
|
|
420
|
+
if (plan.need !== undefined) cards = [...cards, await writeCard(plan.need, cards)]
|
|
421
|
+
const legStart = cards.length > 0 ? cards[cards.length - 1]!.at : 0
|
|
422
|
+
state = analyzeTurn(input.history, { duplicateFrom: legStart })
|
|
423
|
+
base = [
|
|
424
|
+
{ role: 'system', text: system },
|
|
425
|
+
...relayEntries(input.history, cards, { tools, postToolReminder: reminder }),
|
|
426
|
+
]
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const answerStage = async (entries: readonly Entry[], prelude: readonly string[], allowTools = false): Promise<StepResult> => {
|
|
430
|
+
const trimmedEntries = liveWorklistNudge !== undefined
|
|
431
|
+
&& entries.length > 0
|
|
432
|
+
&& entries[entries.length - 1]!.role === 'user'
|
|
433
|
+
&& entries[entries.length - 1]!.text === liveWorklistNudge
|
|
434
|
+
? entries.slice(0, -1)
|
|
435
|
+
: entries
|
|
436
|
+
const staged: Entry[] = [
|
|
437
|
+
...trimmedEntries.filter(entry => !(entry.role === 'user' && entry.text === reminder)),
|
|
438
|
+
...prelude.map(text => ({ role: 'user' as const, text })),
|
|
439
|
+
{ role: 'user', text: oneStageAnswerInstruction() },
|
|
440
|
+
]
|
|
441
|
+
let lastOutput = ''
|
|
442
|
+
let opener: string | undefined
|
|
443
|
+
let priorThink = ''
|
|
444
|
+
const outputs: string[] = []
|
|
445
|
+
const openerMode = config.answerOpenerMode ?? 'default'
|
|
446
|
+
for (let attempt = 0; attempt < (config.guards ? 3 : 1); attempt++) {
|
|
447
|
+
let rawAssistantPrefix: string | undefined
|
|
448
|
+
let extraStops: readonly string[] | undefined
|
|
449
|
+
if (attempt === 2) {
|
|
450
|
+
if (openerMode === 'default') {
|
|
451
|
+
opener = answerOpener(state.task)
|
|
452
|
+
} else if (openerMode === 'zh-only' && isChinese(state.task) && state.successfulCalls > 0) {
|
|
453
|
+
opener = '根据上面的工具结果,'
|
|
454
|
+
} else if (openerMode !== 'zh-only' || !isChinese(state.task)) {
|
|
455
|
+
extraStops = ['<tool_call>', '<tool_call']
|
|
456
|
+
rawAssistantPrefix = config.thinking === 'full' ? ` <think>${priorThink}</think>\n` : undefined
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const genOpts = rawAssistantPrefix !== undefined || extraStops !== undefined
|
|
460
|
+
? {
|
|
461
|
+
...rawAssistantPrefix === undefined ? {} : { rawAssistantPrefix },
|
|
462
|
+
...extraStops === undefined ? {} : { extraStops },
|
|
463
|
+
}
|
|
464
|
+
: undefined
|
|
465
|
+
let { output, result, prompt, promptTokens: answerPromptTokens } = await generate(staged, 'answer', attempt === 0 ? 'answer' : 'answer re-ask', opener, genOpts)
|
|
466
|
+
const closedThink = extractThinkInner(output)
|
|
467
|
+
if (closedThink !== '') priorThink = closedThink
|
|
468
|
+
lastOutput = opener ? `${opener}${output}` : output
|
|
469
|
+
outputs.push(lastOutput)
|
|
470
|
+
let action = parseAction(lastOutput, result.finish, parseOptions)
|
|
471
|
+
const truncatedPlanningAtToolStop = action.type === 'final' && hasPlanningMarker(cleanFinalText(action.text))
|
|
472
|
+
if (
|
|
473
|
+
attempt === 2
|
|
474
|
+
&& openerMode === 'zh-only'
|
|
475
|
+
&& !isChinese(state.task)
|
|
476
|
+
&& ((action.type === 'error' && action.kind === 'empty') || truncatedPlanningAtToolStop)
|
|
477
|
+
&& (result.stop === '<tool_call>' || result.stop === '<tool_call')
|
|
478
|
+
) {
|
|
479
|
+
const retryPrefix = config.thinking === 'full' ? ` <think>${priorThink}</think>Summary:\n` : 'Summary:\n'
|
|
480
|
+
const retry = await generate(staged, 'answer', 'answer re-ask', undefined, {
|
|
481
|
+
rawAssistantPrefix: retryPrefix,
|
|
482
|
+
extraStops: ['<tool_call>', '<tool_call'],
|
|
483
|
+
})
|
|
484
|
+
output = retry.output
|
|
485
|
+
result = retry.result
|
|
486
|
+
prompt = retry.prompt
|
|
487
|
+
answerPromptTokens = retry.promptTokens
|
|
488
|
+
lastOutput = output
|
|
489
|
+
outputs.push(lastOutput)
|
|
490
|
+
action = parseAction(lastOutput, result.finish, parseOptions)
|
|
491
|
+
}
|
|
492
|
+
if (allowTools && action.type === 'tool' && state.steps < config.maxSteps) {
|
|
493
|
+
const gated = gateToolCall(action, state, tools, config, true)
|
|
494
|
+
if (gated.type === 'run') {
|
|
495
|
+
traced('answer', prompt, output, result, action, 'run', gated.repairs, undefined, answerPromptTokens)
|
|
496
|
+
return done({ type: 'tool', tool: gated.tool, args: gated.args, rawArgs: action.args, repairs: [...action.repairs, ...gated.repairs, 'answer_stage_tool'] })
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (action.type === 'final' && !action.text.toLowerCase().includes('<tool_call')) {
|
|
500
|
+
const text = cleanFinalText(action.text)
|
|
501
|
+
if (text !== '') {
|
|
502
|
+
traced('answer', prompt, output, result, action, 'final', [], undefined, answerPromptTokens)
|
|
503
|
+
return done({ type: 'final', text, via: 'answer-stage' })
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (action.type === 'exit' && action.answer !== '') {
|
|
507
|
+
traced('answer', prompt, output, result, action, 'final', [], undefined, answerPromptTokens)
|
|
508
|
+
return done({ type: 'final', text: action.answer, via: 'answer-stage' })
|
|
509
|
+
}
|
|
510
|
+
traced('answer', prompt, output, result, action, config.guards ? 're-ask' : 'raw', [], undefined, answerPromptTokens)
|
|
511
|
+
if (attempt === 0) staged.push({ role: 'user', text: ANSWER_STAGE_REASK })
|
|
512
|
+
}
|
|
513
|
+
if (!config.guards) return done(rawFinal(lastOutput))
|
|
514
|
+
const salvaged = config.fallbackSummary === false
|
|
515
|
+
? salvageLastResortAnswer(outputs, opener)
|
|
516
|
+
: salvageAnswerProse(lastOutput, opener)
|
|
517
|
+
if (salvaged !== '') return done({ type: 'final', text: cleanFinalText(salvaged), via: 'salvage' })
|
|
518
|
+
return done({ type: 'final', text: answerFallbackSummary(state.task, state.results), via: 'summary' })
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
if (state.steps >= config.maxSteps) return answerStage(base, [])
|
|
522
|
+
|
|
523
|
+
const extra: Entry[] = []
|
|
524
|
+
const decisionOutputs: string[] = []
|
|
525
|
+
let protocolRetries = 0
|
|
526
|
+
let duplicateRetryUsed = false
|
|
527
|
+
let blockedRetries = 0
|
|
528
|
+
for (let attempt = 0; attempt < config.protocolRetries + 4; attempt++) {
|
|
529
|
+
const label = attempt === 0 ? 'decide' : 're-ask'
|
|
530
|
+
const { output, result, prompt, promptTokens: decisionPromptTokens } = await generate([...base, ...extra], 'decision', label)
|
|
531
|
+
decisionOutputs.push(output)
|
|
532
|
+
if (result.finish === 'cancelled') throw new DOMException('aborted', 'AbortError')
|
|
533
|
+
const action = parseAction(output, result.finish, parseOptions)
|
|
534
|
+
const note = (outcome: string, gateRepairs?: readonly string[]) => traced('decision', prompt, output, result, action, outcome, gateRepairs, undefined, decisionPromptTokens)
|
|
535
|
+
switch (action.type) {
|
|
536
|
+
case 'final': {
|
|
537
|
+
const text = cleanFinalText(action.text)
|
|
538
|
+
if (text !== '') {
|
|
539
|
+
note('final')
|
|
540
|
+
return done({ type: 'final', text, via: 'model' })
|
|
541
|
+
}
|
|
542
|
+
break
|
|
543
|
+
}
|
|
544
|
+
case 'exit':
|
|
545
|
+
if (action.answer !== '') {
|
|
546
|
+
note('final')
|
|
547
|
+
return done({ type: 'final', text: action.answer, via: 'exit' })
|
|
548
|
+
}
|
|
549
|
+
note(config.guards ? 'empty-exit' : 'raw')
|
|
550
|
+
if (!config.guards) return done(rawFinal(output))
|
|
551
|
+
return answerStage([...base, ...extra], [EMPTY_EXIT_REASK], true)
|
|
552
|
+
case 'tool': {
|
|
553
|
+
const gated = gateToolCall(action, state, tools, config, duplicateRetryUsed)
|
|
554
|
+
if (gated.type === 'run') {
|
|
555
|
+
note('run', gated.repairs)
|
|
556
|
+
return done({ type: 'tool', tool: gated.tool, args: gated.args, rawArgs: action.args, repairs: [...action.repairs, ...gated.repairs] })
|
|
557
|
+
}
|
|
558
|
+
note(gated.type === 'rejected' ? `rejected ${gated.reason}` : gated.type)
|
|
559
|
+
if (gated.type === 'closeout') return answerStage([...base, ...extra], [gated.reminder])
|
|
560
|
+
if (gated.type === 'duplicate-retry') duplicateRetryUsed = true
|
|
561
|
+
extra.push(...gated.receipt)
|
|
562
|
+
if (++blockedRetries > 3) return config.guards ? answerStage([...base, ...extra], []) : done(rawFinal(output))
|
|
563
|
+
continue
|
|
564
|
+
}
|
|
565
|
+
case 'error':
|
|
566
|
+
break
|
|
567
|
+
}
|
|
568
|
+
note(config.guards ? 're-ask' : 'raw')
|
|
569
|
+
if (!config.guards) return done(rawFinal(output))
|
|
570
|
+
if (++protocolRetries > config.protocolRetries) {
|
|
571
|
+
if (state.steps > 0) return answerStage([...base, ...extra], [], true)
|
|
572
|
+
if (config.fallbackSummary === false) {
|
|
573
|
+
const salvaged = salvageLastResortAnswer(decisionOutputs)
|
|
574
|
+
if (salvaged !== '') return done({ type: 'final', text: cleanFinalText(salvaged), via: 'salvage' })
|
|
575
|
+
}
|
|
576
|
+
return done({
|
|
577
|
+
type: 'final',
|
|
578
|
+
text: answerFallbackSummary(state.task, state.results),
|
|
579
|
+
via: 'summary',
|
|
580
|
+
})
|
|
581
|
+
}
|
|
582
|
+
const kind = action.type === 'error' ? action.kind : 'empty'
|
|
583
|
+
extra.push({ role: 'user', text: correction(kind) })
|
|
584
|
+
}
|
|
585
|
+
return answerStage([...base, ...extra], [], true)
|
|
586
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Shared scalar and sampling defaults across the host plugin, headless CLI,
|
|
2
|
+
// pipeline teacher overlay, and browser settings UI. Kept free of Node and
|
|
3
|
+
// WASM imports so browser bundles can import directly without side effects.
|
|
4
|
+
|
|
5
|
+
export interface SamplingDefaults {
|
|
6
|
+
readonly temperature: number
|
|
7
|
+
readonly topK: number
|
|
8
|
+
readonly topP: number
|
|
9
|
+
readonly presencePenalty: number
|
|
10
|
+
readonly frequencyPenalty: number
|
|
11
|
+
readonly penaltyDecay: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const AGENT_FAST_SAMPLING: SamplingDefaults = {
|
|
15
|
+
temperature: 0.35,
|
|
16
|
+
topK: 65536,
|
|
17
|
+
topP: 0.85,
|
|
18
|
+
presencePenalty: 0.5,
|
|
19
|
+
frequencyPenalty: 0.2,
|
|
20
|
+
penaltyDecay: 0.996,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type EditMode = 'tolerant' | 'line-edit' | 'literal'
|
|
24
|
+
export type HistoryMode = 'auto-fold' | 'full' | 'relay' | 'worklist'
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_EDIT_MODE: EditMode = 'tolerant'
|
|
27
|
+
export const DEFAULT_HISTORY_MODE: HistoryMode = 'auto-fold'
|
|
28
|
+
|
|
29
|
+
export const DEFAULT_MAX_STEPS = 30
|
|
30
|
+
export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 2
|
|
31
|
+
export const DEFAULT_PROTOCOL_RETRIES = 2
|
|
32
|
+
export const DEFAULT_DECISION_MAX_TOKENS = 8192
|
|
33
|
+
export const DEFAULT_ANSWER_MAX_TOKENS = 8192
|
|
34
|
+
|
|
35
|
+
export const DEFAULT_RELAY_BUDGET_TOKENS = 8000
|
|
36
|
+
export const DEFAULT_RELAY_CARD_MAX_TOKENS = 768
|
|
37
|
+
|
|
38
|
+
export const DEFAULT_WORKLIST_MIN_FOLD_TOKENS = 8000
|
|
39
|
+
export const DEFAULT_ACTIVE_WORKLIST_BUDGET_TOKENS = 12000
|
|
40
|
+
export const DEFAULT_WORKLIST_BUDGET_TOKENS = 13500
|
|
41
|
+
export const DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS = 9000
|
|
42
|
+
export const DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS = 250
|
|
43
|
+
export const DEFAULT_WORKLIST_HARD_SLACK_TOKENS = 3000
|
|
44
|
+
export const DEFAULT_AUTOFOLD_HARD_SLACK_TOKENS = 1000
|
|
45
|
+
export const DEFAULT_AUTOFOLD_HARD_CAP_TOKENS = 14500
|
|
46
|
+
export const DEFAULT_BACKBONE_MAX_TOKENS = 5000
|
|
47
|
+
export const DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS = 2000
|
|
48
|
+
export const DEFAULT_KEEP_RECENT_PAIRS = 2
|
|
49
|
+
export const DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS = 3
|
|
50
|
+
|
|
51
|
+
export const FOLDED_OUTPUT_MARKER = '[Old '
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// DSH's assembled system prompt as the head of the RWKV system block
|
|
2
|
+
// (names: 'dsh'). DSH joins its sections with blank lines; the Standard
|
|
3
|
+
// prompt carries ten that describe tools and surfaces the RWKV preset does not
|
|
4
|
+
// mount, and two of them (checkout path, Web GUI) are registered globally, so
|
|
5
|
+
// they reach every preset. Those are dropped by their opening words; the rest
|
|
6
|
+
// (persona, @paths, bash exit code, read/write/edit/glob/grep, web) is kept
|
|
7
|
+
// verbatim.
|
|
8
|
+
|
|
9
|
+
/** Opening words of the Standard sections the RWKV preset does not use. */
|
|
10
|
+
export const DROPPED_SECTION_OPENERS: readonly string[] = [
|
|
11
|
+
'Prefer apply_patch over separate edit calls', // apply_patch
|
|
12
|
+
'Track every background job id you start.', // background jobs
|
|
13
|
+
'create_goal may infer goal intent', // goal
|
|
14
|
+
'Only create or modify scheduled tasks', // schedule
|
|
15
|
+
'Use the workflow tool ONLY', // workflow
|
|
16
|
+
// subagent; any delegation tool name (`subagent`, the bundle's `rwkv_agent`, ...)
|
|
17
|
+
'Start independent delegations with `',
|
|
18
|
+
'Agents may use different working directories;', // subagent: shared files
|
|
19
|
+
'Prefer showing the primary results within your final response', // present
|
|
20
|
+
'The runtime context names the DeepSeek Harness implementation checkout.', // DSH checkout path
|
|
21
|
+
'You are interacting with the user through the DeepSeek Harness Web GUI', // Web GUI
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
/** The DSH system prompt without the dropped sections; '' when nothing is left. */
|
|
25
|
+
export function dshSystemSections(system: string): string {
|
|
26
|
+
return system
|
|
27
|
+
.replace(/\r\n/g, '\n')
|
|
28
|
+
.split(/\n{2,}/)
|
|
29
|
+
.map(section => section.trim())
|
|
30
|
+
.filter(section => section !== '' && !DROPPED_SECTION_OPENERS.some(opener => section.startsWith(opener)))
|
|
31
|
+
.join('\n\n')
|
|
32
|
+
}
|