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,371 @@
|
|
|
1
|
+
// Streaming think splitter, tool-call gate, and argument repair pipeline
|
|
2
|
+
// invoked by `decideStep` (`agent.ts`).
|
|
3
|
+
|
|
4
|
+
import { isNoopEditCall } from './edit-modes/index.ts'
|
|
5
|
+
import { cleanFinalText, type Action } from './parse.ts'
|
|
6
|
+
import {
|
|
7
|
+
callKey,
|
|
8
|
+
DUPLICATE_ANSWER_REMINDER,
|
|
9
|
+
DUPLICATE_FAILED_REMINDER,
|
|
10
|
+
DUPLICATE_FAILED_RETRY_REMINDER,
|
|
11
|
+
duplicateRetryReminder,
|
|
12
|
+
NOOP_EDIT_REMINDER,
|
|
13
|
+
sameTargetFile,
|
|
14
|
+
targetFileSuffix,
|
|
15
|
+
toolFailureReminder,
|
|
16
|
+
type TurnState,
|
|
17
|
+
} from './policy.ts'
|
|
18
|
+
import { recordToolCall, toolResponse, type Entry } from './prompt.ts'
|
|
19
|
+
import { isWorklistTool } from './todo-state.ts'
|
|
20
|
+
import {
|
|
21
|
+
coerceArguments,
|
|
22
|
+
normalizeArguments,
|
|
23
|
+
repairNativeValues,
|
|
24
|
+
resolveTool,
|
|
25
|
+
type Args,
|
|
26
|
+
type WireTool,
|
|
27
|
+
} from './tools.ts'
|
|
28
|
+
|
|
29
|
+
/** raw: guards off, output that did not parse is passed on as the answer text. */
|
|
30
|
+
export type FinalVia = 'model' | 'exit' | 'answer-stage' | 'salvage' | 'summary' | 'raw'
|
|
31
|
+
|
|
32
|
+
export type Decision =
|
|
33
|
+
| {
|
|
34
|
+
readonly type: 'tool'
|
|
35
|
+
readonly tool: WireTool
|
|
36
|
+
readonly args: Args
|
|
37
|
+
/** The arguments as the model wrote them, before any repair. */
|
|
38
|
+
readonly rawArgs: Args
|
|
39
|
+
readonly repairs: readonly string[]
|
|
40
|
+
}
|
|
41
|
+
| { readonly type: 'final'; readonly text: string; readonly via: FinalVia }
|
|
42
|
+
|
|
43
|
+
/** Pass-through answer for output the harness does not fix (guards off). */
|
|
44
|
+
export function rawFinal(output: string): Decision {
|
|
45
|
+
return { type: 'final', text: cleanFinalText(output) || output.trim(), via: 'raw' }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function describeAction(action: Action): string {
|
|
49
|
+
switch (action.type) {
|
|
50
|
+
case 'tool':
|
|
51
|
+
return `tool ${action.name}${action.repairs.length > 0 ? ` (${action.repairs.join(',')})` : ''}`
|
|
52
|
+
case 'exit':
|
|
53
|
+
return 'no_tool'
|
|
54
|
+
case 'final':
|
|
55
|
+
return 'final'
|
|
56
|
+
case 'error':
|
|
57
|
+
return `error ${action.kind}`
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const TEXT_STOP_MARKERS = [
|
|
62
|
+
'<tool_call',
|
|
63
|
+
'</tool_call',
|
|
64
|
+
'<tool_response',
|
|
65
|
+
'<tool_result',
|
|
66
|
+
'<answer',
|
|
67
|
+
'<think',
|
|
68
|
+
'</think',
|
|
69
|
+
'\nUser:',
|
|
70
|
+
'\nSystem:',
|
|
71
|
+
'\nTool:',
|
|
72
|
+
'\nAssistant:',
|
|
73
|
+
'✿',
|
|
74
|
+
] as const
|
|
75
|
+
|
|
76
|
+
const MAX_TEXT_STOP_HOLD = Math.max(...TEXT_STOP_MARKERS.map(m => m.length - 1))
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Streams the reasoning of a withheld "<think" generation (dropping the
|
|
80
|
+
* closing ">", stopping reasoning at </think>) and optionally streams the
|
|
81
|
+
* subsequent prose text while stopping cleanly before any protocol tag
|
|
82
|
+
* (<tool_call>, \nUser:, etc.) so tool calls never leak raw XML.
|
|
83
|
+
*/
|
|
84
|
+
export class ThinkSplitter {
|
|
85
|
+
private buffer = ''
|
|
86
|
+
private started = false
|
|
87
|
+
private thinkDone = false
|
|
88
|
+
private textBuffer = ''
|
|
89
|
+
private textStarted = false
|
|
90
|
+
private textStopped = false
|
|
91
|
+
private readonly emitReasoning: ((text: string) => void) | undefined
|
|
92
|
+
private readonly emitText: ((text: string) => void) | undefined
|
|
93
|
+
|
|
94
|
+
constructor(emitReasoning?: (text: string) => void, emitText?: (text: string) => void, startInText = false) {
|
|
95
|
+
this.emitReasoning = emitReasoning
|
|
96
|
+
this.emitText = emitText
|
|
97
|
+
this.thinkDone = startInText
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
feed(delta: string): void {
|
|
101
|
+
if (!this.thinkDone) {
|
|
102
|
+
this.buffer += delta
|
|
103
|
+
if (!this.started) {
|
|
104
|
+
if (this.buffer === '') return
|
|
105
|
+
if (this.buffer.startsWith('>')) this.buffer = this.buffer.slice(1)
|
|
106
|
+
this.started = true
|
|
107
|
+
}
|
|
108
|
+
const end = this.buffer.indexOf('</think>')
|
|
109
|
+
if (end >= 0) {
|
|
110
|
+
if (end > 0) this.emitReasoning?.(this.buffer.slice(0, end))
|
|
111
|
+
const tail = this.buffer.slice(end + '</think>'.length)
|
|
112
|
+
this.buffer = ''
|
|
113
|
+
this.thinkDone = true
|
|
114
|
+
if (tail !== '') this.feedText(tail)
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
let hold = 0
|
|
118
|
+
for (let length = Math.min(7, this.buffer.length); length > 0; length--) {
|
|
119
|
+
if ('</think>'.startsWith(this.buffer.slice(-length))) {
|
|
120
|
+
hold = length
|
|
121
|
+
break
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const ready = this.buffer.slice(0, this.buffer.length - hold)
|
|
125
|
+
if (ready !== '') this.emitReasoning?.(ready)
|
|
126
|
+
this.buffer = this.buffer.slice(this.buffer.length - hold)
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
this.feedText(delta)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private feedText(delta: string): void {
|
|
133
|
+
if (!this.emitText || this.textStopped || delta === '') return
|
|
134
|
+
this.textBuffer += delta
|
|
135
|
+
if (!this.textStarted) {
|
|
136
|
+
const trimmed = this.textBuffer.trimStart()
|
|
137
|
+
if (trimmed === '') {
|
|
138
|
+
this.textBuffer = ''
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
this.textBuffer = trimmed
|
|
142
|
+
}
|
|
143
|
+
let stopAt = -1
|
|
144
|
+
for (const marker of TEXT_STOP_MARKERS) {
|
|
145
|
+
const idx = this.textBuffer.indexOf(marker)
|
|
146
|
+
if (idx >= 0 && (stopAt < 0 || idx < stopAt)) stopAt = idx
|
|
147
|
+
}
|
|
148
|
+
if (stopAt >= 0) {
|
|
149
|
+
const before = this.textBuffer.slice(0, stopAt).trimEnd()
|
|
150
|
+
if (before !== '') {
|
|
151
|
+
this.textStarted = true
|
|
152
|
+
this.emitText(before)
|
|
153
|
+
}
|
|
154
|
+
this.textBuffer = ''
|
|
155
|
+
this.textStopped = true
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
let hold = 0
|
|
159
|
+
for (let length = Math.min(MAX_TEXT_STOP_HOLD, this.textBuffer.length); length > 0; length--) {
|
|
160
|
+
const tail = this.textBuffer.slice(-length)
|
|
161
|
+
if (TEXT_STOP_MARKERS.some(marker => marker.startsWith(tail))) {
|
|
162
|
+
hold = length
|
|
163
|
+
break
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const ready = this.textBuffer.slice(0, this.textBuffer.length - hold)
|
|
167
|
+
if (ready !== '') {
|
|
168
|
+
this.textStarted = true
|
|
169
|
+
this.emitText(ready)
|
|
170
|
+
}
|
|
171
|
+
this.textBuffer = this.textBuffer.slice(this.textBuffer.length - hold)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export type DuplicateGateMode = 'epoch' | 'bounded' | 'adjacent' | 'off'
|
|
176
|
+
|
|
177
|
+
export interface GateOptions {
|
|
178
|
+
readonly outputRepairs: boolean
|
|
179
|
+
readonly guards: boolean
|
|
180
|
+
readonly maxConsecutiveFailures: number
|
|
181
|
+
readonly duplicateGateMode?: DuplicateGateMode
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export type Gate =
|
|
185
|
+
| { readonly type: 'run'; readonly tool: WireTool; readonly args: Args; readonly repairs: readonly string[] }
|
|
186
|
+
| { readonly type: 'closeout'; readonly reminder: string }
|
|
187
|
+
| { readonly type: 'duplicate-retry'; readonly receipt: Entry[] }
|
|
188
|
+
| { readonly type: 'rejected'; readonly reason: 'unknown-tool' | 'blocked'; readonly receipt: Entry[] }
|
|
189
|
+
|
|
190
|
+
export function gateToolCall(
|
|
191
|
+
action: Extract<Action, { type: 'tool' }>,
|
|
192
|
+
state: TurnState,
|
|
193
|
+
tools: readonly WireTool[],
|
|
194
|
+
config: GateOptions,
|
|
195
|
+
duplicateRetryUsed: boolean,
|
|
196
|
+
): Gate {
|
|
197
|
+
const exact = tools.find(tool => tool.name === action.name)
|
|
198
|
+
const resolved = config.outputRepairs ? resolveTool(tools, action.name) : exact && { tool: exact, aliased: false }
|
|
199
|
+
if (resolved === undefined) {
|
|
200
|
+
const error = `unknown tool "${action.name}"`
|
|
201
|
+
return {
|
|
202
|
+
type: 'rejected',
|
|
203
|
+
reason: 'unknown-tool',
|
|
204
|
+
receipt: [
|
|
205
|
+
{ role: 'assistant', text: recordToolCall(action.name, action.args) },
|
|
206
|
+
{ role: 'user', text: toolResponse(action.name, false, error) },
|
|
207
|
+
{ role: 'user', text: toolFailureReminder(action.name, error, false, tools) },
|
|
208
|
+
],
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const { tool } = resolved
|
|
212
|
+
const { args, repairs } = config.outputRepairs ? repairArguments(tool, action.args, resolved.aliased) : { args: action.args, repairs: [] }
|
|
213
|
+
if (!config.guards) return { type: 'run', tool, args, repairs }
|
|
214
|
+
const mode: DuplicateGateMode = config.duplicateGateMode ?? 'epoch'
|
|
215
|
+
if (mode === 'off') {
|
|
216
|
+
// Allow repeated calls without epoch/adjacent blocking; failure and worklist caps below still apply.
|
|
217
|
+
} else if (mode === 'adjacent') {
|
|
218
|
+
if (isNoopEditCall(tool.dshName, args)) {
|
|
219
|
+
return {
|
|
220
|
+
type: 'rejected',
|
|
221
|
+
reason: 'blocked',
|
|
222
|
+
receipt: [
|
|
223
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
224
|
+
{ role: 'user', text: toolResponse(tool.name, false, NOOP_EDIT_REMINDER) },
|
|
225
|
+
{ role: 'user', text: NOOP_EDIT_REMINDER },
|
|
226
|
+
],
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const key = callKey(tool.name, args)
|
|
230
|
+
if (key !== '' && key === state.lastCallKey) {
|
|
231
|
+
const msg = state.lastCallOk ? duplicateRetryReminder(tools) : DUPLICATE_FAILED_RETRY_REMINDER
|
|
232
|
+
return {
|
|
233
|
+
type: 'rejected',
|
|
234
|
+
reason: 'blocked',
|
|
235
|
+
receipt: [
|
|
236
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
237
|
+
{ role: 'user', text: toolResponse(tool.name, false, msg) },
|
|
238
|
+
{ role: 'user', text: msg },
|
|
239
|
+
],
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
} else if (mode === 'bounded') {
|
|
243
|
+
if (isNoopEditCall(tool.dshName, args)) {
|
|
244
|
+
const noopKey = callKey(tool.name, args)
|
|
245
|
+
if ((state.epochKeyCounts.get(noopKey) ?? 0) >= 1 || duplicateRetryUsed) {
|
|
246
|
+
return { type: 'closeout', reminder: NOOP_EDIT_REMINDER }
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
type: 'rejected',
|
|
250
|
+
reason: 'blocked',
|
|
251
|
+
receipt: [
|
|
252
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
253
|
+
{ role: 'user', text: toolResponse(tool.name, false, NOOP_EDIT_REMINDER) },
|
|
254
|
+
{ role: 'user', text: NOOP_EDIT_REMINDER },
|
|
255
|
+
],
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const key = callKey(tool.name, args)
|
|
259
|
+
const seen = key === '' ? 0 : (state.epochKeyCounts.get(key) ?? 0)
|
|
260
|
+
if (seen >= 2) {
|
|
261
|
+
return { type: 'closeout', reminder: state.successfulCalls > 0 ? DUPLICATE_ANSWER_REMINDER : DUPLICATE_FAILED_REMINDER }
|
|
262
|
+
}
|
|
263
|
+
if (key !== '' && key === state.lastCallKey) {
|
|
264
|
+
const msg = state.lastCallOk ? duplicateRetryReminder(tools) : DUPLICATE_FAILED_RETRY_REMINDER
|
|
265
|
+
return {
|
|
266
|
+
type: 'rejected',
|
|
267
|
+
reason: 'blocked',
|
|
268
|
+
receipt: [
|
|
269
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
270
|
+
{ role: 'user', text: toolResponse(tool.name, false, msg) },
|
|
271
|
+
{ role: 'user', text: msg },
|
|
272
|
+
],
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (seen === 1) {
|
|
276
|
+
const msg = state.successKeys.has(key) ? duplicateRetryReminder(tools) : DUPLICATE_FAILED_RETRY_REMINDER
|
|
277
|
+
if (!duplicateRetryUsed) {
|
|
278
|
+
return { type: 'duplicate-retry', receipt: [{ role: 'user', text: msg }] }
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
type: 'rejected',
|
|
282
|
+
reason: 'blocked',
|
|
283
|
+
receipt: [
|
|
284
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
285
|
+
{ role: 'user', text: toolResponse(tool.name, false, msg) },
|
|
286
|
+
{ role: 'user', text: msg },
|
|
287
|
+
],
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (tool.dshName === 'edit' || tool.dshName === 'edit_lines') {
|
|
291
|
+
const file = targetFileSuffix(tool.dshName, args)
|
|
292
|
+
if (file !== '') {
|
|
293
|
+
let failedEdits = 0
|
|
294
|
+
for (const [tracked, count] of state.perFileFailedEdits) {
|
|
295
|
+
if (sameTargetFile(tracked, file)) failedEdits += count
|
|
296
|
+
}
|
|
297
|
+
if (failedEdits >= 5) {
|
|
298
|
+
return { type: 'closeout', reminder: state.successfulCalls > 0 ? DUPLICATE_ANSWER_REMINDER : DUPLICATE_FAILED_REMINDER }
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
} else {
|
|
303
|
+
if (isNoopEditCall(tool.dshName, args)) {
|
|
304
|
+
if (!duplicateRetryUsed) {
|
|
305
|
+
return { type: 'duplicate-retry', receipt: [{ role: 'user', text: NOOP_EDIT_REMINDER }] }
|
|
306
|
+
}
|
|
307
|
+
return { type: 'closeout', reminder: NOOP_EDIT_REMINDER }
|
|
308
|
+
}
|
|
309
|
+
const key = callKey(tool.name, args)
|
|
310
|
+
if (state.successKeys.has(key)) {
|
|
311
|
+
// harness v26: the first repeat of a successful call gets one more decision.
|
|
312
|
+
if (!duplicateRetryUsed) {
|
|
313
|
+
return { type: 'duplicate-retry', receipt: [{ role: 'user', text: duplicateRetryReminder(tools) }] }
|
|
314
|
+
}
|
|
315
|
+
return { type: 'closeout', reminder: DUPLICATE_ANSWER_REMINDER }
|
|
316
|
+
}
|
|
317
|
+
if (state.failedEpochs.get(key) === state.successfulCalls) {
|
|
318
|
+
if (!duplicateRetryUsed) {
|
|
319
|
+
return { type: 'duplicate-retry', receipt: [{ role: 'user', text: DUPLICATE_FAILED_RETRY_REMINDER }] }
|
|
320
|
+
}
|
|
321
|
+
return { type: 'closeout', reminder: state.successfulCalls > 0 ? DUPLICATE_ANSWER_REMINDER : DUPLICATE_FAILED_REMINDER }
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const boundedEditCovered = mode === 'bounded' && (tool.dshName === 'edit' || tool.dshName === 'edit_lines')
|
|
325
|
+
if (!boundedEditCovered && tool.name === state.consecutiveFailedTool && state.consecutiveFailures >= config.maxConsecutiveFailures) {
|
|
326
|
+
const error = `tool "${tool.name}" blocked after ${state.consecutiveFailures} consecutive failures; choose a different tool or answer`
|
|
327
|
+
return {
|
|
328
|
+
type: 'rejected',
|
|
329
|
+
reason: 'blocked',
|
|
330
|
+
receipt: [
|
|
331
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
332
|
+
{ role: 'user', text: toolResponse(tool.name, false, error) },
|
|
333
|
+
{ role: 'user', text: toolFailureReminder(tool.name, error, true, tools) },
|
|
334
|
+
],
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (isWorklistTool(tool.dshName) && state.consecutiveWorklistCalls >= 2) {
|
|
338
|
+
const error = 'work list already updated twice in a row; execute a workspace tool call or answer directly'
|
|
339
|
+
return {
|
|
340
|
+
type: 'rejected',
|
|
341
|
+
reason: 'blocked',
|
|
342
|
+
receipt: [
|
|
343
|
+
{ role: 'assistant', text: recordToolCall(tool.name, args) },
|
|
344
|
+
{ role: 'user', text: toolResponse(tool.name, false, error) },
|
|
345
|
+
{ role: 'user', text: toolFailureReminder(tool.name, error, true, tools) },
|
|
346
|
+
],
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return { type: 'run', tool, args, repairs }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Argument aliases, scalar coercion and the DSH value repairs, with the names of those that applied. */
|
|
353
|
+
export function repairArguments(tool: WireTool, raw: Args, aliased: boolean): { args: Args; repairs: string[] } {
|
|
354
|
+
const normalized = normalizeArguments(tool, raw)
|
|
355
|
+
const coerced = coerceArguments(normalized, tool.schema)
|
|
356
|
+
const repaired = repairNativeValues(tool, coerced)
|
|
357
|
+
// DSH bash requires a description; a missing one is filled from the command.
|
|
358
|
+
const filled = tool.dshName === 'bash' && raw.description === undefined && normalized.description !== undefined
|
|
359
|
+
const renamed = normalized !== raw && (!filled || Object.keys(normalized).length !== Object.keys(raw).length + 1
|
|
360
|
+
|| Object.keys(raw).some(key => !(key in normalized)))
|
|
361
|
+
return {
|
|
362
|
+
args: repaired.args,
|
|
363
|
+
repairs: [
|
|
364
|
+
...aliased ? ['tool_name_alias'] : [],
|
|
365
|
+
...renamed ? ['argument_alias'] : [],
|
|
366
|
+
...filled ? ['bash_description_filled'] : [],
|
|
367
|
+
...JSON.stringify(coerced) !== JSON.stringify(normalized) ? ['scalar_coerced'] : [],
|
|
368
|
+
...repaired.repairs,
|
|
369
|
+
],
|
|
370
|
+
}
|
|
371
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Time zones for collected and evaluated trajectories. The desktop app dates
|
|
2
|
+
// the system prompt in the user's local zone; training data mirrors its mix:
|
|
3
|
+
// mostly Asia/Shanghai, the rest spread over a few common zones. The pick is a
|
|
4
|
+
// pure function of a key (the trajectory id), so a rerun of the same
|
|
5
|
+
// trajectory gets the same zone. rwkv-agent-pipeline's qc.py recomputes it.
|
|
6
|
+
|
|
7
|
+
import { createHash } from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
export const PRIMARY_TIME_ZONE = 'Asia/Shanghai'
|
|
10
|
+
/** Share of keys that get {@link PRIMARY_TIME_ZONE}. */
|
|
11
|
+
export const PRIMARY_SHARE = 0.8
|
|
12
|
+
/** The other zones, picked with equal weight. Order is part of the contract. */
|
|
13
|
+
export const OTHER_TIME_ZONES: readonly string[] = [
|
|
14
|
+
'America/Los_Angeles',
|
|
15
|
+
'America/New_York',
|
|
16
|
+
'Europe/London',
|
|
17
|
+
'Europe/Berlin',
|
|
18
|
+
'Asia/Tokyo',
|
|
19
|
+
'Asia/Singapore',
|
|
20
|
+
'UTC',
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The zone for `key`: the first 8 bytes of SHA-256(key) as two big-endian
|
|
25
|
+
* uint32; the first decides primary vs other (below PRIMARY_SHARE · 2^32), the
|
|
26
|
+
* second picks among the others.
|
|
27
|
+
*/
|
|
28
|
+
export function pickTimeZone(key: string): string {
|
|
29
|
+
const digest = createHash('sha256').update(key, 'utf8').digest()
|
|
30
|
+
if (digest.readUInt32BE(0) < PRIMARY_SHARE * 2 ** 32) return PRIMARY_TIME_ZONE
|
|
31
|
+
return OTHER_TIME_ZONES[digest.readUInt32BE(4) % OTHER_TIME_ZONES.length]!
|
|
32
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Active stateful work list (`todo_plan` + `todo_update`): tool definitions,
|
|
2
|
+
// lenient field parsing, per-turn item state transitions, and Desktop
|
|
3
|
+
// `TodoPanel` projection. Kept separate from the passive/checkpoint folding
|
|
4
|
+
// engine (`fold-pairs.ts`, `fold-window.ts`, `worklist.ts`).
|
|
5
|
+
|
|
6
|
+
export const TODO_PLAN_TOOL = 'todo_plan'
|
|
7
|
+
export const TODO_UPDATE_TOOL = 'todo_update'
|
|
8
|
+
|
|
9
|
+
export const TODO_PLAN_DESCRIPTION =
|
|
10
|
+
'Create or revise the ordered work list for multi-step tasks (touching multiple methods/files, code + docs/tests, or 3+ distinct subgoals). '
|
|
11
|
+
+ 'Skip this tool for casual chat, quick single-goal lookups (1-3 reads or searches), or a trivial one-spot edit. '
|
|
12
|
+
+ 'For multi-step changes, you may inspect 1-2 files first to understand the layout, then call todo_plan BEFORE making your first file edit — do not wait until after editing to plan. '
|
|
13
|
+
+ 'Calling todo_plan mid-turn keeps completed/dropped items and their notes intact and replaces only unfinished items.'
|
|
14
|
+
|
|
15
|
+
export const TODO_UPDATE_DESCRIPTION =
|
|
16
|
+
'Update one item in the current work list by id. '
|
|
17
|
+
+ 'As soon as an item is finished, mark it completed with a concise factual note (<= 120 words: exact /app/... file paths, updated line ranges, signatures, and test exit codes — never mark unexecuted work completed). '
|
|
18
|
+
+ 'Older exploratory tool outputs before the recent workspace actions are folded once note is saved, while your initial todo_plan and the latest workspace results stay visible. '
|
|
19
|
+
+ 'The next pending item becomes in_progress automatically; you may also checkpoint an in_progress item with an interim note before context fills up.'
|
|
20
|
+
|
|
21
|
+
export const WORKLIST_TOOLS: ReadonlySet<string> = new Set([TODO_PLAN_TOOL, TODO_UPDATE_TOOL])
|
|
22
|
+
|
|
23
|
+
export function isWorklistTool(name: string): boolean {
|
|
24
|
+
return WORKLIST_TOOLS.has(name)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type WorklistStatus = 'pending' | 'in_progress' | 'completed' | 'dropped'
|
|
28
|
+
|
|
29
|
+
export interface WorklistItem {
|
|
30
|
+
readonly id: number
|
|
31
|
+
readonly content: string
|
|
32
|
+
readonly status: WorklistStatus
|
|
33
|
+
readonly note?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface TodoUpdateInput {
|
|
37
|
+
readonly id?: unknown
|
|
38
|
+
readonly status?: unknown
|
|
39
|
+
readonly note?: unknown
|
|
40
|
+
readonly content?: unknown
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const WORKLIST_PROTOCOL_TAG = /<\/?(?:think|tool_call|tool_response)(?:\s[^>]*)?>/gi
|
|
44
|
+
const WORKLIST_LEADING_BULLET = /^\s*(?:\[\d+\]|\d+[.)]|[-*•])\s*/
|
|
45
|
+
|
|
46
|
+
export function sanitizeWorklistField(text: string): string {
|
|
47
|
+
return text.replace(WORKLIST_PROTOCOL_TAG, '').replace(/\s*\n+\s*/g, ' | ').trim()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function parsePlanItems(raw: unknown): string[] | undefined {
|
|
51
|
+
if (Array.isArray(raw)) {
|
|
52
|
+
const out: string[] = []
|
|
53
|
+
for (const entry of raw) {
|
|
54
|
+
if (typeof entry === 'string') {
|
|
55
|
+
const cleaned = sanitizeWorklistField(entry.replace(WORKLIST_LEADING_BULLET, ''))
|
|
56
|
+
if (cleaned !== '') out.push(cleaned)
|
|
57
|
+
} else if (typeof entry === 'object' && entry !== null) {
|
|
58
|
+
const obj = entry as Record<string, unknown>
|
|
59
|
+
const candidate = obj.content ?? obj.title ?? obj.text ?? obj.step
|
|
60
|
+
if (typeof candidate === 'string') {
|
|
61
|
+
const cleaned = sanitizeWorklistField(candidate.replace(WORKLIST_LEADING_BULLET, ''))
|
|
62
|
+
if (cleaned !== '') out.push(cleaned)
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return out
|
|
69
|
+
}
|
|
70
|
+
if (typeof raw === 'string') {
|
|
71
|
+
const lines = raw
|
|
72
|
+
.split(/\r?\n/)
|
|
73
|
+
.map(line => sanitizeWorklistField(line.replace(WORKLIST_LEADING_BULLET, '')))
|
|
74
|
+
.filter(line => line !== '')
|
|
75
|
+
return lines.length > 0 ? lines : undefined
|
|
76
|
+
}
|
|
77
|
+
return undefined
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function normalizeWorklistStatus(raw: unknown): WorklistStatus | undefined {
|
|
81
|
+
if (typeof raw !== 'string') return undefined
|
|
82
|
+
const lower = raw.trim().toLowerCase()
|
|
83
|
+
if (lower === 'pending' || lower === 'todo' || lower === 'not_started') return 'pending'
|
|
84
|
+
if (lower === 'in_progress' || lower === 'in-progress' || lower === 'doing' || lower === 'active') return 'in_progress'
|
|
85
|
+
if (lower === 'completed' || lower === 'complete' || lower === 'done' || lower === 'finished') return 'completed'
|
|
86
|
+
if (lower === 'dropped' || lower === 'cancelled' || lower === 'canceled' || lower === 'skipped') return 'dropped'
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Whether `item` is a `todo_update` call that wrote a non-empty `note`. */
|
|
91
|
+
export function isNotedTodoUpdateCall(item: { readonly kind: string; readonly name?: string; readonly args?: Record<string, unknown> }): boolean {
|
|
92
|
+
if (item.kind !== 'call' || item.name !== TODO_UPDATE_TOOL || item.args === undefined) return false
|
|
93
|
+
const note = item.args.note ?? item.args.notes ?? item.args.summary ?? item.args.findings ?? item.args.conclusion
|
|
94
|
+
return typeof note === 'string' && sanitizeWorklistField(note) !== ''
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Apply `todo_plan` to the current turn's list. Completed and dropped items
|
|
99
|
+
* (and their notes) are locked and kept at the top; `rawItems` replaces only
|
|
100
|
+
* the remaining unfinished queue, activating the first unfinished item.
|
|
101
|
+
*/
|
|
102
|
+
export function applyTodoPlan(current: readonly WorklistItem[], rawItems: unknown): WorklistItem[] | string {
|
|
103
|
+
const parsed = parsePlanItems(rawItems)
|
|
104
|
+
if (parsed === undefined || parsed.length === 0) {
|
|
105
|
+
return 'items must be a non-empty array of step strings'
|
|
106
|
+
}
|
|
107
|
+
const locked = current
|
|
108
|
+
.filter(item => item.status === 'completed' || item.status === 'dropped')
|
|
109
|
+
.map((item, idx) => ({ ...item, id: idx + 1 }))
|
|
110
|
+
const lockedTitles = new Set(locked.map(item => item.content))
|
|
111
|
+
// If the model re-sent already completed titles at the top of `items`, skip
|
|
112
|
+
// duplicating them because `locked` already preserves them with their notes.
|
|
113
|
+
const remaining = parsed.filter(title => !lockedTitles.has(title))
|
|
114
|
+
if (locked.length === 0 && remaining.length < 2) {
|
|
115
|
+
return 'todo_plan requires at least 2 steps; execute single-step tasks directly without todo_plan'
|
|
116
|
+
}
|
|
117
|
+
if (remaining.length === 0) {
|
|
118
|
+
return 'todo_plan requires at least 1 new unfinished step after completed items'
|
|
119
|
+
}
|
|
120
|
+
if (locked.length + remaining.length > 12) {
|
|
121
|
+
return `todo_plan accepts at most 12 total items (got ${locked.length + remaining.length}); group micro-actions into coarser subgoals`
|
|
122
|
+
}
|
|
123
|
+
const seen = new Set<string>()
|
|
124
|
+
for (const [idx, title] of remaining.entries()) {
|
|
125
|
+
if (seen.has(title)) {
|
|
126
|
+
return `items[${idx}] duplicates ${JSON.stringify(title)}`
|
|
127
|
+
}
|
|
128
|
+
seen.add(title)
|
|
129
|
+
}
|
|
130
|
+
const tail: WorklistItem[] = remaining.map((content, idx) => ({
|
|
131
|
+
id: locked.length + idx + 1,
|
|
132
|
+
content,
|
|
133
|
+
status: idx === 0 ? 'in_progress' : 'pending',
|
|
134
|
+
}))
|
|
135
|
+
return [...locked, ...tail]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Apply `todo_update` to one item by 1-based `id`. Requires a non-empty `note`
|
|
140
|
+
* when closing an item (`completed` or `dropped`), keeps at most one item
|
|
141
|
+
* `in_progress`, and automatically advances the next `pending` item when the
|
|
142
|
+
* active item finishes.
|
|
143
|
+
*/
|
|
144
|
+
export function applyTodoUpdate(
|
|
145
|
+
current: readonly WorklistItem[],
|
|
146
|
+
input: TodoUpdateInput,
|
|
147
|
+
): { items: WorklistItem[]; noted: boolean } | string {
|
|
148
|
+
if (current.length === 0) {
|
|
149
|
+
return 'no active todo list in this turn; call todo_plan first if this task has multiple subgoals'
|
|
150
|
+
}
|
|
151
|
+
const rawId = typeof input.id === 'string' ? Number(input.id.trim()) : input.id
|
|
152
|
+
if (typeof rawId !== 'number' || !Number.isInteger(rawId) || rawId < 1 || rawId > current.length) {
|
|
153
|
+
return `id must be an integer between 1 and ${current.length} (got ${JSON.stringify(input.id)})`
|
|
154
|
+
}
|
|
155
|
+
const status = normalizeWorklistStatus(input.status)
|
|
156
|
+
if (status === undefined || status === 'pending') {
|
|
157
|
+
return 'status must be one of: in_progress, completed, dropped'
|
|
158
|
+
}
|
|
159
|
+
const target = current[rawId - 1]!
|
|
160
|
+
const providedNote = typeof input.note === 'string' ? sanitizeWorklistField(input.note) : ''
|
|
161
|
+
const effectiveNote = providedNote !== '' ? providedNote : target.note
|
|
162
|
+
if ((status === 'completed' || status === 'dropped') && (!effectiveNote || effectiveNote === '')) {
|
|
163
|
+
return 'note is required when status is completed or dropped: record concrete findings, exact file paths/lines, applied edits, or test results'
|
|
164
|
+
}
|
|
165
|
+
const updatedContent = typeof input.content === 'string' && sanitizeWorklistField(input.content) !== ''
|
|
166
|
+
? sanitizeWorklistField(input.content)
|
|
167
|
+
: target.content
|
|
168
|
+
|
|
169
|
+
const next = current.map((item, index): WorklistItem => {
|
|
170
|
+
if (index === rawId - 1) {
|
|
171
|
+
return {
|
|
172
|
+
id: item.id,
|
|
173
|
+
content: updatedContent,
|
|
174
|
+
status,
|
|
175
|
+
...effectiveNote ? { note: effectiveNote } : {},
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
// Single-active discipline: focusing a later item auto-completes an earlier
|
|
179
|
+
// active item that already recorded a note, and demotes an unnoted/later one.
|
|
180
|
+
if (status === 'in_progress' && item.status === 'in_progress') {
|
|
181
|
+
const autoDone = index < rawId - 1 && Boolean(item.note && item.note.trim() !== '')
|
|
182
|
+
return { ...item, status: autoDone ? 'completed' : 'pending' }
|
|
183
|
+
}
|
|
184
|
+
return item
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
// Auto-advance: when no item is active anymore, promote the next pending item.
|
|
188
|
+
if (!next.some(item => item.status === 'in_progress')) {
|
|
189
|
+
const afterIdx = next.findIndex((item, idx) => idx > rawId - 1 && item.status === 'pending')
|
|
190
|
+
const promoteIdx = afterIdx >= 0 ? afterIdx : next.findIndex(item => item.status === 'pending')
|
|
191
|
+
if (promoteIdx >= 0) {
|
|
192
|
+
next[promoteIdx] = { ...next[promoteIdx]!, status: 'in_progress' }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return { items: next, noted: providedNote !== '' }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Model-facing rendering returned as the tool output of `todo_plan` and `todo_update`. */
|
|
200
|
+
export function formatWorklist(items: readonly WorklistItem[]): string {
|
|
201
|
+
const lines = ['Todo list:']
|
|
202
|
+
for (const item of items) {
|
|
203
|
+
lines.push(`[${item.id}] (${item.status}) ${item.content}`)
|
|
204
|
+
if (item.note) lines.push(` note: ${item.note}`)
|
|
205
|
+
}
|
|
206
|
+
return lines.join('\n')
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Clean single-line projection mirrored onto DSH's native `todo/write` event for
|
|
211
|
+
* the Desktop `TodoPanel` dock (omits long technical notes, and settles lingering
|
|
212
|
+
* `in_progress` spinners to `pending` once `turn/end` fires).
|
|
213
|
+
*/
|
|
214
|
+
export function projectNativeTodos(
|
|
215
|
+
items: readonly WorklistItem[],
|
|
216
|
+
options?: { readonly turnEnded?: boolean },
|
|
217
|
+
): { content: string; status: 'pending' | 'in_progress' | 'completed' }[] {
|
|
218
|
+
const settleActive = options?.turnEnded === true
|
|
219
|
+
return items.map(item => ({
|
|
220
|
+
content: item.status === 'dropped'
|
|
221
|
+
? `[${item.id}] [已跳过] ${item.content}`
|
|
222
|
+
: `[${item.id}] ${item.content}`,
|
|
223
|
+
status: item.status === 'dropped'
|
|
224
|
+
? 'completed'
|
|
225
|
+
: (settleActive && item.status === 'in_progress' ? 'pending' : item.status),
|
|
226
|
+
}))
|
|
227
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Re-export shim: pure `tolerant` engine now lives in `src/core/edit-modes/tolerant.ts`.
|
|
2
|
+
export {
|
|
3
|
+
findRegion,
|
|
4
|
+
fitReplacement,
|
|
5
|
+
reindent,
|
|
6
|
+
resolveTolerantEdit,
|
|
7
|
+
similarity,
|
|
8
|
+
toLF,
|
|
9
|
+
TOLERANT_EDIT_MODE,
|
|
10
|
+
type MatchLevel,
|
|
11
|
+
type RegionMatch,
|
|
12
|
+
type RegionResult,
|
|
13
|
+
type ResolvedTolerantEdit,
|
|
14
|
+
} from './edit-modes/tolerant.ts'
|