@linxin666/dsh-liangshen 0.3.20 → 0.3.22
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 +69 -39
- package/README.zh.md +70 -40
- package/lib/client.js +640 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +11 -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 +11 -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 +129 -86
- package/presets/liangshen/custom-bash.mjs +4 -4
- package/presets/liangshen/minimal-prompt.mjs +835 -0
- package/presets/liangshen/tool-catalog.mjs +631 -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 +11 -6
- package/src/schema.test.ts +1 -1
- package/src/sync.test.ts +4 -4
- package/tools/analyze-session.mjs +25 -5
- package/tools/benchmark-driver.mjs +124 -0
- package/tools/benchmark-live-run.mjs +771 -0
- package/tools/benchmark-report.mjs +354 -0
- package/tools/tasks/liangshen-v41-flash.json +127 -0
- package/presets/liangshen/tool-bootstrap.mjs +0 -601
|
@@ -0,0 +1,835 @@
|
|
|
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, plus the plan
|
|
8
|
+
* policy when plan mode is active and the official PTC tool SDK sections
|
|
9
|
+
* (`tools:sdk` and `tools:ptc-only`) when PTC mode is active: the harness
|
|
10
|
+
* identity, web-surface, tool-guidance, file-reference, and structured-output
|
|
11
|
+
* sections never reach the model. Under PTC presentation, keeping the official
|
|
12
|
+
* `tools:sdk` and `tools:ptc-only` sections ensures the model receives the
|
|
13
|
+
* complete generated tool signatures, argument types, output schemas, and
|
|
14
|
+
* parameter comments without private SDK schemas or renderer duplication.
|
|
15
|
+
*
|
|
16
|
+
* WORKSPACE LINE: the bare persona says nothing about where the session
|
|
17
|
+
* operates, so the selected workspace directory is appended to the persona at
|
|
18
|
+
* assembly time (`Your working directory is <cwd>.`), read from the session
|
|
19
|
+
* header. This is the only orientation fact the persona block carries.
|
|
20
|
+
*
|
|
21
|
+
* WORKSPACE INSTRUCTIONS (default `instructionSource: 'system-prompt'`): the
|
|
22
|
+
* AGENTS.md-style instruction files the harness would inject as user-role
|
|
23
|
+
* context are instead read at assembly time and become part of the system
|
|
24
|
+
* prompt itself, as one `workspace-instructions` section appended after the
|
|
25
|
+
* persona block and plan mode's policy. Discovery mirrors the harness's
|
|
26
|
+
* baseline chain — `$DSH_HOME/AGENTS.md`, then `AGENTS.md` / `CLAUDE.md` and
|
|
27
|
+
* their `.local` overlays from the project root (the nearest ancestor holding
|
|
28
|
+
* a `.git` marker) down to the session cwd, broadest first, with the harness's
|
|
29
|
+
* per-directory duplicate suppression and byte budget — so the content rides
|
|
30
|
+
* the prompt on every request: it survives compaction, needs no durable
|
|
31
|
+
* message, and picks up file edits on the next assembly. The section is
|
|
32
|
+
* appended after the stable prefix, so the anchor's KV-cache prefix stays
|
|
33
|
+
* intact. Because the harness's prompt renderer interpolates every section
|
|
34
|
+
* strictly, the section text is only a `{{workspace_instructions}}` reference
|
|
35
|
+
* and the rendered content travels as that assembly variable's value —
|
|
36
|
+
* variable values are inserted verbatim and never re-scanned, so instruction
|
|
37
|
+
* files may contain `{{...}}` examples without breaking every request.
|
|
38
|
+
*
|
|
39
|
+
* DYNAMIC RECONCILIATION & HOST CONTRACT:
|
|
40
|
+
* - Baseline instructions are resident in the system prompt. When the host's
|
|
41
|
+
* agent-instructions emits a pure baseline message (`source.baseline === true`),
|
|
42
|
+
* if the baseline was successfully loaded in the system prompt for this session,
|
|
43
|
+
* we condense it into a legal, non-empty, brief user message in the normal
|
|
44
|
+
* `decision.messages`, preserving the exact `message.source` schema (including
|
|
45
|
+
* `baseline: true` and `baselineIdentity`). This ensures the host's
|
|
46
|
+
* `visibleBaselineSource` detector observes baseline establishment on the
|
|
47
|
+
* session surface and does not retry baseline injection on every step, without
|
|
48
|
+
* bypassing decision persistence or polluting model context with duplicate prose.
|
|
49
|
+
* If reading baseline instructions failed, the message passes through untouched.
|
|
50
|
+
* - Dynamic subdirectory instructions (e.g. packages/* AGENTS.md) from the host
|
|
51
|
+
* are preserved intact with their original wrappers, intros, and priority rules.
|
|
52
|
+
* - For tools not covered by the host's file-name filter (such as
|
|
53
|
+
* `str_replace_editor` with `path` arguments) and PTC inner calls, we track
|
|
54
|
+
* actual tool executions from `tools/result` without fabricating fake tool events
|
|
55
|
+
* or parsing arbitrary code/bash strings. In `agent/pre-step`, incremental rules
|
|
56
|
+
* for newly touched directories are loaded as legal plugin messages.
|
|
57
|
+
* - PTC MULTI-STEP LIMITATION: Within a single `run_code` execution, multiple
|
|
58
|
+
* tool dispatches run synchronously in the worker thread. Any subpackage
|
|
59
|
+
* instructions triggered by an inner read/edit are projected on the NEXT step;
|
|
60
|
+
* same-program writes execute before that next-step projection reaches model context.
|
|
61
|
+
*
|
|
62
|
+
* `instructionSource: 'hint'` restores hint behavior: the first injection
|
|
63
|
+
* becomes a single non-imperative pointer to the reference files (issue #388,
|
|
64
|
+
* upstream dsh-anchored-standard #49) and every later injection is dropped; the
|
|
65
|
+
* model reaches the knowledge through read / skill_load.
|
|
66
|
+
*
|
|
67
|
+
* PLAN MODE is kept by default. `dsh-plan-mode` enforces its rules through
|
|
68
|
+
* the `plan:policy` prompt section alone. `keepPlanPolicy: false` restores the
|
|
69
|
+
* strict one-line surface.
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
73
|
+
import { homedir } from 'node:os'
|
|
74
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
75
|
+
|
|
76
|
+
/** Cordis plugin name used by loader diagnostics. */
|
|
77
|
+
export const name = 'liangshen-minimal-prompt'
|
|
78
|
+
|
|
79
|
+
/** Prompt assembly must exist before the section filter can register. */
|
|
80
|
+
export const inject = ['systemPrompt']
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Prompt section names that carry the preset persona, newest spelling first.
|
|
84
|
+
* `deployment:persona-prefix` is what `@deepseek-ai/dsh-persona` registers
|
|
85
|
+
* (PERSONA_PREFIX_SECTION); the other two are kept for older harnesses.
|
|
86
|
+
*/
|
|
87
|
+
export const PERSONA_SECTION_NAMES = ['deployment:persona-prefix', 'deployment:persona', 'persona']
|
|
88
|
+
|
|
89
|
+
/** Plan-mode policy section, owned by `@deepseek-ai/dsh-plan-mode`. */
|
|
90
|
+
export const PLAN_POLICY_SECTION_NAME = 'plan:policy'
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Programmatic tool calling (PTC) prompt section names owned by `@deepseek-ai/dsh-tools`.
|
|
94
|
+
* Retaining these ensures model-written `run_code` programs have the complete
|
|
95
|
+
* official SDK definitions, output types, and parameter documentation.
|
|
96
|
+
*/
|
|
97
|
+
export const PTC_SECTION_NAMES = ['tools:ptc-only', 'tools:sdk']
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The section this plugin appends to the prompt with the workspace
|
|
101
|
+
* instructions, and the assembly variable whose value carries the rendered
|
|
102
|
+
* text. The section text is only the variable reference: the harness's
|
|
103
|
+
* renderer interpolates section text strictly (an unknown `{{name}}` throws),
|
|
104
|
+
* while a variable's value is inserted verbatim and never re-scanned.
|
|
105
|
+
*/
|
|
106
|
+
export const WORKSPACE_INSTRUCTIONS_SECTION_NAME = 'workspace-instructions'
|
|
107
|
+
export const WORKSPACE_INSTRUCTIONS_VARIABLE = 'workspace_instructions'
|
|
108
|
+
|
|
109
|
+
/** Accepted `instructionSource` values, default first. */
|
|
110
|
+
export const INSTRUCTION_SOURCES = ['system-prompt', 'hint']
|
|
111
|
+
|
|
112
|
+
/** Tools whose executions touch workspace files and may trigger dynamic instruction discovery. */
|
|
113
|
+
export const FILE_TOUCH_TOOL_NAMES = new Set(['read', 'write', 'edit', 'str_replace_editor'])
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Instruction file candidates per directory, in the harness's order: the
|
|
117
|
+
* shared names first, then the personal `.local` overlays.
|
|
118
|
+
*/
|
|
119
|
+
const INSTRUCTION_FILE_CANDIDATES = ['AGENTS.md', 'CLAUDE.md']
|
|
120
|
+
const LOCAL_INSTRUCTION_FILE_CANDIDATES = ['AGENTS.local.md', 'CLAUDE.local.md']
|
|
121
|
+
|
|
122
|
+
/** Directory marker that ends the project-root walk (the harness's default). */
|
|
123
|
+
const PROJECT_ROOT_MARKER = '.git'
|
|
124
|
+
|
|
125
|
+
/** The single user-global instruction file under the harness home. */
|
|
126
|
+
const USER_GLOBAL_FILE = 'AGENTS.md'
|
|
127
|
+
const DSH_HOME_ENV = 'DSH_HOME'
|
|
128
|
+
const DSH_HOME_DIR_NAME = '.dsh'
|
|
129
|
+
|
|
130
|
+
/** Files larger than this are skipped, as the harness's source cap does. */
|
|
131
|
+
const MAX_SOURCE_BYTES = 1048576
|
|
132
|
+
|
|
133
|
+
/** Default byte budget for the rendered workspace-instructions section. */
|
|
134
|
+
const DEFAULT_INSTRUCTION_MAX_BYTES = 65536
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Reference-file lines one agent-instructions message renders, e.g.
|
|
138
|
+
* `Instructions from: /path/AGENTS.md`.
|
|
139
|
+
*/
|
|
140
|
+
const INSTRUCTION_FROM_RE = /(?:^|\n) *(?:Additional |Updated )?Instructions from: ([^\n]+)/g
|
|
141
|
+
|
|
142
|
+
function optionalBoolean(value, field, fallback) {
|
|
143
|
+
if (value === undefined) return fallback
|
|
144
|
+
if (typeof value !== 'boolean') {
|
|
145
|
+
throw new TypeError(`${name}: ${field} must be a boolean`)
|
|
146
|
+
}
|
|
147
|
+
return value
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function optionalSource(value, field, fallback) {
|
|
151
|
+
if (value === undefined) return fallback
|
|
152
|
+
if (!INSTRUCTION_SOURCES.includes(value)) {
|
|
153
|
+
throw new TypeError(`${name}: ${field} must be one of ${JSON.stringify(INSTRUCTION_SOURCES)}`)
|
|
154
|
+
}
|
|
155
|
+
return value
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function optionalByteSize(value, field, fallback) {
|
|
159
|
+
if (value === undefined) return fallback
|
|
160
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
161
|
+
throw new TypeError(`${name}: ${field} must be a positive finite number`)
|
|
162
|
+
}
|
|
163
|
+
return value
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Expand a leading `~` the way the harness's home paths do. */
|
|
167
|
+
function expandHomePath(path) {
|
|
168
|
+
if (path === '~') return homedir()
|
|
169
|
+
if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
|
|
170
|
+
return path
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The harness home: `$DSH_HOME` when set, else `<home>/.dsh`. */
|
|
174
|
+
export function resolveDshHome(env = process.env) {
|
|
175
|
+
const fromEnv = env[DSH_HOME_ENV]
|
|
176
|
+
const raw = fromEnv !== undefined && fromEnv.trim().length > 0 ? fromEnv : join(homedir(), DSH_HOME_DIR_NAME)
|
|
177
|
+
return resolve(expandHomePath(raw))
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Model-facing display path of the harness home (`~/.dsh` or `$DSH_HOME`). */
|
|
181
|
+
function dshHomeDisplay(home) {
|
|
182
|
+
return home === resolve(join(homedir(), DSH_HOME_DIR_NAME)) ? `~/${DSH_HOME_DIR_NAME}` : `$${DSH_HOME_ENV}`
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function statFile(path) {
|
|
186
|
+
try {
|
|
187
|
+
return await stat(path)
|
|
188
|
+
} catch {
|
|
189
|
+
return undefined
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Discover the project root for a given starting directory by walking
|
|
195
|
+
* ancestor directories until PROJECT_ROOT_MARKER (.git) is found.
|
|
196
|
+
*/
|
|
197
|
+
export async function findProjectRoot(startDir) {
|
|
198
|
+
let root = resolve(startDir)
|
|
199
|
+
for (;;) {
|
|
200
|
+
if (await statFile(join(root, PROJECT_ROOT_MARKER))) return root
|
|
201
|
+
const parent = dirname(root)
|
|
202
|
+
if (parent === root) return resolve(startDir)
|
|
203
|
+
root = parent
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Discover the baseline instruction files for one session cwd, mirroring the
|
|
209
|
+
* harness's baseline chain: the user-global file first, then every directory
|
|
210
|
+
* from the project root (the nearest ancestor holding a `.git` marker, or the
|
|
211
|
+
* cwd itself when none exists) down to the cwd, broadest to most specific.
|
|
212
|
+
*/
|
|
213
|
+
export async function discoverInstructionFiles(cwd, env = process.env) {
|
|
214
|
+
const home = resolveDshHome(env)
|
|
215
|
+
const start = resolve(cwd)
|
|
216
|
+
const files = []
|
|
217
|
+
const seen = new Set()
|
|
218
|
+
const add = (absolutePath, displayPath) => {
|
|
219
|
+
if (seen.has(absolutePath)) return
|
|
220
|
+
seen.add(absolutePath)
|
|
221
|
+
files.push({ absolutePath, displayPath })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const userGlobal = join(home, USER_GLOBAL_FILE)
|
|
225
|
+
if ((await statFile(userGlobal))?.isFile()) {
|
|
226
|
+
add(userGlobal, `${dshHomeDisplay(home)}/${USER_GLOBAL_FILE}`)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const root = await findProjectRoot(start)
|
|
230
|
+
const chain = []
|
|
231
|
+
for (let dir = start; ; dir = dirname(dir)) {
|
|
232
|
+
chain.push(dir)
|
|
233
|
+
if (dir === root) break
|
|
234
|
+
}
|
|
235
|
+
chain.reverse()
|
|
236
|
+
for (const dir of chain) {
|
|
237
|
+
for (const candidates of [INSTRUCTION_FILE_CANDIDATES, LOCAL_INSTRUCTION_FILE_CANDIDATES]) {
|
|
238
|
+
for (const candidate of candidates) {
|
|
239
|
+
const path = join(dir, candidate)
|
|
240
|
+
if ((await statFile(path))?.isFile()) add(path, relative(root, path))
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return files
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Read one instruction file, or undefined when unreadable or over the cap. */
|
|
248
|
+
async function readInstructionFile(path, size) {
|
|
249
|
+
if (size > MAX_SOURCE_BYTES) return undefined
|
|
250
|
+
try {
|
|
251
|
+
const content = await readFile(path, 'utf8')
|
|
252
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_SOURCE_BYTES) return undefined
|
|
253
|
+
return content
|
|
254
|
+
} catch {
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Load the discovered files' content and apply the harness's per-directory
|
|
261
|
+
* duplicate suppression: within one directory the first candidate whose
|
|
262
|
+
* trimmed content differs is kept, so an `AGENTS.md` and an identical
|
|
263
|
+
* `CLAUDE.md` sibling collapse to one block.
|
|
264
|
+
*/
|
|
265
|
+
export async function loadInstructionFiles(cwd, env = process.env) {
|
|
266
|
+
const discovered = await discoverInstructionFiles(cwd, env)
|
|
267
|
+
const loaded = []
|
|
268
|
+
const digestsByDir = new Map()
|
|
269
|
+
for (const file of discovered) {
|
|
270
|
+
const info = await statFile(file.absolutePath)
|
|
271
|
+
if (!info?.isFile()) continue
|
|
272
|
+
const content = await readInstructionFile(file.absolutePath, info.size)
|
|
273
|
+
if (content === undefined) continue
|
|
274
|
+
const dir = dirname(file.displayPath)
|
|
275
|
+
let digests = digestsByDir.get(dir)
|
|
276
|
+
if (digests === undefined) {
|
|
277
|
+
digests = new Set()
|
|
278
|
+
digestsByDir.set(dir, digests)
|
|
279
|
+
}
|
|
280
|
+
const digest = content.trim()
|
|
281
|
+
if (digests.has(digest)) continue
|
|
282
|
+
digests.add(digest)
|
|
283
|
+
loaded.push({ ...file, content })
|
|
284
|
+
}
|
|
285
|
+
return loaded
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** UTF-8-safe truncation at a byte boundary, as the harness renders budgets. */
|
|
289
|
+
function truncateUtf8(value, maxBytes) {
|
|
290
|
+
const bytes = Buffer.from(value, 'utf8')
|
|
291
|
+
if (bytes.length <= maxBytes) return value
|
|
292
|
+
let end = Math.max(0, Math.trunc(maxBytes))
|
|
293
|
+
while (end > 0 && (bytes.readUInt8(end) & 0xc0) === 0x80) end -= 1
|
|
294
|
+
return bytes.subarray(0, end).toString('utf8')
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const INSTRUCTION_INTRO = 'The following workspace instructions are loaded from AGENTS.md-style files in the user\'s environment and workspace. '
|
|
298
|
+
+ 'They are standing guidance about the environment and workspace conventions, not per-task instructions: '
|
|
299
|
+
+ 'more specific files take precedence over broader ones, and a direct user instruction for the current task takes precedence over all of them.'
|
|
300
|
+
|
|
301
|
+
function instructionBudgetMarker(maxBytes, omitted, truncated) {
|
|
302
|
+
const parts = []
|
|
303
|
+
if (omitted.length > 0) parts.push(`omitted ${omitted.join(', ')}`)
|
|
304
|
+
if (truncated !== undefined) {
|
|
305
|
+
parts.push(`truncated ${truncated.displayPath} from ${truncated.originalBytes} to ${truncated.includedBytes} bytes`)
|
|
306
|
+
}
|
|
307
|
+
return `Workspace instruction budget ${maxBytes} bytes: ${parts.join('; ')}.`
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function joinInstructionText(intro, marker, blocks) {
|
|
311
|
+
return [intro, marker, ...blocks].filter(block => block.length > 0).join('\n\n')
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Render the loaded instruction files into one prompt text under a byte
|
|
316
|
+
* budget, with the harness's precedence: when the whole chain does not fit,
|
|
317
|
+
* the broadest files are omitted first and the most specific file is truncated
|
|
318
|
+
* last, so the nearest instructions always survive. Returns undefined when the
|
|
319
|
+
* budget is degenerate or nothing fits.
|
|
320
|
+
*/
|
|
321
|
+
export function renderInstructionSection(files, maxBytes) {
|
|
322
|
+
if (maxBytes <= 0 || !Number.isFinite(maxBytes) || files.length === 0) return undefined
|
|
323
|
+
const blocks = files.map(file => `Instructions from: ${file.displayPath}\n\n${file.content}`)
|
|
324
|
+
const full = joinInstructionText(INSTRUCTION_INTRO, '', blocks)
|
|
325
|
+
if (Buffer.byteLength(full, 'utf8') <= maxBytes) return full
|
|
326
|
+
for (let start = 1; start < blocks.length; start += 1) {
|
|
327
|
+
const omitted = files.slice(0, start).map(file => file.displayPath)
|
|
328
|
+
const suffix = joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, undefined), blocks.slice(start))
|
|
329
|
+
if (Buffer.byteLength(suffix, 'utf8') <= maxBytes) return suffix
|
|
330
|
+
}
|
|
331
|
+
const last = files.at(-1)
|
|
332
|
+
const omitted = files.slice(0, -1).map(file => file.displayPath)
|
|
333
|
+
const originalBytes = Buffer.byteLength(last.content, 'utf8')
|
|
334
|
+
const overheadBytes = Buffer.byteLength(joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, { displayPath: last.displayPath, originalBytes, includedBytes: 0 }), [`Instructions from: ${last.displayPath}\n\n`]), 'utf8')
|
|
335
|
+
if (overheadBytes >= maxBytes) return undefined
|
|
336
|
+
let low = 0
|
|
337
|
+
let high = originalBytes
|
|
338
|
+
let best = ''
|
|
339
|
+
while (low <= high) {
|
|
340
|
+
const mid = Math.floor((low + high) / 2)
|
|
341
|
+
const candidate = truncateUtf8(last.content, mid)
|
|
342
|
+
const truncated = { displayPath: last.displayPath, originalBytes, includedBytes: Buffer.byteLength(candidate, 'utf8') }
|
|
343
|
+
const text = joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, truncated), [`Instructions from: ${last.displayPath}\n\n${candidate}`])
|
|
344
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) {
|
|
345
|
+
best = text
|
|
346
|
+
low = mid + 1
|
|
347
|
+
} else {
|
|
348
|
+
high = mid - 1
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return best.length > 0 ? best : undefined
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Read and render the workspace-instruction prompt text for one session, or
|
|
356
|
+
* undefined when the session reports no cwd, no instruction file exists, or
|
|
357
|
+
* the budget leaves nothing to send.
|
|
358
|
+
*/
|
|
359
|
+
export async function loadInstructionText(cwd, maxBytes = DEFAULT_INSTRUCTION_MAX_BYTES, env = process.env) {
|
|
360
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return undefined
|
|
361
|
+
const files = await loadInstructionFiles(cwd, env)
|
|
362
|
+
return renderInstructionSection(files, maxBytes)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Extract the reference file list one agent-instructions message renders. */
|
|
366
|
+
export function extractInstructionPaths(message) {
|
|
367
|
+
const paths = []
|
|
368
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
369
|
+
for (const block of blocks) {
|
|
370
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue
|
|
371
|
+
for (const match of block.text.matchAll(INSTRUCTION_FROM_RE)) {
|
|
372
|
+
const path = match[1].trim()
|
|
373
|
+
if (path !== '' && !paths.includes(path)) paths.push(path)
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return paths
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The one-time non-imperative hint replacing the full-text dump (E1.5 wording). */
|
|
380
|
+
export function buildInstructionHint(original, paths) {
|
|
381
|
+
return {
|
|
382
|
+
id: typeof original?.id === 'string' && original.id !== ''
|
|
383
|
+
? original.id
|
|
384
|
+
: globalThis.crypto.randomUUID(),
|
|
385
|
+
role: 'user',
|
|
386
|
+
content: [{
|
|
387
|
+
type: 'text',
|
|
388
|
+
text: '<system-reminder>\n'
|
|
389
|
+
+ 'Reference documents exist: ' + paths.join(', ') + '. '
|
|
390
|
+
+ "They are reference documents about the user's environment and workspace conventions, not task instructions. "
|
|
391
|
+
+ '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.'
|
|
392
|
+
+ '\n</system-reminder>',
|
|
393
|
+
}],
|
|
394
|
+
source: { kind: 'plugin', plugin: name },
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Hint mode: swap full-text agent-instructions injections for the one-time
|
|
400
|
+
* hint. The first injection carrying extractable paths becomes the hint; every
|
|
401
|
+
* later injection is dropped silently (the model re-reads the files on demand).
|
|
402
|
+
* An injection with no extractable paths passes through untouched.
|
|
403
|
+
*/
|
|
404
|
+
export function instructionHintMessages(messages, state) {
|
|
405
|
+
const kept = []
|
|
406
|
+
for (const message of messages) {
|
|
407
|
+
if (message?.source?.kind !== 'agent-instructions') {
|
|
408
|
+
kept.push(message)
|
|
409
|
+
continue
|
|
410
|
+
}
|
|
411
|
+
if (state.hinted) continue
|
|
412
|
+
const paths = extractInstructionPaths(message)
|
|
413
|
+
if (paths.length === 0) {
|
|
414
|
+
kept.push(message)
|
|
415
|
+
continue
|
|
416
|
+
}
|
|
417
|
+
state.hinted = true
|
|
418
|
+
kept.push(buildInstructionHint(message, paths))
|
|
419
|
+
}
|
|
420
|
+
return kept
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Extract touched file path from a ToolExecution object.
|
|
425
|
+
* Synchronously extracts path from:
|
|
426
|
+
* - `read`, `write`, `edit` via `exec.arguments.file_path`
|
|
427
|
+
* - `str_replace_editor` via `exec.arguments.path`
|
|
428
|
+
* Supports both top-level and PTC nested executions without guessing code strings.
|
|
429
|
+
*/
|
|
430
|
+
export function filePathFromExecution(exec) {
|
|
431
|
+
if (!exec || typeof exec !== 'object') return undefined
|
|
432
|
+
if (typeof exec.name !== 'string') return undefined
|
|
433
|
+
if (typeof exec.arguments !== 'object' || exec.arguments === null) return undefined
|
|
434
|
+
|
|
435
|
+
if (exec.name === 'str_replace_editor') {
|
|
436
|
+
if ('path' in exec.arguments && typeof exec.arguments.path === 'string') {
|
|
437
|
+
const p = exec.arguments.path.trim()
|
|
438
|
+
return p.length > 0 ? p : undefined
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if ('file_path' in exec.arguments && typeof exec.arguments.file_path === 'string') {
|
|
443
|
+
const p = exec.arguments.file_path.trim()
|
|
444
|
+
return p.length > 0 ? p : undefined
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
return undefined
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Helper to check whether a path string belongs to covered baseline files.
|
|
452
|
+
*/
|
|
453
|
+
export function isBaselineInstructionPath(path, baselinePaths, cwd) {
|
|
454
|
+
if (!path || typeof path !== 'string') return false
|
|
455
|
+
const trimmed = path.trim()
|
|
456
|
+
if (trimmed.length === 0) return false
|
|
457
|
+
|
|
458
|
+
if (baselinePaths && (baselinePaths.has(trimmed) || baselinePaths.has(resolve(trimmed)))) {
|
|
459
|
+
return true
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (trimmed === '~/.dsh/AGENTS.md' || trimmed === '$DSH_HOME/AGENTS.md'
|
|
463
|
+
|| trimmed.replace(/\\/g, '/').endsWith('.dsh/AGENTS.md')) {
|
|
464
|
+
return true
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const normalized = trimmed.replace(/\\/g, '/')
|
|
468
|
+
if (baselinePaths) {
|
|
469
|
+
for (const bp of baselinePaths) {
|
|
470
|
+
if (typeof bp === 'string' && bp.replace(/\\/g, '/') === normalized) {
|
|
471
|
+
return true
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
if (typeof cwd === 'string' && cwd.length > 0) {
|
|
477
|
+
const normCwd = resolve(cwd).replace(/\\/g, '/')
|
|
478
|
+
const normPath = resolve(cwd, trimmed).replace(/\\/g, '/')
|
|
479
|
+
const dir = dirname(normPath)
|
|
480
|
+
if (normCwd === dir || normCwd.startsWith(dir + '/')) {
|
|
481
|
+
return true
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (normalized === 'AGENTS.md' || normalized === 'CLAUDE.md'
|
|
486
|
+
|| normalized === 'AGENTS.local.md' || normalized === 'CLAUDE.local.md'
|
|
487
|
+
|| normalized === '/repo/AGENTS.md' || normalized === '/repo/CLAUDE.md') {
|
|
488
|
+
return true
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
return false
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Check whether an agent-instructions message is purely baseline instructions,
|
|
496
|
+
* by examining both structured changes in source and text headers in content.
|
|
497
|
+
*/
|
|
498
|
+
export function isMessagePureBaseline(message, cwd, baselinePaths) {
|
|
499
|
+
// If structured changes exist, check for any non-baseline actions or scopes
|
|
500
|
+
if (Array.isArray(message?.source?.changes) && message.source.changes.length > 0) {
|
|
501
|
+
for (const change of message.source.changes) {
|
|
502
|
+
if (change?.action === 'replace' || change?.action === 'remove') return false
|
|
503
|
+
if (typeof change?.path === 'string' && !isBaselineInstructionPath(change.path, baselinePaths, cwd)) {
|
|
504
|
+
return false
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// Check content blocks for explicit dynamic headers
|
|
510
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
511
|
+
for (const block of blocks) {
|
|
512
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue
|
|
513
|
+
const lower = block.text.toLowerCase()
|
|
514
|
+
if (lower.includes('additional instructions from:')
|
|
515
|
+
|| lower.includes('updated instructions from:')
|
|
516
|
+
|| lower.includes('instructions removed:')) {
|
|
517
|
+
return false
|
|
518
|
+
}
|
|
519
|
+
for (const match of block.text.matchAll(INSTRUCTION_FROM_RE)) {
|
|
520
|
+
const p = match[1]?.trim()
|
|
521
|
+
if (p && !isBaselineInstructionPath(p, baselinePaths, cwd)) {
|
|
522
|
+
return false
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
return true
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Discover instruction files in a specific subdirectory under projectRoot.
|
|
532
|
+
*/
|
|
533
|
+
export async function discoverSubdirectoryInstructions(cwd, targetDir, deliveredScopes = new Set()) {
|
|
534
|
+
const root = await findProjectRoot(cwd)
|
|
535
|
+
const normTarget = resolve(targetDir)
|
|
536
|
+
const normRoot = resolve(root)
|
|
537
|
+
const normCwd = resolve(cwd)
|
|
538
|
+
|
|
539
|
+
if (!normTarget.startsWith(normRoot)) return []
|
|
540
|
+
if (normTarget === normCwd || normCwd.startsWith(normTarget + '/')) return []
|
|
541
|
+
|
|
542
|
+
const dirs = []
|
|
543
|
+
for (let curr = normTarget; curr.length >= normRoot.length && curr.startsWith(normRoot); curr = dirname(curr)) {
|
|
544
|
+
if (curr === normCwd || normCwd.startsWith(curr + '/')) break
|
|
545
|
+
dirs.push(curr)
|
|
546
|
+
}
|
|
547
|
+
dirs.reverse()
|
|
548
|
+
|
|
549
|
+
const results = []
|
|
550
|
+
for (const dir of dirs) {
|
|
551
|
+
const scope = relative(normRoot, dir).replace(/\\/g, '/')
|
|
552
|
+
if (deliveredScopes.has(scope)) continue
|
|
553
|
+
|
|
554
|
+
for (const candidate of INSTRUCTION_FILE_CANDIDATES) {
|
|
555
|
+
const filePath = join(dir, candidate)
|
|
556
|
+
const st = await statFile(filePath)
|
|
557
|
+
if (st?.isFile()) {
|
|
558
|
+
const content = await readInstructionFile(filePath, st.size)
|
|
559
|
+
if (content !== undefined) {
|
|
560
|
+
results.push({
|
|
561
|
+
displayPath: relative(normRoot, filePath).replace(/\\/g, '/'),
|
|
562
|
+
scope,
|
|
563
|
+
content,
|
|
564
|
+
})
|
|
565
|
+
break
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return results
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export function formatAdditionalSection(displayPath, scope, content) {
|
|
574
|
+
return [
|
|
575
|
+
`Additional instructions from: ${displayPath}`,
|
|
576
|
+
'',
|
|
577
|
+
`These instructions apply to work under \`${scope}\`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.`,
|
|
578
|
+
'',
|
|
579
|
+
content,
|
|
580
|
+
].join('\n')
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Filter and reconcile instructions messages:
|
|
585
|
+
* - Condenses pure covered baseline messages into a concise legal user message
|
|
586
|
+
* preserving source.baseline and schema in normal decision.messages.
|
|
587
|
+
* - Leaves dynamic/updated instructions intact.
|
|
588
|
+
* - Passes through untouched if baseline loading failed.
|
|
589
|
+
*/
|
|
590
|
+
export function filterInstructionMessages(messages, baselineFiles = [], baselineLoaded = false, agent = undefined) {
|
|
591
|
+
const kept = []
|
|
592
|
+
const cwd = agent?.session?.header?.cwd
|
|
593
|
+
const baselinePaths = new Set(baselineFiles.map(f => f.displayPath).concat(baselineFiles.map(f => f.absolutePath)))
|
|
594
|
+
|
|
595
|
+
for (const message of messages) {
|
|
596
|
+
if (message?.source?.kind !== 'agent-instructions') {
|
|
597
|
+
kept.push(message)
|
|
598
|
+
continue
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const pureBaseline = isMessagePureBaseline(message, cwd, baselinePaths)
|
|
602
|
+
|
|
603
|
+
if (!pureBaseline) {
|
|
604
|
+
// Dynamic subdirectory instructions or mixed changes: keep safely.
|
|
605
|
+
kept.push(message)
|
|
606
|
+
continue
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// The message duplicates content the system prompt carries, so it is
|
|
610
|
+
// redundant ONLY when that prompt really carries it. A failed or empty
|
|
611
|
+
// baseline read must never cost the model its instructions, whatever shape
|
|
612
|
+
// the message has: pass it through untouched.
|
|
613
|
+
if (!baselineLoaded) {
|
|
614
|
+
kept.push(message)
|
|
615
|
+
continue
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// A marked baseline keeps a short marker message, which is what the host's
|
|
619
|
+
// baseline detector reads to stop re-injecting the same baseline every step.
|
|
620
|
+
// An unmarked one has nothing to contribute on top of the prompt.
|
|
621
|
+
if (message?.source?.baseline !== true) continue
|
|
622
|
+
|
|
623
|
+
const covered = baselineFiles.map(f => f.displayPath).filter(Boolean)
|
|
624
|
+
const text = covered.length > 0
|
|
625
|
+
? `<system-reminder>\nWorkspace baseline instructions (${covered.join(', ')}) are active in the system prompt.\n</system-reminder>`
|
|
626
|
+
: '<system-reminder>\nWorkspace baseline instructions are active in the system prompt.\n</system-reminder>'
|
|
627
|
+
kept.push({
|
|
628
|
+
...message,
|
|
629
|
+
content: [{ type: 'text', text }],
|
|
630
|
+
})
|
|
631
|
+
}
|
|
632
|
+
return kept
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** Backward-compatible export: alias for filterInstructionMessages. */
|
|
636
|
+
export function dropInstructionMessages(messages, baselineFiles = [], baselineLoaded = false, agent = undefined) {
|
|
637
|
+
return filterInstructionMessages(messages, baselineFiles, baselineLoaded, agent)
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Workspace line the persona gains. The one-line persona carries no
|
|
642
|
+
* orientation facts, so the session's selected workspace directory is appended
|
|
643
|
+
* to the persona section at assembly time. The literal cwd comes from the
|
|
644
|
+
* session header, so the line stays correct after a workspace switch, and a
|
|
645
|
+
* session without a readable cwd keeps the bare persona rather than failing.
|
|
646
|
+
*/
|
|
647
|
+
const WORKSPACE_LINE_PREFIX = '\n\nYour working directory is '
|
|
648
|
+
|
|
649
|
+
/** Append the workspace line to the persona section, once. */
|
|
650
|
+
export function withWorkspaceLine(sections, agent) {
|
|
651
|
+
const cwd = agent?.session?.header?.cwd
|
|
652
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return sections
|
|
653
|
+
const line = `${WORKSPACE_LINE_PREFIX}${cwd}.`
|
|
654
|
+
const persona = sections.find(section =>
|
|
655
|
+
PERSONA_SECTION_NAMES.includes(section?.name)
|
|
656
|
+
&& typeof section?.text === 'string'
|
|
657
|
+
&& !section.text.includes(line))
|
|
658
|
+
if (persona === undefined) return sections
|
|
659
|
+
return sections.map(section => section === persona
|
|
660
|
+
? { ...section, text: `${section.text}${line}` }
|
|
661
|
+
: section)
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** Register the section filter, workspace-instruction source, and dynamic discovery hooks. */
|
|
665
|
+
export function apply(ctx, config) {
|
|
666
|
+
const keepPlanPolicy = optionalBoolean(config?.keepPlanPolicy, 'keepPlanPolicy', true)
|
|
667
|
+
const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'system-prompt')
|
|
668
|
+
const instructionMaxBytes = optionalByteSize(config?.instructionMaxBytes, 'instructionMaxBytes', DEFAULT_INSTRUCTION_MAX_BYTES)
|
|
669
|
+
const keep = new Set([
|
|
670
|
+
...PERSONA_SECTION_NAMES,
|
|
671
|
+
...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
|
|
672
|
+
...PTC_SECTION_NAMES,
|
|
673
|
+
])
|
|
674
|
+
|
|
675
|
+
// Per-session state tracking (durable across steps, recoverable on replay)
|
|
676
|
+
const sessionStateMap = new WeakMap()
|
|
677
|
+
const getSessionState = (session) => {
|
|
678
|
+
let state = sessionStateMap.get(session)
|
|
679
|
+
if (!state) {
|
|
680
|
+
state = {
|
|
681
|
+
touchedDirs: new Set(),
|
|
682
|
+
deliveredScopes: new Set(),
|
|
683
|
+
baselineLoaded: false,
|
|
684
|
+
baselineFiles: [],
|
|
685
|
+
hinted: false,
|
|
686
|
+
}
|
|
687
|
+
sessionStateMap.set(session, state)
|
|
688
|
+
|
|
689
|
+
// Reconstruct touched directories from durable history if available
|
|
690
|
+
if (typeof session?.snapshotEvents === 'function') {
|
|
691
|
+
try {
|
|
692
|
+
const events = session.snapshotEvents()
|
|
693
|
+
const cwd = session.header?.cwd ?? process.cwd()
|
|
694
|
+
for (const ev of events) {
|
|
695
|
+
if (ev?.type === 'tool/call' && ev.data) {
|
|
696
|
+
let args = ev.data.arguments
|
|
697
|
+
if (typeof args === 'string') {
|
|
698
|
+
try { args = JSON.parse(args) } catch {}
|
|
699
|
+
}
|
|
700
|
+
const p = filePathFromExecution({ name: ev.data.name, arguments: args })
|
|
701
|
+
if (p) state.touchedDirs.add(dirname(resolve(cwd, p)))
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
} catch {
|
|
705
|
+
// Replay reconstruction fallback
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return state
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
let warned = false
|
|
713
|
+
const warnOnce = (message) => {
|
|
714
|
+
if (warned) return
|
|
715
|
+
warned = true
|
|
716
|
+
try {
|
|
717
|
+
ctx.logger?.warn?.(message)
|
|
718
|
+
} catch {
|
|
719
|
+
// Logger unavailable
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// 1. System Prompt Assembly
|
|
724
|
+
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
725
|
+
const assembled = await next()
|
|
726
|
+
if (!Array.isArray(assembled.sections)) return assembled
|
|
727
|
+
const sections = assembled.sections.filter(section => keep.has(section?.name))
|
|
728
|
+
if (sections.length === 0) {
|
|
729
|
+
warnOnce(`${name}: no section matched ${JSON.stringify([...keep])} — `
|
|
730
|
+
+ 'keeping the assembled prompt instead of sending an empty one')
|
|
731
|
+
return assembled
|
|
732
|
+
}
|
|
733
|
+
const narrowed = withWorkspaceLine(sections, context?.agent)
|
|
734
|
+
if (instructionSource !== 'system-prompt') return { ...assembled, sections: narrowed }
|
|
735
|
+
|
|
736
|
+
let text
|
|
737
|
+
const session = context?.agent?.session
|
|
738
|
+
const state = session ? getSessionState(session) : undefined
|
|
739
|
+
const cwd = session?.header?.cwd
|
|
740
|
+
try {
|
|
741
|
+
if (cwd) {
|
|
742
|
+
const files = await loadInstructionFiles(cwd)
|
|
743
|
+
if (state) {
|
|
744
|
+
state.baselineLoaded = true
|
|
745
|
+
state.baselineFiles = files
|
|
746
|
+
}
|
|
747
|
+
text = renderInstructionSection(files, instructionMaxBytes)
|
|
748
|
+
}
|
|
749
|
+
} catch (error) {
|
|
750
|
+
if (state) state.baselineLoaded = false
|
|
751
|
+
warnOnce(`${name}: reading the workspace instructions failed — sending the prompt without them (${error instanceof Error ? error.message : String(error)})`)
|
|
752
|
+
return { ...assembled, sections: narrowed }
|
|
753
|
+
}
|
|
754
|
+
if (text === undefined) return { ...assembled, sections: narrowed }
|
|
755
|
+
|
|
756
|
+
return {
|
|
757
|
+
...assembled,
|
|
758
|
+
sections: [...narrowed, { name: WORKSPACE_INSTRUCTIONS_SECTION_NAME, text: `{{${WORKSPACE_INSTRUCTIONS_VARIABLE}}}` }],
|
|
759
|
+
variables: { ...assembled.variables, [WORKSPACE_INSTRUCTIONS_VARIABLE]: text },
|
|
760
|
+
}
|
|
761
|
+
}, { prepend: true })
|
|
762
|
+
|
|
763
|
+
// 2. Synchronous tool result tracking (no fake emit, no async work in emit listener)
|
|
764
|
+
ctx.on('tools/result', (exec, result) => {
|
|
765
|
+
if (result?.isError || !exec?.agent || exec?.signal?.aborted) return
|
|
766
|
+
const path = filePathFromExecution(exec)
|
|
767
|
+
if (!path) return
|
|
768
|
+
|
|
769
|
+
const session = exec.agent.session
|
|
770
|
+
if (!session) return
|
|
771
|
+
|
|
772
|
+
const cwd = session.header?.cwd ?? process.cwd()
|
|
773
|
+
const state = getSessionState(session)
|
|
774
|
+
state.touchedDirs.add(dirname(resolve(cwd, path)))
|
|
775
|
+
})
|
|
776
|
+
|
|
777
|
+
// 3. Agent pre-step message filter & dynamic discovery
|
|
778
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
779
|
+
const decision = await next()
|
|
780
|
+
if (decision.kind !== 'enter') return decision
|
|
781
|
+
|
|
782
|
+
const agent = payload?.agent
|
|
783
|
+
const session = agent?.session
|
|
784
|
+
const state = session ? getSessionState(session) : undefined
|
|
785
|
+
|
|
786
|
+
if (instructionSource === 'hint') {
|
|
787
|
+
if (session === undefined) return decision
|
|
788
|
+
return { ...decision, messages: instructionHintMessages(decision.messages, state) }
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// System-prompt mode:
|
|
792
|
+
const cwd = session?.header?.cwd
|
|
793
|
+
const baselineLoaded = state?.baselineLoaded ?? false
|
|
794
|
+
const baselineFiles = state?.baselineFiles ?? []
|
|
795
|
+
|
|
796
|
+
// Step A: Filter incoming decision messages
|
|
797
|
+
const filtered = filterInstructionMessages(decision.messages, baselineFiles, baselineLoaded, agent)
|
|
798
|
+
|
|
799
|
+
// Step B: Asynchronously discover dynamic instructions for touched directories
|
|
800
|
+
if (state && cwd) {
|
|
801
|
+
const newSections = []
|
|
802
|
+
for (const dir of state.touchedDirs) {
|
|
803
|
+
const discovered = await discoverSubdirectoryInstructions(cwd, dir, state.deliveredScopes)
|
|
804
|
+
for (const file of discovered) {
|
|
805
|
+
state.deliveredScopes.add(file.scope)
|
|
806
|
+
newSections.push(formatAdditionalSection(file.displayPath, file.scope, file.content))
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
if (newSections.length > 0) {
|
|
810
|
+
filtered.push({
|
|
811
|
+
id: globalThis.crypto.randomUUID(),
|
|
812
|
+
role: 'user',
|
|
813
|
+
content: [{
|
|
814
|
+
type: 'text',
|
|
815
|
+
text: `<system-reminder>\n${newSections.join('\n\n')}\n</system-reminder>`,
|
|
816
|
+
}],
|
|
817
|
+
source: { kind: 'plugin', plugin: name },
|
|
818
|
+
})
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
return { ...decision, messages: filtered }
|
|
823
|
+
}, { prepend: true })
|
|
824
|
+
|
|
825
|
+
// 4. Session lifecycle / compaction recovery
|
|
826
|
+
ctx.on('session/event', (session, event) => {
|
|
827
|
+
if (event?.type === 'compaction/end') {
|
|
828
|
+
const state = sessionStateMap.get(session)
|
|
829
|
+
if (state) {
|
|
830
|
+
state.hinted = false
|
|
831
|
+
state.deliveredScopes.clear()
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
})
|
|
835
|
+
}
|