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,150 @@
|
|
|
1
|
+
// Shared session context assembly used by both the student adapter (`src/adapter.ts`)
|
|
2
|
+
// and the teacher distillation overlay (`rwkv-agent-pipeline/plugins/teacher.ts`),
|
|
3
|
+
// guaranteeing identical tool exclusion rules, history-mode options, and prompt
|
|
4
|
+
// overhead accounting across student and teacher runs.
|
|
5
|
+
//
|
|
6
|
+
// Zero `@deepseek-ai/*` runtime imports so container collection can load it
|
|
7
|
+
// directly from `/opt/dsh-rwkv-plugin/src`.
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_ACTIVE_WORKLIST_BUDGET_TOKENS,
|
|
11
|
+
DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS,
|
|
12
|
+
DEFAULT_AUTOFOLD_HARD_SLACK_TOKENS,
|
|
13
|
+
DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS,
|
|
14
|
+
DEFAULT_BACKBONE_MAX_TOKENS,
|
|
15
|
+
DEFAULT_KEEP_RECENT_PAIRS,
|
|
16
|
+
DEFAULT_RELAY_BUDGET_TOKENS,
|
|
17
|
+
DEFAULT_RELAY_CARD_MAX_TOKENS,
|
|
18
|
+
DEFAULT_WORKLIST_BUDGET_TOKENS,
|
|
19
|
+
DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS,
|
|
20
|
+
DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS,
|
|
21
|
+
DEFAULT_WORKLIST_MIN_FOLD_TOKENS,
|
|
22
|
+
type EditMode,
|
|
23
|
+
type HistoryMode,
|
|
24
|
+
} from './core/defaults.ts'
|
|
25
|
+
import { excludedToolsForEditMode } from './core/edit-modes/index.ts'
|
|
26
|
+
import { POST_TOOL_REMINDER_THINK } from './core/policy.ts'
|
|
27
|
+
import { cleanChatText, systemPrompt, WORKLIST_SYSTEM_GUIDANCE } from './core/prompt.ts'
|
|
28
|
+
import type { RelayOptions } from './core/relay.ts'
|
|
29
|
+
import { TODO_PLAN_TOOL, TODO_UPDATE_TOOL } from './core/todo-state.ts'
|
|
30
|
+
import type { WireTool } from './core/tools.ts'
|
|
31
|
+
import type { WorklistOptions } from './core/worklist.ts'
|
|
32
|
+
import { countTokens } from './tokenizer.ts'
|
|
33
|
+
|
|
34
|
+
export interface HistoryModeConfigInput {
|
|
35
|
+
readonly historyMode?: HistoryMode
|
|
36
|
+
readonly relayBudgetTokens?: number
|
|
37
|
+
readonly relayCardMaxTokens?: number
|
|
38
|
+
readonly worklistMinFoldTokens?: number
|
|
39
|
+
readonly worklistBudgetTokens?: number
|
|
40
|
+
readonly worklistKeepRecentPairs?: number
|
|
41
|
+
readonly worklistKeepInitialPlan?: boolean
|
|
42
|
+
readonly worklistSystemGuidance?: boolean
|
|
43
|
+
readonly worklistEpochTargetTokens?: number
|
|
44
|
+
readonly worklistPinUneditedRead?: boolean
|
|
45
|
+
readonly worklistImmediatePriorFold?: boolean
|
|
46
|
+
readonly worklistBackboneMaxTokens?: number
|
|
47
|
+
readonly worklistExemptResultTokens?: number
|
|
48
|
+
readonly worklistInPlaceMask?: boolean
|
|
49
|
+
readonly worklistHardCapTokens?: number
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function resolveHistoryModeConfig(input: HistoryModeConfigInput): {
|
|
53
|
+
readonly relay?: RelayOptions
|
|
54
|
+
readonly worklist?: WorklistOptions
|
|
55
|
+
} {
|
|
56
|
+
if (input.historyMode === 'relay') {
|
|
57
|
+
return {
|
|
58
|
+
relay: {
|
|
59
|
+
budgetTokens: input.relayBudgetTokens ?? DEFAULT_RELAY_BUDGET_TOKENS,
|
|
60
|
+
cardMaxTokens: input.relayCardMaxTokens ?? DEFAULT_RELAY_CARD_MAX_TOKENS,
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (input.historyMode === 'auto-fold') {
|
|
65
|
+
const immediatePriorFold = input.worklistImmediatePriorFold ?? true
|
|
66
|
+
const inPlaceMask = input.worklistInPlaceMask ?? true
|
|
67
|
+
const budgetTokens = input.worklistBudgetTokens ?? DEFAULT_WORKLIST_BUDGET_TOKENS
|
|
68
|
+
const epochTargetTokens = input.worklistEpochTargetTokens ?? DEFAULT_WORKLIST_EPOCH_TARGET_TOKENS
|
|
69
|
+
const hardCapTokens = input.worklistHardCapTokens !== undefined && input.worklistHardCapTokens > 0
|
|
70
|
+
? input.worklistHardCapTokens
|
|
71
|
+
: budgetTokens + DEFAULT_AUTOFOLD_HARD_SLACK_TOKENS
|
|
72
|
+
return {
|
|
73
|
+
worklist: {
|
|
74
|
+
passive: true,
|
|
75
|
+
systemGuidance: false,
|
|
76
|
+
immediatePriorFold,
|
|
77
|
+
inPlaceMask,
|
|
78
|
+
backboneMaxTokens: input.worklistBackboneMaxTokens ?? DEFAULT_AUTOFOLD_BACKBONE_MAX_TOKENS,
|
|
79
|
+
minFoldTokens: immediatePriorFold ? 0 : (input.worklistMinFoldTokens ?? DEFAULT_WORKLIST_MIN_FOLD_TOKENS),
|
|
80
|
+
budgetTokens,
|
|
81
|
+
epochTargetTokens,
|
|
82
|
+
keepRecentPairs: input.worklistKeepRecentPairs ?? DEFAULT_AUTOFOLD_KEEP_RECENT_PAIRS,
|
|
83
|
+
exemptResultTokens: input.worklistExemptResultTokens ?? DEFAULT_WORKLIST_EXEMPT_RESULT_TOKENS,
|
|
84
|
+
hardCapTokens,
|
|
85
|
+
...(input.worklistPinUneditedRead ? { pinUneditedRead: true } : {}),
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (input.historyMode === 'worklist') {
|
|
90
|
+
return {
|
|
91
|
+
worklist: {
|
|
92
|
+
...(input.worklistSystemGuidance !== undefined ? { systemGuidance: input.worklistSystemGuidance } : {}),
|
|
93
|
+
minFoldTokens: input.worklistMinFoldTokens ?? DEFAULT_WORKLIST_MIN_FOLD_TOKENS,
|
|
94
|
+
budgetTokens: input.worklistBudgetTokens ?? DEFAULT_ACTIVE_WORKLIST_BUDGET_TOKENS,
|
|
95
|
+
backboneMaxTokens: input.worklistBackboneMaxTokens ?? DEFAULT_BACKBONE_MAX_TOKENS,
|
|
96
|
+
keepRecentPairs: input.worklistKeepRecentPairs ?? DEFAULT_KEEP_RECENT_PAIRS,
|
|
97
|
+
...(input.worklistKeepInitialPlan !== undefined ? { keepInitialPlan: input.worklistKeepInitialPlan } : {}),
|
|
98
|
+
...(input.worklistHardCapTokens !== undefined && input.worklistHardCapTokens > 0
|
|
99
|
+
? { hardCapTokens: input.worklistHardCapTokens }
|
|
100
|
+
: {}),
|
|
101
|
+
...(input.worklistPinUneditedRead ? { pinUneditedRead: true } : {}),
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return {}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function buildExcludedTools(options: {
|
|
109
|
+
readonly excludeTools?: readonly string[]
|
|
110
|
+
readonly editMode?: EditMode
|
|
111
|
+
readonly worklist?: WorklistOptions
|
|
112
|
+
}): string[] {
|
|
113
|
+
return [
|
|
114
|
+
...(options.excludeTools ?? []),
|
|
115
|
+
...excludedToolsForEditMode(options.editMode),
|
|
116
|
+
...(options.worklist === undefined || options.worklist.passive === true ? [TODO_PLAN_TOOL, TODO_UPDATE_TOOL] : []),
|
|
117
|
+
]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const TRAILING_DATE_LINE_RE = /\n(?:Current date: \d{4}-\d{2}-\d{2} \(.+\)\.)$/
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Build the teacher-facing system string and exact RWKV token overhead for
|
|
124
|
+
* `worklist` / `auto-fold` mode so teacher folding cuts at the exact same
|
|
125
|
+
* step boundaries the student plugin sees.
|
|
126
|
+
*/
|
|
127
|
+
export function prepareTeacherWorklistPrompts(options: {
|
|
128
|
+
readonly catalog: readonly WireTool[]
|
|
129
|
+
readonly filteredHead: string
|
|
130
|
+
readonly dateLine?: string
|
|
131
|
+
readonly guidance?: string
|
|
132
|
+
readonly worklist: WorklistOptions
|
|
133
|
+
}): {
|
|
134
|
+
readonly teacherSystem: string
|
|
135
|
+
readonly rwkvSystemTokens: number
|
|
136
|
+
readonly reminderTokens: number
|
|
137
|
+
} {
|
|
138
|
+
const cleanHead = options.filteredHead.replace(TRAILING_DATE_LINE_RE, '')
|
|
139
|
+
const useGuidance = options.worklist.passive !== true && options.worklist.systemGuidance !== false
|
|
140
|
+
const worklistHead = useGuidance
|
|
141
|
+
? `${cleanHead}\n\n${WORKLIST_SYSTEM_GUIDANCE}${options.dateLine ? `\n\n${options.dateLine}` : ''}`
|
|
142
|
+
: `${cleanHead}${options.dateLine ? `\n\n${options.dateLine}` : ''}`
|
|
143
|
+
const teacherSystem = options.guidance ? `${worklistHead}\n\n${options.guidance}` : worklistHead
|
|
144
|
+
const rwkvSystem = systemPrompt(options.catalog, 'full', undefined, cleanHead, options.dateLine, { worklistGuidance: useGuidance })
|
|
145
|
+
return {
|
|
146
|
+
teacherSystem,
|
|
147
|
+
rwkvSystemTokens: countTokens(rwkvSystem),
|
|
148
|
+
reminderTokens: countTokens(`User: ${cleanChatText(POST_TOOL_REMINDER_THINK)}\n\n`),
|
|
149
|
+
}
|
|
150
|
+
}
|
package/src/todo.ts
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// DSH plugin `rwkv-todo`: registers `todo_plan` and `todo_update` (Stateful
|
|
2
|
+
// Work List) for RWKV and teacher sessions.
|
|
3
|
+
//
|
|
4
|
+
// Why a separate tool plugin instead of DSH's stock `@deepseek-ai/dsh-tool-todo`:
|
|
5
|
+
// 1. `todo_write` enforces `additionalProperties: false` on `{content, status}`,
|
|
6
|
+
// and DSH's session-format validator rejects extra keys on `todo/write`
|
|
7
|
+
// events, so `note` cannot be stored on `todo/write` directly.
|
|
8
|
+
// 2. `todo_write` is whole-list replacement and returns only status counts
|
|
9
|
+
// (`Updated todo list: ...`), never echoing the list back into context.
|
|
10
|
+
// 3. Rewriting the whole list on every step wastes tokens and causes 7B models
|
|
11
|
+
// to paraphrase or drop earlier line numbers/paths from `note`.
|
|
12
|
+
//
|
|
13
|
+
// `rwkv-todo` stores the full `{id, content, status, note}` state per turn in an
|
|
14
|
+
// ignorable `plugin:rwkv-todo/state` session record (surviving process-per-turn
|
|
15
|
+
// runners), echoes the full formatted list in every tool result, and mirrors a
|
|
16
|
+
// valid `{content, status}` projection onto `todo/write` so DSH's native Desktop
|
|
17
|
+
// TodoPanel renders live progress without modifying `deepseek-harness`.
|
|
18
|
+
|
|
19
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
20
|
+
import { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'
|
|
21
|
+
import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'
|
|
22
|
+
import {
|
|
23
|
+
applyTodoPlan,
|
|
24
|
+
applyTodoUpdate,
|
|
25
|
+
formatWorklist,
|
|
26
|
+
isWorklistTool,
|
|
27
|
+
normalizeWorklistStatus,
|
|
28
|
+
projectNativeTodos,
|
|
29
|
+
TODO_PLAN_TOOL,
|
|
30
|
+
TODO_UPDATE_TOOL,
|
|
31
|
+
type WorklistItem,
|
|
32
|
+
type WorklistStatus,
|
|
33
|
+
} from './core/worklist.ts'
|
|
34
|
+
import { TODO_PLAN_DESCRIPTION, TODO_UPDATE_DESCRIPTION } from './core/tools.ts'
|
|
35
|
+
|
|
36
|
+
export { TODO_PLAN_DESCRIPTION, TODO_UPDATE_DESCRIPTION }
|
|
37
|
+
|
|
38
|
+
export const name = 'rwkv-todo'
|
|
39
|
+
export const inject = ['tools']
|
|
40
|
+
|
|
41
|
+
const STATE_RECORD = 'plugin:rwkv-todo/state'
|
|
42
|
+
|
|
43
|
+
interface PersistedState {
|
|
44
|
+
readonly turn: number
|
|
45
|
+
readonly items: readonly WorklistItem[]
|
|
46
|
+
readonly completed?: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface SessionEventLike {
|
|
50
|
+
readonly type?: string
|
|
51
|
+
readonly data?: unknown
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface SessionLike {
|
|
55
|
+
snapshotEvents?(): readonly SessionEventLike[]
|
|
56
|
+
append?(type: 'todo/write', data: { todos: { content: string; status: 'pending' | 'in_progress' | 'completed' }[] }): unknown
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface ExecLike {
|
|
60
|
+
readonly agent?: { readonly session?: SessionLike }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface ContextLike {
|
|
64
|
+
readonly tools: { register(definition: unknown): () => void }
|
|
65
|
+
on?(event: string, listener: (session: SessionLike, ev: SessionEventLike) => void): () => void
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const appendRecord = appendPluginRecord as unknown as (session: object, type: string, data: unknown) => unknown
|
|
69
|
+
const recordOf = pluginRecordOf as unknown as (event: unknown) => { type: string; data: unknown } | undefined
|
|
70
|
+
|
|
71
|
+
const VALID_STATUSES = new Set<string>(['pending', 'in_progress', 'completed', 'dropped'])
|
|
72
|
+
|
|
73
|
+
export { projectNativeTodos }
|
|
74
|
+
|
|
75
|
+
function decodeItems(raw: unknown): WorklistItem[] | undefined {
|
|
76
|
+
if (!Array.isArray(raw)) return undefined
|
|
77
|
+
const items: WorklistItem[] = []
|
|
78
|
+
for (const entry of raw) {
|
|
79
|
+
if (typeof entry !== 'object' || entry === null) return undefined
|
|
80
|
+
const { id, content, status, note } = entry as Record<string, unknown>
|
|
81
|
+
if (typeof id !== 'number' || !Number.isInteger(id) || id < 1) return undefined
|
|
82
|
+
if (typeof content !== 'string' || content === '') return undefined
|
|
83
|
+
if (typeof status !== 'string' || !VALID_STATUSES.has(status)) return undefined
|
|
84
|
+
if (note !== undefined && typeof note !== 'string') return undefined
|
|
85
|
+
items.push({
|
|
86
|
+
id,
|
|
87
|
+
content,
|
|
88
|
+
status: status as WorklistStatus,
|
|
89
|
+
...(typeof note === 'string' && note !== '' ? { note } : {}),
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
return items
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function turnIndexOf(events: readonly SessionEventLike[] | undefined): number {
|
|
96
|
+
if (events === undefined) return 1
|
|
97
|
+
let turns = 0
|
|
98
|
+
for (const event of events) {
|
|
99
|
+
if (event.type === 'turn/start') turns++
|
|
100
|
+
}
|
|
101
|
+
return Math.max(1, turns)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* True when an earlier `todo_update` in the current turn already marked an item
|
|
106
|
+
* `completed` and NO workspace tool (`read`, `edit_lines`, `write`, `bash`, ...)
|
|
107
|
+
* has executed since then — preventing empty-window hallucinated closeouts.
|
|
108
|
+
*/
|
|
109
|
+
export function blockedBackToBackComplete(events: readonly SessionEventLike[] | undefined): boolean {
|
|
110
|
+
if (events === undefined || events.length === 0) return false
|
|
111
|
+
let skippedCurrentCall = false
|
|
112
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
113
|
+
const ev = events[i]!
|
|
114
|
+
if (ev.type === 'turn/start') return false
|
|
115
|
+
if (ev.type === 'tool/call') {
|
|
116
|
+
if (!skippedCurrentCall) {
|
|
117
|
+
skippedCurrentCall = true
|
|
118
|
+
continue
|
|
119
|
+
}
|
|
120
|
+
const toolName = typeof ev.data === 'object' && ev.data !== null
|
|
121
|
+
? (ev.data as { name?: unknown }).name
|
|
122
|
+
: undefined
|
|
123
|
+
if (typeof toolName === 'string' && !isWorklistTool(toolName) && toolName !== 'todo_write') {
|
|
124
|
+
return false
|
|
125
|
+
}
|
|
126
|
+
continue
|
|
127
|
+
}
|
|
128
|
+
const rec = recordOf(ev)
|
|
129
|
+
if (rec?.type === STATE_RECORD && typeof rec.data === 'object' && rec.data !== null) {
|
|
130
|
+
if ((rec.data as { completed?: unknown }).completed === true) {
|
|
131
|
+
return true
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return false
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** One active worklist per agent session and user turn ("one turn, one list"). */
|
|
139
|
+
class WorklistStore {
|
|
140
|
+
private readonly bySession = new WeakMap<object, { turn: number; items: WorklistItem[] }>()
|
|
141
|
+
private readonly hydrated = new WeakSet<object>()
|
|
142
|
+
private fallback: WorklistItem[] = []
|
|
143
|
+
|
|
144
|
+
get(session: SessionLike | undefined): { turn: number; items: WorklistItem[] } {
|
|
145
|
+
if (session === undefined) return { turn: 1, items: this.fallback }
|
|
146
|
+
const events = session.snapshotEvents?.()
|
|
147
|
+
const currentTurn = turnIndexOf(events)
|
|
148
|
+
if (!this.hydrated.has(session)) {
|
|
149
|
+
this.hydrated.add(session)
|
|
150
|
+
let items: WorklistItem[] = []
|
|
151
|
+
if (events !== undefined) {
|
|
152
|
+
let logTurn = 0
|
|
153
|
+
for (const event of events) {
|
|
154
|
+
if (event.type === 'turn/start') {
|
|
155
|
+
logTurn++
|
|
156
|
+
items = []
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
const rec = recordOf(event)
|
|
160
|
+
if (rec?.type !== STATE_RECORD || typeof rec.data !== 'object' || rec.data === null) continue
|
|
161
|
+
const decoded = decodeItems((rec.data as { items?: unknown }).items)
|
|
162
|
+
const recTurn = (rec.data as { turn?: unknown }).turn
|
|
163
|
+
if (decoded !== undefined && (typeof recTurn !== 'number' || recTurn === Math.max(1, logTurn))) {
|
|
164
|
+
items = decoded
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const entry = { turn: currentTurn, items }
|
|
169
|
+
this.bySession.set(session, entry)
|
|
170
|
+
return entry
|
|
171
|
+
}
|
|
172
|
+
const existing = this.bySession.get(session)
|
|
173
|
+
if (existing === undefined || existing.turn !== currentTurn) {
|
|
174
|
+
const fresh = { turn: currentTurn, items: [] as WorklistItem[] }
|
|
175
|
+
this.bySession.set(session, fresh)
|
|
176
|
+
return fresh
|
|
177
|
+
}
|
|
178
|
+
return existing
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
save(session: SessionLike | undefined, turn: number, items: WorklistItem[], completed = false): void {
|
|
182
|
+
if (session === undefined) {
|
|
183
|
+
this.fallback = items
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
this.bySession.set(session, { turn, items })
|
|
187
|
+
const payload: PersistedState = { turn, items, ...(completed ? { completed: true } : {}) }
|
|
188
|
+
try {
|
|
189
|
+
appendRecord(session, STATE_RECORD, payload)
|
|
190
|
+
} catch {
|
|
191
|
+
// Outside a live DSH session store (unit tests): keep in memory.
|
|
192
|
+
}
|
|
193
|
+
// Mirror onto DSH's native `todo/write` projection so the Desktop TodoPanel
|
|
194
|
+
// renders clean single-line checklist titles (`[id] title`, without stuffing
|
|
195
|
+
// multi-line technical notes into the compact dock row).
|
|
196
|
+
try {
|
|
197
|
+
session.append?.('todo/write', { todos: projectNativeTodos(items) })
|
|
198
|
+
} catch {
|
|
199
|
+
// Ignore if session does not accept todo/write in minimal test harnesses.
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Settle any lingering `in_progress` indicator in the Desktop `TodoPanel` once
|
|
205
|
+
* `turn/end` commits so an unfinished item does not keep spinning while idle.
|
|
206
|
+
*/
|
|
207
|
+
settleTurnEnd(session: SessionLike | undefined): void {
|
|
208
|
+
if (session === undefined) return
|
|
209
|
+
const { items } = this.get(session)
|
|
210
|
+
if (!items.some(item => item.status === 'in_progress')) return
|
|
211
|
+
try {
|
|
212
|
+
session.append?.('todo/write', { todos: projectNativeTodos(items, { turnEnded: true }) })
|
|
213
|
+
} catch {
|
|
214
|
+
// Ignore if session rejects post-turn UI projection append.
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const STATUS_CN: Record<string, string> = {
|
|
220
|
+
completed: '已完成',
|
|
221
|
+
in_progress: '记录进展',
|
|
222
|
+
dropped: '已跳过',
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function apply(ctx: Context): void {
|
|
226
|
+
const host = ctx as unknown as ContextLike
|
|
227
|
+
const store = new WorklistStore()
|
|
228
|
+
|
|
229
|
+
host.on?.('session/event', (session, ev) => {
|
|
230
|
+
if (ev?.type === 'turn/end') store.settleTurnEnd(session)
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
host.tools.register(defineTool({
|
|
234
|
+
name: TODO_PLAN_TOOL,
|
|
235
|
+
description: TODO_PLAN_DESCRIPTION,
|
|
236
|
+
parameters: {
|
|
237
|
+
items: {
|
|
238
|
+
type: 'array',
|
|
239
|
+
required: true,
|
|
240
|
+
description: 'Ordered list of concrete subgoals (2-10 short action lines, without numbers). Mid-turn calls keep completed/dropped items and their notes and replace only unfinished items.',
|
|
241
|
+
items: { type: 'string' },
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
output: {
|
|
245
|
+
schema: {
|
|
246
|
+
type: 'object',
|
|
247
|
+
additionalProperties: false,
|
|
248
|
+
properties: {
|
|
249
|
+
summary: { type: 'string', required: true },
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
render: (_args: unknown, value: { summary: string }) => [{ type: 'text', text: value.summary }],
|
|
253
|
+
},
|
|
254
|
+
execute(args: { items: string[] }, exec: ExecLike) {
|
|
255
|
+
const session = exec.agent?.session
|
|
256
|
+
const current = store.get(session)
|
|
257
|
+
const updated = applyTodoPlan(current.items, args.items)
|
|
258
|
+
if (typeof updated === 'string') throw new ToolArgsError([updated])
|
|
259
|
+
store.save(session, current.turn, updated)
|
|
260
|
+
return Promise.resolve({ summary: formatWorklist(updated) })
|
|
261
|
+
},
|
|
262
|
+
presentCall: (args: { items?: unknown }) => ({
|
|
263
|
+
card: 'generic',
|
|
264
|
+
title: `规划工单(${Array.isArray(args.items) ? args.items.length : 0} 项)`,
|
|
265
|
+
kind: 'other',
|
|
266
|
+
rawInput: args.items,
|
|
267
|
+
}),
|
|
268
|
+
} as never))
|
|
269
|
+
|
|
270
|
+
host.tools.register(defineTool({
|
|
271
|
+
name: TODO_UPDATE_TOOL,
|
|
272
|
+
description: TODO_UPDATE_DESCRIPTION,
|
|
273
|
+
parameters: {
|
|
274
|
+
id: {
|
|
275
|
+
type: 'number',
|
|
276
|
+
required: true,
|
|
277
|
+
description: '1-based item number from the current todo list.',
|
|
278
|
+
},
|
|
279
|
+
status: {
|
|
280
|
+
type: 'string',
|
|
281
|
+
required: true,
|
|
282
|
+
enum: ['in_progress', 'completed', 'dropped'],
|
|
283
|
+
description: 'in_progress | completed | dropped. Marking completed or dropped automatically sets the next pending item to in_progress.',
|
|
284
|
+
},
|
|
285
|
+
note: {
|
|
286
|
+
type: 'string',
|
|
287
|
+
description: 'Concrete findings, exact file paths/lines, applied edits, or test outcomes. Required when status is completed or dropped; also used on in_progress to checkpoint progress.',
|
|
288
|
+
},
|
|
289
|
+
content: {
|
|
290
|
+
type: 'string',
|
|
291
|
+
description: 'Optional refined title for this item if the initial wording was inaccurate.',
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
output: {
|
|
295
|
+
schema: {
|
|
296
|
+
type: 'object',
|
|
297
|
+
additionalProperties: false,
|
|
298
|
+
properties: {
|
|
299
|
+
summary: { type: 'string', required: true },
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
render: (_args: unknown, value: { summary: string }) => [{ type: 'text', text: value.summary }],
|
|
303
|
+
},
|
|
304
|
+
execute(args: { id: number; status: string; note?: string; content?: string }, exec: ExecLike) {
|
|
305
|
+
const session = exec.agent?.session
|
|
306
|
+
const statusNorm = normalizeWorklistStatus(args.status)
|
|
307
|
+
if (statusNorm === 'completed' && blockedBackToBackComplete(session?.snapshotEvents?.())) {
|
|
308
|
+
throw new ToolArgsError([
|
|
309
|
+
'Cannot mark another item completed immediately after a previous completion with no workspace tool call in between. Execute or verify this item with a workspace tool first (read, edit_lines, write, or bash), or use status="in_progress" / "dropped".',
|
|
310
|
+
])
|
|
311
|
+
}
|
|
312
|
+
const current = store.get(session)
|
|
313
|
+
const updated = applyTodoUpdate(current.items, args)
|
|
314
|
+
if (typeof updated === 'string') throw new ToolArgsError([updated])
|
|
315
|
+
store.save(session, current.turn, updated.items, statusNorm === 'completed')
|
|
316
|
+
return Promise.resolve({ summary: formatWorklist(updated.items) })
|
|
317
|
+
},
|
|
318
|
+
presentCall: (args: Record<string, unknown>) => {
|
|
319
|
+
const st = typeof args.status === 'string' ? (STATUS_CN[args.status] ?? args.status) : '更新'
|
|
320
|
+
return {
|
|
321
|
+
card: 'generic',
|
|
322
|
+
title: `更新工单 #${String(args.id ?? '?')} · ${st}`,
|
|
323
|
+
kind: 'other',
|
|
324
|
+
rawInput: args,
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
} as never))
|
|
328
|
+
}
|
package/src/tokenizer.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Exact RWKV World token counts.
|
|
2
|
+
//
|
|
3
|
+
// One process-wide tokenizer over the vendored rwkv-tokenizer WASM (CJS glue,
|
|
4
|
+
// see vendor/rwkv-tokenizer/NOTICE.md). The vocabulary is the same one
|
|
5
|
+
// rwkv-tokenizer-go counts with, so budgets and every token number reported
|
|
6
|
+
// for training data / evaluations share one unit.
|
|
7
|
+
//
|
|
8
|
+
// The WASM is loaded lazily on the first count: 2.3 MB read plus instantiation,
|
|
9
|
+
// about 5 ms, once per process. Nothing here imports the DSH runtime, so the
|
|
10
|
+
// pipeline's teacher plugin can mount the same code.
|
|
11
|
+
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { dirname, join } from 'node:path'
|
|
14
|
+
import { fileURLToPath } from 'node:url'
|
|
15
|
+
|
|
16
|
+
interface WorldTokenizer {
|
|
17
|
+
encode(text: string): Uint16Array
|
|
18
|
+
decode(ids: Uint16Array): string
|
|
19
|
+
vocab_size(): number
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let cached: WorldTokenizer | undefined
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The package root, one level above both `src/` (pipeline imports the source)
|
|
26
|
+
* and `lib/index.js` (DSH loads the bundle), so `vendor/` resolves the same way
|
|
27
|
+
* in both.
|
|
28
|
+
*/
|
|
29
|
+
function load(): WorldTokenizer {
|
|
30
|
+
const require = createRequire(import.meta.url)
|
|
31
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
32
|
+
const module = require(join(root, 'vendor/rwkv-tokenizer/rwkv_tokenizer.js')) as {
|
|
33
|
+
WorldTokenizer: new () => WorldTokenizer
|
|
34
|
+
}
|
|
35
|
+
return new module.WorldTokenizer()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Exact number of RWKV World tokens `text` encodes to. */
|
|
39
|
+
export function countTokens(text: string): number {
|
|
40
|
+
cached ??= load()
|
|
41
|
+
return cached.encode(text).length
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Vocabulary size of the vendored tokenizer (65,530 = rwkv_vocab_v20230424). */
|
|
45
|
+
export function vocabSize(): number {
|
|
46
|
+
cached ??= load()
|
|
47
|
+
return cached.vocab_size()
|
|
48
|
+
}
|