dsh-better-edit 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +173 -53
- package/README.zh.md +133 -47
- package/lib/guidance.js +391 -0
- package/lib/index.js +56 -32
- package/lib/prompts.js +53 -49
- package/lib/types/guidance.d.ts +130 -0
- package/lib/types/index.d.ts +4 -0
- package/lib/types/prompts.d.ts +19 -9
- package/package.json +3 -10
package/lib/guidance.js
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-preset guidance overrides for the hashline tool sections.
|
|
3
|
+
*
|
|
4
|
+
* Each of the four `tool:*` prompt sections the plugin registers has a
|
|
5
|
+
* compiled default rendered from `prompts.ts` (byte-identical to the inline
|
|
6
|
+
* rendering `src/index.ts` uses today). A user can override any section's text
|
|
7
|
+
* and `order` with a plain markdown file keyed by agent preset: the override
|
|
8
|
+
* files live in the plugin's shared home (`$DSH_HOME/plugins/dsh-better-edit`,
|
|
9
|
+
* never the workspace store) and are resolved per section as
|
|
10
|
+
* `<preset>/<section>.md` → compiled default.
|
|
11
|
+
*
|
|
12
|
+
* fence carrying only an `order` key (`---` / `order: N` / `---`). Any
|
|
13
|
+
* well-formed fence — even keyless, even an empty body — is deliberate content
|
|
14
|
+
* and wins. A leading `---` that does not parse (a missing closing fence, a
|
|
15
|
+
* non-integer `order`, an unknown key) is a MALFORMED override and must never
|
|
16
|
+
* reach the model: resolution falls back to the compiled default and reports
|
|
17
|
+
* the file and parse reason. An absent or blank override (whitespace-only body,
|
|
18
|
+
* no fence) means "use the default" and is re-seeded at boot.
|
|
19
|
+
*
|
|
20
|
+
* Resolution is pure: no cordis services, no harness wiring. The installer
|
|
21
|
+
* ticket reads the resolved sections once per agent at session-start;
|
|
22
|
+
* nothing here watches or caches files.
|
|
23
|
+
* @module dsh-better-edit/guidance
|
|
24
|
+
*/
|
|
25
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { BATCH_EDIT_GUIDANCE, EDIT_GUIDANCE, READ_GUIDANCE, UNDO_GUIDANCE, } from "./prompts.js";
|
|
28
|
+
import { errCode } from "./utils.js";
|
|
29
|
+
/** The presets shipped by the harness, each seeded with editable guidance. */
|
|
30
|
+
export const DEFAULT_PRESETS = [
|
|
31
|
+
"standard",
|
|
32
|
+
"code",
|
|
33
|
+
"minimal",
|
|
34
|
+
"cordis",
|
|
35
|
+
];
|
|
36
|
+
/**
|
|
37
|
+
* Render one tool's guidance as its intro line, a blank line, then bullets.
|
|
38
|
+
* Uniform across the four sections: no tool-schema description is duplicated
|
|
39
|
+
* (that already reaches the model through the tool catalog).
|
|
40
|
+
*/
|
|
41
|
+
function guidanceText(g) {
|
|
42
|
+
return [g.intro, "", bulletLines(g.lines)].join("\n");
|
|
43
|
+
}
|
|
44
|
+
function bulletLines(lines) {
|
|
45
|
+
return lines.map((line) => `- ${line}`).join("\n");
|
|
46
|
+
}
|
|
47
|
+
/** The four sections, in default-order sequence. */
|
|
48
|
+
export const GUIDANCE_SECTIONS = [
|
|
49
|
+
{
|
|
50
|
+
name: "tool:read",
|
|
51
|
+
file: "read.md",
|
|
52
|
+
defaultOrder: 130,
|
|
53
|
+
renderDefault: () => guidanceText(READ_GUIDANCE),
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "tool:edit",
|
|
57
|
+
file: "edit.md",
|
|
58
|
+
defaultOrder: 131,
|
|
59
|
+
renderDefault: () => guidanceText(EDIT_GUIDANCE),
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: "tool:batch_edit",
|
|
63
|
+
file: "batch_edit.md",
|
|
64
|
+
defaultOrder: 132,
|
|
65
|
+
renderDefault: () => guidanceText(BATCH_EDIT_GUIDANCE),
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
name: "tool:undo_last_edit",
|
|
69
|
+
file: "undo_last_edit.md",
|
|
70
|
+
defaultOrder: 133,
|
|
71
|
+
renderDefault: () => guidanceText(UNDO_GUIDANCE),
|
|
72
|
+
},
|
|
73
|
+
];
|
|
74
|
+
const SECTION_BY_NAME = new Map(GUIDANCE_SECTIONS.map((section) => [section.name, section]));
|
|
75
|
+
/** Render the compiled default text for one section. */
|
|
76
|
+
export function renderSectionDefault(name) {
|
|
77
|
+
const section = SECTION_BY_NAME.get(name);
|
|
78
|
+
if (!section)
|
|
79
|
+
throw new Error(`unknown guidance section: ${name}`);
|
|
80
|
+
return section.renderDefault();
|
|
81
|
+
}
|
|
82
|
+
function stripCR(line) {
|
|
83
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parse an override file. Only a leading `---` fence whose lines are empty or
|
|
87
|
+
* `order: <integer>` is accepted. A leading `---` that does not parse (no
|
|
88
|
+
* closing fence, unknown key, non-integer value) is a malformed override;
|
|
89
|
+
* anything else is pure prose (the whole file as text).
|
|
90
|
+
*/
|
|
91
|
+
export function parseSectionFile(content) {
|
|
92
|
+
const lines = content.split("\n");
|
|
93
|
+
if (stripCR(lines[0]) !== "---") {
|
|
94
|
+
return { text: content };
|
|
95
|
+
}
|
|
96
|
+
const close = lines.findIndex((line, index) => index > 0 && stripCR(line) === "---");
|
|
97
|
+
if (close < 0) {
|
|
98
|
+
return { text: content, malformed: true, reason: "missing closing fence" };
|
|
99
|
+
}
|
|
100
|
+
let order;
|
|
101
|
+
for (let index = 1; index < close; index++) {
|
|
102
|
+
const line = stripCR(lines[index]);
|
|
103
|
+
if (line.trim() === "")
|
|
104
|
+
continue;
|
|
105
|
+
const key = line.split(":")[0].trim();
|
|
106
|
+
const match = /^order:\s*(-?\d+)\s*$/.exec(line);
|
|
107
|
+
if (!match) {
|
|
108
|
+
if (key === "order") {
|
|
109
|
+
const value = line.slice(line.indexOf(":") + 1).trim();
|
|
110
|
+
return {
|
|
111
|
+
text: content,
|
|
112
|
+
malformed: true,
|
|
113
|
+
reason: `non-integer order '${value}'`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
text: content,
|
|
118
|
+
malformed: true,
|
|
119
|
+
reason: `unknown key '${key}'`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
order = Number.parseInt(match[1], 10);
|
|
123
|
+
}
|
|
124
|
+
// Front-matter body: strip leading blank lines after the closing fence so
|
|
125
|
+
// `---\n…\n---\n\nbody` and `---\n…\n---\nbody` parse identically (the
|
|
126
|
+
// materialized preset files carry a blank line after the fence).
|
|
127
|
+
const body = lines.slice(close + 1);
|
|
128
|
+
let bodyStart = 0;
|
|
129
|
+
while (bodyStart < body.length && body[bodyStart].trim() === "")
|
|
130
|
+
bodyStart++;
|
|
131
|
+
return { order, text: body.slice(bodyStart).join("\n") };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* True when an override file is blank: whitespace-only body and NO front-matter
|
|
135
|
+
* fence (the "I want the default" case). The single source of truth for whether
|
|
136
|
+
* a boot-time materialization pass should re-seed a file. False for prose with
|
|
137
|
+
* content, for any valid fence (including a keyless/empty one — a deliberate
|
|
138
|
+
* blank), and for malformed files.
|
|
139
|
+
*/
|
|
140
|
+
export function isBlankOverride(content) {
|
|
141
|
+
const parsed = parseSectionFile(content);
|
|
142
|
+
return (!parsed.malformed &&
|
|
143
|
+
parsed.order === undefined &&
|
|
144
|
+
parsed.text.trim() === "" &&
|
|
145
|
+
!startsWithFenceLine(content));
|
|
146
|
+
}
|
|
147
|
+
/** True when an override file opens with a leading `---` fence that is malformed. */
|
|
148
|
+
export function isMalformedOverride(content) {
|
|
149
|
+
return parseSectionFile(content).malformed === true;
|
|
150
|
+
}
|
|
151
|
+
function startsWithFenceLine(content) {
|
|
152
|
+
return stripCR(content.split("\n")[0]) === "---";
|
|
153
|
+
}
|
|
154
|
+
function overrideCandidates(file, options) {
|
|
155
|
+
const candidates = [];
|
|
156
|
+
if (options.presetId !== undefined) {
|
|
157
|
+
candidates.push(join(options.homeDir, options.presetId, file));
|
|
158
|
+
}
|
|
159
|
+
return candidates;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Resolve one section's guidance: the first override file that exists wins,
|
|
163
|
+
* falling back to the compiled default. A missing or blank file (ENOENT, or
|
|
164
|
+
* whitespace-only with no fence) advances the chain; a malformed file resolves
|
|
165
|
+
* to the compiled default and reports itself; any other read error propagates.
|
|
166
|
+
*/
|
|
167
|
+
export async function resolveSection(name, options) {
|
|
168
|
+
const section = SECTION_BY_NAME.get(name);
|
|
169
|
+
if (!section)
|
|
170
|
+
throw new Error(`unknown guidance section: ${name}`);
|
|
171
|
+
for (const candidate of overrideCandidates(section.file, options)) {
|
|
172
|
+
const content = await readFile(candidate, "utf-8").catch((error) => {
|
|
173
|
+
if (errCode(error) === "ENOENT")
|
|
174
|
+
return undefined;
|
|
175
|
+
throw error;
|
|
176
|
+
});
|
|
177
|
+
if (content === undefined)
|
|
178
|
+
continue;
|
|
179
|
+
const parsed = parseSectionFile(content);
|
|
180
|
+
if (parsed.malformed) {
|
|
181
|
+
// A broken override must never reach the model. Resolve to the
|
|
182
|
+
// compiled default and report the file + parse reason to the caller.
|
|
183
|
+
return {
|
|
184
|
+
order: section.defaultOrder,
|
|
185
|
+
text: section.renderDefault(),
|
|
186
|
+
malformed: {
|
|
187
|
+
file: candidate,
|
|
188
|
+
reason: parsed.reason ?? "malformed override",
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
// Blank (no fence, whitespace-only) means "use the default": advance the
|
|
193
|
+
// fallback chain rather than render an empty section.
|
|
194
|
+
if (isBlankOverride(content))
|
|
195
|
+
continue;
|
|
196
|
+
return { order: parsed.order ?? section.defaultOrder, text: parsed.text };
|
|
197
|
+
}
|
|
198
|
+
return { order: section.defaultOrder, text: section.renderDefault() };
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Resolve all four sections for a preset. `presetId === undefined` skips the
|
|
202
|
+
* `<preset>/` layer and resolves straight to the compiled defaults.
|
|
203
|
+
*/
|
|
204
|
+
export async function composeSections(presetId, homeDir) {
|
|
205
|
+
return Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
|
|
206
|
+
const resolved = await resolveSection(section.name, {
|
|
207
|
+
presetId,
|
|
208
|
+
homeDir,
|
|
209
|
+
});
|
|
210
|
+
return {
|
|
211
|
+
name: section.name,
|
|
212
|
+
order: resolved.order,
|
|
213
|
+
text: resolved.text,
|
|
214
|
+
malformed: resolved.malformed,
|
|
215
|
+
};
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The root README: the per-preset customization convention users see in the
|
|
220
|
+
* plugin home.
|
|
221
|
+
*/
|
|
222
|
+
export const GUIDANCE_HOME_README = `# dsh-better-edit guidance
|
|
223
|
+
|
|
224
|
+
Each agent preset has its own guidance directory here: \`<preset>/<section>.md\`.
|
|
225
|
+
On first boot the plugin seeds the shipped presets (\`standard\`, \`code\`,
|
|
226
|
+
\`minimal\`, \`cordis\`) with the compiled defaults; existing files are never
|
|
227
|
+
overwritten, so your edits survive.
|
|
228
|
+
|
|
229
|
+
Each file is one tool section:
|
|
230
|
+
|
|
231
|
+
- \`read.md\` -> \`tool:read\`
|
|
232
|
+
- \`edit.md\` -> \`tool:edit\`
|
|
233
|
+
- \`batch_edit.md\` -> \`tool:batch_edit\`
|
|
234
|
+
- \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
|
|
235
|
+
|
|
236
|
+
## Customize
|
|
237
|
+
|
|
238
|
+
Edit the \`<section>.md\` file for the preset and section you want to change —
|
|
239
|
+
the file body IS the text the model reads for that section. Files are read once
|
|
240
|
+
per agent at session-start, so edits apply to new sessions.
|
|
241
|
+
|
|
242
|
+
An optional YAML front-matter fence places the section at a custom position in
|
|
243
|
+
the assembled system prompt:
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
order: 150
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
<section text>
|
|
250
|
+
|
|
251
|
+
A file without front-matter keeps the default order. A malformed fence (a
|
|
252
|
+
missing closing \`---\`, a non-integer \`order\`, an unknown key) makes the whole
|
|
253
|
+
file plain prose.
|
|
254
|
+
|
|
255
|
+
## Fallback
|
|
256
|
+
|
|
257
|
+
A preset with no directory here, or a missing section file, falls back to the
|
|
258
|
+
compiled defaults in the plugin bundle. To customize a preset that has no
|
|
259
|
+
seeded directory, copy a seeded one to its name.
|
|
260
|
+
`;
|
|
261
|
+
export const GUIDANCE_HOME_README_ZH = `# dsh-better-edit 指引
|
|
262
|
+
|
|
263
|
+
每个 agent preset 在这里都有自己的指引目录:\`<preset>/<section>.md\`。首次启动时
|
|
264
|
+
插件会为随附的 preset(\`standard\`、\`code\`、\`minimal\`、\`cordis\`)写入编译内置的
|
|
265
|
+
默认内容;已有文件绝不被覆盖,因此你的编辑会保留。
|
|
266
|
+
|
|
267
|
+
每个文件对应一个工具片段:
|
|
268
|
+
|
|
269
|
+
- \`read.md\` -> \`tool:read\`
|
|
270
|
+
- \`edit.md\` -> \`tool:edit\`
|
|
271
|
+
- \`batch_edit.md\` -> \`tool:batch_edit\`
|
|
272
|
+
- \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
|
|
273
|
+
|
|
274
|
+
## 自定义
|
|
275
|
+
|
|
276
|
+
编辑你想修改的 preset 与片段的 \`<section>.md\` 文件即可——文件正文就是该片段呈
|
|
277
|
+
现给模型的文本。文件在 agent 的 session-start 时读取一次,因此修改只影响新会话。
|
|
278
|
+
|
|
279
|
+
可以用可选的 YAML front-matter 栅栏把片段放到组装后系统提示中的自定义位置:
|
|
280
|
+
|
|
281
|
+
---
|
|
282
|
+
order: 150
|
|
283
|
+
---
|
|
284
|
+
|
|
285
|
+
<片段文本>
|
|
286
|
+
|
|
287
|
+
没有 front-matter 的文件保持默认顺序。格式错误的栅栏(缺少收尾 \`---\`、非整数
|
|
288
|
+
\`order\`、未知键)会让整个文件退化为纯文本。
|
|
289
|
+
|
|
290
|
+
## 回退
|
|
291
|
+
|
|
292
|
+
这里没有对应目录的 preset、或缺失某个片段文件时,会回退到插件包内的编译内置默认
|
|
293
|
+
值。要自定义没有种子目录的 preset,把一个种子目录复制成它的名字即可。
|
|
294
|
+
`;
|
|
295
|
+
/**
|
|
296
|
+
* Materialize per-preset guidance directories in the plugin home.
|
|
297
|
+
*
|
|
298
|
+
* For each of \`DEFAULT_PRESETS\` creates \`<preset>/{read,edit,batch_edit,
|
|
299
|
+
* undo_last_edit}.md\` rendered from the compiled defaults (with order
|
|
300
|
+
* front-matter), plus a root \`README.md\` documenting the convention.
|
|
301
|
+
* Idempotent: a user-edited file survives repeated calls. A blank override file
|
|
302
|
+
* (whitespace-only body, no fence) is re-seeded with the current compiled
|
|
303
|
+
* default; malformed, non-blank, and deliberate-blank (valid-fence) files are
|
|
304
|
+
* never touched. Custom preset directories present on disk are scanned the same
|
|
305
|
+
* way but never fabricated. Missing directories are created on demand (shipped
|
|
306
|
+
* presets only), and shipped files are written exclusively so two concurrent
|
|
307
|
+
* first runs race safely.
|
|
308
|
+
*/
|
|
309
|
+
export async function ensurePresetGuidance(homeDir) {
|
|
310
|
+
await mkdir(homeDir, { recursive: true });
|
|
311
|
+
await Promise.all(DEFAULT_PRESETS.map(async (preset) => {
|
|
312
|
+
const dir = join(homeDir, preset);
|
|
313
|
+
await mkdir(dir, { recursive: true });
|
|
314
|
+
const existing = new Set(await readdir(dir));
|
|
315
|
+
await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
|
|
316
|
+
const path = join(dir, section.file);
|
|
317
|
+
if (existing.has(section.file)) {
|
|
318
|
+
await healBlankOverride(path, section);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
await writeFile(path, seededContent(section), {
|
|
322
|
+
encoding: "utf-8",
|
|
323
|
+
flag: "wx",
|
|
324
|
+
}).catch((error) => {
|
|
325
|
+
// A concurrent writer landed first; never clobber it.
|
|
326
|
+
if (errCode(error) === "EEXIST")
|
|
327
|
+
return;
|
|
328
|
+
throw error;
|
|
329
|
+
});
|
|
330
|
+
}));
|
|
331
|
+
}));
|
|
332
|
+
// Custom presets present on disk: heal existing blank section files only.
|
|
333
|
+
// Absence is respected — a custom preset's files are never fabricated, and
|
|
334
|
+
// malformed / non-blank / deliberate-blank files are left untouched.
|
|
335
|
+
const entries = await readdir(homeDir, { withFileTypes: true });
|
|
336
|
+
await Promise.all(entries
|
|
337
|
+
.filter((entry) => entry.isDirectory() && !DEFAULT_PRESETS.includes(entry.name))
|
|
338
|
+
.map(async (entry) => {
|
|
339
|
+
const dir = join(homeDir, entry.name);
|
|
340
|
+
const existing = new Set(await readdir(dir));
|
|
341
|
+
await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
|
|
342
|
+
if (!existing.has(section.file))
|
|
343
|
+
return;
|
|
344
|
+
await healBlankOverride(join(dir, section.file), section);
|
|
345
|
+
}));
|
|
346
|
+
}));
|
|
347
|
+
const homeFiles = new Set(await readdir(homeDir));
|
|
348
|
+
const readmes = [
|
|
349
|
+
["README.md", GUIDANCE_HOME_README],
|
|
350
|
+
["README.zh.md", GUIDANCE_HOME_README_ZH],
|
|
351
|
+
];
|
|
352
|
+
await Promise.all(readmes.map(async ([file, content]) => {
|
|
353
|
+
if (homeFiles.has(file))
|
|
354
|
+
return;
|
|
355
|
+
await writeFile(join(homeDir, file), content, {
|
|
356
|
+
encoding: "utf-8",
|
|
357
|
+
flag: "wx",
|
|
358
|
+
}).catch((error) => {
|
|
359
|
+
if (errCode(error) === "EEXIST")
|
|
360
|
+
return;
|
|
361
|
+
throw error;
|
|
362
|
+
});
|
|
363
|
+
}));
|
|
364
|
+
}
|
|
365
|
+
/** The content a seeded override file carries, rendered from the current defaults. */
|
|
366
|
+
function seededContent(section) {
|
|
367
|
+
return `---\norder: ${section.defaultOrder}\n---\n\n${section.renderDefault()}`;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Heal an existing empty override file: a blank file means "use the default",
|
|
371
|
+
* so it is rewritten with the current seeded default. Malformed, non-blank, and
|
|
372
|
+
* deliberate-blank (valid-fence) files are left untouched — overwriting a
|
|
373
|
+
* malformed file would destroy the user's salvageable body. Plain overwrite:
|
|
374
|
+
* the file already exists. Errors propagate to the boot caller, which never
|
|
375
|
+
* fails init.
|
|
376
|
+
*/
|
|
377
|
+
async function healBlankOverride(path, section) {
|
|
378
|
+
let content;
|
|
379
|
+
try {
|
|
380
|
+
content = await readFile(path, "utf-8");
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
// Vanished between readdir and read; nothing to heal.
|
|
384
|
+
if (errCode(error) === "ENOENT")
|
|
385
|
+
return;
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
388
|
+
if (!isBlankOverride(content))
|
|
389
|
+
return;
|
|
390
|
+
await writeFile(path, seededContent(section), { encoding: "utf-8" });
|
|
391
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
* automatically when the agent is disposed. The built-in `write` stays in
|
|
10
10
|
* place; a scoped `tools/post-execute` listener appends the fresh hashline
|
|
11
11
|
* preview to write results.
|
|
12
|
+
*
|
|
13
|
+
* The four `tool:*` guidance sections resolve per agent preset from override
|
|
14
|
+
* files in the shared home (see `src/guidance.ts`); deployments without the
|
|
15
|
+
* `agentPresets` service keep the compiled defaults unchanged.
|
|
12
16
|
* @module dsh-better-edit
|
|
13
17
|
*/
|
|
14
18
|
import { ctxFsIO } from "./fs-bridge.js";
|
|
@@ -19,7 +23,8 @@ import { registerBatchEditTool } from "./tool-batch-edit.js";
|
|
|
19
23
|
import { registerUndoTool } from "./tool-undo.js";
|
|
20
24
|
import { registerWriteHook } from "./write-hook.js";
|
|
21
25
|
import { initHasher } from "./hashline/hasher.js";
|
|
22
|
-
import {
|
|
26
|
+
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
27
|
+
import { configDir } from "./paths.js";
|
|
23
28
|
/** Cordis plugin name used by loader diagnostics. */
|
|
24
29
|
export const name = "dsh-better-edit";
|
|
25
30
|
/**
|
|
@@ -30,8 +35,44 @@ export const name = "dsh-better-edit";
|
|
|
30
35
|
* session-start.
|
|
31
36
|
*/
|
|
32
37
|
export const inject = ["tools", "systemPrompt", "fs"];
|
|
38
|
+
/** The four sections as compiled, byte-identical to the pre-guidance install. */
|
|
39
|
+
function compiledDefaultSections() {
|
|
40
|
+
return GUIDANCE_SECTIONS.map((section) => ({
|
|
41
|
+
name: section.name,
|
|
42
|
+
order: section.defaultOrder,
|
|
43
|
+
text: section.renderDefault(),
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Resolve the four guidance sections for one agent. Without the `agentPresets`
|
|
48
|
+
* service the fast path returns the compiled defaults untouched. With it, the
|
|
49
|
+
* agent's preset id drives `composeSections` against the shared home; any
|
|
50
|
+
* resolution failure degrades to compiled defaults so a bad override file can
|
|
51
|
+
* never fail the install.
|
|
52
|
+
*/
|
|
53
|
+
async function resolveAgentSections(rootCtx, agent) {
|
|
54
|
+
const agentPresets = rootCtx.get("agentPresets");
|
|
55
|
+
if (!agentPresets)
|
|
56
|
+
return compiledDefaultSections();
|
|
57
|
+
try {
|
|
58
|
+
const presetId = agentPresets.composedPreset(agent.ctx);
|
|
59
|
+
const sections = await composeSections(presetId, configDir());
|
|
60
|
+
// Warn once per agent install (this runs once per agent, under the
|
|
61
|
+
// WeakSet guard) about any malformed override we had to ignore.
|
|
62
|
+
for (const section of sections) {
|
|
63
|
+
if (section.malformed) {
|
|
64
|
+
rootCtx.logger.warn(`dsh-better-edit: ignoring malformed guidance override ${section.malformed.file}: ${section.malformed.reason}; using compiled default`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return sections;
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
rootCtx.logger.warn(`dsh-better-edit: guidance resolution failed for agent ${agent.id}, using compiled defaults: ${error instanceof Error ? error.message : String(error)}`);
|
|
71
|
+
return compiledDefaultSections();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
33
74
|
function installAgentTools(rootCtx, agent) {
|
|
34
|
-
|
|
75
|
+
agent.ctx.effect(async () => {
|
|
35
76
|
// `fs` is host-plane: use the plugin's own context (covered by
|
|
36
77
|
// inject) rather than the agent's scoped one, whose fiber chain does
|
|
37
78
|
// not declare it. Session cwd still reaches the bridge per call via
|
|
@@ -44,36 +85,13 @@ function installAgentTools(rootCtx, agent) {
|
|
|
44
85
|
disposers.push(registerBatchEditTool(rootCtx, agent.ctx, io, sandbox));
|
|
45
86
|
disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
|
|
46
87
|
disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
|
|
47
|
-
// Shadow the preset's built-in tool guidance with the hashline
|
|
48
|
-
// Same section names on the agent's own layer win over the
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"",
|
|
55
|
-
EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
56
|
-
].join("\n"),
|
|
57
|
-
}));
|
|
58
|
-
disposers.push(agent.ctx.systemPrompt.section({
|
|
59
|
-
name: "tool:read",
|
|
60
|
-
order: 100,
|
|
61
|
-
text: [
|
|
62
|
-
"Use the read tool — not shell commands like cat — to inspect text files.",
|
|
63
|
-
"",
|
|
64
|
-
READ_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
65
|
-
].join("\n"),
|
|
66
|
-
}));
|
|
67
|
-
disposers.push(agent.ctx.systemPrompt.section({
|
|
68
|
-
name: "tool:batch_edit",
|
|
69
|
-
order: 103,
|
|
70
|
-
text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
71
|
-
}));
|
|
72
|
-
disposers.push(agent.ctx.systemPrompt.section({
|
|
73
|
-
name: "tool:undo_last_edit",
|
|
74
|
-
order: 104,
|
|
75
|
-
text: UNDO_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
76
|
-
}));
|
|
88
|
+
// Shadow the preset's built-in tool guidance with the hashline
|
|
89
|
+
// contract. Same section names on the agent's own layer win over the
|
|
90
|
+
// preset's; text and order come from the per-preset resolution.
|
|
91
|
+
const sections = await resolveAgentSections(rootCtx, agent);
|
|
92
|
+
for (const section of sections) {
|
|
93
|
+
disposers.push(agent.ctx.systemPrompt.section(section));
|
|
94
|
+
}
|
|
77
95
|
return () => {
|
|
78
96
|
for (const dispose of disposers)
|
|
79
97
|
dispose();
|
|
@@ -88,6 +106,12 @@ export function apply(rootCtx) {
|
|
|
88
106
|
initHasher().catch((error) => {
|
|
89
107
|
rootCtx.logger.warn(`dsh-better-edit: hasher warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
90
108
|
});
|
|
109
|
+
// Seed each shipped preset's guidance directory once, so users have
|
|
110
|
+
// editable per-preset overrides (idempotent: never rewrites existing
|
|
111
|
+
// files). A failure must never fail the boot.
|
|
112
|
+
ensurePresetGuidance(configDir()).catch((error) => {
|
|
113
|
+
rootCtx.logger.warn(`dsh-better-edit: guidance materialization failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
114
|
+
});
|
|
91
115
|
const registered = new WeakSet();
|
|
92
116
|
rootCtx.on("agent/session-start", ({ agent }) => {
|
|
93
117
|
if (registered.has(agent))
|
package/lib/prompts.js
CHANGED
|
@@ -1,54 +1,58 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Model-facing prompt text for the hashline tools, embedded so the bundle
|
|
3
|
-
* ships no external prompt files. Each tool's description is short;
|
|
4
|
-
* `tool:*` system-prompt sections carry the
|
|
5
|
-
* reads when the tools are presented.
|
|
3
|
+
* ships no external prompt files. Each tool's schema `description` is short;
|
|
4
|
+
* the `tool:*` system-prompt sections carry the brief guidance the model
|
|
5
|
+
* reads when the tools are presented. Guidance is uniform: a one-line opener
|
|
6
|
+
* followed by tight bullets.
|
|
6
7
|
* @module dsh-better-edit/prompts
|
|
7
8
|
*/
|
|
8
|
-
export const EDIT_DESCRIPTION =
|
|
9
|
-
|
|
9
|
+
export const EDIT_DESCRIPTION = "Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. " +
|
|
10
|
+
"remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the " +
|
|
10
11
|
'leftmost column of a read row (row `ve7│function hello() {` means `"remove_from": "ve7"`). ' +
|
|
11
|
-
|
|
12
|
-
export const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
export const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
export const BATCH_EDIT_DESCRIPTION =
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
export const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
export const UNDO_DESCRIPTION =
|
|
50
|
-
|
|
51
|
-
export const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
12
|
+
"Never pass the line content, a code line, or a paragraph into these fields.";
|
|
13
|
+
export const EDIT_GUIDANCE = {
|
|
14
|
+
intro: "Edit a range of lines via a bare 3-char HASH anchor from read output — never by line content.",
|
|
15
|
+
lines: [
|
|
16
|
+
"`edit`: anchor the exact first and last lines that change by their stripped hash (`ve7`, not `ve7│function…`). A single line uses the same hash in both fields; never anchor a whole function or import block when part of it changes.",
|
|
17
|
+
"`edit`: replacement_text is byte-exact for the whole range — every line inside it you do not reproduce byte-exact is deleted, and leading whitespace is preserved exactly.",
|
|
18
|
+
"`edit`: `\\n` is a line break, so a range ending on a blank line must end replacement_text with `\\n` and a non-blank last line must not; a blank-line run is one `\\n` per blank line.",
|
|
19
|
+
"`edit`: the post-edit diff rows carry fresh anchors for follow-ups. A stale or never-served range is hard-rejected (`[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]`); copy the echoed rows and retry — only tool-served rows count.",
|
|
20
|
+
"`edit`: for multiple edits to one file, use batch_edit — it validates every item before writing and applies them all-or-nothing.",
|
|
21
|
+
],
|
|
22
|
+
};
|
|
23
|
+
export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
|
|
24
|
+
"No line numbers — use the HASH as the anchor in edit calls. Binary/directory → rejected; " +
|
|
25
|
+
"empty → HASH│ (edit to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.";
|
|
26
|
+
export const READ_GUIDANCE = {
|
|
27
|
+
intro: "Use read, not shell commands, to inspect text files and obtain the HASH anchors the editing tools require.",
|
|
28
|
+
lines: [
|
|
29
|
+
"`read`: call it only for content the tools have not served — a page you never saw, or lines past the post-edit diff.",
|
|
30
|
+
"`read`: each row is `HASH│content`; the HASH is the anchor (no line numbers). Rejection echoes return fresh rows that count as serves.",
|
|
31
|
+
"`read`: binary/directory rejects; page large files with offset/limit.",
|
|
32
|
+
],
|
|
33
|
+
};
|
|
34
|
+
export const BATCH_EDIT_DESCRIPTION = "Apply several edits in one atomic call. Each item is exactly like the edit tool: " +
|
|
35
|
+
"{ path?, remove_from, remove_to, replacement_text }, where remove_from and remove_to are " +
|
|
36
|
+
"bare 3-char hashes from read or diff output. Items targeting the same file are applied in order. " +
|
|
37
|
+
"Every item is verified against what the tool served you before ANYTHING is written: if any item " +
|
|
38
|
+
"fails — stale or ambiguous anchor, changed range interior, never-served line — the whole batch " +
|
|
39
|
+
"is rejected and no file changes. The failing item\u2019s current range is served back as fresh " +
|
|
40
|
+
"HASH│content rows so you can retry without a read. Use batch_edit whenever you have multiple " +
|
|
41
|
+
"edits; do not issue several edit calls in one message.";
|
|
42
|
+
export const BATCH_EDIT_GUIDANCE = {
|
|
43
|
+
intro: "Apply several edits in one atomic call.",
|
|
44
|
+
lines: [
|
|
45
|
+
"`batch_edit`: each item is edit\u2019s shape — { path?, remove_from, remove_to, replacement_text } — with bare hash anchors; items apply in order, and same-file ranges must not overlap.",
|
|
46
|
+
"`batch_edit`: all-or-nothing — any failing item writes nothing anywhere and echoes its current range as fresh rows that count as serves.",
|
|
47
|
+
"`batch_edit`: a no-op item is reported without failing; the result is one combined diff per file with fresh anchors.",
|
|
48
|
+
],
|
|
49
|
+
};
|
|
50
|
+
export const UNDO_DESCRIPTION = "Undo the last edit on a file, reverting it to its previous state. Use when an edit produced " +
|
|
51
|
+
"incorrect results (e.g., wrong content, duplicated lines, broken syntax).";
|
|
52
|
+
export const UNDO_GUIDANCE = {
|
|
53
|
+
intro: "Revert the last edit on a file.",
|
|
54
|
+
lines: [
|
|
55
|
+
"`undo_last_edit`: reverts only the most recent edit — any write clears history, so call it immediately after a bad edit.",
|
|
56
|
+
"`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits.",
|
|
57
|
+
],
|
|
58
|
+
};
|