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
package/lib/todo.js ADDED
@@ -0,0 +1,610 @@
1
+ // src/todo.ts
2
+ import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
3
+ import { defineTool, ToolArgsError } from "@deepseek-ai/dsh-tools";
4
+
5
+ // src/core/todo-state.ts
6
+ var TODO_PLAN_TOOL = "todo_plan";
7
+ var TODO_UPDATE_TOOL = "todo_update";
8
+ var TODO_PLAN_DESCRIPTION = "Create or revise the ordered work list for multi-step tasks (touching multiple methods/files, code + docs/tests, or 3+ distinct subgoals). Skip this tool for casual chat, quick single-goal lookups (1-3 reads or searches), or a trivial one-spot edit. 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. Calling todo_plan mid-turn keeps completed/dropped items and their notes intact and replaces only unfinished items.";
9
+ var TODO_UPDATE_DESCRIPTION = "Update one item in the current work list by id. 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). 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. The next pending item becomes in_progress automatically; you may also checkpoint an in_progress item with an interim note before context fills up.";
10
+ var WORKLIST_TOOLS = /* @__PURE__ */ new Set([TODO_PLAN_TOOL, TODO_UPDATE_TOOL]);
11
+ function isWorklistTool(name2) {
12
+ return WORKLIST_TOOLS.has(name2);
13
+ }
14
+ var WORKLIST_PROTOCOL_TAG = /<\/?(?:think|tool_call|tool_response)(?:\s[^>]*)?>/gi;
15
+ var WORKLIST_LEADING_BULLET = /^\s*(?:\[\d+\]|\d+[.)]|[-*•])\s*/;
16
+ function sanitizeWorklistField(text) {
17
+ return text.replace(WORKLIST_PROTOCOL_TAG, "").replace(/\s*\n+\s*/g, " | ").trim();
18
+ }
19
+ function parsePlanItems(raw) {
20
+ if (Array.isArray(raw)) {
21
+ const out = [];
22
+ for (const entry of raw) {
23
+ if (typeof entry === "string") {
24
+ const cleaned = sanitizeWorklistField(entry.replace(WORKLIST_LEADING_BULLET, ""));
25
+ if (cleaned !== "") out.push(cleaned);
26
+ } else if (typeof entry === "object" && entry !== null) {
27
+ const obj = entry;
28
+ const candidate = obj.content ?? obj.title ?? obj.text ?? obj.step;
29
+ if (typeof candidate === "string") {
30
+ const cleaned = sanitizeWorklistField(candidate.replace(WORKLIST_LEADING_BULLET, ""));
31
+ if (cleaned !== "") out.push(cleaned);
32
+ }
33
+ } else {
34
+ return void 0;
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ if (typeof raw === "string") {
40
+ const lines = raw.split(/\r?\n/).map((line) => sanitizeWorklistField(line.replace(WORKLIST_LEADING_BULLET, ""))).filter((line) => line !== "");
41
+ return lines.length > 0 ? lines : void 0;
42
+ }
43
+ return void 0;
44
+ }
45
+ function normalizeWorklistStatus(raw) {
46
+ if (typeof raw !== "string") return void 0;
47
+ const lower = raw.trim().toLowerCase();
48
+ if (lower === "pending" || lower === "todo" || lower === "not_started") return "pending";
49
+ if (lower === "in_progress" || lower === "in-progress" || lower === "doing" || lower === "active") return "in_progress";
50
+ if (lower === "completed" || lower === "complete" || lower === "done" || lower === "finished") return "completed";
51
+ if (lower === "dropped" || lower === "cancelled" || lower === "canceled" || lower === "skipped") return "dropped";
52
+ return void 0;
53
+ }
54
+ function applyTodoPlan(current, rawItems) {
55
+ const parsed = parsePlanItems(rawItems);
56
+ if (parsed === void 0 || parsed.length === 0) {
57
+ return "items must be a non-empty array of step strings";
58
+ }
59
+ const locked = current.filter((item) => item.status === "completed" || item.status === "dropped").map((item, idx) => ({ ...item, id: idx + 1 }));
60
+ const lockedTitles = new Set(locked.map((item) => item.content));
61
+ const remaining = parsed.filter((title) => !lockedTitles.has(title));
62
+ if (locked.length === 0 && remaining.length < 2) {
63
+ return "todo_plan requires at least 2 steps; execute single-step tasks directly without todo_plan";
64
+ }
65
+ if (remaining.length === 0) {
66
+ return "todo_plan requires at least 1 new unfinished step after completed items";
67
+ }
68
+ if (locked.length + remaining.length > 12) {
69
+ return `todo_plan accepts at most 12 total items (got ${locked.length + remaining.length}); group micro-actions into coarser subgoals`;
70
+ }
71
+ const seen = /* @__PURE__ */ new Set();
72
+ for (const [idx, title] of remaining.entries()) {
73
+ if (seen.has(title)) {
74
+ return `items[${idx}] duplicates ${JSON.stringify(title)}`;
75
+ }
76
+ seen.add(title);
77
+ }
78
+ const tail = remaining.map((content, idx) => ({
79
+ id: locked.length + idx + 1,
80
+ content,
81
+ status: idx === 0 ? "in_progress" : "pending"
82
+ }));
83
+ return [...locked, ...tail];
84
+ }
85
+ function applyTodoUpdate(current, input) {
86
+ if (current.length === 0) {
87
+ return "no active todo list in this turn; call todo_plan first if this task has multiple subgoals";
88
+ }
89
+ const rawId = typeof input.id === "string" ? Number(input.id.trim()) : input.id;
90
+ if (typeof rawId !== "number" || !Number.isInteger(rawId) || rawId < 1 || rawId > current.length) {
91
+ return `id must be an integer between 1 and ${current.length} (got ${JSON.stringify(input.id)})`;
92
+ }
93
+ const status = normalizeWorklistStatus(input.status);
94
+ if (status === void 0 || status === "pending") {
95
+ return "status must be one of: in_progress, completed, dropped";
96
+ }
97
+ const target = current[rawId - 1];
98
+ const providedNote = typeof input.note === "string" ? sanitizeWorklistField(input.note) : "";
99
+ const effectiveNote = providedNote !== "" ? providedNote : target.note;
100
+ if ((status === "completed" || status === "dropped") && (!effectiveNote || effectiveNote === "")) {
101
+ return "note is required when status is completed or dropped: record concrete findings, exact file paths/lines, applied edits, or test results";
102
+ }
103
+ const updatedContent = typeof input.content === "string" && sanitizeWorklistField(input.content) !== "" ? sanitizeWorklistField(input.content) : target.content;
104
+ const next = current.map((item, index) => {
105
+ if (index === rawId - 1) {
106
+ return {
107
+ id: item.id,
108
+ content: updatedContent,
109
+ status,
110
+ ...effectiveNote ? { note: effectiveNote } : {}
111
+ };
112
+ }
113
+ if (status === "in_progress" && item.status === "in_progress") {
114
+ const autoDone = index < rawId - 1 && Boolean(item.note && item.note.trim() !== "");
115
+ return { ...item, status: autoDone ? "completed" : "pending" };
116
+ }
117
+ return item;
118
+ });
119
+ if (!next.some((item) => item.status === "in_progress")) {
120
+ const afterIdx = next.findIndex((item, idx) => idx > rawId - 1 && item.status === "pending");
121
+ const promoteIdx = afterIdx >= 0 ? afterIdx : next.findIndex((item) => item.status === "pending");
122
+ if (promoteIdx >= 0) {
123
+ next[promoteIdx] = { ...next[promoteIdx], status: "in_progress" };
124
+ }
125
+ }
126
+ return { items: next, noted: providedNote !== "" };
127
+ }
128
+ function formatWorklist(items) {
129
+ const lines = ["Todo list:"];
130
+ for (const item of items) {
131
+ lines.push(`[${item.id}] (${item.status}) ${item.content}`);
132
+ if (item.note) lines.push(` note: ${item.note}`);
133
+ }
134
+ return lines.join("\n");
135
+ }
136
+ function projectNativeTodos(items, options) {
137
+ const settleActive = options?.turnEnded === true;
138
+ return items.map((item) => ({
139
+ content: item.status === "dropped" ? `[${item.id}] [\u5DF2\u8DF3\u8FC7] ${item.content}` : `[${item.id}] ${item.content}`,
140
+ status: item.status === "dropped" ? "completed" : settleActive && item.status === "in_progress" ? "pending" : item.status
141
+ }));
142
+ }
143
+
144
+ // src/core/tool-mappings.ts
145
+ var nonEmptyStr = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
146
+ var finiteInt = (value) => typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : void 0;
147
+ function stripUndefined(args) {
148
+ return Object.fromEntries(Object.entries(args).filter(([, value]) => value !== void 0));
149
+ }
150
+ function workspacePath(value) {
151
+ const path = nonEmptyStr(value);
152
+ if (path === void 0) return void 0;
153
+ const index = path.lastIndexOf("workspace/");
154
+ if (path.startsWith("/") && index >= 0) return path.slice(index + "workspace/".length) || ".";
155
+ if (path === "/workspace") return ".";
156
+ return path;
157
+ }
158
+ function escapeRegex(text) {
159
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
160
+ }
161
+ function unescapeRegex(text) {
162
+ return text.replace(/\\([.*+?^${}()|[\]\\])/g, "$1");
163
+ }
164
+ var BUILTIN_MAPPINGS = {
165
+ read: {
166
+ wireName: "read_file",
167
+ 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.",
168
+ arguments: '{"path":"relative file path","start_line":"optional integer >= 1","end_line":"optional integer >= start_line"}',
169
+ schema: { properties: { path: { type: "string" }, start_line: { type: "integer" }, end_line: { type: "integer" } } },
170
+ toDsh(args) {
171
+ const start = finiteInt(args.start_line);
172
+ const end = finiteInt(args.end_line);
173
+ return stripUndefined({
174
+ file_path: workspacePath(args.path),
175
+ offset: start,
176
+ limit: end !== void 0 ? Math.max(1, end - (start ?? 1) + 1) : void 0
177
+ });
178
+ },
179
+ fromDsh(args) {
180
+ const offset = finiteInt(args.offset);
181
+ const limit = finiteInt(args.limit);
182
+ return stripUndefined({
183
+ path: args.file_path,
184
+ start_line: offset,
185
+ end_line: limit !== void 0 ? (offset ?? 1) + limit - 1 : void 0
186
+ });
187
+ }
188
+ },
189
+ write: {
190
+ wireName: "write_file",
191
+ description: "Create or overwrite a workspace text file with the given content. The content becomes the whole file.",
192
+ arguments: '{"path":"relative file path","content":"full file content"}',
193
+ schema: { properties: { path: { type: "string" }, content: { type: "string" } } },
194
+ toDsh: (args) => ({ file_path: workspacePath(args.path), content: args.content ?? "" }),
195
+ fromDsh: (args) => ({ path: args.file_path, content: args.content })
196
+ },
197
+ edit: {
198
+ wireName: "edit_file",
199
+ 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.",
200
+ arguments: '{"path":"relative file path","old_text":"exact text to replace","new_text":"replacement text"}',
201
+ schema: { properties: { path: { type: "string" }, old_text: { type: "string" }, new_text: { type: "string" } } },
202
+ toDsh: (args) => ({ file_path: workspacePath(args.path), old_string: args.old_text ?? "", new_string: args.new_text ?? "" }),
203
+ fromDsh: (args) => ({ path: args.file_path, old_text: args.old_string, new_text: args.new_string })
204
+ },
205
+ // Line-range edit (src/line-edit.ts); offered only where that plugin is mounted.
206
+ edit_lines: {
207
+ wireName: "edit_lines",
208
+ 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.",
209
+ arguments: '{"path":"relative file path","start_line":"first line to replace","end_line":"last line to replace","new_text":"replacement lines without line numbers"}',
210
+ schema: { properties: { path: { type: "string" }, start_line: { type: "integer" }, end_line: { type: "integer" }, new_text: { type: "string" } } },
211
+ toDsh: (args) => ({ file_path: workspacePath(args.path), start_line: args.start_line, end_line: args.end_line, new_text: args.new_text ?? "" }),
212
+ fromDsh: (args) => ({ path: args.file_path, start_line: args.start_line, end_line: args.end_line, new_text: args.new_text })
213
+ },
214
+ glob: {
215
+ wireName: "list_files",
216
+ description: "List files below a workspace-relative path.",
217
+ arguments: '{"path":"optional relative directory","pattern":"optional glob such as *.ts"}',
218
+ schema: { properties: { path: { type: "string" }, pattern: { type: "string" } } },
219
+ toDsh: (args) => stripUndefined({ pattern: nonEmptyStr(args.pattern) ?? "*", path: workspacePath(args.path) }),
220
+ fromDsh: (args) => stripUndefined({ path: args.path, pattern: args.pattern === "*" ? void 0 : args.pattern })
221
+ },
222
+ grep: {
223
+ wireName: "search_text",
224
+ description: "Search literal text in workspace files. Returns matching lines with line numbers.",
225
+ arguments: '{"query":"literal text","path":"optional relative path"}',
226
+ schema: { properties: { query: { type: "string" }, path: { type: "string" } } },
227
+ toDsh: (args) => stripUndefined({ pattern: escapeRegex(String(args.query ?? "")), path: workspacePath(args.path) }),
228
+ fromDsh: (args) => stripUndefined({ query: unescapeRegex(String(args.pattern ?? "")), path: args.path })
229
+ },
230
+ bash: {
231
+ wireName: "bash",
232
+ 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.",
233
+ arguments: '{"command":"bash command line"}',
234
+ schema: { properties: { command: { type: "string" } } },
235
+ toDsh(args) {
236
+ const command = String(args.command ?? "");
237
+ const firstLine = command.split("\n")[0] ?? "";
238
+ return { description: firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || "Run command", command };
239
+ },
240
+ fromDsh: (args) => ({ command: args.command })
241
+ },
242
+ web_search: {
243
+ wireName: "web_search",
244
+ description: "Search the public web and return titles, URLs, snippets, and source IDs.",
245
+ arguments: '{"query":"search query"}',
246
+ schema: { properties: { query: { type: "string" } } },
247
+ toDsh: (args) => ({ queries: [String(args.query ?? "")] }),
248
+ fromDsh: (args) => ({ query: Array.isArray(args.queries) ? args.queries.join(" ") : args.queries })
249
+ },
250
+ web_fetch: {
251
+ wireName: "web_fetch",
252
+ description: "Fetch the readable content of one public web page.",
253
+ arguments: '{"url":"https://example.com/page"}',
254
+ schema: { properties: { url: { type: "string" } } },
255
+ toDsh(args) {
256
+ const url = nonEmptyStr(args.url) ?? (Array.isArray(args.urls) ? nonEmptyStr(args.urls[0]) : void 0);
257
+ return { url: url ?? "" };
258
+ },
259
+ fromDsh: (args) => ({ url: args.url })
260
+ },
261
+ // Stateful work list (src/todo.ts); offered when historyMode === 'worklist'.
262
+ [TODO_PLAN_TOOL]: {
263
+ wireName: TODO_PLAN_TOOL,
264
+ description: TODO_PLAN_DESCRIPTION,
265
+ arguments: '{"items":"array of string"}',
266
+ schema: { properties: { items: { type: "array", items: { type: "string" } } } },
267
+ toDsh: (args) => ({ items: parsePlanItems(args.items) ?? args.items }),
268
+ fromDsh: (args) => ({ items: args.items })
269
+ },
270
+ [TODO_UPDATE_TOOL]: {
271
+ wireName: TODO_UPDATE_TOOL,
272
+ description: TODO_UPDATE_DESCRIPTION,
273
+ 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"}',
274
+ schema: {
275
+ properties: {
276
+ id: { type: "integer" },
277
+ status: { type: "string", enum: ["in_progress", "completed", "dropped"] },
278
+ note: { type: "string" },
279
+ content: { type: "string" }
280
+ }
281
+ },
282
+ toDsh: (args) => stripUndefined({
283
+ id: finiteInt(typeof args.id === "string" ? Number(args.id.trim()) : args.id) ?? args.id,
284
+ status: normalizeWorklistStatus(args.status) ?? args.status,
285
+ note: nonEmptyStr(args.note),
286
+ content: nonEmptyStr(args.content)
287
+ }),
288
+ fromDsh: (args) => stripUndefined({
289
+ id: args.id,
290
+ status: args.status,
291
+ note: args.note,
292
+ content: args.content
293
+ })
294
+ }
295
+ };
296
+
297
+ // src/core/tool-repairs.ts
298
+ var PATH_ALIASES = ["file_path", "filepath", "file", "filename", "file_name"];
299
+ var NATIVE_PATH_ALIASES = ["path", "filepath", "file", "filename", "file_name"];
300
+ var ARGUMENT_ALIASES = {
301
+ read_file: { path: PATH_ALIASES, start_line: ["line_start", "from_line"], end_line: ["line_end", "to_line"] },
302
+ write_file: { path: PATH_ALIASES, content: ["text", "file_text", "contents", "data", "code"] },
303
+ edit_file: {
304
+ path: PATH_ALIASES,
305
+ old_text: ["old_string", "old_str", "old", "search", "find", "original"],
306
+ new_text: ["new_string", "new_str", "new", "replace", "replacement", "updated"]
307
+ },
308
+ edit_lines: {
309
+ path: PATH_ALIASES,
310
+ start_line: ["line_start", "from_line", "start", "line"],
311
+ end_line: ["line_end", "to_line", "end"],
312
+ new_text: ["new_string", "new_str", "text", "content", "replacement", "lines"]
313
+ },
314
+ list_files: { path: ["directory", "dir", "folder", "dir_path"], pattern: ["glob"] },
315
+ search_text: { query: ["pattern", "text", "search", "keyword", "regex"], path: ["file_path", "directory", "dir"] },
316
+ bash: { command: ["cmd", "script", "code", "shell"] },
317
+ web_fetch: { url: ["link", "href", "page"] },
318
+ web_search: { query: ["q", "keywords", "search", "search_query"] },
319
+ [TODO_PLAN_TOOL]: { items: ["todos", "tasks", "steps", "plan"] },
320
+ [TODO_UPDATE_TOOL]: {
321
+ id: ["index", "item_id", "task_id", "step"],
322
+ note: ["notes", "summary", "finding", "findings", "conclusion", "result"],
323
+ content: ["title", "task", "text", "description"]
324
+ }
325
+ };
326
+ var NATIVE_ARGUMENT_ALIASES = {
327
+ read: { file_path: NATIVE_PATH_ALIASES, offset: ["start_line", "line_start", "from_line"] },
328
+ write: { file_path: NATIVE_PATH_ALIASES, content: ["text", "file_text", "contents", "data", "code"] },
329
+ edit: {
330
+ file_path: NATIVE_PATH_ALIASES,
331
+ old_string: ["old_text", "old_str", "old", "search", "find", "original"],
332
+ new_string: ["new_text", "new_str", "new", "replace", "replacement", "updated"]
333
+ },
334
+ edit_lines: {
335
+ file_path: NATIVE_PATH_ALIASES,
336
+ start_line: ["line_start", "from_line", "start", "line", "offset"],
337
+ end_line: ["line_end", "to_line", "end"],
338
+ new_text: ["new_string", "new_str", "text", "content", "replacement", "lines"]
339
+ },
340
+ glob: { pattern: ["glob"], path: ["directory", "dir", "folder", "dir_path"] },
341
+ grep: { pattern: ["query", "text", "search", "keyword", "regex"], path: ["file_path", "directory", "dir"] },
342
+ bash: { command: ["cmd", "script", "code", "shell"] },
343
+ web_fetch: { url: ["link", "href", "page"] },
344
+ web_search: { queries: ["query", "q", "keywords", "search", "search_query"] },
345
+ [TODO_PLAN_TOOL]: ARGUMENT_ALIASES[TODO_PLAN_TOOL],
346
+ [TODO_UPDATE_TOOL]: ARGUMENT_ALIASES[TODO_UPDATE_TOOL]
347
+ };
348
+
349
+ // src/core/policy.ts
350
+ var POST_TOOL_REMINDER = `Use the Tool results above to continue the current task.
351
+ If the evidence is sufficient, answer now. Call another tool only for a specific missing fact.
352
+ Never repeat a successful tool call. Do not open a <think> block or repeat the Tool payload.`;
353
+ var POST_TOOL_REMINDER_THINK = POST_TOOL_REMINDER.replace(
354
+ "Do not open a <think> block or repeat the Tool payload.",
355
+ "Do not repeat the Tool payload."
356
+ );
357
+ var SHELL_WRITE = new RegExp([
358
+ String.raw`(?<![<>&=-])\d?>>?(?![>&=])\s*(?!/dev/null\b)[^\s&|;)]`,
359
+ String.raw`\bsed\s+(?:-[a-zA-Z]*\s+)*-[a-zA-Z]*i`,
360
+ String.raw`\b(?:tee|mv|cp|rm|rmdir|touch|mkdir|chmod|ln|patch|truncate|unzip|tar)\b`,
361
+ String.raw`\bgit\s+(?:apply|checkout|restore|reset|commit|merge|rebase|stash|am|cherry-pick|add|rm|mv)\b`,
362
+ String.raw`\b(?:pip3?|npm|pnpm|yarn|uv|cargo|go)\s+(?:install|add|get)\b`
363
+ ].join("|"));
364
+
365
+ // src/todo.ts
366
+ var name = "rwkv-todo";
367
+ var inject = ["tools"];
368
+ var STATE_RECORD = "plugin:rwkv-todo/state";
369
+ var appendRecord = appendPluginRecord;
370
+ var recordOf = pluginRecordOf;
371
+ var VALID_STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "completed", "dropped"]);
372
+ function decodeItems(raw) {
373
+ if (!Array.isArray(raw)) return void 0;
374
+ const items = [];
375
+ for (const entry of raw) {
376
+ if (typeof entry !== "object" || entry === null) return void 0;
377
+ const { id, content, status, note } = entry;
378
+ if (typeof id !== "number" || !Number.isInteger(id) || id < 1) return void 0;
379
+ if (typeof content !== "string" || content === "") return void 0;
380
+ if (typeof status !== "string" || !VALID_STATUSES.has(status)) return void 0;
381
+ if (note !== void 0 && typeof note !== "string") return void 0;
382
+ items.push({
383
+ id,
384
+ content,
385
+ status,
386
+ ...typeof note === "string" && note !== "" ? { note } : {}
387
+ });
388
+ }
389
+ return items;
390
+ }
391
+ function turnIndexOf(events) {
392
+ if (events === void 0) return 1;
393
+ let turns = 0;
394
+ for (const event of events) {
395
+ if (event.type === "turn/start") turns++;
396
+ }
397
+ return Math.max(1, turns);
398
+ }
399
+ function blockedBackToBackComplete(events) {
400
+ if (events === void 0 || events.length === 0) return false;
401
+ let skippedCurrentCall = false;
402
+ for (let i = events.length - 1; i >= 0; i--) {
403
+ const ev = events[i];
404
+ if (ev.type === "turn/start") return false;
405
+ if (ev.type === "tool/call") {
406
+ if (!skippedCurrentCall) {
407
+ skippedCurrentCall = true;
408
+ continue;
409
+ }
410
+ const toolName = typeof ev.data === "object" && ev.data !== null ? ev.data.name : void 0;
411
+ if (typeof toolName === "string" && !isWorklistTool(toolName) && toolName !== "todo_write") {
412
+ return false;
413
+ }
414
+ continue;
415
+ }
416
+ const rec = recordOf(ev);
417
+ if (rec?.type === STATE_RECORD && typeof rec.data === "object" && rec.data !== null) {
418
+ if (rec.data.completed === true) {
419
+ return true;
420
+ }
421
+ }
422
+ }
423
+ return false;
424
+ }
425
+ var WorklistStore = class {
426
+ bySession = /* @__PURE__ */ new WeakMap();
427
+ hydrated = /* @__PURE__ */ new WeakSet();
428
+ fallback = [];
429
+ get(session) {
430
+ if (session === void 0) return { turn: 1, items: this.fallback };
431
+ const events = session.snapshotEvents?.();
432
+ const currentTurn = turnIndexOf(events);
433
+ if (!this.hydrated.has(session)) {
434
+ this.hydrated.add(session);
435
+ let items = [];
436
+ if (events !== void 0) {
437
+ let logTurn = 0;
438
+ for (const event of events) {
439
+ if (event.type === "turn/start") {
440
+ logTurn++;
441
+ items = [];
442
+ continue;
443
+ }
444
+ const rec = recordOf(event);
445
+ if (rec?.type !== STATE_RECORD || typeof rec.data !== "object" || rec.data === null) continue;
446
+ const decoded = decodeItems(rec.data.items);
447
+ const recTurn = rec.data.turn;
448
+ if (decoded !== void 0 && (typeof recTurn !== "number" || recTurn === Math.max(1, logTurn))) {
449
+ items = decoded;
450
+ }
451
+ }
452
+ }
453
+ const entry = { turn: currentTurn, items };
454
+ this.bySession.set(session, entry);
455
+ return entry;
456
+ }
457
+ const existing = this.bySession.get(session);
458
+ if (existing === void 0 || existing.turn !== currentTurn) {
459
+ const fresh = { turn: currentTurn, items: [] };
460
+ this.bySession.set(session, fresh);
461
+ return fresh;
462
+ }
463
+ return existing;
464
+ }
465
+ save(session, turn, items, completed = false) {
466
+ if (session === void 0) {
467
+ this.fallback = items;
468
+ return;
469
+ }
470
+ this.bySession.set(session, { turn, items });
471
+ const payload = { turn, items, ...completed ? { completed: true } : {} };
472
+ try {
473
+ appendRecord(session, STATE_RECORD, payload);
474
+ } catch {
475
+ }
476
+ try {
477
+ session.append?.("todo/write", { todos: projectNativeTodos(items) });
478
+ } catch {
479
+ }
480
+ }
481
+ /**
482
+ * Settle any lingering `in_progress` indicator in the Desktop `TodoPanel` once
483
+ * `turn/end` commits so an unfinished item does not keep spinning while idle.
484
+ */
485
+ settleTurnEnd(session) {
486
+ if (session === void 0) return;
487
+ const { items } = this.get(session);
488
+ if (!items.some((item) => item.status === "in_progress")) return;
489
+ try {
490
+ session.append?.("todo/write", { todos: projectNativeTodos(items, { turnEnded: true }) });
491
+ } catch {
492
+ }
493
+ }
494
+ };
495
+ var STATUS_CN = {
496
+ completed: "\u5DF2\u5B8C\u6210",
497
+ in_progress: "\u8BB0\u5F55\u8FDB\u5C55",
498
+ dropped: "\u5DF2\u8DF3\u8FC7"
499
+ };
500
+ function apply(ctx) {
501
+ const host = ctx;
502
+ const store = new WorklistStore();
503
+ host.on?.("session/event", (session, ev) => {
504
+ if (ev?.type === "turn/end") store.settleTurnEnd(session);
505
+ });
506
+ host.tools.register(defineTool({
507
+ name: TODO_PLAN_TOOL,
508
+ description: TODO_PLAN_DESCRIPTION,
509
+ parameters: {
510
+ items: {
511
+ type: "array",
512
+ required: true,
513
+ 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.",
514
+ items: { type: "string" }
515
+ }
516
+ },
517
+ output: {
518
+ schema: {
519
+ type: "object",
520
+ additionalProperties: false,
521
+ properties: {
522
+ summary: { type: "string", required: true }
523
+ }
524
+ },
525
+ render: (_args, value) => [{ type: "text", text: value.summary }]
526
+ },
527
+ execute(args, exec) {
528
+ const session = exec.agent?.session;
529
+ const current = store.get(session);
530
+ const updated = applyTodoPlan(current.items, args.items);
531
+ if (typeof updated === "string") throw new ToolArgsError([updated]);
532
+ store.save(session, current.turn, updated);
533
+ return Promise.resolve({ summary: formatWorklist(updated) });
534
+ },
535
+ presentCall: (args) => ({
536
+ card: "generic",
537
+ title: `\u89C4\u5212\u5DE5\u5355\uFF08${Array.isArray(args.items) ? args.items.length : 0} \u9879\uFF09`,
538
+ kind: "other",
539
+ rawInput: args.items
540
+ })
541
+ }));
542
+ host.tools.register(defineTool({
543
+ name: TODO_UPDATE_TOOL,
544
+ description: TODO_UPDATE_DESCRIPTION,
545
+ parameters: {
546
+ id: {
547
+ type: "number",
548
+ required: true,
549
+ description: "1-based item number from the current todo list."
550
+ },
551
+ status: {
552
+ type: "string",
553
+ required: true,
554
+ enum: ["in_progress", "completed", "dropped"],
555
+ description: "in_progress | completed | dropped. Marking completed or dropped automatically sets the next pending item to in_progress."
556
+ },
557
+ note: {
558
+ type: "string",
559
+ 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."
560
+ },
561
+ content: {
562
+ type: "string",
563
+ description: "Optional refined title for this item if the initial wording was inaccurate."
564
+ }
565
+ },
566
+ output: {
567
+ schema: {
568
+ type: "object",
569
+ additionalProperties: false,
570
+ properties: {
571
+ summary: { type: "string", required: true }
572
+ }
573
+ },
574
+ render: (_args, value) => [{ type: "text", text: value.summary }]
575
+ },
576
+ execute(args, exec) {
577
+ const session = exec.agent?.session;
578
+ const statusNorm = normalizeWorklistStatus(args.status);
579
+ if (statusNorm === "completed" && blockedBackToBackComplete(session?.snapshotEvents?.())) {
580
+ throw new ToolArgsError([
581
+ '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".'
582
+ ]);
583
+ }
584
+ const current = store.get(session);
585
+ const updated = applyTodoUpdate(current.items, args);
586
+ if (typeof updated === "string") throw new ToolArgsError([updated]);
587
+ store.save(session, current.turn, updated.items, statusNorm === "completed");
588
+ return Promise.resolve({ summary: formatWorklist(updated.items) });
589
+ },
590
+ presentCall: (args) => {
591
+ const st = typeof args.status === "string" ? STATUS_CN[args.status] ?? args.status : "\u66F4\u65B0";
592
+ return {
593
+ card: "generic",
594
+ title: `\u66F4\u65B0\u5DE5\u5355 #${String(args.id ?? "?")} \xB7 ${st}`,
595
+ kind: "other",
596
+ rawInput: args
597
+ };
598
+ }
599
+ }));
600
+ }
601
+ export {
602
+ TODO_PLAN_DESCRIPTION,
603
+ TODO_UPDATE_DESCRIPTION,
604
+ apply,
605
+ blockedBackToBackComplete,
606
+ inject,
607
+ name,
608
+ projectNativeTodos
609
+ };
610
+ //# sourceMappingURL=todo.js.map