dsh-coding-enhanced 0.5.16 → 0.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -7
- package/README.md +76 -74
- package/docs/prior-art.md +194 -0
- package/docs/ui-directions/README.md +35 -0
- package/docs/ui-directions/index.html +869 -0
- package/docs/web-review-architecture.md +668 -0
- package/lib/client.js +306 -28
- package/lib/index.js +385 -60
- package/package.json +9 -6
package/lib/index.js
CHANGED
|
@@ -17,15 +17,133 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { execFile } from 'node:child_process'
|
|
19
19
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
20
|
-
import { createHash } from 'node:crypto'
|
|
20
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
21
21
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
|
|
22
22
|
import fs from 'node:fs/promises'
|
|
23
23
|
import os from 'node:os'
|
|
24
24
|
import path from 'node:path'
|
|
25
|
+
import { fileURLToPath } from 'node:url'
|
|
25
26
|
|
|
26
27
|
export const name = 'coding-enhanced'
|
|
27
28
|
export const inject = ['sessions', 'connection', 'tools', 'systemPrompt']
|
|
28
29
|
|
|
30
|
+
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
31
|
+
const PLUGIN_VERSION = (() => {
|
|
32
|
+
try {
|
|
33
|
+
const parsed = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'))
|
|
34
|
+
return typeof parsed.version === 'string' ? parsed.version : '0.0.0'
|
|
35
|
+
} catch {
|
|
36
|
+
return '0.0.0'
|
|
37
|
+
}
|
|
38
|
+
})()
|
|
39
|
+
|
|
40
|
+
const compareVersions = (left, right) => {
|
|
41
|
+
const parse = (value) => String(value).split('-')[0].split('.').map((part) => Number.parseInt(part, 10) || 0)
|
|
42
|
+
const a = parse(left)
|
|
43
|
+
const b = parse(right)
|
|
44
|
+
for (let index = 0; index < 3; index += 1) {
|
|
45
|
+
if ((a[index] ?? 0) === (b[index] ?? 0)) continue
|
|
46
|
+
return (a[index] ?? 0) < (b[index] ?? 0) ? -1 : 1
|
|
47
|
+
}
|
|
48
|
+
return 0
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const execOnce = (command, args, options) => new Promise((resolve, reject) => {
|
|
52
|
+
execFile(command, args, { maxBuffer: 8 * 1024 * 1024, timeout: 120000, ...options }, (error, stdout, stderr) => {
|
|
53
|
+
if (error !== null) {
|
|
54
|
+
reject(new Error(`${command} ${args.join(' ')}: ${String(stderr || error.message).trim()}`))
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
resolve({ stdout, stderr })
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const readConfiguredRegistry = () => {
|
|
62
|
+
const files = [
|
|
63
|
+
path.join(os.homedir(), '.npmrc'),
|
|
64
|
+
path.join(path.dirname(path.dirname(PACKAGE_ROOT)), '.npmrc'),
|
|
65
|
+
]
|
|
66
|
+
for (const file of files) {
|
|
67
|
+
try {
|
|
68
|
+
for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
69
|
+
const match = line.match(/^\s*registry\s*=\s*(\S+)\s*$/)
|
|
70
|
+
if (match !== null) return match[1]
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
// ignore missing/unreadable npmrc
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return process.env.npm_config_registry
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const registryBases = () => {
|
|
80
|
+
const configured = readConfiguredRegistry()
|
|
81
|
+
return [...new Set([
|
|
82
|
+
configured,
|
|
83
|
+
'https://registry.npmjs.org',
|
|
84
|
+
'https://registry.npmmirror.com',
|
|
85
|
+
].filter((value) => typeof value === 'string' && value.length > 0))]
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const latestNpmVersion = async () => {
|
|
89
|
+
const failures = []
|
|
90
|
+
for (const base of registryBases()) {
|
|
91
|
+
const url = `${base.replace(/\/+$/, '')}/dsh-coding-enhanced/latest`
|
|
92
|
+
try {
|
|
93
|
+
const response = await fetch(url, {
|
|
94
|
+
headers: { accept: 'application/vnd.npm.install-v1+json, application/json' },
|
|
95
|
+
signal: AbortSignal.timeout(12000),
|
|
96
|
+
})
|
|
97
|
+
if (response.ok !== true) throw new Error(`HTTP ${response.status}`)
|
|
98
|
+
const data = await response.json()
|
|
99
|
+
if (typeof data.version !== 'string' || data.version === '') throw new Error('no version in response')
|
|
100
|
+
return { version: data.version, registry: base }
|
|
101
|
+
} catch (error) {
|
|
102
|
+
failures.push(`${base} (${String(error)})`)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
throw new Error(`No npm registry reachable. Tried: ${failures.join('; ')}`)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const findBundledPnpm = () => {
|
|
109
|
+
const candidates = []
|
|
110
|
+
if (typeof process.resourcesPath === 'string' && process.resourcesPath !== '') {
|
|
111
|
+
candidates.push(path.join(process.resourcesPath, 'app.asar', 'runtime', 'pnpm', 'bin', 'pnpm.cjs'))
|
|
112
|
+
candidates.push(path.join(process.resourcesPath, 'runtime', 'pnpm', 'bin', 'pnpm.cjs'))
|
|
113
|
+
}
|
|
114
|
+
candidates.push(path.join(path.dirname(process.execPath), '..', 'Resources', 'app.asar', 'runtime', 'pnpm', 'bin', 'pnpm.cjs'))
|
|
115
|
+
return candidates.find((candidate) => existsSync(candidate))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const installPackage = async (spec, profileDir) => {
|
|
119
|
+
const failures = []
|
|
120
|
+
try {
|
|
121
|
+
await execOnce('pnpm', ['add', spec], { cwd: profileDir })
|
|
122
|
+
return 'pnpm'
|
|
123
|
+
} catch (error) {
|
|
124
|
+
failures.push(String(error))
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
await execOnce('npm', ['install', spec, '--no-audit', '--no-fund'], { cwd: profileDir })
|
|
128
|
+
return 'npm'
|
|
129
|
+
} catch (error) {
|
|
130
|
+
failures.push(String(error))
|
|
131
|
+
}
|
|
132
|
+
const bundled = findBundledPnpm()
|
|
133
|
+
if (bundled !== undefined) {
|
|
134
|
+
try {
|
|
135
|
+
await execOnce(process.execPath, [bundled, 'add', spec], {
|
|
136
|
+
cwd: profileDir,
|
|
137
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
|
138
|
+
})
|
|
139
|
+
return 'dsh-bundled-pnpm'
|
|
140
|
+
} catch (error) {
|
|
141
|
+
failures.push(String(error))
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
throw new Error(failures.join(' | '))
|
|
145
|
+
}
|
|
146
|
+
|
|
29
147
|
const SURFACE_TYPES = new Set([
|
|
30
148
|
'system/message',
|
|
31
149
|
'developer/message',
|
|
@@ -264,6 +382,27 @@ function computeDiff(beforeText, afterText) {
|
|
|
264
382
|
return { hunks, added, removed, truncated }
|
|
265
383
|
}
|
|
266
384
|
|
|
385
|
+
/** Optional AI explanations anchored to a new-file line or a 1-based hunk. */
|
|
386
|
+
function normalizeNotes(raw) {
|
|
387
|
+
if (!Array.isArray(raw)) return []
|
|
388
|
+
const notes = []
|
|
389
|
+
for (const item of raw.slice(0, 30)) {
|
|
390
|
+
if (item === null || typeof item !== 'object') continue
|
|
391
|
+
const text = typeof item.text === 'string' ? item.text.trim() : ''
|
|
392
|
+
if (text === '') continue
|
|
393
|
+
const line = Number.isSafeInteger(item.line) && item.line >= 1 ? item.line : undefined
|
|
394
|
+
const hunk = Number.isSafeInteger(item.hunk) && item.hunk >= 1 ? item.hunk : undefined
|
|
395
|
+
notes.push({
|
|
396
|
+
id: `note-${notes.length + 1}`,
|
|
397
|
+
...(line === undefined ? {} : { line }),
|
|
398
|
+
...(hunk === undefined ? {} : { hunk }),
|
|
399
|
+
text: text.slice(0, 1200),
|
|
400
|
+
at: Date.now(),
|
|
401
|
+
})
|
|
402
|
+
}
|
|
403
|
+
return notes
|
|
404
|
+
}
|
|
405
|
+
|
|
267
406
|
export function apply(ctx) {
|
|
268
407
|
const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
269
408
|
const root = path.join(home, 'coding-enhanced')
|
|
@@ -334,6 +473,31 @@ export function apply(ctx) {
|
|
|
334
473
|
|
|
335
474
|
const withdrawnOf = (sessionId) => state.sessions[sessionId]?.withdrawn ?? {}
|
|
336
475
|
|
|
476
|
+
const backupOf = (sessionId) => {
|
|
477
|
+
const backup = state.sessions[sessionId]?.backup
|
|
478
|
+
if (backup === null || typeof backup !== 'object') return undefined
|
|
479
|
+
if (typeof backup.tree !== 'string' || typeof backup.cwd !== 'string' || typeof backup.gitDir !== 'string') return undefined
|
|
480
|
+
return {
|
|
481
|
+
tree: backup.tree,
|
|
482
|
+
cwd: backup.cwd,
|
|
483
|
+
gitDir: backup.gitDir,
|
|
484
|
+
nested: Array.isArray(backup.nested)
|
|
485
|
+
? backup.nested.filter((nested) =>
|
|
486
|
+
nested !== null && typeof nested === 'object'
|
|
487
|
+
&& typeof nested.cwd === 'string' && typeof nested.tree === 'string' && typeof nested.gitDir === 'string')
|
|
488
|
+
: [],
|
|
489
|
+
at: Number.isSafeInteger(backup.at) ? backup.at : undefined,
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const setBackup = (sessionId, backup) => {
|
|
494
|
+
const record = state.sessions[sessionId] ?? {}
|
|
495
|
+
record.backup = backup
|
|
496
|
+
record.updatedAt = Date.now()
|
|
497
|
+
state.sessions[sessionId] = record
|
|
498
|
+
saveState()
|
|
499
|
+
}
|
|
500
|
+
|
|
337
501
|
// ------------------------------------------------------------ snapshots ---
|
|
338
502
|
/** sessionId -> Map<turn, { sessionId, turn, tree, cwd, gitDir, endSeq, createdAt }> */
|
|
339
503
|
const snapshots = new Map()
|
|
@@ -357,6 +521,25 @@ export function apply(ctx) {
|
|
|
357
521
|
}
|
|
358
522
|
}
|
|
359
523
|
|
|
524
|
+
const backupRef = (sessionId) =>
|
|
525
|
+
`refs/coding-enhanced/${createHash('sha256').update(sessionId).digest('hex').slice(0, 16)}/backup`
|
|
526
|
+
|
|
527
|
+
const writeBackupRefs = async (backup) => {
|
|
528
|
+
const ref = backupRef(backup.sessionId)
|
|
529
|
+
try {
|
|
530
|
+
await runGit(['update-ref', ref, backup.tree], { gitDir: backup.gitDir })
|
|
531
|
+
} catch (error) {
|
|
532
|
+
ctx.logger?.warn?.(`coding-enhanced: cannot create backup ref: ${String(error)}`)
|
|
533
|
+
}
|
|
534
|
+
for (const nested of Array.isArray(backup.nested) ? backup.nested : []) {
|
|
535
|
+
try {
|
|
536
|
+
await runGit(['update-ref', ref, nested.tree], { gitDir: nested.gitDir })
|
|
537
|
+
} catch (error) {
|
|
538
|
+
ctx.logger?.warn?.(`coding-enhanced: cannot create nested backup ref: ${String(error)}`)
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
360
543
|
const deleteSnapshotRefs = async (snapshot) => {
|
|
361
544
|
const ref = snapshotRef(snapshot.sessionId, snapshot.turn)
|
|
362
545
|
try {
|
|
@@ -397,6 +580,11 @@ export function apply(ctx) {
|
|
|
397
580
|
if (map.size > 0) snapshots.set(sessionId, map)
|
|
398
581
|
}
|
|
399
582
|
|
|
583
|
+
for (const sessionId of Object.keys(state.sessions)) {
|
|
584
|
+
const backup = backupOf(sessionId)
|
|
585
|
+
if (backup !== undefined) void writeBackupRefs({ ...backup, sessionId })
|
|
586
|
+
}
|
|
587
|
+
|
|
400
588
|
const latestSnapshot = (sessionId) => {
|
|
401
589
|
const map = snapshots.get(sessionId)
|
|
402
590
|
if (map === undefined || map.size === 0) return undefined
|
|
@@ -617,56 +805,63 @@ export function apply(ctx) {
|
|
|
617
805
|
return found
|
|
618
806
|
}
|
|
619
807
|
|
|
620
|
-
const
|
|
621
|
-
const
|
|
622
|
-
|
|
623
|
-
|
|
808
|
+
const captureWorkspace = async (sessionId, cwd) => {
|
|
809
|
+
const gitDir = await ensureRepo(cwd)
|
|
810
|
+
// `--ignore-errors` keeps unreadable files from failing the whole turn.
|
|
811
|
+
try {
|
|
812
|
+
await addAll(gitDir, cwd)
|
|
813
|
+
} catch (error) {
|
|
814
|
+
ctx.logger?.warn?.(`coding-enhanced: snapshot add failed for ${cwd}: ${String(error)}`)
|
|
815
|
+
return undefined
|
|
816
|
+
}
|
|
817
|
+
const tree = (await runGit(['write-tree'], { gitDir, workTree: cwd })).trim()
|
|
818
|
+
if (tree === '') return undefined
|
|
819
|
+
const nested = []
|
|
820
|
+
if (featureFlags.nestedSnapshots === true) {
|
|
821
|
+
let candidates = []
|
|
624
822
|
try {
|
|
625
|
-
await
|
|
823
|
+
candidates = await findNestedRepos(cwd)
|
|
626
824
|
} catch (error) {
|
|
627
|
-
ctx.logger?.warn?.(`coding-enhanced:
|
|
628
|
-
return
|
|
825
|
+
ctx.logger?.warn?.(`coding-enhanced: cannot scan nested repositories in ${cwd}: ${String(error)}`)
|
|
629
826
|
}
|
|
630
|
-
const
|
|
631
|
-
if (tree === '') return
|
|
632
|
-
const nested = []
|
|
633
|
-
if (featureFlags.nestedSnapshots === true) {
|
|
634
|
-
let candidates = []
|
|
827
|
+
for (const nestedCwd of candidates) {
|
|
635
828
|
try {
|
|
636
|
-
|
|
829
|
+
const nestedGitDir = await ensureRepo(nestedCwd)
|
|
830
|
+
await serialized(`snapshot:${nestedCwd}`, async () => {
|
|
831
|
+
await addAll(nestedGitDir, nestedCwd)
|
|
832
|
+
const nestedTree = (await runGit(['write-tree'], { gitDir: nestedGitDir, workTree: nestedCwd })).trim()
|
|
833
|
+
if (nestedTree !== '') nested.push({ cwd: nestedCwd, tree: nestedTree, gitDir: nestedGitDir })
|
|
834
|
+
})
|
|
637
835
|
} catch (error) {
|
|
638
|
-
ctx.logger?.warn?.(`coding-enhanced: cannot
|
|
639
|
-
}
|
|
640
|
-
for (const nestedCwd of candidates) {
|
|
641
|
-
try {
|
|
642
|
-
const nestedGitDir = await ensureRepo(nestedCwd)
|
|
643
|
-
await serialized(`snapshot:${nestedCwd}`, async () => {
|
|
644
|
-
await addAll(nestedGitDir, nestedCwd)
|
|
645
|
-
const nestedTree = (await runGit(['write-tree'], { gitDir: nestedGitDir, workTree: nestedCwd })).trim()
|
|
646
|
-
if (nestedTree !== '') nested.push({ cwd: nestedCwd, tree: nestedTree, gitDir: nestedGitDir })
|
|
647
|
-
})
|
|
648
|
-
} catch (error) {
|
|
649
|
-
ctx.logger?.warn?.(`coding-enhanced: cannot snapshot nested repository ${nestedCwd}: ${String(error)}`)
|
|
650
|
-
}
|
|
836
|
+
ctx.logger?.warn?.(`coding-enhanced: cannot snapshot nested repository ${nestedCwd}: ${String(error)}`)
|
|
651
837
|
}
|
|
652
838
|
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
turn,
|
|
656
|
-
tree,
|
|
657
|
-
cwd,
|
|
658
|
-
gitDir,
|
|
659
|
-
endSeq: undefined,
|
|
660
|
-
createdAt: Date.now(),
|
|
661
|
-
nested,
|
|
662
|
-
}
|
|
663
|
-
await writeSnapshotRefs(snapshot)
|
|
664
|
-
setSnapshot(snapshot)
|
|
665
|
-
pruneSnapshots(sessionId)
|
|
666
|
-
})()
|
|
667
|
-
return serialized(`snapshot:${cwd}`, () => work)
|
|
839
|
+
}
|
|
840
|
+
return { sessionId, tree, cwd, gitDir, nested }
|
|
668
841
|
}
|
|
669
842
|
|
|
843
|
+
const captureSnapshot = (sessionId, cwd, turn) => serialized(`snapshot:${cwd}`, async () => {
|
|
844
|
+
const base = await captureWorkspace(sessionId, cwd)
|
|
845
|
+
if (base === undefined) return
|
|
846
|
+
const snapshot = {
|
|
847
|
+
...base,
|
|
848
|
+
turn,
|
|
849
|
+
endSeq: undefined,
|
|
850
|
+
createdAt: Date.now(),
|
|
851
|
+
}
|
|
852
|
+
await writeSnapshotRefs(snapshot)
|
|
853
|
+
setSnapshot(snapshot)
|
|
854
|
+
pruneSnapshots(sessionId)
|
|
855
|
+
})
|
|
856
|
+
|
|
857
|
+
const captureBackup = (sessionId, cwd) => serialized(`snapshot:${cwd}`, async () => {
|
|
858
|
+
const base = await captureWorkspace(sessionId, cwd)
|
|
859
|
+
if (base === undefined) return undefined
|
|
860
|
+
const backup = { ...base, at: Date.now() }
|
|
861
|
+
await writeBackupRefs(backup)
|
|
862
|
+
setBackup(sessionId, backup)
|
|
863
|
+
return backup
|
|
864
|
+
})
|
|
670
865
|
|
|
671
866
|
// ------------------------------------------------------- review gate ---
|
|
672
867
|
const REVIEW_TOOLS = new Set(['write', 'edit', 'apply_patch'])
|
|
@@ -685,6 +880,7 @@ export function apply(ctx) {
|
|
|
685
880
|
if (review === undefined || review.finished) {
|
|
686
881
|
review = {
|
|
687
882
|
id: `review-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
883
|
+
waitKey: randomBytes(24).toString('hex'),
|
|
688
884
|
sessionId,
|
|
689
885
|
createdAt: Date.now(),
|
|
690
886
|
entries: new Map(),
|
|
@@ -763,6 +959,7 @@ export function apply(ctx) {
|
|
|
763
959
|
removed: 0,
|
|
764
960
|
truncated: false,
|
|
765
961
|
hunks: [],
|
|
962
|
+
notes: [],
|
|
766
963
|
editable: false,
|
|
767
964
|
canApply: true,
|
|
768
965
|
updatedAt: Date.now(),
|
|
@@ -824,6 +1021,7 @@ export function apply(ctx) {
|
|
|
824
1021
|
entry.hunks = diff.hunks
|
|
825
1022
|
entry.editable = entry.before.length <= MAX_EDITABLE_BYTES && entry.after.length <= MAX_EDITABLE_BYTES
|
|
826
1023
|
}
|
|
1024
|
+
entry.notes = normalizeNotes(args.notes)
|
|
827
1025
|
bumpReview()
|
|
828
1026
|
return { review, entry }
|
|
829
1027
|
}
|
|
@@ -900,6 +1098,7 @@ export function apply(ctx) {
|
|
|
900
1098
|
removed: entry.removed,
|
|
901
1099
|
truncated: entry.truncated,
|
|
902
1100
|
hunks: entry.hunks,
|
|
1101
|
+
notes: Array.isArray(entry.notes) ? entry.notes : [],
|
|
903
1102
|
editable: entry.editable === true,
|
|
904
1103
|
canApply: entry.canApply !== false,
|
|
905
1104
|
beforeText: entry.editable === true ? entry.before : null,
|
|
@@ -1002,7 +1201,7 @@ export function apply(ctx) {
|
|
|
1002
1201
|
return rest.trim()
|
|
1003
1202
|
}
|
|
1004
1203
|
|
|
1005
|
-
const stagePatch = async (session, exec, patch) => {
|
|
1204
|
+
const stagePatch = async (session, exec, patch, notes) => {
|
|
1006
1205
|
if (typeof patch !== 'string' || patch.trim() === '') throw new Error('patch is required.')
|
|
1007
1206
|
if (patch.length > MAX_REVIEW_FILE_BYTES) throw new Error('The patch is too large for the review gate.')
|
|
1008
1207
|
const cwd = typeof session.header?.cwd === 'string' && session.header.cwd !== '' ? session.header.cwd : process.cwd()
|
|
@@ -1111,10 +1310,18 @@ export function apply(ctx) {
|
|
|
1111
1310
|
}
|
|
1112
1311
|
const files = []
|
|
1113
1312
|
for (const { target, content } of staged) {
|
|
1313
|
+
const targetNotes = Array.isArray(notes)
|
|
1314
|
+
? notes.filter((note) => {
|
|
1315
|
+
if (note === null || typeof note !== 'object') return false
|
|
1316
|
+
const rawPath = typeof note.path === 'string' ? note.path.replace(/^[ab]\//, '').replace(/^\.\//, '') : ''
|
|
1317
|
+
if (rawPath !== '') return rawPath === target.relative
|
|
1318
|
+
return targets.size <= 1
|
|
1319
|
+
})
|
|
1320
|
+
: []
|
|
1114
1321
|
const queued = await stageFileChange(session, {
|
|
1115
1322
|
id: exec.callId,
|
|
1116
1323
|
name: 'write',
|
|
1117
|
-
arguments: { file_path: target.absolute, content },
|
|
1324
|
+
arguments: { file_path: target.absolute, content, notes: targetNotes },
|
|
1118
1325
|
})
|
|
1119
1326
|
files.push(queued.entry.display)
|
|
1120
1327
|
}
|
|
@@ -1127,42 +1334,72 @@ export function apply(ctx) {
|
|
|
1127
1334
|
const registerReviewTools = () => {
|
|
1128
1335
|
ctx.tools.register(defineTool({
|
|
1129
1336
|
name: 'review_write',
|
|
1130
|
-
description: 'Queue a new file or a full-file rewrite for the user\'s review. This does not write the file: the change is held in the Code review tab until the user finishes. Use review_patch for edits to existing files.
|
|
1337
|
+
description: 'Queue a new file or a full-file rewrite for the user\'s review. This does not write the file: the change is held in the Code review tab until the user finishes. Use review_patch for edits to existing files. Add a short notes entry for each group of added lines so the reviewer sees your explanation. The result includes a reviewId and waitKey; reuse the persistent review waiter child with send_message, or start one, instead of blocking this turn.',
|
|
1131
1338
|
parameters: {
|
|
1132
1339
|
file_path: { type: 'string', required: true, description: 'Path to write, resolved like the write tool.' },
|
|
1133
1340
|
content: { type: 'string', required: true, description: 'Full UTF-8 text content to write.' },
|
|
1341
|
+
notes: {
|
|
1342
|
+
type: 'array',
|
|
1343
|
+
description: 'Optional 1-2 sentence explanations for groups of added lines.',
|
|
1344
|
+
items: {
|
|
1345
|
+
type: 'object',
|
|
1346
|
+
additionalProperties: false,
|
|
1347
|
+
properties: {
|
|
1348
|
+
line: { type: 'integer', description: '1-based new-file line inside the added group (recommended).' },
|
|
1349
|
+
hunk: { type: 'integer', description: '1-based hunk index when the line is not known.' },
|
|
1350
|
+
text: { type: 'string', required: true, description: 'Why this group changed.' },
|
|
1351
|
+
},
|
|
1352
|
+
},
|
|
1353
|
+
},
|
|
1134
1354
|
},
|
|
1135
1355
|
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
1136
1356
|
async execute(args, exec) {
|
|
1137
1357
|
const session = exec.agent?.session
|
|
1138
1358
|
if (session === undefined) return 'No active session.'
|
|
1139
1359
|
if (featureFlags.review !== true) return 'The review gate is off. Use the write tool instead.'
|
|
1140
|
-
const queued = await stageFileChange(session, { id: exec.callId, name: 'write', arguments: { file_path: args.file_path, content: args.content } })
|
|
1360
|
+
const queued = await stageFileChange(session, { id: exec.callId, name: 'write', arguments: { file_path: args.file_path, content: args.content, notes: args.notes } })
|
|
1141
1361
|
if (queued === undefined) return 'Could not queue this change (missing or invalid file_path).'
|
|
1142
|
-
return `Queued for review: ${queued.entry.display} (${queued.review.entries.size} file(s) queued). Nothing is written until the user finishes.
|
|
1362
|
+
return `Queued for review: ${queued.entry.display} (${queued.review.entries.size} file(s) queued). Nothing is written until the user finishes. reviewId: ${queued.review.id}; waitKey: ${queued.review.waitKey}; if you already have a review waiter child, send_message it the id and key; otherwise start one; only call review_wait yourself if delegation is unavailable.`
|
|
1143
1363
|
},
|
|
1144
1364
|
}), { when: () => featureFlags.review === true && featureFlags.autoReview === true })
|
|
1145
1365
|
|
|
1146
1366
|
ctx.tools.register(defineTool({
|
|
1147
1367
|
name: 'review_patch',
|
|
1148
|
-
description: 'Queue a unified diff for the user\'s review. The patch must use ---/+++ headers and @@ hunks with paths relative to the working directory; a/ and b/ prefixes and diff --git headers are accepted. Use one patch per file when possible; multiple files are allowed. This does not modify the workspace: the change is held in the Code review tab until the user finishes. Example:\n--- a/src/app.ts\n+++ b/src/app.ts\n@@ -10,7 +10,9 @@\n const app = createApp()\n- app.use(oldRouter)\n+ app.use(newRouter)\n+ app.use(logger)\n app.listen(3000)\nAfter queueing every change for this turn,
|
|
1368
|
+
description: 'Queue a unified diff for the user\'s review. The patch must use ---/+++ headers and @@ hunks with paths relative to the working directory; a/ and b/ prefixes and diff --git headers are accepted. Use one patch per file when possible; multiple files are allowed. This does not modify the workspace: the change is held in the Code review tab until the user finishes. Add a short notes entry for each group of added lines so the reviewer sees your explanation. The result includes a reviewId and waitKey; reuse the persistent review waiter child with send_message, or start one, instead of blocking this turn. Example:\n--- a/src/app.ts\n+++ b/src/app.ts\n@@ -10,7 +10,9 @@\n const app = createApp()\n- app.use(oldRouter)\n+ app.use(newRouter)\n+ app.use(logger)\n app.listen(3000)\nAfter queueing every change for this turn, start a review waiter subagent with the reviewId and waitKey.',
|
|
1149
1369
|
parameters: {
|
|
1150
1370
|
patch: { type: 'string', required: true, description: 'A unified diff (---/+++/@@) to queue for review.' },
|
|
1371
|
+
notes: {
|
|
1372
|
+
type: 'array',
|
|
1373
|
+
description: 'Optional 1-2 sentence explanations for groups of added lines.',
|
|
1374
|
+
items: {
|
|
1375
|
+
type: 'object',
|
|
1376
|
+
additionalProperties: false,
|
|
1377
|
+
properties: {
|
|
1378
|
+
path: { type: 'string', description: 'File path this note belongs to when the patch touches several files.' },
|
|
1379
|
+
line: { type: 'integer', description: '1-based new-file line inside the added group (recommended).' },
|
|
1380
|
+
hunk: { type: 'integer', description: '1-based hunk index when the line is not known.' },
|
|
1381
|
+
text: { type: 'string', required: true, description: 'Why this group changed.' },
|
|
1382
|
+
},
|
|
1383
|
+
},
|
|
1384
|
+
},
|
|
1151
1385
|
},
|
|
1152
1386
|
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
1153
1387
|
async execute(args, exec) {
|
|
1154
1388
|
const session = exec.agent?.session
|
|
1155
1389
|
if (session === undefined) return 'No active session.'
|
|
1156
1390
|
if (featureFlags.review !== true) return 'The review gate is off. Use apply_patch or edit instead.'
|
|
1157
|
-
const queued = await stagePatch(session, exec, args.patch)
|
|
1158
|
-
return `Queued for review: ${queued.files.join(', ')} (${queued.review.entries.size} file(s) in this review). Nothing is written until the user finishes.
|
|
1391
|
+
const queued = await stagePatch(session, exec, args.patch, args.notes)
|
|
1392
|
+
return `Queued for review: ${queued.files.join(', ')} (${queued.review.entries.size} file(s) in this review). Nothing is written until the user finishes. reviewId: ${queued.review.id}; waitKey: ${queued.review.waitKey}; if you already have a review waiter child, send_message it the id and key; otherwise start one; only call review_wait yourself if delegation is unavailable.`
|
|
1159
1393
|
},
|
|
1160
1394
|
}), { when: () => featureFlags.review === true && featureFlags.autoReview === true })
|
|
1161
1395
|
|
|
1162
1396
|
ctx.tools.register(defineTool({
|
|
1163
1397
|
name: 'review_wait',
|
|
1164
|
-
description: 'Wait for the
|
|
1165
|
-
parameters: {
|
|
1398
|
+
description: 'Wait for a review. Recommended: call it from a review waiter subagent with the reviewId and waitKey from review_write/review_patch. It blocks only the calling agent; the main agent can continue or end its turn. As an owner fallback, omit both to wait on this session\'s review. Returns one structured result per file: applied, rejected (with the user\'s comment), edited, or failed.',
|
|
1399
|
+
parameters: {
|
|
1400
|
+
reviewId: { type: 'string', description: 'Review id returned by review_write/review_patch.' },
|
|
1401
|
+
waitKey: { type: 'string', description: 'Wait key returned by the same tool result.' },
|
|
1402
|
+
},
|
|
1166
1403
|
output: {
|
|
1167
1404
|
schema: {
|
|
1168
1405
|
type: 'object',
|
|
@@ -1186,11 +1423,20 @@ export function apply(ctx) {
|
|
|
1186
1423
|
},
|
|
1187
1424
|
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
1188
1425
|
},
|
|
1189
|
-
async execute(
|
|
1426
|
+
async execute(args, exec) {
|
|
1190
1427
|
const session = exec.agent?.session
|
|
1191
1428
|
if (session === undefined) return { status: 'open', files: [] }
|
|
1192
|
-
const
|
|
1193
|
-
|
|
1429
|
+
const reviewId = typeof args?.reviewId === 'string' && args.reviewId !== '' ? args.reviewId : undefined
|
|
1430
|
+
const waitKey = typeof args?.waitKey === 'string' && args.waitKey !== '' ? args.waitKey : undefined
|
|
1431
|
+
let review
|
|
1432
|
+
if (reviewId !== undefined) {
|
|
1433
|
+
review = [...reviews.values()].find((candidate) => candidate.id === reviewId)
|
|
1434
|
+
if (review === undefined) return { status: 'not-found', files: [] }
|
|
1435
|
+
if (review.waitKey !== waitKey) return { status: 'forbidden', files: [] }
|
|
1436
|
+
} else {
|
|
1437
|
+
review = reviews.get(session.id)
|
|
1438
|
+
if (review === undefined || review.entries.size === 0) return { status: 'empty', files: [] }
|
|
1439
|
+
}
|
|
1194
1440
|
if (review.submitted !== true) {
|
|
1195
1441
|
review.submitted = true
|
|
1196
1442
|
bumpReview()
|
|
@@ -1209,7 +1455,7 @@ export function apply(ctx) {
|
|
|
1209
1455
|
if (!REVIEW_TOOLS.has(exec.name)) return next()
|
|
1210
1456
|
return {
|
|
1211
1457
|
kind: 'deny',
|
|
1212
|
-
reason: 'File changes must go through the review gate while
|
|
1458
|
+
reason: 'File changes must go through the review gate while Pre-review is on. Use review_write (new file / full file) or review_patch (unified diff); after queueing all changes start a review waiter subagent (or call review_wait if delegation is unavailable). Shell commands are outside the review.',
|
|
1213
1459
|
}
|
|
1214
1460
|
}
|
|
1215
1461
|
|
|
@@ -1220,7 +1466,7 @@ export function apply(ctx) {
|
|
|
1220
1466
|
name: 'tool:review-gate',
|
|
1221
1467
|
order: 110,
|
|
1222
1468
|
text: () => featureFlags.review === true && featureFlags.autoReview === true
|
|
1223
|
-
? '🎟️ FILE-EDIT VELVET ROPE: The human personally reviews every file change, and you do not have a backstage pass. Queue every change with review_write (new file / full file) or review_patch (unified diff); when you have queued everything,
|
|
1469
|
+
? '🎟️ FILE-EDIT VELVET ROPE: The human personally reviews every file change, and you do not have a backstage pass. Queue every change with review_write (new file / full file) or review_patch (unified diff); when you have queued everything, hand the review to a review waiter subagent and continue. Do not use write/edit/apply_patch — that is the staff-only door, and the bouncer has a long memory. If a file is rejected, read the comment, say "fair enough", and revise. For every group of added lines, include a short notes entry ({"line": <new-file line>, "text": "why this group changed"}) so the human sees a purple explanation row; keep each note to 1-2 sentences. After queueing, do not call review_wait yourself. Use ONE persistent review waiter subagent per conversation: if you already have a waiter child id, send the new reviewId and waitKey to it with send_message; otherwise start it once with the subagent tool. Tell it to call review_wait with both and report the per-file outcomes. Then continue helping the user or end the turn; the waiter will wake you. If delegation is unavailable, call review_wait yourself as a fallback. This is house rules, not a suggestion. 💅'
|
|
1224
1470
|
: '',
|
|
1225
1471
|
}), 'coding-enhanced: review prompt')
|
|
1226
1472
|
})
|
|
@@ -1481,6 +1727,9 @@ export function apply(ctx) {
|
|
|
1481
1727
|
const info = inspectSession(session)
|
|
1482
1728
|
const latestTurn = info.latestTurn
|
|
1483
1729
|
const withdrawn = withdrawnOf(sessionId)
|
|
1730
|
+
const snapshotMap = snapshots.get(sessionId)
|
|
1731
|
+
const snapshotTurns = snapshotMap === undefined ? [] : [...snapshotMap.keys()].sort((left, right) => left - right)
|
|
1732
|
+
const backup = backupOf(sessionId)
|
|
1484
1733
|
const anchors = {}
|
|
1485
1734
|
const withdrawable = {}
|
|
1486
1735
|
if (featureFlags.withdraw === true && !activeTurns.has(sessionId)) {
|
|
@@ -1529,6 +1778,8 @@ export function apply(ctx) {
|
|
|
1529
1778
|
turns: withdrawn,
|
|
1530
1779
|
anchors,
|
|
1531
1780
|
withdrawable,
|
|
1781
|
+
snapshotTurns,
|
|
1782
|
+
backupAt: backup?.at ?? null,
|
|
1532
1783
|
})
|
|
1533
1784
|
}
|
|
1534
1785
|
|
|
@@ -1591,6 +1842,17 @@ export function apply(ctx) {
|
|
|
1591
1842
|
}
|
|
1592
1843
|
}
|
|
1593
1844
|
|
|
1845
|
+
let backup
|
|
1846
|
+
try {
|
|
1847
|
+
backup = await captureBackup(sessionId, session.header?.cwd ?? snapshot.cwd)
|
|
1848
|
+
} catch (error) {
|
|
1849
|
+
ctx.logger?.error?.(`coding-enhanced: backup failed: ${String(error)}`)
|
|
1850
|
+
return fail('backup-failed', `Could not capture the pre-withdraw backup, so nothing was restored: ${String(error)}`)
|
|
1851
|
+
}
|
|
1852
|
+
if (backup === undefined) {
|
|
1853
|
+
return fail('backup-failed', 'Could not capture the pre-withdraw backup, so nothing was restored.')
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1594
1856
|
let restored
|
|
1595
1857
|
try {
|
|
1596
1858
|
restored = await restoreTree(snapshot)
|
|
@@ -1628,7 +1890,8 @@ export function apply(ctx) {
|
|
|
1628
1890
|
}
|
|
1629
1891
|
|
|
1630
1892
|
const restoredAt = Date.now()
|
|
1631
|
-
const record = state.sessions[sessionId] ?? {
|
|
1893
|
+
const record = state.sessions[sessionId] ?? {}
|
|
1894
|
+
if (record.withdrawn === undefined) record.withdrawn = {}
|
|
1632
1895
|
for (const affectedTurn of affected) {
|
|
1633
1896
|
record.withdrawn[affectedTurn] = {
|
|
1634
1897
|
at: restoredAt,
|
|
@@ -1720,16 +1983,78 @@ export function apply(ctx) {
|
|
|
1720
1983
|
cancelReview(review.id, (entry) => `The review gate was turned off in Settings. Nothing was written for "${entry.display}". Do not retry immediately; wait for the user.`)
|
|
1721
1984
|
}
|
|
1722
1985
|
}
|
|
1723
|
-
return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc })
|
|
1986
|
+
return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc, version: PLUGIN_VERSION })
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
const handleUpdateCheck = async () => {
|
|
1990
|
+
try {
|
|
1991
|
+
const check = await latestNpmVersion()
|
|
1992
|
+
return ok({ current: PLUGIN_VERSION, latest: check.version, registry: check.registry, available: compareVersions(check.version, PLUGIN_VERSION) > 0 })
|
|
1993
|
+
} catch (error) {
|
|
1994
|
+
return fail('update-check-failed', String(error))
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
const handleUpdateInstall = async () => {
|
|
1999
|
+
let latest
|
|
2000
|
+
try {
|
|
2001
|
+
latest = (await latestNpmVersion()).version
|
|
2002
|
+
} catch (error) {
|
|
2003
|
+
return fail('update-check-failed', String(error))
|
|
2004
|
+
}
|
|
2005
|
+
if (compareVersions(latest, PLUGIN_VERSION) <= 0) {
|
|
2006
|
+
return ok({ updated: false, current: PLUGIN_VERSION, latest })
|
|
2007
|
+
}
|
|
2008
|
+
const profileDir = path.dirname(path.dirname(PACKAGE_ROOT))
|
|
2009
|
+
if (!existsSync(path.join(profileDir, 'package.json')) || !existsSync(path.join(profileDir, 'node_modules'))) {
|
|
2010
|
+
return fail('update-not-profile', 'This plugin is linked from a development checkout; update it through Plugins or npm install.')
|
|
2011
|
+
}
|
|
2012
|
+
const spec = `dsh-coding-enhanced@${latest}`
|
|
2013
|
+
const profileName = path.basename(profileDir)
|
|
2014
|
+
let manager
|
|
2015
|
+
try {
|
|
2016
|
+
manager = await installPackage(spec, profileDir)
|
|
2017
|
+
} catch (error) {
|
|
2018
|
+
return fail('update-failed', `Could not install ${spec}. Run \`dsh plugin --profile ${profileName} add ${spec}\` and restart DSH. ${String(error)}`)
|
|
2019
|
+
}
|
|
2020
|
+
return ok({
|
|
2021
|
+
updated: true,
|
|
2022
|
+
from: PLUGIN_VERSION,
|
|
2023
|
+
to: latest,
|
|
2024
|
+
restart: true,
|
|
2025
|
+
profile: profileName,
|
|
2026
|
+
manager,
|
|
2027
|
+
command: manager === 'dsh-bundled-pnpm' ? `dsh-bundled pnpm add ${spec}` : `${manager} add ${spec}`,
|
|
2028
|
+
})
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
const handleRestoreBackup = async (payload) => {
|
|
2032
|
+
const sessionId = payload?.sessionId
|
|
2033
|
+
if (typeof sessionId !== 'string' || sessionId === '') return fail('bad-request', 'sessionId is required')
|
|
2034
|
+
if (ctx.sessions.get(sessionId) === undefined) return fail('session-not-live', 'Session is not active in this Host')
|
|
2035
|
+
if (activeTurns.has(sessionId)) return fail('turn-active', 'A turn is still running')
|
|
2036
|
+
const backup = backupOf(sessionId)
|
|
2037
|
+
if (backup === undefined) return fail('no-backup', 'No pre-withdraw backup exists for this session')
|
|
2038
|
+
let restored
|
|
2039
|
+
try {
|
|
2040
|
+
restored = await restoreTree({ ...backup, sessionId })
|
|
2041
|
+
} catch (error) {
|
|
2042
|
+
ctx.logger?.error?.(`coding-enhanced: restore backup failed: ${String(error)}`)
|
|
2043
|
+
return fail('restore-backup-failed', String(error))
|
|
2044
|
+
}
|
|
2045
|
+
return ok({ restored: restored.count, files: restored.files, skipped: restored.skipped, at: backup.at ?? null })
|
|
1724
2046
|
}
|
|
1725
2047
|
|
|
1726
2048
|
const dispatch = async (endpoint, payload) => {
|
|
1727
2049
|
try {
|
|
1728
2050
|
if (endpoint === 'status') return handleStatus(payload?.sessionId)
|
|
1729
|
-
if (endpoint === 'settings') return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc })
|
|
2051
|
+
if (endpoint === 'settings') return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc, version: PLUGIN_VERSION })
|
|
1730
2052
|
if (endpoint === 'setSettings') return updateSettings(payload)
|
|
1731
2053
|
if (endpoint === 'cleanup') return ok(await cleanupSnapshots())
|
|
1732
2054
|
if (endpoint === 'withdraw') return await handleWithdraw(payload)
|
|
2055
|
+
if (endpoint === 'restoreBackup') return await handleRestoreBackup(payload)
|
|
2056
|
+
if (endpoint === 'updateCheck') return await handleUpdateCheck()
|
|
2057
|
+
if (endpoint === 'updateInstall') return await handleUpdateInstall()
|
|
1733
2058
|
if (endpoint === 'reviews') {
|
|
1734
2059
|
const since = payload?.since
|
|
1735
2060
|
if (Number.isSafeInteger(since) && since === reviewVersion) {
|