@linxin666/dsh-liangshen 0.3.21 → 0.3.23
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 +38 -24
- package/README.zh.md +38 -24
- package/lib/index.js +11 -10
- package/lib/types/index.d.ts +11 -10
- package/package.json +2 -2
- package/presets/liangshen/agent.cordis.yml +34 -27
- package/presets/liangshen/minimal-prompt.mjs +393 -92
- package/presets/liangshen/tool-catalog.mjs +302 -189
- package/src/index.ts +11 -10
- 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
|
@@ -4,16 +4,14 @@
|
|
|
4
4
|
* tool surface is staged behind the anchor turn and handed to PTC presentation
|
|
5
5
|
* after it.
|
|
6
6
|
*
|
|
7
|
-
* The assembled prompt is filtered down to the persona section,
|
|
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
|
|
8
10
|
* identity, web-surface, tool-guidance, file-reference, and structured-output
|
|
9
|
-
* sections never reach the model
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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).
|
|
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.
|
|
17
15
|
*
|
|
18
16
|
* WORKSPACE LINE: the bare persona says nothing about where the session
|
|
19
17
|
* operates, so the selected workspace directory is appended to the persona at
|
|
@@ -36,33 +34,39 @@
|
|
|
36
34
|
* strictly, the section text is only a `{{workspace_instructions}}` reference
|
|
37
35
|
* and the rendered content travels as that assembly variable's value —
|
|
38
36
|
* variable values are inserted verbatim and never re-scanned, so instruction
|
|
39
|
-
* files may contain `{{...}}` examples without breaking every request.
|
|
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.
|
|
37
|
+
* files may contain `{{...}}` examples without breaking every request.
|
|
51
38
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
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.
|
|
57
61
|
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
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.
|
|
66
70
|
*/
|
|
67
71
|
|
|
68
72
|
import { readFile, stat } from 'node:fs/promises'
|
|
@@ -85,6 +89,13 @@ export const PERSONA_SECTION_NAMES = ['deployment:persona-prefix', 'deployment:p
|
|
|
85
89
|
/** Plan-mode policy section, owned by `@deepseek-ai/dsh-plan-mode`. */
|
|
86
90
|
export const PLAN_POLICY_SECTION_NAME = 'plan:policy'
|
|
87
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
|
+
|
|
88
99
|
/**
|
|
89
100
|
* The section this plugin appends to the prompt with the workspace
|
|
90
101
|
* instructions, and the assembly variable whose value carries the rendered
|
|
@@ -98,6 +109,9 @@ export const WORKSPACE_INSTRUCTIONS_VARIABLE = 'workspace_instructions'
|
|
|
98
109
|
/** Accepted `instructionSource` values, default first. */
|
|
99
110
|
export const INSTRUCTION_SOURCES = ['system-prompt', 'hint']
|
|
100
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
|
+
|
|
101
115
|
/**
|
|
102
116
|
* Instruction file candidates per directory, in the harness's order: the
|
|
103
117
|
* shared names first, then the personal `.local` overlays.
|
|
@@ -176,6 +190,20 @@ async function statFile(path) {
|
|
|
176
190
|
}
|
|
177
191
|
}
|
|
178
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
|
+
|
|
179
207
|
/**
|
|
180
208
|
* Discover the baseline instruction files for one session cwd, mirroring the
|
|
181
209
|
* harness's baseline chain: the user-global file first, then every directory
|
|
@@ -198,16 +226,7 @@ export async function discoverInstructionFiles(cwd, env = process.env) {
|
|
|
198
226
|
add(userGlobal, `${dshHomeDisplay(home)}/${USER_GLOBAL_FILE}`)
|
|
199
227
|
}
|
|
200
228
|
|
|
201
|
-
|
|
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
|
-
}
|
|
229
|
+
const root = await findProjectRoot(start)
|
|
211
230
|
const chain = []
|
|
212
231
|
for (let dir = start; ; dir = dirname(dir)) {
|
|
213
232
|
chain.push(dir)
|
|
@@ -309,8 +328,6 @@ export function renderInstructionSection(files, maxBytes) {
|
|
|
309
328
|
const suffix = joinInstructionText(INSTRUCTION_INTRO, instructionBudgetMarker(maxBytes, omitted, undefined), blocks.slice(start))
|
|
310
329
|
if (Buffer.byteLength(suffix, 'utf8') <= maxBytes) return suffix
|
|
311
330
|
}
|
|
312
|
-
// Even the most specific file does not fit whole: truncate its content to
|
|
313
|
-
// the largest byte length the frame accepts.
|
|
314
331
|
const last = files.at(-1)
|
|
315
332
|
const omitted = files.slice(0, -1).map(file => file.displayPath)
|
|
316
333
|
const originalBytes = Buffer.byteLength(last.content, 'utf8')
|
|
@@ -362,10 +379,6 @@ export function extractInstructionPaths(message) {
|
|
|
362
379
|
/** The one-time non-imperative hint replacing the full-text dump (E1.5 wording). */
|
|
363
380
|
export function buildInstructionHint(original, paths) {
|
|
364
381
|
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
382
|
id: typeof original?.id === 'string' && original.id !== ''
|
|
370
383
|
? original.id
|
|
371
384
|
: globalThis.crypto.randomUUID(),
|
|
@@ -378,13 +391,6 @@ export function buildInstructionHint(original, paths) {
|
|
|
378
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.'
|
|
379
392
|
+ '\n</system-reminder>',
|
|
380
393
|
}],
|
|
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
394
|
source: { kind: 'plugin', plugin: name },
|
|
389
395
|
}
|
|
390
396
|
}
|
|
@@ -414,9 +420,221 @@ export function instructionHintMessages(messages, state) {
|
|
|
414
420
|
return kept
|
|
415
421
|
}
|
|
416
422
|
|
|
417
|
-
/**
|
|
418
|
-
|
|
419
|
-
|
|
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)
|
|
420
638
|
}
|
|
421
639
|
|
|
422
640
|
/**
|
|
@@ -443,7 +661,7 @@ export function withWorkspaceLine(sections, agent) {
|
|
|
443
661
|
: section)
|
|
444
662
|
}
|
|
445
663
|
|
|
446
|
-
/** Register the section filter
|
|
664
|
+
/** Register the section filter, workspace-instruction source, and dynamic discovery hooks. */
|
|
447
665
|
export function apply(ctx, config) {
|
|
448
666
|
const keepPlanPolicy = optionalBoolean(config?.keepPlanPolicy, 'keepPlanPolicy', true)
|
|
449
667
|
const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'system-prompt')
|
|
@@ -451,17 +669,42 @@ export function apply(ctx, config) {
|
|
|
451
669
|
const keep = new Set([
|
|
452
670
|
...PERSONA_SECTION_NAMES,
|
|
453
671
|
...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
|
|
672
|
+
...PTC_SECTION_NAMES,
|
|
454
673
|
])
|
|
455
674
|
|
|
456
|
-
// Per-session
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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
|
+
}
|
|
465
708
|
}
|
|
466
709
|
return state
|
|
467
710
|
}
|
|
@@ -473,41 +716,43 @@ export function apply(ctx, config) {
|
|
|
473
716
|
try {
|
|
474
717
|
ctx.logger?.warn?.(message)
|
|
475
718
|
} catch {
|
|
476
|
-
// Logger unavailable
|
|
719
|
+
// Logger unavailable
|
|
477
720
|
}
|
|
478
721
|
}
|
|
479
722
|
|
|
480
|
-
//
|
|
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.
|
|
723
|
+
// 1. System Prompt Assembly
|
|
484
724
|
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
725
|
const assembled = await next()
|
|
488
726
|
if (!Array.isArray(assembled.sections)) return assembled
|
|
489
727
|
const sections = assembled.sections.filter(section => keep.has(section?.name))
|
|
490
728
|
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
729
|
warnOnce(`${name}: no section matched ${JSON.stringify([...keep])} — `
|
|
494
730
|
+ 'keeping the assembled prompt instead of sending an empty one')
|
|
495
731
|
return assembled
|
|
496
732
|
}
|
|
497
733
|
const narrowed = withWorkspaceLine(sections, context?.agent)
|
|
498
734
|
if (instructionSource !== 'system-prompt') return { ...assembled, sections: narrowed }
|
|
735
|
+
|
|
499
736
|
let text
|
|
737
|
+
const session = context?.agent?.session
|
|
738
|
+
const state = session ? getSessionState(session) : undefined
|
|
739
|
+
const cwd = session?.header?.cwd
|
|
500
740
|
try {
|
|
501
|
-
|
|
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
|
+
}
|
|
502
749
|
} catch (error) {
|
|
750
|
+
if (state) state.baselineLoaded = false
|
|
503
751
|
warnOnce(`${name}: reading the workspace instructions failed — sending the prompt without them (${error instanceof Error ? error.message : String(error)})`)
|
|
504
752
|
return { ...assembled, sections: narrowed }
|
|
505
753
|
}
|
|
506
754
|
if (text === undefined) return { ...assembled, sections: narrowed }
|
|
507
|
-
|
|
508
|
-
// renderer interpolates section text strictly, and instruction files may
|
|
509
|
-
// legitimately contain `{{...}}` examples. Variable values are inserted
|
|
510
|
-
// verbatim and never re-scanned.
|
|
755
|
+
|
|
511
756
|
return {
|
|
512
757
|
...assembled,
|
|
513
758
|
sections: [...narrowed, { name: WORKSPACE_INSTRUCTIONS_SECTION_NAME, text: `{{${WORKSPACE_INSTRUCTIONS_VARIABLE}}}` }],
|
|
@@ -515,20 +760,76 @@ export function apply(ctx, config) {
|
|
|
515
760
|
}
|
|
516
761
|
}, { prepend: true })
|
|
517
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
|
|
518
778
|
ctx.on('agent/pre-step', async (payload, next) => {
|
|
519
779
|
const decision = await next()
|
|
520
780
|
if (decision.kind !== 'enter') return decision
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
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) }
|
|
525
789
|
}
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
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 }
|
|
529
823
|
}, { prepend: true })
|
|
530
824
|
|
|
825
|
+
// 4. Session lifecycle / compaction recovery
|
|
531
826
|
ctx.on('session/event', (session, event) => {
|
|
532
|
-
if (event?.type === 'compaction/end')
|
|
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
|
+
}
|
|
533
834
|
})
|
|
534
835
|
}
|