@linxin666/dsh-liangshen 0.3.20 → 0.3.21
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/README.i18n.yaml +2 -2
- package/README.md +51 -35
- package/README.zh.md +53 -37
- package/lib/client.js +640 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +10 -6
- package/lib/types/announce.test.d.ts +1 -0
- package/lib/types/client/LiangShenLever.d.ts +17 -0
- package/lib/types/client/index.d.ts +45 -0
- package/lib/types/client/lever-controller.d.ts +133 -0
- package/lib/types/client/locales.d.ts +27 -0
- package/lib/types/core/lever.d.ts +50 -0
- package/lib/types/index.d.ts +10 -6
- package/lib/types/index.test.d.ts +1 -0
- package/lib/types/schema.test.d.ts +1 -0
- package/lib/types/sync.test.d.ts +1 -0
- package/package.json +29 -2
- package/presets/liangshen/NOTICE +4 -3
- package/presets/liangshen/agent.cordis.yml +122 -86
- package/presets/liangshen/custom-bash.mjs +4 -4
- package/presets/liangshen/minimal-prompt.mjs +534 -0
- package/presets/liangshen/tool-catalog.mjs +518 -0
- package/src/client/LiangShenLever.module.css +314 -0
- package/src/client/LiangShenLever.tsx +176 -0
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +89 -0
- package/src/client/lever-controller.ts +331 -0
- package/src/client/locales.ts +46 -0
- package/src/core/lever.ts +68 -0
- package/src/index.ts +10 -6
- package/src/schema.test.ts +1 -1
- package/src/sync.test.ts +4 -4
- package/tools/analyze-session.mjs +25 -5
- package/presets/liangshen/tool-bootstrap.mjs +0 -601
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* minimal-prompt — keep this preset's system prompt on the builtin Minimal
|
|
3
|
+
* preset's one-line persona (plus the session's workspace directory) while the
|
|
4
|
+
* tool surface is staged behind the anchor turn and handed to PTC presentation
|
|
5
|
+
* after it.
|
|
6
|
+
*
|
|
7
|
+
* The assembled prompt is filtered down to the persona section, so the harness
|
|
8
|
+
* identity, web-surface, tool-guidance, file-reference, and structured-output
|
|
9
|
+
* sections never reach the model: the one-line surface is what anchors the
|
|
10
|
+
* trajectory, and the model's capability facts arrive as the `tool-catalog`
|
|
11
|
+
* pre-step message instead of system-prompt prose. Under PTC presentation that
|
|
12
|
+
* filter also drops the harness's generated `tools:sdk` and `tools:ptc-only`
|
|
13
|
+
* sections — the only two places the SDK bindings and the "only `run_code` may
|
|
14
|
+
* be called directly" rule would otherwise appear — which is why the injected
|
|
15
|
+
* catalog carries both (the SDK entries as argument signatures, the rule as its
|
|
16
|
+
* closing sentence).
|
|
17
|
+
*
|
|
18
|
+
* WORKSPACE LINE: the bare persona says nothing about where the session
|
|
19
|
+
* operates, so the selected workspace directory is appended to the persona at
|
|
20
|
+
* assembly time (`Your working directory is <cwd>.`), read from the session
|
|
21
|
+
* header. This is the only orientation fact the persona block carries.
|
|
22
|
+
*
|
|
23
|
+
* WORKSPACE INSTRUCTIONS (default `instructionSource: 'system-prompt'`): the
|
|
24
|
+
* AGENTS.md-style instruction files the harness would inject as user-role
|
|
25
|
+
* context are instead read at assembly time and become part of the system
|
|
26
|
+
* prompt itself, as one `workspace-instructions` section appended after the
|
|
27
|
+
* persona block and plan mode's policy. Discovery mirrors the harness's
|
|
28
|
+
* baseline chain — `$DSH_HOME/AGENTS.md`, then `AGENTS.md` / `CLAUDE.md` and
|
|
29
|
+
* their `.local` overlays from the project root (the nearest ancestor holding
|
|
30
|
+
* a `.git` marker) down to the session cwd, broadest first, with the harness's
|
|
31
|
+
* per-directory duplicate suppression and byte budget — so the content rides
|
|
32
|
+
* the prompt on every request: it survives compaction, needs no durable
|
|
33
|
+
* message, and picks up file edits on the next assembly. The section is
|
|
34
|
+
* appended after the stable prefix, so the anchor's KV-cache prefix stays
|
|
35
|
+
* intact. Because the harness's prompt renderer interpolates every section
|
|
36
|
+
* strictly, the section text is only a `{{workspace_instructions}}` reference
|
|
37
|
+
* and the rendered content travels as that assembly variable's value —
|
|
38
|
+
* variable values are inserted verbatim and never re-scanned, so instruction
|
|
39
|
+
* files may contain `{{...}}` examples without breaking every request. The
|
|
40
|
+
* harness's own agent-instructions injections are dropped entirely in this
|
|
41
|
+
* mode (the baseline would otherwise duplicate the prompt's content); the
|
|
42
|
+
* harness's DYNAMIC reconciliation — nested instruction files surfaced when a
|
|
43
|
+
* read/write/edit tool touches their directory — is not reproduced: those
|
|
44
|
+
* injections are dropped too, and this mode's file tools (`str_replace_editor`,
|
|
45
|
+
* PTC programs) rarely carry the `read` / `write` / `edit` names that trigger
|
|
46
|
+
* it anyway. `instructionSource: 'hint'` restores the previous behavior: the
|
|
47
|
+
* first injection becomes a single non-imperative pointer to the reference
|
|
48
|
+
* files (issue #388, upstream dsh-anchored-standard #49, E1/E1.5/E2) and every
|
|
49
|
+
* later injection is dropped; the model reaches the knowledge through read /
|
|
50
|
+
* skill_load.
|
|
51
|
+
*
|
|
52
|
+
* PLAN MODE is the one exception kept by default. `dsh-plan-mode` enforces its
|
|
53
|
+
* rules through the `plan:policy` prompt section alone — the exit tool stays
|
|
54
|
+
* registered in every mode and no tool restriction backs it — so dropping the
|
|
55
|
+
* section would leave plan mode silently unenforced rather than merely
|
|
56
|
+
* unmentioned. `keepPlanPolicy: false` restores the strict one-line surface.
|
|
57
|
+
*
|
|
58
|
+
* ROBUSTNESS: a composition whose persona section carries none of the accepted
|
|
59
|
+
* names degrades to the unfiltered assembly with a one-time warning instead of
|
|
60
|
+
* sending an empty system prompt. Three names are accepted because the persona
|
|
61
|
+
* slot has been spelled `deployment:persona-prefix` (current SDK), and
|
|
62
|
+
* `deployment:persona` / `persona` (legacy harnesses) over the preset's
|
|
63
|
+
* supported range. The same degradation guards the instruction reader: an
|
|
64
|
+
* assembly-time read failure contributes no section (warned once) instead of
|
|
65
|
+
* failing the request.
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
69
|
+
import { homedir } from 'node:os'
|
|
70
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
71
|
+
|
|
72
|
+
/** Cordis plugin name used by loader diagnostics. */
|
|
73
|
+
export const name = 'liangshen-minimal-prompt'
|
|
74
|
+
|
|
75
|
+
/** Prompt assembly must exist before the section filter can register. */
|
|
76
|
+
export const inject = ['systemPrompt']
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Prompt section names that carry the preset persona, newest spelling first.
|
|
80
|
+
* `deployment:persona-prefix` is what `@deepseek-ai/dsh-persona` registers
|
|
81
|
+
* (PERSONA_PREFIX_SECTION); the other two are kept for older harnesses.
|
|
82
|
+
*/
|
|
83
|
+
export const PERSONA_SECTION_NAMES = ['deployment:persona-prefix', 'deployment:persona', 'persona']
|
|
84
|
+
|
|
85
|
+
/** Plan-mode policy section, owned by `@deepseek-ai/dsh-plan-mode`. */
|
|
86
|
+
export const PLAN_POLICY_SECTION_NAME = 'plan:policy'
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The section this plugin appends to the prompt with the workspace
|
|
90
|
+
* instructions, and the assembly variable whose value carries the rendered
|
|
91
|
+
* text. The section text is only the variable reference: the harness's
|
|
92
|
+
* renderer interpolates section text strictly (an unknown `{{name}}` throws),
|
|
93
|
+
* while a variable's value is inserted verbatim and never re-scanned.
|
|
94
|
+
*/
|
|
95
|
+
export const WORKSPACE_INSTRUCTIONS_SECTION_NAME = 'workspace-instructions'
|
|
96
|
+
export const WORKSPACE_INSTRUCTIONS_VARIABLE = 'workspace_instructions'
|
|
97
|
+
|
|
98
|
+
/** Accepted `instructionSource` values, default first. */
|
|
99
|
+
export const INSTRUCTION_SOURCES = ['system-prompt', 'hint']
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Instruction file candidates per directory, in the harness's order: the
|
|
103
|
+
* shared names first, then the personal `.local` overlays.
|
|
104
|
+
*/
|
|
105
|
+
const INSTRUCTION_FILE_CANDIDATES = ['AGENTS.md', 'CLAUDE.md']
|
|
106
|
+
const LOCAL_INSTRUCTION_FILE_CANDIDATES = ['AGENTS.local.md', 'CLAUDE.local.md']
|
|
107
|
+
|
|
108
|
+
/** Directory marker that ends the project-root walk (the harness's default). */
|
|
109
|
+
const PROJECT_ROOT_MARKER = '.git'
|
|
110
|
+
|
|
111
|
+
/** The single user-global instruction file under the harness home. */
|
|
112
|
+
const USER_GLOBAL_FILE = 'AGENTS.md'
|
|
113
|
+
const DSH_HOME_ENV = 'DSH_HOME'
|
|
114
|
+
const DSH_HOME_DIR_NAME = '.dsh'
|
|
115
|
+
|
|
116
|
+
/** Files larger than this are skipped, as the harness's source cap does. */
|
|
117
|
+
const MAX_SOURCE_BYTES = 1048576
|
|
118
|
+
|
|
119
|
+
/** Default byte budget for the rendered workspace-instructions section. */
|
|
120
|
+
const DEFAULT_INSTRUCTION_MAX_BYTES = 65536
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Reference-file lines one agent-instructions message renders, e.g.
|
|
124
|
+
* `Instructions from: /path/AGENTS.md`.
|
|
125
|
+
*/
|
|
126
|
+
const INSTRUCTION_FROM_RE = /(?:^|\n) *(?:Additional |Updated )?Instructions from: ([^\n]+)/g
|
|
127
|
+
|
|
128
|
+
function optionalBoolean(value, field, fallback) {
|
|
129
|
+
if (value === undefined) return fallback
|
|
130
|
+
if (typeof value !== 'boolean') {
|
|
131
|
+
throw new TypeError(`${name}: ${field} must be a boolean`)
|
|
132
|
+
}
|
|
133
|
+
return value
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function optionalSource(value, field, fallback) {
|
|
137
|
+
if (value === undefined) return fallback
|
|
138
|
+
if (!INSTRUCTION_SOURCES.includes(value)) {
|
|
139
|
+
throw new TypeError(`${name}: ${field} must be one of ${JSON.stringify(INSTRUCTION_SOURCES)}`)
|
|
140
|
+
}
|
|
141
|
+
return value
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function optionalByteSize(value, field, fallback) {
|
|
145
|
+
if (value === undefined) return fallback
|
|
146
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
147
|
+
throw new TypeError(`${name}: ${field} must be a positive finite number`)
|
|
148
|
+
}
|
|
149
|
+
return value
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Expand a leading `~` the way the harness's home paths do. */
|
|
153
|
+
function expandHomePath(path) {
|
|
154
|
+
if (path === '~') return homedir()
|
|
155
|
+
if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
|
|
156
|
+
return path
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The harness home: `$DSH_HOME` when set, else `<home>/.dsh`. */
|
|
160
|
+
export function resolveDshHome(env = process.env) {
|
|
161
|
+
const fromEnv = env[DSH_HOME_ENV]
|
|
162
|
+
const raw = fromEnv !== undefined && fromEnv.trim().length > 0 ? fromEnv : join(homedir(), DSH_HOME_DIR_NAME)
|
|
163
|
+
return resolve(expandHomePath(raw))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Model-facing display path of the harness home (`~/.dsh` or `$DSH_HOME`). */
|
|
167
|
+
function dshHomeDisplay(home) {
|
|
168
|
+
return home === resolve(join(homedir(), DSH_HOME_DIR_NAME)) ? `~/${DSH_HOME_DIR_NAME}` : `$${DSH_HOME_ENV}`
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function statFile(path) {
|
|
172
|
+
try {
|
|
173
|
+
return await stat(path)
|
|
174
|
+
} catch {
|
|
175
|
+
return undefined
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Discover the baseline instruction files for one session cwd, mirroring the
|
|
181
|
+
* harness's baseline chain: the user-global file first, then every directory
|
|
182
|
+
* from the project root (the nearest ancestor holding a `.git` marker, or the
|
|
183
|
+
* cwd itself when none exists) down to the cwd, broadest to most specific.
|
|
184
|
+
*/
|
|
185
|
+
export async function discoverInstructionFiles(cwd, env = process.env) {
|
|
186
|
+
const home = resolveDshHome(env)
|
|
187
|
+
const start = resolve(cwd)
|
|
188
|
+
const files = []
|
|
189
|
+
const seen = new Set()
|
|
190
|
+
const add = (absolutePath, displayPath) => {
|
|
191
|
+
if (seen.has(absolutePath)) return
|
|
192
|
+
seen.add(absolutePath)
|
|
193
|
+
files.push({ absolutePath, displayPath })
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const userGlobal = join(home, USER_GLOBAL_FILE)
|
|
197
|
+
if ((await statFile(userGlobal))?.isFile()) {
|
|
198
|
+
add(userGlobal, `${dshHomeDisplay(home)}/${USER_GLOBAL_FILE}`)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let root = start
|
|
202
|
+
for (;;) {
|
|
203
|
+
if (await statFile(join(root, PROJECT_ROOT_MARKER))) break
|
|
204
|
+
const parent = dirname(root)
|
|
205
|
+
if (parent === root) {
|
|
206
|
+
root = start
|
|
207
|
+
break
|
|
208
|
+
}
|
|
209
|
+
root = parent
|
|
210
|
+
}
|
|
211
|
+
const chain = []
|
|
212
|
+
for (let dir = start; ; dir = dirname(dir)) {
|
|
213
|
+
chain.push(dir)
|
|
214
|
+
if (dir === root) break
|
|
215
|
+
}
|
|
216
|
+
chain.reverse()
|
|
217
|
+
for (const dir of chain) {
|
|
218
|
+
for (const candidates of [INSTRUCTION_FILE_CANDIDATES, LOCAL_INSTRUCTION_FILE_CANDIDATES]) {
|
|
219
|
+
for (const candidate of candidates) {
|
|
220
|
+
const path = join(dir, candidate)
|
|
221
|
+
if ((await statFile(path))?.isFile()) add(path, relative(root, path))
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return files
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Read one instruction file, or undefined when unreadable or over the cap. */
|
|
229
|
+
async function readInstructionFile(path, size) {
|
|
230
|
+
if (size > MAX_SOURCE_BYTES) return undefined
|
|
231
|
+
try {
|
|
232
|
+
const content = await readFile(path, 'utf8')
|
|
233
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_SOURCE_BYTES) return undefined
|
|
234
|
+
return content
|
|
235
|
+
} catch {
|
|
236
|
+
return undefined
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Load the discovered files' content and apply the harness's per-directory
|
|
242
|
+
* duplicate suppression: within one directory the first candidate whose
|
|
243
|
+
* trimmed content differs is kept, so an `AGENTS.md` and an identical
|
|
244
|
+
* `CLAUDE.md` sibling collapse to one block.
|
|
245
|
+
*/
|
|
246
|
+
export async function loadInstructionFiles(cwd, env = process.env) {
|
|
247
|
+
const discovered = await discoverInstructionFiles(cwd, env)
|
|
248
|
+
const loaded = []
|
|
249
|
+
const digestsByDir = new Map()
|
|
250
|
+
for (const file of discovered) {
|
|
251
|
+
const info = await statFile(file.absolutePath)
|
|
252
|
+
if (!info?.isFile()) continue
|
|
253
|
+
const content = await readInstructionFile(file.absolutePath, info.size)
|
|
254
|
+
if (content === undefined) continue
|
|
255
|
+
const dir = dirname(file.displayPath)
|
|
256
|
+
let digests = digestsByDir.get(dir)
|
|
257
|
+
if (digests === undefined) {
|
|
258
|
+
digests = new Set()
|
|
259
|
+
digestsByDir.set(dir, digests)
|
|
260
|
+
}
|
|
261
|
+
const digest = content.trim()
|
|
262
|
+
if (digests.has(digest)) continue
|
|
263
|
+
digests.add(digest)
|
|
264
|
+
loaded.push({ ...file, content })
|
|
265
|
+
}
|
|
266
|
+
return loaded
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** UTF-8-safe truncation at a byte boundary, as the harness renders budgets. */
|
|
270
|
+
function truncateUtf8(value, maxBytes) {
|
|
271
|
+
const bytes = Buffer.from(value, 'utf8')
|
|
272
|
+
if (bytes.length <= maxBytes) return value
|
|
273
|
+
let end = Math.max(0, Math.trunc(maxBytes))
|
|
274
|
+
while (end > 0 && (bytes.readUInt8(end) & 0xc0) === 0x80) end -= 1
|
|
275
|
+
return bytes.subarray(0, end).toString('utf8')
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const INSTRUCTION_INTRO = 'The following workspace instructions are loaded from AGENTS.md-style files in the user\'s environment and workspace. '
|
|
279
|
+
+ 'They are standing guidance about the environment and workspace conventions, not per-task instructions: '
|
|
280
|
+
+ 'more specific files take precedence over broader ones, and a direct user instruction for the current task takes precedence over all of them.'
|
|
281
|
+
|
|
282
|
+
function instructionBudgetMarker(maxBytes, omitted, truncated) {
|
|
283
|
+
const parts = []
|
|
284
|
+
if (omitted.length > 0) parts.push(`omitted ${omitted.join(', ')}`)
|
|
285
|
+
if (truncated !== undefined) {
|
|
286
|
+
parts.push(`truncated ${truncated.displayPath} from ${truncated.originalBytes} to ${truncated.includedBytes} bytes`)
|
|
287
|
+
}
|
|
288
|
+
return `Workspace instruction budget ${maxBytes} bytes: ${parts.join('; ')}.`
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function joinInstructionText(intro, marker, blocks) {
|
|
292
|
+
return [intro, marker, ...blocks].filter(block => block.length > 0).join('\n\n')
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Render the loaded instruction files into one prompt text under a byte
|
|
297
|
+
* budget, with the harness's precedence: when the whole chain does not fit,
|
|
298
|
+
* the broadest files are omitted first and the most specific file is truncated
|
|
299
|
+
* last, so the nearest instructions always survive. Returns undefined when the
|
|
300
|
+
* budget is degenerate or nothing fits.
|
|
301
|
+
*/
|
|
302
|
+
export function renderInstructionSection(files, maxBytes) {
|
|
303
|
+
if (maxBytes <= 0 || !Number.isFinite(maxBytes) || files.length === 0) return undefined
|
|
304
|
+
const blocks = files.map(file => `Instructions from: ${file.displayPath}\n\n${file.content}`)
|
|
305
|
+
const full = joinInstructionText(INSTRUCTION_INTRO, '', blocks)
|
|
306
|
+
if (Buffer.byteLength(full, 'utf8') <= maxBytes) return full
|
|
307
|
+
for (let start = 1; start < blocks.length; start += 1) {
|
|
308
|
+
const omitted = files.slice(0, start).map(file => file.displayPath)
|
|
309
|
+
const suffix = joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, undefined), blocks.slice(start))
|
|
310
|
+
if (Buffer.byteLength(suffix, 'utf8') <= maxBytes) return suffix
|
|
311
|
+
}
|
|
312
|
+
// Even the most specific file does not fit whole: truncate its content to
|
|
313
|
+
// the largest byte length the frame accepts.
|
|
314
|
+
const last = files.at(-1)
|
|
315
|
+
const omitted = files.slice(0, -1).map(file => file.displayPath)
|
|
316
|
+
const originalBytes = Buffer.byteLength(last.content, 'utf8')
|
|
317
|
+
const overheadBytes = Buffer.byteLength(joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, { displayPath: last.displayPath, originalBytes, includedBytes: 0 }), [`Instructions from: ${last.displayPath}\n\n`]), 'utf8')
|
|
318
|
+
if (overheadBytes >= maxBytes) return undefined
|
|
319
|
+
let low = 0
|
|
320
|
+
let high = originalBytes
|
|
321
|
+
let best = ''
|
|
322
|
+
while (low <= high) {
|
|
323
|
+
const mid = Math.floor((low + high) / 2)
|
|
324
|
+
const candidate = truncateUtf8(last.content, mid)
|
|
325
|
+
const truncated = { displayPath: last.displayPath, originalBytes, includedBytes: Buffer.byteLength(candidate, 'utf8') }
|
|
326
|
+
const text = joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, truncated), [`Instructions from: ${last.displayPath}\n\n${candidate}`])
|
|
327
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) {
|
|
328
|
+
best = text
|
|
329
|
+
low = mid + 1
|
|
330
|
+
} else {
|
|
331
|
+
high = mid - 1
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return best.length > 0 ? best : undefined
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Read and render the workspace-instruction prompt text for one session, or
|
|
339
|
+
* undefined when the session reports no cwd, no instruction file exists, or
|
|
340
|
+
* the budget leaves nothing to send.
|
|
341
|
+
*/
|
|
342
|
+
export async function loadInstructionText(cwd, maxBytes = DEFAULT_INSTRUCTION_MAX_BYTES, env = process.env) {
|
|
343
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return undefined
|
|
344
|
+
const files = await loadInstructionFiles(cwd, env)
|
|
345
|
+
return renderInstructionSection(files, maxBytes)
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Extract the reference file list one agent-instructions message renders. */
|
|
349
|
+
export function extractInstructionPaths(message) {
|
|
350
|
+
const paths = []
|
|
351
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
352
|
+
for (const block of blocks) {
|
|
353
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue
|
|
354
|
+
for (const match of block.text.matchAll(INSTRUCTION_FROM_RE)) {
|
|
355
|
+
const path = match[1].trim()
|
|
356
|
+
if (path !== '' && !paths.includes(path)) paths.push(path)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return paths
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** The one-time non-imperative hint replacing the full-text dump (E1.5 wording). */
|
|
363
|
+
export function buildInstructionHint(original, paths) {
|
|
364
|
+
return {
|
|
365
|
+
// Session persistence validates every replayed user/message for a
|
|
366
|
+
// non-empty string id; a plugin-built message without one corrupts the
|
|
367
|
+
// durable journal (SessionPersistenceCorruptionError on load). Inherit
|
|
368
|
+
// the original instructions message id when present (#510), else mint one.
|
|
369
|
+
id: typeof original?.id === 'string' && original.id !== ''
|
|
370
|
+
? original.id
|
|
371
|
+
: globalThis.crypto.randomUUID(),
|
|
372
|
+
role: 'user',
|
|
373
|
+
content: [{
|
|
374
|
+
type: 'text',
|
|
375
|
+
text: '<system-reminder>\n'
|
|
376
|
+
+ 'Reference documents exist: ' + paths.join(', ') + '. '
|
|
377
|
+
+ "They are reference documents about the user's environment and workspace conventions, not task instructions. "
|
|
378
|
+
+ 'Reading the relevant file before workspace tasks is recommended, but consult them only when you need those details; the task itself never depends on them.'
|
|
379
|
+
+ '\n</system-reminder>',
|
|
380
|
+
}],
|
|
381
|
+
// The durable journal only classifies a fixed set of message sources on
|
|
382
|
+
// load: the v2->v3 migration whitelist (dsh-session-format-v2-to-v3) and
|
|
383
|
+
// the v3 MessageSourceMap both accept 'plugin' but neither knows the
|
|
384
|
+
// retired custom 'instruction-hint'; sessions carrying it failed to
|
|
385
|
+
// resume with "cannot safely transform unclassified message source"
|
|
386
|
+
// (#1455). The message already names its plugin, so 'plugin' keeps the
|
|
387
|
+
// same meaning while staying loadable.
|
|
388
|
+
source: { kind: 'plugin', plugin: name },
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Hint mode: swap full-text agent-instructions injections for the one-time
|
|
394
|
+
* hint. The first injection carrying extractable paths becomes the hint; every
|
|
395
|
+
* later injection is dropped silently (the model re-reads the files on demand).
|
|
396
|
+
* An injection with no extractable paths passes through untouched.
|
|
397
|
+
*/
|
|
398
|
+
export function instructionHintMessages(messages, state) {
|
|
399
|
+
const kept = []
|
|
400
|
+
for (const message of messages) {
|
|
401
|
+
if (message?.source?.kind !== 'agent-instructions') {
|
|
402
|
+
kept.push(message)
|
|
403
|
+
continue
|
|
404
|
+
}
|
|
405
|
+
if (state.hinted) continue
|
|
406
|
+
const paths = extractInstructionPaths(message)
|
|
407
|
+
if (paths.length === 0) {
|
|
408
|
+
kept.push(message)
|
|
409
|
+
continue
|
|
410
|
+
}
|
|
411
|
+
state.hinted = true
|
|
412
|
+
kept.push(buildInstructionHint(message, paths))
|
|
413
|
+
}
|
|
414
|
+
return kept
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** System-prompt mode: drop every agent-instructions injection. */
|
|
418
|
+
export function dropInstructionMessages(messages) {
|
|
419
|
+
return messages.filter(message => message?.source?.kind !== 'agent-instructions')
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Workspace line the persona gains. The one-line persona carries no
|
|
424
|
+
* orientation facts, so the session's selected workspace directory is appended
|
|
425
|
+
* to the persona section at assembly time. The literal cwd comes from the
|
|
426
|
+
* session header, so the line stays correct after a workspace switch, and a
|
|
427
|
+
* session without a readable cwd keeps the bare persona rather than failing.
|
|
428
|
+
*/
|
|
429
|
+
const WORKSPACE_LINE_PREFIX = '\n\nYour working directory is '
|
|
430
|
+
|
|
431
|
+
/** Append the workspace line to the persona section, once. */
|
|
432
|
+
export function withWorkspaceLine(sections, agent) {
|
|
433
|
+
const cwd = agent?.session?.header?.cwd
|
|
434
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return sections
|
|
435
|
+
const line = `${WORKSPACE_LINE_PREFIX}${cwd}.`
|
|
436
|
+
const persona = sections.find(section =>
|
|
437
|
+
PERSONA_SECTION_NAMES.includes(section?.name)
|
|
438
|
+
&& typeof section?.text === 'string'
|
|
439
|
+
&& !section.text.includes(line))
|
|
440
|
+
if (persona === undefined) return sections
|
|
441
|
+
return sections.map(section => section === persona
|
|
442
|
+
? { ...section, text: `${section.text}${line}` }
|
|
443
|
+
: section)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** Register the section filter and the workspace-instruction source. */
|
|
447
|
+
export function apply(ctx, config) {
|
|
448
|
+
const keepPlanPolicy = optionalBoolean(config?.keepPlanPolicy, 'keepPlanPolicy', true)
|
|
449
|
+
const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'system-prompt')
|
|
450
|
+
const instructionMaxBytes = optionalByteSize(config?.instructionMaxBytes, 'instructionMaxBytes', DEFAULT_INSTRUCTION_MAX_BYTES)
|
|
451
|
+
const keep = new Set([
|
|
452
|
+
...PERSONA_SECTION_NAMES,
|
|
453
|
+
...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
|
|
454
|
+
])
|
|
455
|
+
|
|
456
|
+
// Per-session hint state (hint mode only). A compaction rewrites the
|
|
457
|
+
// model-visible surface, so the next agent-instructions injection is a
|
|
458
|
+
// fresh first injection and may be hinted again.
|
|
459
|
+
const hintedBySession = new WeakMap()
|
|
460
|
+
const stateFor = (session) => {
|
|
461
|
+
let state = hintedBySession.get(session)
|
|
462
|
+
if (state === undefined) {
|
|
463
|
+
state = { hinted: false }
|
|
464
|
+
hintedBySession.set(session, state)
|
|
465
|
+
}
|
|
466
|
+
return state
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
let warned = false
|
|
470
|
+
const warnOnce = (message) => {
|
|
471
|
+
if (warned) return
|
|
472
|
+
warned = true
|
|
473
|
+
try {
|
|
474
|
+
ctx.logger?.warn?.(message)
|
|
475
|
+
} catch {
|
|
476
|
+
// Logger unavailable — the guard exists only to avoid spamming.
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// `prepend: true` puts the filter at the outermost position of the
|
|
481
|
+
// waterfall, so `await next()` always observes the complete downstream
|
|
482
|
+
// section list (including sections other listeners added) before it is
|
|
483
|
+
// narrowed to the persona and extended with the workspace instructions.
|
|
484
|
+
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
485
|
+
// Downstream errors propagate untouched; only this filter's own logic is
|
|
486
|
+
// guarded (a filter bug must never brick every request of a session).
|
|
487
|
+
const assembled = await next()
|
|
488
|
+
if (!Array.isArray(assembled.sections)) return assembled
|
|
489
|
+
const sections = assembled.sections.filter(section => keep.has(section?.name))
|
|
490
|
+
if (sections.length === 0) {
|
|
491
|
+
// A persona-less assembly must not become an empty system prompt: keep
|
|
492
|
+
// the assembled prompt and say so once.
|
|
493
|
+
warnOnce(`${name}: no section matched ${JSON.stringify([...keep])} — `
|
|
494
|
+
+ 'keeping the assembled prompt instead of sending an empty one')
|
|
495
|
+
return assembled
|
|
496
|
+
}
|
|
497
|
+
const narrowed = withWorkspaceLine(sections, context?.agent)
|
|
498
|
+
if (instructionSource !== 'system-prompt') return { ...assembled, sections: narrowed }
|
|
499
|
+
let text
|
|
500
|
+
try {
|
|
501
|
+
text = await loadInstructionText(context?.agent?.session?.header?.cwd, instructionMaxBytes)
|
|
502
|
+
} catch (error) {
|
|
503
|
+
warnOnce(`${name}: reading the workspace instructions failed — sending the prompt without them (${error instanceof Error ? error.message : String(error)})`)
|
|
504
|
+
return { ...assembled, sections: narrowed }
|
|
505
|
+
}
|
|
506
|
+
if (text === undefined) return { ...assembled, sections: narrowed }
|
|
507
|
+
// The rendered content travels as an assembly variable: the harness's
|
|
508
|
+
// renderer interpolates section text strictly, and instruction files may
|
|
509
|
+
// legitimately contain `{{...}}` examples. Variable values are inserted
|
|
510
|
+
// verbatim and never re-scanned.
|
|
511
|
+
return {
|
|
512
|
+
...assembled,
|
|
513
|
+
sections: [...narrowed, { name: WORKSPACE_INSTRUCTIONS_SECTION_NAME, text: `{{${WORKSPACE_INSTRUCTIONS_VARIABLE}}}` }],
|
|
514
|
+
variables: { ...assembled.variables, [WORKSPACE_INSTRUCTIONS_VARIABLE]: text },
|
|
515
|
+
}
|
|
516
|
+
}, { prepend: true })
|
|
517
|
+
|
|
518
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
519
|
+
const decision = await next()
|
|
520
|
+
if (decision.kind !== 'enter') return decision
|
|
521
|
+
if (instructionSource === 'system-prompt') {
|
|
522
|
+
return decision.messages.some(message => message?.source?.kind === 'agent-instructions')
|
|
523
|
+
? { ...decision, messages: dropInstructionMessages(decision.messages) }
|
|
524
|
+
: decision
|
|
525
|
+
}
|
|
526
|
+
const session = payload?.agent?.session
|
|
527
|
+
if (session === undefined) return decision
|
|
528
|
+
return { ...decision, messages: instructionHintMessages(decision.messages, stateFor(session)) }
|
|
529
|
+
}, { prepend: true })
|
|
530
|
+
|
|
531
|
+
ctx.on('session/event', (session, event) => {
|
|
532
|
+
if (event?.type === 'compaction/end') hintedBySession.delete(session)
|
|
533
|
+
})
|
|
534
|
+
}
|