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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/cordis.patch.yml +59 -0
  4. package/lib/client.js +3148 -0
  5. package/lib/client.js.map +7 -0
  6. package/lib/index.js +6294 -0
  7. package/lib/index.js.map +7 -0
  8. package/lib/line-edit.js +1423 -0
  9. package/lib/line-edit.js.map +7 -0
  10. package/lib/todo.js +610 -0
  11. package/lib/todo.js.map +7 -0
  12. package/package.json +72 -4
  13. package/scripts/build.mjs +77 -0
  14. package/scripts/headless.ts +279 -0
  15. package/scripts/link-dsh.sh +31 -0
  16. package/scripts/relay-e2e.mjs +157 -0
  17. package/scripts/smoke.ts +116 -0
  18. package/scripts/state.ts +39 -0
  19. package/scripts/tokenizer-parity.ts +107 -0
  20. package/scripts/trace-stats.ts +33 -0
  21. package/src/adapter.ts +388 -0
  22. package/src/backend/generator.ts +221 -0
  23. package/src/backend/irwkv.ts +117 -0
  24. package/src/backend/lightning.ts +228 -0
  25. package/src/backend/stream.ts +97 -0
  26. package/src/client/AdapterPicker.tsx +264 -0
  27. package/src/client/DeveloperPanel.tsx +403 -0
  28. package/src/client/FoldNode.tsx +82 -0
  29. package/src/client/ModelCard.tsx +230 -0
  30. package/src/client/RwkvSettings.tsx +265 -0
  31. package/src/client/Segment.tsx +15 -0
  32. package/src/client/StatePicker.tsx +248 -0
  33. package/src/client/TraceFrames.tsx +462 -0
  34. package/src/client/TraceView.tsx +77 -0
  35. package/src/client/WirePanel.tsx +566 -0
  36. package/src/client/fields.tsx +362 -0
  37. package/src/client/index.tsx +109 -0
  38. package/src/client/styles.ts +277 -0
  39. package/src/client/traces-api.ts +222 -0
  40. package/src/client/url.ts +20 -0
  41. package/src/core/agent.ts +586 -0
  42. package/src/core/defaults.ts +51 -0
  43. package/src/core/dsh-prompt.ts +32 -0
  44. package/src/core/edit-modes/index.ts +108 -0
  45. package/src/core/edit-modes/line-edit.ts +793 -0
  46. package/src/core/edit-modes/literal.ts +26 -0
  47. package/src/core/edit-modes/shared.ts +213 -0
  48. package/src/core/edit-modes/tolerant.ts +558 -0
  49. package/src/core/fold-pairs.ts +407 -0
  50. package/src/core/fold-window.ts +563 -0
  51. package/src/core/line-edit.ts +33 -0
  52. package/src/core/parse.ts +290 -0
  53. package/src/core/policy.ts +500 -0
  54. package/src/core/prompt.ts +220 -0
  55. package/src/core/relay.ts +400 -0
  56. package/src/core/step-gates.ts +371 -0
  57. package/src/core/time-zone.ts +32 -0
  58. package/src/core/todo-state.ts +227 -0
  59. package/src/core/tolerant-edit.ts +14 -0
  60. package/src/core/tool-mappings.ts +209 -0
  61. package/src/core/tool-repairs.ts +255 -0
  62. package/src/core/tools.ts +162 -0
  63. package/src/core/worklist.ts +606 -0
  64. package/src/dsh-host.ts +48 -0
  65. package/src/edit-modes/folded-read-guard.ts +32 -0
  66. package/src/edit-modes/index.ts +26 -0
  67. package/src/edit-modes/line-edit.ts +154 -0
  68. package/src/edit-modes/literal.ts +9 -0
  69. package/src/edit-modes/observations.ts +234 -0
  70. package/src/edit-modes/syntax-check.ts +226 -0
  71. package/src/edit-modes/tolerant.ts +232 -0
  72. package/src/folded-read-guard.ts +6 -0
  73. package/src/history.ts +163 -0
  74. package/src/index.ts +287 -0
  75. package/src/line-edit.ts +15 -0
  76. package/src/live-wire.ts +133 -0
  77. package/src/paths.ts +91 -0
  78. package/src/relay-store.ts +59 -0
  79. package/src/result-budget.ts +225 -0
  80. package/src/routes.ts +324 -0
  81. package/src/session-setup.ts +150 -0
  82. package/src/syntax-check.ts +2 -0
  83. package/src/todo.ts +328 -0
  84. package/src/tokenizer.ts +48 -0
  85. package/src/tolerant-edit.ts +2 -0
  86. package/src/trace-stats.ts +225 -0
  87. package/src/traces.ts +289 -0
  88. package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
  89. package/vendor/rwkv-tokenizer/package.json +5 -0
  90. package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
  91. package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
  92. package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/todo.ts", "../src/core/todo-state.ts", "../src/core/tool-mappings.ts", "../src/core/tool-repairs.ts", "../src/core/policy.ts"],
4
+ "sourcesContent": ["// DSH plugin `rwkv-todo`: registers `todo_plan` and `todo_update` (Stateful\n// Work List) for RWKV and teacher sessions.\n//\n// Why a separate tool plugin instead of DSH's stock `@deepseek-ai/dsh-tool-todo`:\n// 1. `todo_write` enforces `additionalProperties: false` on `{content, status}`,\n// and DSH's session-format validator rejects extra keys on `todo/write`\n// events, so `note` cannot be stored on `todo/write` directly.\n// 2. `todo_write` is whole-list replacement and returns only status counts\n// (`Updated todo list: ...`), never echoing the list back into context.\n// 3. Rewriting the whole list on every step wastes tokens and causes 7B models\n// to paraphrase or drop earlier line numbers/paths from `note`.\n//\n// `rwkv-todo` stores the full `{id, content, status, note}` state per turn in an\n// ignorable `plugin:rwkv-todo/state` session record (surviving process-per-turn\n// runners), echoes the full formatted list in every tool result, and mirrors a\n// valid `{content, status}` projection onto `todo/write` so DSH's native Desktop\n// TodoPanel renders live progress without modifying `deepseek-harness`.\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'\nimport { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'\nimport {\n applyTodoPlan,\n applyTodoUpdate,\n formatWorklist,\n isWorklistTool,\n normalizeWorklistStatus,\n projectNativeTodos,\n TODO_PLAN_TOOL,\n TODO_UPDATE_TOOL,\n type WorklistItem,\n type WorklistStatus,\n} from './core/worklist.ts'\nimport { TODO_PLAN_DESCRIPTION, TODO_UPDATE_DESCRIPTION } from './core/tools.ts'\n\nexport { TODO_PLAN_DESCRIPTION, TODO_UPDATE_DESCRIPTION }\n\nexport const name = 'rwkv-todo'\nexport const inject = ['tools']\n\nconst STATE_RECORD = 'plugin:rwkv-todo/state'\n\ninterface PersistedState {\n readonly turn: number\n readonly items: readonly WorklistItem[]\n readonly completed?: boolean\n}\n\ninterface SessionEventLike {\n readonly type?: string\n readonly data?: unknown\n}\n\ninterface SessionLike {\n snapshotEvents?(): readonly SessionEventLike[]\n append?(type: 'todo/write', data: { todos: { content: string; status: 'pending' | 'in_progress' | 'completed' }[] }): unknown\n}\n\ninterface ExecLike {\n readonly agent?: { readonly session?: SessionLike }\n}\n\ninterface ContextLike {\n readonly tools: { register(definition: unknown): () => void }\n on?(event: string, listener: (session: SessionLike, ev: SessionEventLike) => void): () => void\n}\n\nconst appendRecord = appendPluginRecord as unknown as (session: object, type: string, data: unknown) => unknown\nconst recordOf = pluginRecordOf as unknown as (event: unknown) => { type: string; data: unknown } | undefined\n\nconst VALID_STATUSES = new Set<string>(['pending', 'in_progress', 'completed', 'dropped'])\n\nexport { projectNativeTodos }\n\nfunction decodeItems(raw: unknown): WorklistItem[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const items: WorklistItem[] = []\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) return undefined\n const { id, content, status, note } = entry as Record<string, unknown>\n if (typeof id !== 'number' || !Number.isInteger(id) || id < 1) return undefined\n if (typeof content !== 'string' || content === '') return undefined\n if (typeof status !== 'string' || !VALID_STATUSES.has(status)) return undefined\n if (note !== undefined && typeof note !== 'string') return undefined\n items.push({\n id,\n content,\n status: status as WorklistStatus,\n ...(typeof note === 'string' && note !== '' ? { note } : {}),\n })\n }\n return items\n}\n\nfunction turnIndexOf(events: readonly SessionEventLike[] | undefined): number {\n if (events === undefined) return 1\n let turns = 0\n for (const event of events) {\n if (event.type === 'turn/start') turns++\n }\n return Math.max(1, turns)\n}\n\n/**\n * True when an earlier `todo_update` in the current turn already marked an item\n * `completed` and NO workspace tool (`read`, `edit_lines`, `write`, `bash`, ...)\n * has executed since then \u2014 preventing empty-window hallucinated closeouts.\n */\nexport function blockedBackToBackComplete(events: readonly SessionEventLike[] | undefined): boolean {\n if (events === undefined || events.length === 0) return false\n let skippedCurrentCall = false\n for (let i = events.length - 1; i >= 0; i--) {\n const ev = events[i]!\n if (ev.type === 'turn/start') return false\n if (ev.type === 'tool/call') {\n if (!skippedCurrentCall) {\n skippedCurrentCall = true\n continue\n }\n const toolName = typeof ev.data === 'object' && ev.data !== null\n ? (ev.data as { name?: unknown }).name\n : undefined\n if (typeof toolName === 'string' && !isWorklistTool(toolName) && toolName !== 'todo_write') {\n return false\n }\n continue\n }\n const rec = recordOf(ev)\n if (rec?.type === STATE_RECORD && typeof rec.data === 'object' && rec.data !== null) {\n if ((rec.data as { completed?: unknown }).completed === true) {\n return true\n }\n }\n }\n return false\n}\n\n/** One active worklist per agent session and user turn (\"one turn, one list\"). */\nclass WorklistStore {\n private readonly bySession = new WeakMap<object, { turn: number; items: WorklistItem[] }>()\n private readonly hydrated = new WeakSet<object>()\n private fallback: WorklistItem[] = []\n\n get(session: SessionLike | undefined): { turn: number; items: WorklistItem[] } {\n if (session === undefined) return { turn: 1, items: this.fallback }\n const events = session.snapshotEvents?.()\n const currentTurn = turnIndexOf(events)\n if (!this.hydrated.has(session)) {\n this.hydrated.add(session)\n let items: WorklistItem[] = []\n if (events !== undefined) {\n let logTurn = 0\n for (const event of events) {\n if (event.type === 'turn/start') {\n logTurn++\n items = []\n continue\n }\n const rec = recordOf(event)\n if (rec?.type !== STATE_RECORD || typeof rec.data !== 'object' || rec.data === null) continue\n const decoded = decodeItems((rec.data as { items?: unknown }).items)\n const recTurn = (rec.data as { turn?: unknown }).turn\n if (decoded !== undefined && (typeof recTurn !== 'number' || recTurn === Math.max(1, logTurn))) {\n items = decoded\n }\n }\n }\n const entry = { turn: currentTurn, items }\n this.bySession.set(session, entry)\n return entry\n }\n const existing = this.bySession.get(session)\n if (existing === undefined || existing.turn !== currentTurn) {\n const fresh = { turn: currentTurn, items: [] as WorklistItem[] }\n this.bySession.set(session, fresh)\n return fresh\n }\n return existing\n }\n\n save(session: SessionLike | undefined, turn: number, items: WorklistItem[], completed = false): void {\n if (session === undefined) {\n this.fallback = items\n return\n }\n this.bySession.set(session, { turn, items })\n const payload: PersistedState = { turn, items, ...(completed ? { completed: true } : {}) }\n try {\n appendRecord(session, STATE_RECORD, payload)\n } catch {\n // Outside a live DSH session store (unit tests): keep in memory.\n }\n // Mirror onto DSH's native `todo/write` projection so the Desktop TodoPanel\n // renders clean single-line checklist titles (`[id] title`, without stuffing\n // multi-line technical notes into the compact dock row).\n try {\n session.append?.('todo/write', { todos: projectNativeTodos(items) })\n } catch {\n // Ignore if session does not accept todo/write in minimal test harnesses.\n }\n }\n\n /**\n * Settle any lingering `in_progress` indicator in the Desktop `TodoPanel` once\n * `turn/end` commits so an unfinished item does not keep spinning while idle.\n */\n settleTurnEnd(session: SessionLike | undefined): void {\n if (session === undefined) return\n const { items } = this.get(session)\n if (!items.some(item => item.status === 'in_progress')) return\n try {\n session.append?.('todo/write', { todos: projectNativeTodos(items, { turnEnded: true }) })\n } catch {\n // Ignore if session rejects post-turn UI projection append.\n }\n }\n}\n\nconst STATUS_CN: Record<string, string> = {\n completed: '\u5DF2\u5B8C\u6210',\n in_progress: '\u8BB0\u5F55\u8FDB\u5C55',\n dropped: '\u5DF2\u8DF3\u8FC7',\n}\n\nexport function apply(ctx: Context): void {\n const host = ctx as unknown as ContextLike\n const store = new WorklistStore()\n\n host.on?.('session/event', (session, ev) => {\n if (ev?.type === 'turn/end') store.settleTurnEnd(session)\n })\n\n host.tools.register(defineTool({\n name: TODO_PLAN_TOOL,\n description: TODO_PLAN_DESCRIPTION,\n parameters: {\n items: {\n type: 'array',\n required: true,\n 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.',\n items: { type: 'string' },\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n summary: { type: 'string', required: true },\n },\n },\n render: (_args: unknown, value: { summary: string }) => [{ type: 'text', text: value.summary }],\n },\n execute(args: { items: string[] }, exec: ExecLike) {\n const session = exec.agent?.session\n const current = store.get(session)\n const updated = applyTodoPlan(current.items, args.items)\n if (typeof updated === 'string') throw new ToolArgsError([updated])\n store.save(session, current.turn, updated)\n return Promise.resolve({ summary: formatWorklist(updated) })\n },\n presentCall: (args: { items?: unknown }) => ({\n card: 'generic',\n title: `\u89C4\u5212\u5DE5\u5355\uFF08${Array.isArray(args.items) ? args.items.length : 0} \u9879\uFF09`,\n kind: 'other',\n rawInput: args.items,\n }),\n } as never))\n\n host.tools.register(defineTool({\n name: TODO_UPDATE_TOOL,\n description: TODO_UPDATE_DESCRIPTION,\n parameters: {\n id: {\n type: 'number',\n required: true,\n description: '1-based item number from the current todo list.',\n },\n status: {\n type: 'string',\n required: true,\n enum: ['in_progress', 'completed', 'dropped'],\n description: 'in_progress | completed | dropped. Marking completed or dropped automatically sets the next pending item to in_progress.',\n },\n note: {\n type: 'string',\n 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.',\n },\n content: {\n type: 'string',\n description: 'Optional refined title for this item if the initial wording was inaccurate.',\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n summary: { type: 'string', required: true },\n },\n },\n render: (_args: unknown, value: { summary: string }) => [{ type: 'text', text: value.summary }],\n },\n execute(args: { id: number; status: string; note?: string; content?: string }, exec: ExecLike) {\n const session = exec.agent?.session\n const statusNorm = normalizeWorklistStatus(args.status)\n if (statusNorm === 'completed' && blockedBackToBackComplete(session?.snapshotEvents?.())) {\n throw new ToolArgsError([\n '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\".',\n ])\n }\n const current = store.get(session)\n const updated = applyTodoUpdate(current.items, args)\n if (typeof updated === 'string') throw new ToolArgsError([updated])\n store.save(session, current.turn, updated.items, statusNorm === 'completed')\n return Promise.resolve({ summary: formatWorklist(updated.items) })\n },\n presentCall: (args: Record<string, unknown>) => {\n const st = typeof args.status === 'string' ? (STATUS_CN[args.status] ?? args.status) : '\u66F4\u65B0'\n return {\n card: 'generic',\n title: `\u66F4\u65B0\u5DE5\u5355 #${String(args.id ?? '?')} \u00B7 ${st}`,\n kind: 'other',\n rawInput: args,\n }\n },\n } as never))\n}\n", "// Active stateful work list (`todo_plan` + `todo_update`): tool definitions,\n// lenient field parsing, per-turn item state transitions, and Desktop\n// `TodoPanel` projection. Kept separate from the passive/checkpoint folding\n// engine (`fold-pairs.ts`, `fold-window.ts`, `worklist.ts`).\n\nexport const TODO_PLAN_TOOL = 'todo_plan'\nexport const TODO_UPDATE_TOOL = 'todo_update'\n\nexport const TODO_PLAN_DESCRIPTION =\n 'Create or revise the ordered work list for multi-step tasks (touching multiple methods/files, code + docs/tests, or 3+ distinct subgoals). '\n + 'Skip this tool for casual chat, quick single-goal lookups (1-3 reads or searches), or a trivial one-spot edit. '\n + '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 \u2014 do not wait until after editing to plan. '\n + 'Calling todo_plan mid-turn keeps completed/dropped items and their notes intact and replaces only unfinished items.'\n\nexport const TODO_UPDATE_DESCRIPTION =\n 'Update one item in the current work list by id. '\n + '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 \u2014 never mark unexecuted work completed). '\n + '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. '\n + 'The next pending item becomes in_progress automatically; you may also checkpoint an in_progress item with an interim note before context fills up.'\n\nexport const WORKLIST_TOOLS: ReadonlySet<string> = new Set([TODO_PLAN_TOOL, TODO_UPDATE_TOOL])\n\nexport function isWorklistTool(name: string): boolean {\n return WORKLIST_TOOLS.has(name)\n}\n\nexport type WorklistStatus = 'pending' | 'in_progress' | 'completed' | 'dropped'\n\nexport interface WorklistItem {\n readonly id: number\n readonly content: string\n readonly status: WorklistStatus\n readonly note?: string\n}\n\nexport interface TodoUpdateInput {\n readonly id?: unknown\n readonly status?: unknown\n readonly note?: unknown\n readonly content?: unknown\n}\n\nconst WORKLIST_PROTOCOL_TAG = /<\\/?(?:think|tool_call|tool_response)(?:\\s[^>]*)?>/gi\nconst WORKLIST_LEADING_BULLET = /^\\s*(?:\\[\\d+\\]|\\d+[.)]|[-*\u2022])\\s*/\n\nexport function sanitizeWorklistField(text: string): string {\n return text.replace(WORKLIST_PROTOCOL_TAG, '').replace(/\\s*\\n+\\s*/g, ' | ').trim()\n}\n\nexport function parsePlanItems(raw: unknown): string[] | undefined {\n if (Array.isArray(raw)) {\n const out: string[] = []\n for (const entry of raw) {\n if (typeof entry === 'string') {\n const cleaned = sanitizeWorklistField(entry.replace(WORKLIST_LEADING_BULLET, ''))\n if (cleaned !== '') out.push(cleaned)\n } else if (typeof entry === 'object' && entry !== null) {\n const obj = entry as Record<string, unknown>\n const candidate = obj.content ?? obj.title ?? obj.text ?? obj.step\n if (typeof candidate === 'string') {\n const cleaned = sanitizeWorklistField(candidate.replace(WORKLIST_LEADING_BULLET, ''))\n if (cleaned !== '') out.push(cleaned)\n }\n } else {\n return undefined\n }\n }\n return out\n }\n if (typeof raw === 'string') {\n const lines = raw\n .split(/\\r?\\n/)\n .map(line => sanitizeWorklistField(line.replace(WORKLIST_LEADING_BULLET, '')))\n .filter(line => line !== '')\n return lines.length > 0 ? lines : undefined\n }\n return undefined\n}\n\nexport function normalizeWorklistStatus(raw: unknown): WorklistStatus | undefined {\n if (typeof raw !== 'string') return undefined\n const lower = raw.trim().toLowerCase()\n if (lower === 'pending' || lower === 'todo' || lower === 'not_started') return 'pending'\n if (lower === 'in_progress' || lower === 'in-progress' || lower === 'doing' || lower === 'active') return 'in_progress'\n if (lower === 'completed' || lower === 'complete' || lower === 'done' || lower === 'finished') return 'completed'\n if (lower === 'dropped' || lower === 'cancelled' || lower === 'canceled' || lower === 'skipped') return 'dropped'\n return undefined\n}\n\n/** Whether `item` is a `todo_update` call that wrote a non-empty `note`. */\nexport function isNotedTodoUpdateCall(item: { readonly kind: string; readonly name?: string; readonly args?: Record<string, unknown> }): boolean {\n if (item.kind !== 'call' || item.name !== TODO_UPDATE_TOOL || item.args === undefined) return false\n const note = item.args.note ?? item.args.notes ?? item.args.summary ?? item.args.findings ?? item.args.conclusion\n return typeof note === 'string' && sanitizeWorklistField(note) !== ''\n}\n\n/**\n * Apply `todo_plan` to the current turn's list. Completed and dropped items\n * (and their notes) are locked and kept at the top; `rawItems` replaces only\n * the remaining unfinished queue, activating the first unfinished item.\n */\nexport function applyTodoPlan(current: readonly WorklistItem[], rawItems: unknown): WorklistItem[] | string {\n const parsed = parsePlanItems(rawItems)\n if (parsed === undefined || parsed.length === 0) {\n return 'items must be a non-empty array of step strings'\n }\n const locked = current\n .filter(item => item.status === 'completed' || item.status === 'dropped')\n .map((item, idx) => ({ ...item, id: idx + 1 }))\n const lockedTitles = new Set(locked.map(item => item.content))\n // If the model re-sent already completed titles at the top of `items`, skip\n // duplicating them because `locked` already preserves them with their notes.\n const remaining = parsed.filter(title => !lockedTitles.has(title))\n if (locked.length === 0 && remaining.length < 2) {\n return 'todo_plan requires at least 2 steps; execute single-step tasks directly without todo_plan'\n }\n if (remaining.length === 0) {\n return 'todo_plan requires at least 1 new unfinished step after completed items'\n }\n if (locked.length + remaining.length > 12) {\n return `todo_plan accepts at most 12 total items (got ${locked.length + remaining.length}); group micro-actions into coarser subgoals`\n }\n const seen = new Set<string>()\n for (const [idx, title] of remaining.entries()) {\n if (seen.has(title)) {\n return `items[${idx}] duplicates ${JSON.stringify(title)}`\n }\n seen.add(title)\n }\n const tail: WorklistItem[] = remaining.map((content, idx) => ({\n id: locked.length + idx + 1,\n content,\n status: idx === 0 ? 'in_progress' : 'pending',\n }))\n return [...locked, ...tail]\n}\n\n/**\n * Apply `todo_update` to one item by 1-based `id`. Requires a non-empty `note`\n * when closing an item (`completed` or `dropped`), keeps at most one item\n * `in_progress`, and automatically advances the next `pending` item when the\n * active item finishes.\n */\nexport function applyTodoUpdate(\n current: readonly WorklistItem[],\n input: TodoUpdateInput,\n): { items: WorklistItem[]; noted: boolean } | string {\n if (current.length === 0) {\n return 'no active todo list in this turn; call todo_plan first if this task has multiple subgoals'\n }\n const rawId = typeof input.id === 'string' ? Number(input.id.trim()) : input.id\n if (typeof rawId !== 'number' || !Number.isInteger(rawId) || rawId < 1 || rawId > current.length) {\n return `id must be an integer between 1 and ${current.length} (got ${JSON.stringify(input.id)})`\n }\n const status = normalizeWorklistStatus(input.status)\n if (status === undefined || status === 'pending') {\n return 'status must be one of: in_progress, completed, dropped'\n }\n const target = current[rawId - 1]!\n const providedNote = typeof input.note === 'string' ? sanitizeWorklistField(input.note) : ''\n const effectiveNote = providedNote !== '' ? providedNote : target.note\n if ((status === 'completed' || status === 'dropped') && (!effectiveNote || effectiveNote === '')) {\n return 'note is required when status is completed or dropped: record concrete findings, exact file paths/lines, applied edits, or test results'\n }\n const updatedContent = typeof input.content === 'string' && sanitizeWorklistField(input.content) !== ''\n ? sanitizeWorklistField(input.content)\n : target.content\n\n const next = current.map((item, index): WorklistItem => {\n if (index === rawId - 1) {\n return {\n id: item.id,\n content: updatedContent,\n status,\n ...effectiveNote ? { note: effectiveNote } : {},\n }\n }\n // Single-active discipline: focusing a later item auto-completes an earlier\n // active item that already recorded a note, and demotes an unnoted/later one.\n if (status === 'in_progress' && item.status === 'in_progress') {\n const autoDone = index < rawId - 1 && Boolean(item.note && item.note.trim() !== '')\n return { ...item, status: autoDone ? 'completed' : 'pending' }\n }\n return item\n })\n\n // Auto-advance: when no item is active anymore, promote the next pending item.\n if (!next.some(item => item.status === 'in_progress')) {\n const afterIdx = next.findIndex((item, idx) => idx > rawId - 1 && item.status === 'pending')\n const promoteIdx = afterIdx >= 0 ? afterIdx : next.findIndex(item => item.status === 'pending')\n if (promoteIdx >= 0) {\n next[promoteIdx] = { ...next[promoteIdx]!, status: 'in_progress' }\n }\n }\n\n return { items: next, noted: providedNote !== '' }\n}\n\n/** Model-facing rendering returned as the tool output of `todo_plan` and `todo_update`. */\nexport function formatWorklist(items: readonly WorklistItem[]): string {\n const lines = ['Todo list:']\n for (const item of items) {\n lines.push(`[${item.id}] (${item.status}) ${item.content}`)\n if (item.note) lines.push(` note: ${item.note}`)\n }\n return lines.join('\\n')\n}\n\n/**\n * Clean single-line projection mirrored onto DSH's native `todo/write` event for\n * the Desktop `TodoPanel` dock (omits long technical notes, and settles lingering\n * `in_progress` spinners to `pending` once `turn/end` fires).\n */\nexport function projectNativeTodos(\n items: readonly WorklistItem[],\n options?: { readonly turnEnded?: boolean },\n): { content: string; status: 'pending' | 'in_progress' | 'completed' }[] {\n const settleActive = options?.turnEnded === true\n return items.map(item => ({\n content: item.status === 'dropped'\n ? `[${item.id}] [\u5DF2\u8DF3\u8FC7] ${item.content}`\n : `[${item.id}] ${item.content}`,\n status: item.status === 'dropped'\n ? 'completed'\n : (settleActive && item.status === 'in_progress' ? 'pending' : item.status),\n }))\n}\n", "// Built-in RWKV <-> DSH tool mappings (`agent-tool-v3` wire shapes and\n// bidirectional argument converters).\n\nimport {\n normalizeWorklistStatus,\n parsePlanItems,\n TODO_PLAN_DESCRIPTION,\n TODO_PLAN_TOOL,\n TODO_UPDATE_DESCRIPTION,\n TODO_UPDATE_TOOL,\n} from './todo-state.ts'\n\nexport interface DshToolSchema {\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n}\n\nexport type Args = Record<string, unknown>\n\nexport interface WireTool {\n /** Name the model sees and calls. */\n readonly name: string\n readonly description: string\n /** Flat placeholder JSON object (or JSON string) shown in the catalog. */\n readonly arguments: string\n /** DSH tool that executes the call. */\n readonly dshName: string\n /** JSON Schema used for lenient scalar coercion of model arguments. */\n readonly schema?: Record<string, unknown>\n /** Shown under its DSH name with DSH arguments (names: 'dsh'). */\n readonly native?: boolean\n toDsh(args: Args): Args\n fromDsh(args: Args): Args\n}\n\nexport interface ToolMapping {\n readonly wireName: string\n readonly description: string\n readonly arguments: string\n readonly schema: Record<string, unknown>\n toDsh(args: Args): Args\n fromDsh(args: Args): Args\n}\n\nexport const nonEmptyStr = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() !== '' ? value : undefined\n\nexport const finiteInt = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined\n\nfunction stripUndefined(args: Args): Args {\n return Object.fromEntries(Object.entries(args).filter(([, value]) => value !== undefined))\n}\n\n/** Workspace-relative path; models trained on a sandbox emit /workspace/... and fabricated home paths. */\nexport function workspacePath(value: unknown): string | undefined {\n const path = nonEmptyStr(value)\n if (path === undefined) return undefined\n const index = path.lastIndexOf('workspace/')\n if (path.startsWith('/') && index >= 0) return path.slice(index + 'workspace/'.length) || '.'\n if (path === '/workspace') return '.'\n return path\n}\n\nfunction escapeRegex(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction unescapeRegex(text: string): string {\n return text.replace(/\\\\([.*+?^${}()|[\\]\\\\])/g, '$1')\n}\n\n/**\n * Built-in mappings keyed by DSH tool name. Descriptions and placeholders are\n * the agent-tool-v3 strings the RWKV-Agent corpora were rendered with.\n */\nexport const BUILTIN_MAPPINGS: Readonly<Record<string, ToolMapping>> = {\n read: {\n wireName: 'read_file',\n description: 'Read a UTF-8 text file in the workspace. Lines come numbered. Without start_line/end_line it returns the start of the file.',\n arguments: '{\"path\":\"relative file path\",\"start_line\":\"optional integer >= 1\",\"end_line\":\"optional integer >= start_line\"}',\n schema: { properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' } } },\n toDsh(args) {\n const start = finiteInt(args.start_line)\n const end = finiteInt(args.end_line)\n return stripUndefined({\n file_path: workspacePath(args.path),\n offset: start,\n limit: end !== undefined ? Math.max(1, end - (start ?? 1) + 1) : undefined,\n })\n },\n fromDsh(args) {\n const offset = finiteInt(args.offset)\n const limit = finiteInt(args.limit)\n return stripUndefined({\n path: args.file_path,\n start_line: offset,\n end_line: limit !== undefined ? (offset ?? 1) + limit - 1 : undefined,\n })\n },\n },\n write: {\n wireName: 'write_file',\n description: 'Create or overwrite a workspace text file with the given content. The content becomes the whole file.',\n arguments: '{\"path\":\"relative file path\",\"content\":\"full file content\"}',\n schema: { properties: { path: { type: 'string' }, content: { type: 'string' } } },\n toDsh: args => ({ file_path: workspacePath(args.path), content: args.content ?? '' }),\n fromDsh: args => ({ path: args.file_path, content: args.content }),\n },\n edit: {\n wireName: 'edit_file',\n description: 'Replace one exact piece of text in a workspace text file. old_text must appear exactly once; copy it from read_file without the line numbers.',\n arguments: '{\"path\":\"relative file path\",\"old_text\":\"exact text to replace\",\"new_text\":\"replacement text\"}',\n schema: { properties: { path: { type: 'string' }, old_text: { type: 'string' }, new_text: { type: 'string' } } },\n toDsh: args => ({ file_path: workspacePath(args.path), old_string: args.old_text ?? '', new_string: args.new_text ?? '' }),\n fromDsh: args => ({ path: args.file_path, old_text: args.old_string, new_text: args.new_string }),\n },\n // Line-range edit (src/line-edit.ts); offered only where that plugin is mounted.\n edit_lines: {\n wireName: 'edit_lines',\n description: 'Replace a range of lines in a workspace text file, numbered as read_file shows them. end_line = start_line - 1 inserts before start_line.',\n arguments: '{\"path\":\"relative file path\",\"start_line\":\"first line to replace\",\"end_line\":\"last line to replace\",\"new_text\":\"replacement lines without line numbers\"}',\n schema: { properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' }, new_text: { type: 'string' } } },\n toDsh: args => ({ file_path: workspacePath(args.path), start_line: args.start_line, end_line: args.end_line, new_text: args.new_text ?? '' }),\n fromDsh: args => ({ path: args.file_path, start_line: args.start_line, end_line: args.end_line, new_text: args.new_text }),\n },\n glob: {\n wireName: 'list_files',\n description: 'List files below a workspace-relative path.',\n arguments: '{\"path\":\"optional relative directory\",\"pattern\":\"optional glob such as *.ts\"}',\n schema: { properties: { path: { type: 'string' }, pattern: { type: 'string' } } },\n toDsh: args => stripUndefined({ pattern: nonEmptyStr(args.pattern) ?? '*', path: workspacePath(args.path) }),\n fromDsh: args => stripUndefined({ path: args.path, pattern: args.pattern === '*' ? undefined : args.pattern }),\n },\n grep: {\n wireName: 'search_text',\n description: 'Search literal text in workspace files. Returns matching lines with line numbers.',\n arguments: '{\"query\":\"literal text\",\"path\":\"optional relative path\"}',\n schema: { properties: { query: { type: 'string' }, path: { type: 'string' } } },\n toDsh: args => stripUndefined({ pattern: escapeRegex(String(args.query ?? '')), path: workspacePath(args.path) }),\n fromDsh: args => stripUndefined({ query: unescapeRegex(String(args.pattern ?? '')), path: args.path }),\n },\n bash: {\n wireName: 'bash',\n description: 'Run a bash command in the workspace and return stdout and stderr. Each call starts in the workspace and does not keep cd or variables from earlier calls.',\n arguments: '{\"command\":\"bash command line\"}',\n schema: { properties: { command: { type: 'string' } } },\n toDsh(args) {\n const command = String(args.command ?? '')\n const firstLine = command.split('\\n')[0] ?? ''\n return { description: firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || 'Run command', command }\n },\n fromDsh: args => ({ command: args.command }),\n },\n web_search: {\n wireName: 'web_search',\n description: 'Search the public web and return titles, URLs, snippets, and source IDs.',\n arguments: '{\"query\":\"search query\"}',\n schema: { properties: { query: { type: 'string' } } },\n toDsh: args => ({ queries: [String(args.query ?? '')] }),\n fromDsh: args => ({ query: Array.isArray(args.queries) ? args.queries.join(' ') : args.queries }),\n },\n web_fetch: {\n wireName: 'web_fetch',\n description: 'Fetch the readable content of one public web page.',\n arguments: '{\"url\":\"https://example.com/page\"}',\n schema: { properties: { url: { type: 'string' } } },\n toDsh(args) {\n const url = nonEmptyStr(args.url) ?? (Array.isArray(args.urls) ? nonEmptyStr(args.urls[0]) : undefined)\n return { url: url ?? '' }\n },\n fromDsh: args => ({ url: args.url }),\n },\n // Stateful work list (src/todo.ts); offered when historyMode === 'worklist'.\n [TODO_PLAN_TOOL]: {\n wireName: TODO_PLAN_TOOL,\n description: TODO_PLAN_DESCRIPTION,\n arguments: '{\"items\":\"array of string\"}',\n schema: { properties: { items: { type: 'array', items: { type: 'string' } } } },\n toDsh: args => ({ items: parsePlanItems(args.items) ?? args.items }),\n fromDsh: args => ({ items: args.items }),\n },\n [TODO_UPDATE_TOOL]: {\n wireName: TODO_UPDATE_TOOL,\n description: TODO_UPDATE_DESCRIPTION,\n arguments: '{\"id\":\"integer\",\"status\":\"in_progress|completed|dropped\",\"note\":\"optional Concrete findings, exact file paths/lines, applied edits, or test outcomes\",\"content\":\"optional Refined title for this item if the initial wording was inaccurate\"}',\n schema: {\n properties: {\n id: { type: 'integer' },\n status: { type: 'string', enum: ['in_progress', 'completed', 'dropped'] },\n note: { type: 'string' },\n content: { type: 'string' },\n },\n },\n toDsh: args => stripUndefined({\n id: finiteInt(typeof args.id === 'string' ? Number(args.id.trim()) : args.id) ?? args.id,\n status: normalizeWorklistStatus(args.status) ?? args.status,\n note: nonEmptyStr(args.note),\n content: nonEmptyStr(args.content),\n }),\n fromDsh: args => stripUndefined({\n id: args.id,\n status: args.status,\n note: args.note,\n content: args.content,\n }),\n },\n}\n", "// Lenient tool-name resolution, argument key aliases, scalar coercion, and\n// DSH native value shape repairs for 7B outputs.\n\nimport { editLinesAliasesFor } from './edit-modes/index.ts'\nimport { normalizeLineEditArgs } from './edit-modes/line-edit.ts'\nimport {\n normalizeWorklistStatus,\n parsePlanItems,\n TODO_PLAN_TOOL,\n TODO_UPDATE_TOOL,\n} from './todo-state.ts'\nimport { BUILTIN_MAPPINGS, finiteInt, nonEmptyStr, type Args, type WireTool } from './tool-mappings.ts'\n\n/**\n * Other names the model uses for the wire tools: DSH's own names, Claude Code\n * / OpenAI-agent habits, and capitalised forms (\"Bash\"). Matched after an\n * exact, then a case-insensitive, lookup fails.\n */\nconst TOOL_NAME_ALIASES: Readonly<Record<string, string>> = {\n read: 'read_file', view: 'read_file', cat: 'read_file', open_file: 'read_file',\n write: 'write_file', create_file: 'write_file', save_file: 'write_file',\n edit: 'edit_file', str_replace: 'edit_file', replace: 'edit_file', replace_in_file: 'edit_file',\n glob: 'list_files', ls: 'list_files', list_dir: 'list_files', list_directory: 'list_files',\n grep: 'search_text', search: 'search_text', search_files: 'search_text',\n shell: 'bash', run: 'bash', terminal: 'bash', execute_command: 'bash', run_command: 'bash',\n fetch: 'web_fetch', webfetch: 'web_fetch', search_web: 'web_search', websearch: 'web_search',\n worklist_plan: TODO_PLAN_TOOL, plan_todo: TODO_PLAN_TOOL,\n worklist_update: TODO_UPDATE_TOOL, update_todo: TODO_UPDATE_TOOL,\n}\n\n/** The offered tool a model-written name refers to, and whether an alias was needed. */\nexport function resolveTool(tools: readonly WireTool[], name: string): { tool: WireTool; aliased: boolean } | undefined {\n const exact = tools.find(tool => tool.name === name)\n if (exact) return { tool: exact, aliased: false }\n const lower = name.trim().toLowerCase().replace(/^functions\\./, '')\n const target = tools.find(tool => tool.name.toLowerCase() === lower)\n ?? tools.find(tool => tool.name === TOOL_NAME_ALIASES[lower])\n ?? tools.find(tool => tool.dshName.toLowerCase() === lower)\n // DSH-named catalog: the trained names (read_file, ...) and their aliases.\n ?? tools.find(tool => BUILTIN_MAPPINGS[tool.dshName]?.wireName === (TOOL_NAME_ALIASES[lower] ?? lower))\n // Cross-harness compatibility: when `edit_lines` replaces `edit`, route `edit`/`edit_file` calls to `edit_lines`.\n ?? ((lower === 'edit' || lower === 'edit_file' || TOOL_NAME_ALIASES[lower] === 'edit_file')\n ? tools.find(tool => tool.dshName === 'edit_lines')\n : undefined)\n return target ? { tool: target, aliased: true } : undefined\n}\n\nconst PATH_ALIASES = ['file_path', 'filepath', 'file', 'filename', 'file_name']\nconst NATIVE_PATH_ALIASES = ['path', 'filepath', 'file', 'filename', 'file_name']\n\n/** Canonical argument key -> other keys the model writes for it, per wire tool. */\nconst ARGUMENT_ALIASES: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>> = {\n read_file: { path: PATH_ALIASES, start_line: ['line_start', 'from_line'], end_line: ['line_end', 'to_line'] },\n write_file: { path: PATH_ALIASES, content: ['text', 'file_text', 'contents', 'data', 'code'] },\n edit_file: {\n path: PATH_ALIASES,\n old_text: ['old_string', 'old_str', 'old', 'search', 'find', 'original'],\n new_text: ['new_string', 'new_str', 'new', 'replace', 'replacement', 'updated'],\n },\n edit_lines: {\n path: PATH_ALIASES,\n start_line: ['line_start', 'from_line', 'start', 'line'],\n end_line: ['line_end', 'to_line', 'end'],\n new_text: ['new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],\n },\n list_files: { path: ['directory', 'dir', 'folder', 'dir_path'], pattern: ['glob'] },\n search_text: { query: ['pattern', 'text', 'search', 'keyword', 'regex'], path: ['file_path', 'directory', 'dir'] },\n bash: { command: ['cmd', 'script', 'code', 'shell'] },\n web_fetch: { url: ['link', 'href', 'page'] },\n web_search: { query: ['q', 'keywords', 'search', 'search_query'] },\n [TODO_PLAN_TOOL]: { items: ['todos', 'tasks', 'steps', 'plan'] },\n [TODO_UPDATE_TOOL]: {\n id: ['index', 'item_id', 'task_id', 'step'],\n note: ['notes', 'summary', 'finding', 'findings', 'conclusion', 'result'],\n content: ['title', 'task', 'text', 'description'],\n },\n}\n\n/** The same table for DSH-named tools: trained and Claude-style keys -> DSH keys. */\nconst NATIVE_ARGUMENT_ALIASES: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>> = {\n read: { file_path: NATIVE_PATH_ALIASES, offset: ['start_line', 'line_start', 'from_line'] },\n write: { file_path: NATIVE_PATH_ALIASES, content: ['text', 'file_text', 'contents', 'data', 'code'] },\n edit: {\n file_path: NATIVE_PATH_ALIASES,\n old_string: ['old_text', 'old_str', 'old', 'search', 'find', 'original'],\n new_string: ['new_text', 'new_str', 'new', 'replace', 'replacement', 'updated'],\n },\n edit_lines: {\n file_path: NATIVE_PATH_ALIASES,\n start_line: ['line_start', 'from_line', 'start', 'line', 'offset'],\n end_line: ['line_end', 'to_line', 'end'],\n new_text: ['new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],\n },\n glob: { pattern: ['glob'], path: ['directory', 'dir', 'folder', 'dir_path'] },\n grep: { pattern: ['query', 'text', 'search', 'keyword', 'regex'], path: ['file_path', 'directory', 'dir'] },\n bash: { command: ['cmd', 'script', 'code', 'shell'] },\n web_fetch: { url: ['link', 'href', 'page'] },\n web_search: { queries: ['query', 'q', 'keywords', 'search', 'search_query'] },\n [TODO_PLAN_TOOL]: ARGUMENT_ALIASES[TODO_PLAN_TOOL]!,\n [TODO_UPDATE_TOOL]: ARGUMENT_ALIASES[TODO_UPDATE_TOOL]!,\n}\n\nfunction renameAliases(args: Args, aliases: Readonly<Record<string, readonly string[]>>): Args | undefined {\n let out: Args | undefined\n for (const [canonical, others] of Object.entries(aliases)) {\n if (args[canonical] !== undefined && args[canonical] !== '') continue\n const found = others.find(key => args[key] !== undefined && args[key] !== '')\n if (found === undefined) continue\n out ??= { ...args }\n out[canonical] = args[found]\n delete out[found]\n }\n return out\n}\n\nconst looseInt = (value: unknown) => finiteInt(typeof value === 'string' ? Number(value.trim()) : value)\n\n/** DSH-named tools: alias keys, end_line -> limit, a lone query string -> queries, a bash description. */\nfunction normalizeNativeArguments(tool: WireTool, args: Args): Args {\n const aliases = tool.dshName === 'edit_lines'\n ? editLinesAliasesFor({ native: true })\n : NATIVE_ARGUMENT_ALIASES[tool.dshName]\n if (aliases === undefined) return args\n let out = renameAliases(args, aliases)\n const current = out ?? args\n if (tool.dshName === 'edit_lines' && current.edits !== undefined) {\n out = normalizeLineEditArgs(current)\n }\n if (tool.dshName === 'read' && current.end_line !== undefined) {\n const start = looseInt(current.offset) ?? 1\n const end = looseInt(current.end_line)\n out ??= { ...args }\n delete out.end_line\n if (end !== undefined && current.limit === undefined) out.limit = Math.max(1, end - start + 1)\n }\n if (tool.dshName === 'web_search' && typeof current.queries === 'string') {\n out ??= { ...args }\n out.queries = [current.queries]\n }\n if (tool.dshName === 'bash' && nonEmptyStr(current.description) === undefined && nonEmptyStr(current.command) !== undefined) {\n const firstLine = String(current.command).split('\\n')[0] ?? ''\n out ??= { ...args }\n out.description = firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine\n }\n return out ?? args\n}\n\n/**\n * Renames alias keys to the tool's own keys when the own key is absent\n * (edit_file with Claude's old_string/new_string, read_file with file_path,\n * ...). read_file's DSH-style offset/limit become start_line/end_line.\n * Returns the args unchanged (same object) when nothing applied.\n */\nexport function normalizeArguments(tool: WireTool, args: Args): Args {\n if (tool.native === true) return normalizeNativeArguments(tool, args)\n const aliases = tool.name === 'edit_lines'\n ? editLinesAliasesFor({ native: false })\n : ARGUMENT_ALIASES[tool.name]\n if (aliases === undefined) return args\n let out = renameAliases(args, aliases)\n if (tool.name === 'edit_lines' && (out ?? args).edits !== undefined) {\n out = normalizeLineEditArgs(out ?? args)\n }\n if (tool.name === 'read_file' && args.start_line === undefined && args.offset !== undefined) {\n const start = looseInt(args.offset)\n const limit = looseInt(args.limit)\n out ??= { ...args }\n delete out.offset\n delete out.limit\n if (start !== undefined) out.start_line = start\n if (start !== undefined && limit !== undefined) out.end_line = start + limit - 1\n }\n return out ?? args\n}\n\n/**\n * Lenient scalars: \"10\" for an integer, \"true\" for a boolean, \"6,412\" with\n * thousands separators. Structural mismatches are left for the tool to reject.\n */\nexport function coerceArguments(args: Args, schema: Record<string, unknown> | undefined): Args {\n const properties = (schema?.properties ?? {}) as Record<string, Record<string, unknown>>\n const result: Args = {}\n for (const [key, value] of Object.entries(args)) {\n const type = properties[key]?.type\n if (value === null) continue\n if ((type === 'integer' || type === 'number') && typeof value === 'string') {\n const parsed = Number(value.replace(/,/g, '').trim())\n result[key] = value.trim() !== '' && Number.isFinite(parsed) ? parsed : value\n } else if (type === 'boolean' && typeof value === 'string' && /^(true|false)$/i.test(value.trim())) {\n result[key] = value.trim().toLowerCase() === 'true'\n } else if (type === 'string' && (typeof value === 'number' || typeof value === 'boolean')) {\n result[key] = String(value)\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n/**\n * DSH-named tools, after scalar coercion: value shapes 7B writes from other\n * harnesses' habits that DSH would reject. Keys outside the DSH schema\n * (Claude Code's grep output_mode, ...) are dropped; glob without a pattern\n * (list_files{path}) lists everything; read offset 0 (0-based habit) is line 1;\n * a pattern array becomes one pattern. The same object when nothing applied.\n */\nexport function repairNativeValues(tool: WireTool, args: Args): { args: Args; repairs: string[] } {\n if (tool.native !== true || tool.schema === undefined) return { args, repairs: [] }\n const properties = (tool.schema.properties ?? {}) as Record<string, unknown>\n const repairs: string[] = []\n let out: Args | undefined\n const edit = () => (out ??= { ...args })\n const unknown = Object.keys(args).filter(key => !(key in properties))\n if (unknown.length > 0) {\n for (const key of unknown) delete edit()[key]\n repairs.push('unknown_arguments_dropped')\n }\n const current = () => out ?? args\n if ((tool.dshName === 'grep' || tool.dshName === 'glob') && Array.isArray(current().pattern)) {\n const parts = (current().pattern as unknown[]).filter((part): part is string => typeof part === 'string' && part !== '')\n if (parts.length > 0) {\n edit().pattern = tool.dshName === 'grep' ? parts.join('|') : parts[0]\n repairs.push('pattern_array')\n }\n }\n if (tool.dshName === 'glob' && nonEmptyStr(current().pattern) === undefined) {\n edit().pattern = '*'\n repairs.push('glob_default_pattern')\n }\n if (tool.dshName === 'read') {\n for (const key of ['offset', 'limit']) {\n const value = current()[key]\n if (typeof value === 'number' && value < 1) {\n if (key === 'offset') edit().offset = 1\n else delete edit().limit\n repairs.push(`${key}_below_one`)\n }\n }\n }\n if (tool.dshName === TODO_PLAN_TOOL && current().items !== undefined) {\n const parsed = parsePlanItems(current().items)\n if (parsed !== undefined && JSON.stringify(parsed) !== JSON.stringify(current().items)) {\n edit().items = parsed\n repairs.push('plan_items_coerced')\n }\n }\n if (tool.dshName === TODO_UPDATE_TOOL && typeof current().status === 'string') {\n const normalized = normalizeWorklistStatus(current().status)\n if (normalized !== undefined && normalized !== current().status) {\n edit().status = normalized\n repairs.push('worklist_status_alias')\n }\n }\n return { args: out ?? args, repairs }\n}\n", "// Harness feedback text and per-turn state, ported from RWKV-Agent\n// internal/agent (runner_policy.go, runner_config.go, protocol_g1.go,\n// runner_turn.go, runner_answer_fallback.go). DSH executes the tools and keeps\n// the history, so the turn state is rebuilt from that history on every request.\n\nimport { FOLDED_OUTPUT_MARKER } from './defaults.ts'\nimport { cleanFinalText, type ParseErrorKind } from './parse.ts'\nimport { recordToolCall, toolResponse, type Entry } from './prompt.ts'\nimport type { Args, WireTool } from './tools.ts'\n\nexport type HistoryItem =\n | { readonly kind: 'user'; readonly text: string }\n | { readonly kind: 'note'; readonly text: string }\n | { readonly kind: 'assistant'; readonly text: string; readonly reasoning?: string }\n | { readonly kind: 'call'; readonly id: string; readonly name: string; readonly args: Args; readonly reasoning?: string }\n | { readonly kind: 'result'; readonly id: string; readonly name: string; readonly ok: boolean; readonly text: string }\n\nexport const POST_TOOL_REMINDER = `Use the Tool results above to continue the current task.\nIf the evidence is sufficient, answer now. Call another tool only for a specific missing fact.\nNever repeat a successful tool call. Do not open a <think> block or repeat the Tool payload.`\n\n/** nudge=think (agent-wire-think-v1.0): the reminder that does not forbid thinking. */\nexport const POST_TOOL_REMINDER_THINK = POST_TOOL_REMINDER.replace(\n 'Do not open a <think> block or repeat the Tool payload.',\n 'Do not repeat the Tool payload.',\n)\n\nexport const DUPLICATE_ANSWER_REMINDER = `That tool call was rejected because it repeats a successful call.\nAnswer the current task from the evidence already collected.`\n\nexport const DUPLICATE_FAILED_REMINDER = `That tool call was rejected because it repeats an earlier failed call.\nTools are now unavailable. Answer from the Tool results, and clearly state anything that could not be verified.`\n\nexport const NOOP_EDIT_REMINDER = 'That edit call was rejected because old_string and new_string are identical, so the file would not change. '\n + 'Provide the actual target text to change, or if the edits are already complete, answer the user directly.'\n\nexport const DUPLICATE_FAILED_RETRY_REMINDER = 'That tool call was rejected because it repeats an earlier failed call with the exact same arguments. '\n + 'Do not repeat the same call. Inspect the previous error and change the arguments, try a different tool, or answer directly.'\n\n/** harness v26: the first repeat of a successful call gets one more decision with an edit hint. */\nexport function duplicateRetryReminder(tools: readonly WireTool[]): string {\n let prompt = 'That tool call was rejected because it repeats a successful call; its result is already above. Do not call it again.\\n'\n const edits = ['edit', 'edit_lines', 'write'].flatMap(dsh => tools.filter(tool => tool.dshName === dsh).map(tool => tool.name))\n if (edits.length > 0) {\n prompt += `If the task asks to change a file you have already read, make the change now with ${edits.join(' or ')}, using the text already shown.\\n`\n }\n return `${prompt}If one specific fact is still missing, call a tool with different arguments. Otherwise answer now.`\n}\n\n/** Keyed by DSH tool name; the hint names the tools as the catalog shows them. */\nconst FAILURE_HINTS: Record<string, { companions: string[]; hint: (names: Record<string, string>) => string }> = {\n read: {\n companions: ['read', 'glob', 'grep'],\n hint: n => `If the path is uncertain, use ${n.glob} or ${n.grep} before another ${n.read} call. `,\n },\n glob: {\n companions: ['grep'],\n hint: n => `Try an existing parent directory or workspace root, or use ${n.grep} for a known literal. `,\n },\n}\n\nexport function toolFailureReminder(name: string, error: string, recoveryBlocked: boolean, tools: readonly WireTool[]): string {\n const summary = oneLine(error)\n if (/already applied|no edit needed/i.test(summary)) {\n return `${summary} Do not repeat this edit. Continue with any remaining changes, or answer the user directly if all work is done.`\n }\n let prompt = `The tool call failed: ${summary}. `\n prompt += recoveryBlocked ? 'Do not call the same tool again in this turn. ' : 'Do not repeat the same call. '\n const failed = tools.find(tool => tool.name === name)\n const entry = failed === undefined ? undefined : FAILURE_HINTS[failed.dshName]\n const names: Record<string, string> = Object.fromEntries(tools.map(tool => [tool.dshName, tool.name]))\n if (entry && entry.companions.every(companion => names[companion] !== undefined)) prompt += entry.hint(names)\n return `${prompt}Choose a different useful tool or answer with the limitation. Do not guess.`\n}\n\nexport function oneStageAnswerInstruction(): string {\n return `Tool execution is complete and tools are now unavailable.\nAnswer the original current task directly in ordinary text using the Tool results above. Do not call another tool or repeat the Tool results. If they are insufficient, say what could not be verified.`\n}\n\nexport const ANSWER_STAGE_REASK = 'Answer the original current task in ordinary Markdown NOW using the Function outputs above. This is your final answer; tool calls are forbidden.'\n\nexport const EMPTY_EXIT_REASK = 'The no_tool decision with empty arguments was accepted. No tool will be executed. '\n + 'No user-facing reason or answer was provided, and no tool evidence exists. '\n + 'Answer the original current task directly in ordinary Markdown now. '\n + 'Do not output another function call or repeat the no_tool action.'\n\nexport function correction(kind: ParseErrorKind): string {\n const action = 'Either answer directly in ordinary text, or output exactly one '\n + '<tool_call>{\"name\":\"...\",\"arguments\":{...}}</tool_call> and nothing else.'\n switch (kind) {\n case 'unclosed-think':\n return 'Your previous reasoning never finished and was cut off. Do not restart it. '\n + `Close the thinking block with </think> immediately, then ${action} `\n + 'Decide with the evidence you already have instead of reasoning further.'\n case 'length':\n return `Your previous response was cut off by the output limit. Be far more concise. Skip preamble and restated reasoning, then ${action}`\n default:\n return `Your previous response was invalid. ${action}`\n }\n}\n\nexport function isChinese(text: string): boolean {\n return /\\p{Script=Han}/u.test(text)\n}\n\n/** Prose opening prefilled for the last answer generation; a continuation mid-sentence rarely becomes a call. */\nexport function answerOpener(task: string): string {\n return isChinese(task) ? '\u6839\u636E\u4E0A\u9762\u7684\u5DE5\u5177\u7ED3\u679C\uFF0C' : 'Based on the tool results above,'\n}\n\nconst PLANNING_MARKERS = ['\u8BA9\u6211', '\u6211\u9700\u8981', '\u6211\u5C06', '\u6211\u4F1A\u518D', '\u63A5\u4E0B\u6765', '\u518D\u641C', '\u518D\u67E5', 'let me', 'i need to', 'i will', 'i\\'ll', 'next,']\n\nexport function hasPlanningMarker(text: string): boolean {\n const lower = text.trim().toLowerCase()\n return PLANNING_MARKERS.some(marker => lower.includes(marker))\n}\n\n/** Prose written before a tool frame, when it is a real answer and not a plan. */\nexport function salvageAnswerProse(output: string, opener = ''): string {\n let text = output\n const think = text.lastIndexOf('</think>')\n if (think >= 0) text = text.slice(think + '</think>'.length)\n const frame = text.toLowerCase().indexOf('<tool_call')\n if (frame >= 0) text = text.slice(0, frame)\n text = text.trim()\n const rest = text.startsWith(opener) ? text.slice(opener.length).trim() : text\n if ([...rest].length < 8) return ''\n const lower = rest.toLowerCase()\n return PLANNING_MARKERS.some(marker => lower.includes(marker)) ? '' : text\n}\n\n/** Extracts text inside the last closed <think>...</think> block, stripping any stray tool frames. */\nexport function extractThinkInner(output: string): string {\n const close = output.lastIndexOf('</think>')\n if (close < 0) return ''\n const open = output.lastIndexOf('<think>', close)\n if (open < 0) return ''\n let inner = output.slice(open + '<think>'.length, close)\n const frame = inner.toLowerCase().indexOf('<tool_call')\n if (frame >= 0) inner = inner.slice(0, frame)\n return inner.trim()\n}\n\n/**\n * Stronger last-resort extraction for `fallbackSummary: false`: tries `salvageAnswerProse`\n * first, then any post-think non-frame prose across attempts, and finally the clearest\n * inner reasoning so deduced facts survive instead of \"I looked up...\".\n */\nexport function salvageLastResortAnswer(outputs: readonly string[], opener = ''): string {\n for (let index = outputs.length - 1; index >= 0; index--) {\n const salvaged = salvageAnswerProse(outputs[index]!, opener)\n if (salvaged !== '') return salvaged\n }\n for (let index = outputs.length - 1; index >= 0; index--) {\n let text = outputs[index]!\n const think = text.lastIndexOf('</think>')\n if (think >= 0) text = text.slice(think + '</think>'.length)\n const frame = text.toLowerCase().indexOf('<tool_call')\n if (frame >= 0) text = text.slice(0, frame)\n text = cleanFinalText(text.replace(/<\\/?think>/g, ''))\n if ([...text].length >= 4) return text\n }\n for (let index = outputs.length - 1; index >= 0; index--) {\n const inner = cleanFinalText(extractThinkInner(outputs[index]!))\n if ([...inner].length >= 4) return inner\n }\n return ''\n}\n\n/** Harness-written last resort: what was looked up and how it went; it never claims a fact. */\nexport function answerFallbackSummary(task: string, results: readonly TurnResult[]): string {\n const zh = isChinese(task)\n const lines = results.map(result => {\n const outcome = result.ok ? (zh ? '\u6210\u529F' : 'succeeded') : (zh ? '\u5931\u8D25' : 'failed')\n return `- ${result.name}: ${outcome}`\n })\n const gotContent = results.some(result => result.ok)\n if (zh) {\n const head = lines.length > 0 ? `\u8FD9\u6B21\u6211\u505A\u4E86\u8FD9\u4E9B\u67E5\u8BE2\uFF1A\\n${lines.join('\\n')}\\n\\n` : ''\n return head + (gotContent\n ? '\u5DE5\u5177\u8FD4\u56DE\u4E86\u4E00\u4E9B\u5185\u5BB9\uFF0C\u4F46\u8FD9\u6B21\u6CA1\u80FD\u6574\u7406\u6210\u7B54\u6848\u3002\u53EF\u4EE5\u8BA9\u6211\u518D\u8BD5\u4E00\u6B21\u3002'\n : '\u6CA1\u6709\u627E\u5230\u80FD\u56DE\u7B54\u8FD9\u4E2A\u95EE\u9898\u7684\u5185\u5BB9\u3002\u53EF\u4EE5\u6362\u4E2A\u8BF4\u6CD5\uFF0C\u6216\u8005\u544A\u8BC9\u6211\u5177\u4F53\u8981\u67E5\u7684\u6587\u4EF6\u6216\u7F51\u5740\u3002')\n }\n const head = lines.length > 0 ? `I looked up:\\n${lines.join('\\n')}\\n\\n` : ''\n return head + (gotContent\n ? 'The tools returned some content, but I could not turn it into an answer this time. You can ask me to try again.'\n : 'Nothing I found answers the question. You can rephrase it, or give me a specific URL or file to check.')\n}\n\nfunction oneLine(text: string): string {\n const line = text.trim().replace(/\\s+/g, ' ')\n return line.length > 300 ? `${line.slice(0, 297)}...` : line\n}\n\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonical)\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical((value as Args)[key])]))\n }\n return value\n}\n\nexport function callKey(name: string, args: Args): string {\n return `${name}\\u0000${JSON.stringify(canonical(args))}`\n}\n\n/** Tools that change workspace files, under their trained and DSH names. */\nconst FILE_WRITERS = new Set(['edit_file', 'write_file', 'edit', 'edit_lines', 'write'])\n\n/**\n * Shell commands that look like they change files or the environment: an\n * output redirect (not to /dev/null, not an fd duplication such as 2>&1), an\n * in-place sed, tee, file operations, git operations that touch the tree, and\n * package installs. A false positive only lets one more repeat through.\n */\nconst SHELL_WRITE = new RegExp([\n String.raw`(?<![<>&=-])\\d?>>?(?![>&=])\\s*(?!/dev/null\\b)[^\\s&|;)]`,\n String.raw`\\bsed\\s+(?:-[a-zA-Z]*\\s+)*-[a-zA-Z]*i`,\n String.raw`\\b(?:tee|mv|cp|rm|rmdir|touch|mkdir|chmod|ln|patch|truncate|unzip|tar)\\b`,\n String.raw`\\bgit\\s+(?:apply|checkout|restore|reset|commit|merge|rebase|stash|am|cherry-pick|add|rm|mv)\\b`,\n String.raw`\\b(?:pip3?|npm|pnpm|yarn|uv|cargo|go)\\s+(?:install|add|get)\\b`,\n].join('|'))\n\n/**\n * A call that may change what a later read or test run sees: an edit or write\n * of a file, or a shell command matching {@link SHELL_WRITE}.\n */\nexport function targetFileSuffix(_name: string, args: Args): string {\n const raw = typeof args.file_path === 'string' ? args.file_path : typeof args.path === 'string' ? args.path : ''\n return raw.replace(/\\\\/g, '/').replace(/^\\.\\//, '').replace(/\\/+$/, '')\n}\n\nexport function sameTargetFile(a: string, b: string): boolean {\n return a !== '' && b !== '' && (a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`))\n}\n\nexport function isMutatingCall(name: string, args: Args): boolean {\n if (FILE_WRITERS.has(name)) return true\n return name === 'bash' && typeof args.command === 'string' && SHELL_WRITE.test(args.command)\n}\n\nexport interface TurnResult {\n readonly name: string\n readonly ok: boolean\n}\n\nexport interface TurnState {\n /** The current turn's user request, for language choices. */\n readonly task: string\n /** Workspace tool calls DSH executed in the current turn (excludes worklist bookkeeping). */\n readonly steps: number\n /** Consecutive worklist calls (`todo_plan`/`todo_update`) since the last workspace call. */\n readonly consecutiveWorklistCalls: number\n readonly results: readonly TurnResult[]\n readonly successfulCalls: number\n /**\n * Successful calls since the latest successful mutating call (that call\n * included): rereading a file or rerunning a test after a change is not a\n * repeat, but repeating the change itself, or any call since, still is.\n */\n readonly successKeys: ReadonlySet<string>\n /** Failed call key \u2192 successful-call count when it failed (no success since = same epoch). */\n readonly failedEpochs: ReadonlyMap<string, number>\n /** Canonical key of the immediately preceding non-bookkeeping workspace call in this gate window. */\n readonly lastCallKey: string\n /** Whether that immediately preceding workspace call succeeded. */\n readonly lastCallOk: boolean\n /** Count of each non-bookkeeping call key executed in the active epoch/window. */\n readonly epochKeyCounts: ReadonlyMap<string, number>\n /** Consecutive/current failed edits per target file path until a succeeding write/edit resets it. */\n readonly perFileFailedEdits: ReadonlyMap<string, number>\n readonly consecutiveFailedTool: string\n readonly consecutiveFailures: number\n}\n\nconst BOOKKEEPING_TOOLS = new Set(['todo_plan', 'todo_update'])\n\nexport function currentTurnStart(history: readonly HistoryItem[]): number {\n for (let index = history.length - 1; index >= 0; index--) {\n if (history[index]!.kind === 'user') return index\n }\n return 0\n}\n\nexport interface TurnOptions {\n /**\n * First history item whose calls take part in the duplicate and failure\n * gates. The relay and worklist modes reset them at each cut/checkpoint:\n * earlier raw file reads were folded out, so re-reading a file slice after a\n * cut is not a repeated call. Workspace steps still count from the user\n * turn's start, so maxSteps is unchanged.\n */\n readonly duplicateFrom?: number\n /**\n * Tool-call IDs whose corresponding result was masked in-place in the active\n * window (`auto-fold v2`). Re-reading an in-place-masked file is allowed,\n * while unmasked short results keep duplicate-call protection.\n */\n readonly maskedCallIds?: ReadonlySet<string>\n}\n\nexport function analyzeTurn(history: readonly HistoryItem[], options: TurnOptions = {}): TurnState {\n const start = currentTurnStart(history)\n const gateStart = Math.max(start, options.duplicateFrom ?? start)\n const first = history[start]\n const calls = new Map<string, { name: string; key: string; mutating: boolean; file: string }>()\n const successKeys = new Set<string>()\n const failedEpochs = new Map<string, number>()\n const failedEditFiles = new Map<string, string>()\n const epochKeyCounts = new Map<string, number>()\n const readKeys = new Map<string, string>()\n const perFileFailedEdits = new Map<string, number>()\n const results: TurnResult[] = []\n let workspaceSteps = 0\n let consecutiveWorklistCalls = 0\n let successfulCalls = 0\n let lastCallKey = ''\n let lastCallOk = false\n let consecutiveFailedTool = ''\n let consecutiveFailures = 0\n const READ_TOOLS = new Set(['read', 'read_file'])\n const EDIT_FAIL_TRACKERS = new Set(['edit', 'edit_file', 'edit_lines', 'write', 'write_file'])\n for (let index = start; index < history.length; index++) {\n const item = history[index]!\n if (item.kind === 'call') {\n calls.set(item.id, {\n name: item.name,\n key: callKey(item.name, item.args),\n mutating: isMutatingCall(item.name, item.args),\n file: targetFileSuffix(item.name, item.args),\n })\n }\n if (item.kind !== 'result') continue\n const { name: calledName, key, mutating, file } = calls.get(item.id) ?? {\n name: item.name,\n key: callKey(item.name, {}),\n mutating: false,\n file: '',\n }\n results.push({ name: item.name, ok: item.ok })\n const isBookkeeping = BOOKKEEPING_TOOLS.has(calledName) || BOOKKEEPING_TOOLS.has(item.name)\n if (isBookkeeping) {\n consecutiveWorklistCalls++\n } else {\n workspaceSteps++\n consecutiveWorklistCalls = 0\n }\n if (index < gateStart) continue\n if (item.ok) {\n if (mutating) {\n successKeys.clear()\n epochKeyCounts.clear()\n readKeys.clear()\n failedEditFiles.clear()\n }\n if (READ_TOOLS.has(calledName) && file !== '') {\n // Re-reading file F unlocks retrying an edit on F that was previously blocked\n // (e.g. by folded-read-guard after cross-turn auto-fold).\n for (const [ek, ef] of [...failedEditFiles.entries()]) {\n if (sameTargetFile(ef, file)) {\n epochKeyCounts.delete(ek)\n failedEpochs.delete(ek)\n failedEditFiles.delete(ek)\n if (lastCallKey === ek) lastCallKey = ''\n }\n }\n }\n if (EDIT_FAIL_TRACKERS.has(calledName) && file !== '') {\n for (const tracked of [...perFileFailedEdits.keys()]) {\n if (sameTargetFile(tracked, file)) perFileFailedEdits.delete(tracked)\n }\n }\n const maskedInPlace = item.text.startsWith(FOLDED_OUTPUT_MARKER) || (options.maskedCallIds?.has(item.id) ?? false)\n if (!maskedInPlace) {\n successKeys.add(key)\n if (!isBookkeeping) {\n epochKeyCounts.set(key, (epochKeyCounts.get(key) ?? 0) + 1)\n if (READ_TOOLS.has(calledName)) readKeys.set(key, file)\n }\n }\n if (!isBookkeeping) {\n lastCallKey = maskedInPlace ? '' : key\n lastCallOk = true\n }\n failedEpochs.delete(key)\n failedEditFiles.delete(key)\n successfulCalls++\n consecutiveFailedTool = ''\n consecutiveFailures = 0\n } else {\n failedEpochs.set(key, successfulCalls)\n if (!isBookkeeping) {\n epochKeyCounts.set(key, (epochKeyCounts.get(key) ?? 0) + 1)\n lastCallKey = key\n lastCallOk = false\n }\n if (EDIT_FAIL_TRACKERS.has(calledName) && file !== '') {\n failedEditFiles.set(key, file)\n const isFoldedGuardBlock = /folded out of the active context window|has not been read/i.test(item.text)\n if (!isFoldedGuardBlock) {\n perFileFailedEdits.set(file, (perFileFailedEdits.get(file) ?? 0) + 1)\n }\n for (const [rk, rf] of [...readKeys.entries()]) {\n if (sameTargetFile(rf, file)) {\n epochKeyCounts.delete(rk)\n readKeys.delete(rk)\n }\n }\n }\n if (item.name === consecutiveFailedTool) consecutiveFailures++\n else {\n consecutiveFailedTool = item.name\n consecutiveFailures = 1\n }\n }\n }\n return {\n task: first?.kind === 'user' ? first.text : '',\n steps: workspaceSteps,\n consecutiveWorklistCalls,\n results,\n successfulCalls,\n successKeys,\n failedEpochs,\n lastCallKey,\n lastCallOk,\n epochKeyCounts,\n perFileFailedEdits,\n consecutiveFailedTool,\n consecutiveFailures,\n }\n}\n\nexport const analyseHistory = analyzeTurn\n\nexport interface TranscriptOptions {\n readonly tools: readonly WireTool[]\n readonly postToolReminder: string\n /**\n * Add the per-step reminders after results of the current turn. Off for a\n * recap request: it is not a step, and the model that writes the card must\n * see the same bytes the teacher and the export rebuild.\n */\n readonly reminders?: boolean\n /**\n * Legacy: cut results longer than this when rendering. Live sessions are cut\n * once, when the tool runs (src/result-budget.ts), so the plugin leaves this\n * unset; only the pipeline sets it, to render data recorded before that.\n */\n readonly maxResultChars?: number\n}\n\n/**\n * Legacy prompt-time cut (head 80%, tail 20%, no saved copy), for rendering\n * data recorded before the execution-time budget (src/result-budget.ts).\n */\nexport function truncateResult(text: string, maxChars: number | undefined): string {\n if (maxChars === undefined || maxChars <= 0 || text.length <= maxChars) return text\n const head = Math.floor(maxChars * 0.8)\n const tail = maxChars - head\n return `${text.slice(0, head)}\\n\u2026(${text.length - maxChars} characters omitted)\u2026\\n${text.slice(text.length - tail)}`\n}\n\n/**\n * Transcript entries for the history. Earlier turns keep their calls, results\n * and answers; the per-step reminders exist only in the current turn, as the\n * Go runner commits a turn without them.\n */\nexport function transcriptEntries(history: readonly HistoryItem[], options: TranscriptOptions): Entry[] {\n const start = currentTurnStart(history)\n const entries: Entry[] = []\n history.forEach((item, index) => {\n const current = index >= start\n switch (item.kind) {\n case 'user':\n case 'note':\n entries.push({ role: 'user', text: item.text })\n break\n case 'assistant':\n entries.push({ role: 'assistant', text: item.text, ...(item.reasoning ? { reasoning: item.reasoning } : {}) })\n break\n case 'call':\n entries.push({ role: 'assistant', text: recordToolCall(item.name, item.args), ...(item.reasoning ? { reasoning: item.reasoning } : {}) })\n break\n case 'result': {\n const body = truncateResult(item.text, options.maxResultChars)\n entries.push({ role: 'user', text: toolResponse(item.name, item.ok, body) })\n if (!current || options.reminders === false) break\n if (item.ok) {\n if (options.postToolReminder) entries.push({ role: 'user', text: options.postToolReminder })\n } else {\n entries.push({ role: 'user', text: toolFailureReminder(item.name, item.text, false, options.tools) })\n }\n break\n }\n }\n })\n return entries\n}\n"],
5
+ "mappings": ";AAmBA,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY,qBAAqB;;;ACfnC,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAEzB,IAAM,wBACX;AAKK,IAAM,0BACX;AAKK,IAAM,iBAAsC,oBAAI,IAAI,CAAC,gBAAgB,gBAAgB,CAAC;AAEtF,SAAS,eAAeA,OAAuB;AACpD,SAAO,eAAe,IAAIA,KAAI;AAChC;AAkBA,IAAM,wBAAwB;AAC9B,IAAM,0BAA0B;AAEzB,SAAS,sBAAsB,MAAsB;AAC1D,SAAO,KAAK,QAAQ,uBAAuB,EAAE,EAAE,QAAQ,cAAc,KAAK,EAAE,KAAK;AACnF;AAEO,SAAS,eAAe,KAAoC;AACjE,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,IAChG;AAAA,IACA,QAAQ,MAAuE,MAAgB;AAC7F,YAAM,UAAU,KAAK,OAAO;AAC5B,YAAM,aAAa,wBAAwB,KAAK,MAAM;AACtD,UAAI,eAAe,eAAe,0BAA0B,SAAS,iBAAiB,CAAC,GAAG;AACxF,cAAM,IAAI,cAAc;AAAA,UACtB;AAAA,QACF,CAAC;AAAA,MACH;AACA,YAAM,UAAU,MAAM,IAAI,OAAO;AACjC,YAAM,UAAU,gBAAgB,QAAQ,OAAO,IAAI;AACnD,UAAI,OAAO,YAAY,SAAU,OAAM,IAAI,cAAc,CAAC,OAAO,CAAC;AAClE,YAAM,KAAK,SAAS,QAAQ,MAAM,QAAQ,OAAO,eAAe,WAAW;AAC3E,aAAO,QAAQ,QAAQ,EAAE,SAAS,eAAe,QAAQ,KAAK,EAAE,CAAC;AAAA,IACnE;AAAA,IACA,aAAa,CAAC,SAAkC;AAC9C,YAAM,KAAK,OAAO,KAAK,WAAW,WAAY,UAAU,KAAK,MAAM,KAAK,KAAK,SAAU;AACvF,aAAO;AAAA,QACL,MAAM;AAAA,QACN,OAAO,6BAAS,OAAO,KAAK,MAAM,GAAG,CAAC,SAAM,EAAE;AAAA,QAC9C,MAAM;AAAA,QACN,UAAU;AAAA,MACZ;AAAA,IACF;AAAA,EACF,CAAU,CAAC;AACb;",
6
+ "names": ["name"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "dsh-rwkv-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "description": "RWKV-7 G1 continuation models as a DeepSeek Harness LLM provider, with the RWKV-Agent harness (agent-wire XML, parser repairs, duplicate/closeout policy) ported in.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/No-22-Github/dsh-rwkv-plugin.git"
9
+ },
10
+ "homepage": "https://github.com/No-22-Github/dsh-rwkv-plugin#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/No-22-Github/dsh-rwkv-plugin/issues"
13
+ },
14
+ "keywords": [
15
+ "rwkv",
16
+ "rwkv-7",
17
+ "deepseek-harness",
18
+ "dsh",
19
+ "dsh-plugin",
20
+ "llm",
21
+ "agent"
22
+ ],
23
+ "type": "module",
24
+ "main": "lib/index.js",
25
+ "files": [
26
+ "lib",
27
+ "src",
28
+ "scripts",
29
+ "vendor",
30
+ "cordis.patch.yml"
31
+ ],
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "prepublishOnly": "npm run build",
35
+ "typecheck": "../deepseek-harness/node_modules/.bin/tsc --noEmit",
36
+ "test": "node --test test/*.test.ts",
37
+ "smoke": "node scripts/smoke.ts",
38
+ "state": "node scripts/state.ts",
39
+ "headless": "node scripts/headless.ts"
40
+ },
41
+ "engines": {
42
+ "node": ">=24.9.0",
43
+ "dsh": ">=0.2.2-alpha.3 <0.3.0"
44
+ },
45
+ "dsh": {
46
+ "bundle": {
47
+ "patch": "./cordis.patch.yml"
48
+ },
49
+ "client": {
50
+ "platform": "web",
51
+ "inject": [
52
+ "@deepseek-ai/dsh-client-ui-settings"
53
+ ]
54
+ }
55
+ },
56
+ "peerDependencies": {
57
+ "@deepseek-ai/cordis": "*",
58
+ "@deepseek-ai/dsh-brand": "*",
59
+ "@deepseek-ai/dsh-llm": "*",
60
+ "@deepseek-ai/dsh-session": "*",
61
+ "@deepseek-ai/dsh-tools": "*",
62
+ "@deepseek-ai/schemastery": "*"
63
+ },
64
+ "exports": {
65
+ ".": "./lib/index.js",
66
+ "./line-edit": "./lib/line-edit.js",
67
+ "./todo": "./lib/todo.js",
68
+ "./client": "./lib/client.js",
69
+ "./package.json": "./package.json"
70
+ },
71
+ "devDependencies": {
72
+ "esbuild": "^0.28.2"
73
+ }
74
+ }
@@ -0,0 +1,77 @@
1
+ // Builds both halves into lib/:
2
+ // lib/index.js Host half (ESM). Profile installs live under node_modules,
3
+ // where Node refuses to strip TypeScript, so DSH loads this
4
+ // JS. @deepseek-ai/* stay external: the profile resolves them
5
+ // to the running DSH's own copies.
6
+ // lib/client.js Browser half in the lazy-CJS factory format the DSH client
7
+ // module system loads:
8
+ // window.__ModuleLoader__.load({ id, factory: (require) => { ...; return module.exports } })
9
+ // Only react is shared from the page's module table.
10
+ // esbuild comes from the DSH checkout (DSH_ROOT, default ../deepseek-harness)
11
+ // or from this package's own devDependencies.
12
+
13
+ import { createRequire } from 'node:module'
14
+ import { readFileSync } from 'node:fs'
15
+ import { dirname, join, resolve } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+
18
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
19
+ const dshRoot = resolve(process.env.DSH_ROOT ?? join(root, '../deepseek-harness'))
20
+
21
+ function loadEsbuild() {
22
+ for (const base of [join(root, 'package.json'), join(dshRoot, 'package.json')]) {
23
+ const require = createRequire(base)
24
+ try {
25
+ return require('esbuild')
26
+ } catch {
27
+ try {
28
+ return createRequire(require.resolve('tsdown/package.json'))('esbuild')
29
+ } catch {
30
+ // Try the next location.
31
+ }
32
+ }
33
+ }
34
+ throw new Error('esbuild not found: run `npm install` here, or set DSH_ROOT to a DSH checkout')
35
+ }
36
+
37
+ const esbuild = loadEsbuild()
38
+ const { name } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
39
+ const only = process.argv[2]
40
+
41
+ if (only !== 'client') {
42
+ await esbuild.build({
43
+ // index: the provider; line-edit / todo: tool plugins (mounted separately).
44
+ entryPoints: {
45
+ index: join(root, 'src/index.ts'),
46
+ 'line-edit': join(root, 'src/line-edit.ts'),
47
+ todo: join(root, 'src/todo.ts'),
48
+ },
49
+ outdir: join(root, 'lib'),
50
+ bundle: true,
51
+ format: 'esm',
52
+ platform: 'node',
53
+ target: 'node22',
54
+ packages: 'external',
55
+ sourcemap: 'linked',
56
+ legalComments: 'none',
57
+ logLevel: 'info',
58
+ })
59
+ }
60
+
61
+ if (only !== 'host') {
62
+ await esbuild.build({
63
+ entryPoints: [join(root, 'src/client/index.tsx')],
64
+ outfile: join(root, 'lib/client.js'),
65
+ bundle: true,
66
+ format: 'cjs',
67
+ platform: 'browser',
68
+ target: 'es2022',
69
+ jsx: 'automatic',
70
+ external: ['react', 'react/jsx-runtime', 'react-dom', '@deepseek-ai/cordis'],
71
+ sourcemap: 'linked',
72
+ legalComments: 'none',
73
+ banner: { js: `window.__ModuleLoader__.load({ id: ${JSON.stringify(name)}, factory: (require) => {\nvar module = { exports: {} }; var exports = module.exports;` },
74
+ footer: { js: 'return module.exports; } });' },
75
+ logLevel: 'info',
76
+ })
77
+ }