dsh-workspace-scratch 0.0.0-stage → 0.2.0

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/index.js ADDED
@@ -0,0 +1,638 @@
1
+ /**
2
+ * dsh-workspace-scratch — keep a workspace clean by giving every session a
3
+ * private `.dsh/` home for scratch files and durable memory notes.
4
+ *
5
+ * Behaviour:
6
+ * - On plugin activation and on every `agent/created`, the workspace root of the
7
+ * session gets `.dsh/` with `tmp/<session>/` and `memory/`, a `.dsh/.gitignore`
8
+ * that hides its contents from git, and (when the workspace is a git checkout)
9
+ * a `/.dsh/` entry in `.git/info/exclude`.
10
+ * - Old `<session>/` scratch directories are pruned after `retentionDays`.
11
+ * - Two model-facing tools, `scratch` and `memory`, read and write only inside
12
+ * `.dsh/`; every path is resolved and checked so nothing can escape it.
13
+ * - A system-prompt section and a runtime-context line tell the model the rule
14
+ * and the exact directories of the current session.
15
+ *
16
+ * The plugin imports nothing from `@deepseek-ai/*`: every DSH service is read
17
+ * through the plugin context, and the two tools are declared with plain JSON
18
+ * Schema objects, so the package installs and loads without extra dependencies.
19
+ */
20
+
21
+ import { appendFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
22
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
23
+
24
+ import {
25
+ applyConfig as mirrorConfig,
26
+ composeConfig,
27
+ createApiRoutes,
28
+ readSettings,
29
+ removeSettings,
30
+ settingsFile,
31
+ validateLayer,
32
+ writeSettings,
33
+ } from './settings.js'
34
+
35
+ /** Stable Cordis plugin name. */
36
+ export const name = 'workspace-scratch'
37
+
38
+ /** Services this plugin needs: the agent registry, prompt registry and tool registry. */
39
+ export const inject = ['agents', 'systemPrompt', 'tools']
40
+
41
+ /** File name of the human-readable memory index inside the memory directory. */
42
+ const MEMORY_INDEX = 'MEMORY.md'
43
+
44
+ /** Case-insensitive identity of the reserved index file name, for filesystem comparisons. */
45
+ const MEMORY_INDEX_UPPER = MEMORY_INDEX.toUpperCase()
46
+
47
+ /** Prompt section order: just after the terminal guidance, before web tools. */
48
+ const SECTION_ORDER = 1750
49
+
50
+ /** Runtime-context order: after the team identity, before harness facts. */
51
+ const CONTEXT_ORDER = 130
52
+
53
+ /** Pruning is attempted at most once per hour for a given workspace root. */
54
+ const PRUNE_INTERVAL_MS = 60 * 60 * 1000
55
+
56
+ /** Hard ceiling for one scratch read or memory read, in bytes. */
57
+ const READ_MAX_BYTES = 64 * 1024
58
+
59
+ /** Hard ceiling for entries returned by a recursive scratch listing. */
60
+ const LIST_MAX_ENTRIES = 200
61
+
62
+ /** Warn through the plugin logger without ever failing the caller. */
63
+ function warn(ctx, message) {
64
+ try {
65
+ ctx.logger?.warn?.(`workspace-scratch: ${message}`)
66
+ } catch {
67
+ /* logging must never break the plugin */
68
+ }
69
+ }
70
+
71
+ /** Read a DSH service, tolerating compositions that do not mount it. */
72
+ function service(ctx, serviceName) {
73
+ try {
74
+ return ctx.get(serviceName)
75
+ } catch {
76
+ return undefined
77
+ }
78
+ }
79
+
80
+ /** The workspace root a session was opened in: its recorded `cwd`, never a later `cd`. */
81
+ function workspaceRootOf(ctx, agent) {
82
+ const recorded = agent?.session?.header?.cwd
83
+ if (typeof recorded === 'string' && isAbsolute(recorded)) return recorded
84
+ const profileContext = service(ctx, 'profileContext')
85
+ const fallback = profileContext?.cwd
86
+ if (typeof fallback === 'string' && isAbsolute(fallback)) return fallback
87
+ return process.cwd()
88
+ }
89
+
90
+ /** Filesystem-safe directory name for one session's scratch files. */
91
+ function sessionKeyOf(agent, sharedKey) {
92
+ const raw = agent?.session?.id
93
+ const id = typeof raw === 'string' ? raw : String(raw ?? '')
94
+ const safe = id.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^[._]+/, '').slice(0, 96)
95
+ return safe.length > 0 ? safe : sharedKey
96
+ }
97
+
98
+ /**
99
+ * Resolve the layout of one session's `.dsh` home.
100
+ * @returns every absolute path the plugin and its tools use for that session.
101
+ */
102
+ function layoutFor(ctx, cfg, agent, sharedKey = 'default') {
103
+ const root = workspaceRootOf(ctx, agent)
104
+ if (dirname(root) === root) throw new Error(`workspace-scratch: refusing to manage ${JSON.stringify(root)}: it is a filesystem root`)
105
+ const base = join(root, cfg.dirName)
106
+ const tmp = join(base, cfg.tmpDirName)
107
+ const memory = join(base, cfg.memoryDirName)
108
+ const sessionKey = sessionKeyOf(agent, sharedKey)
109
+ return { root, base, tmp, memory, sessionKey, scratch: join(tmp, sessionKey) }
110
+ }
111
+
112
+ /** Write a file only when it is absent, keeping user edits intact. */
113
+ async function ensureFile(path, content) {
114
+ try {
115
+ await stat(path)
116
+ return false
117
+ } catch {
118
+ await writeFile(path, content, { encoding: 'utf8', mode: 0o644 })
119
+ return true
120
+ }
121
+ }
122
+
123
+ /** Keep `.dsh/` out of `git status` without touching the repository's tracked files. */
124
+ async function ensureGitExclude(ctx, root, dirName) {
125
+ try {
126
+ const gitDir = join(root, '.git')
127
+ const info = await stat(gitDir)
128
+ if (!info.isDirectory()) return
129
+ const excludeFile = join(gitDir, 'info', 'exclude')
130
+ const marker = `/${dirName}/`
131
+ let existing = ''
132
+ try {
133
+ existing = await readFile(excludeFile, 'utf8')
134
+ } catch {
135
+ await mkdir(dirname(excludeFile), { recursive: true })
136
+ }
137
+ if (existing.split(/\r?\n/).some((line) => line.trim() === marker)) return
138
+ const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : ''
139
+ await appendFile(excludeFile, `${prefix}# DeepSeek Harness session scratch and memory (workspace-scratch plugin)\n${marker}\n`, 'utf8')
140
+ } catch (error) {
141
+ warn(ctx, `could not update .git/info/exclude: ${String(error)}`)
142
+ }
143
+ }
144
+
145
+ /** Create the `.dsh` layout for one session, idempotently. */
146
+ async function ensureLayout(ctx, cfg, agent, options = {}) {
147
+ const layout = layoutFor(ctx, cfg, agent, options.sharedKey)
148
+ await mkdir(layout.scratch, { recursive: true, mode: 0o755 })
149
+ await mkdir(layout.memory, { recursive: true, mode: 0o755 })
150
+ if (cfg.writeGitIgnore) await ensureFile(join(layout.base, '.gitignore'), '*\n')
151
+ if (cfg.gitExclude) await ensureGitExclude(ctx, layout.root, cfg.dirName)
152
+ await pruneScratch(ctx, cfg, layout, options.now)
153
+ return layout
154
+ }
155
+
156
+ /**
157
+ * Delete session scratch directories that have not been touched for
158
+ * `retentionDays`. The active session is always kept.
159
+ */
160
+ async function pruneScratch(ctx, cfg, layout, now = Date.now()) {
161
+ if (cfg.retentionDays <= 0) return
162
+ const last = pruneState.get(layout.root) ?? 0
163
+ if (now - last < PRUNE_INTERVAL_MS) return
164
+ pruneState.set(layout.root, now)
165
+ const cutoff = now - cfg.retentionDays * 24 * 60 * 60 * 1000
166
+ let entries
167
+ try {
168
+ entries = await readdir(layout.tmp, { withFileTypes: true })
169
+ } catch {
170
+ return
171
+ }
172
+ for (const entry of entries) {
173
+ if (!entry.isDirectory() || entry.name === layout.sessionKey) continue
174
+ const path = join(layout.tmp, entry.name)
175
+ try {
176
+ const info = await stat(path)
177
+ if (info.mtimeMs >= cutoff) continue
178
+ await rm(path, { recursive: true, force: true })
179
+ } catch (error) {
180
+ warn(ctx, `could not prune ${path}: ${String(error)}`)
181
+ }
182
+ }
183
+ }
184
+
185
+ /** Last pruning attempt per workspace root, so one layout never scans on every step. */
186
+ const pruneState = new Map()
187
+
188
+ /** Resolve `relative` inside `root`, refusing anything that climbs out. */
189
+ function resolveInside(root, relative, label) {
190
+ if (typeof relative !== 'string' || relative.length === 0) throw new Error(`workspace-scratch: ${label} must be a non-empty path`)
191
+ if (isAbsolute(relative)) throw new Error(`workspace-scratch: ${label} must be relative to the session directory, received ${JSON.stringify(relative)}`)
192
+ const target = resolve(root, relative)
193
+ if (target !== root && !target.startsWith(root + sep)) {
194
+ throw new Error(`workspace-scratch: ${label} must stay inside the session directory, received ${JSON.stringify(relative)}`)
195
+ }
196
+ return target
197
+ }
198
+
199
+ /** Model-facing path: relative to the workspace root, with forward slashes. */
200
+ function displayPath(root, path) {
201
+ const relative = path === root ? '.' : path.slice(root.length + 1)
202
+ return relative.split(sep).join('/')
203
+ }
204
+
205
+ /** Turn a memory note name into one `*.md` file name. */
206
+ function memoryFileName(name) {
207
+ if (typeof name !== 'string' || name.trim().length === 0) throw new Error('workspace-scratch: name must be a non-empty memory note name')
208
+ const trimmed = name.trim().replace(/\.md$/i, '')
209
+ const slug = trimmed
210
+ .replace(/[^\p{L}\p{N}._-]+/gu, '-')
211
+ .replace(/^[._-]+|[._-]+$/g, '')
212
+ .slice(0, 80)
213
+ if (slug.length === 0) throw new Error(`workspace-scratch: ${JSON.stringify(name)} has no usable characters for a memory file name`)
214
+ const file = `${slug}.md`
215
+ if (file.toUpperCase() === MEMORY_INDEX_UPPER) throw new Error(`workspace-scratch: ${JSON.stringify(MEMORY_INDEX)} is reserved for the memory index`)
216
+ return file
217
+ }
218
+
219
+ /** Read a text file with a byte ceiling instead of buffering it whole. */
220
+ async function readCapped(path) {
221
+ const info = await stat(path)
222
+ const content = await readFile(path, 'utf8')
223
+ if (Buffer.byteLength(content, 'utf8') <= READ_MAX_BYTES) return { content, truncated: false, totalBytes: info.size }
224
+ return { content: content.slice(0, READ_MAX_BYTES), truncated: true, totalBytes: info.size }
225
+ }
226
+
227
+ /** Walk a directory tree, returning entries in stable path order. */
228
+ async function walk(current, depth = 0, out = []) {
229
+ if (out.length >= LIST_MAX_ENTRIES) return out
230
+ let entries
231
+ try {
232
+ entries = await readdir(current, { withFileTypes: true })
233
+ } catch {
234
+ return out
235
+ }
236
+ entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
237
+ for (const entry of entries) {
238
+ if (out.length >= LIST_MAX_ENTRIES) return out
239
+ const path = join(current, entry.name)
240
+ if (entry.isDirectory()) {
241
+ out.push({ path, directory: true })
242
+ if (depth < 6) await walk(path, depth + 1, out)
243
+ } else {
244
+ out.push({ path, directory: false })
245
+ }
246
+ }
247
+ return out
248
+ }
249
+
250
+ /** Format a byte count for a one-line listing. */
251
+ function formatBytes(bytes) {
252
+ if (bytes < 1024) return `${bytes} B`
253
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
254
+ return `${(bytes / 1024 / 1024).toFixed(1)} MiB`
255
+ }
256
+
257
+ /** Whether a directory entry is a memory note rather than the reserved index file. */
258
+ function isNoteFile(entry) {
259
+ return entry.isFile() && entry.name.toLowerCase().endsWith('.md') && entry.name.toUpperCase() !== MEMORY_INDEX_UPPER
260
+ }
261
+
262
+ /** Format a date as `YYYY-MM-DD HH:MM` in the process time zone. */
263
+ function localTimestamp(date) {
264
+ const pad = (value) => String(value).padStart(2, '0')
265
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
266
+ }
267
+
268
+ /** Rebuild `MEMORY.md` from the notes on disk so the index never drifts. */
269
+ async function rebuildMemoryIndex(layout) {
270
+ let entries
271
+ try {
272
+ entries = await readdir(layout.memory, { withFileTypes: true })
273
+ } catch {
274
+ entries = []
275
+ }
276
+ const notes = entries
277
+ .filter(isNoteFile)
278
+ .map((entry) => entry.name)
279
+ .sort()
280
+ const rows = []
281
+ for (const file of notes) {
282
+ const path = join(layout.memory, file)
283
+ let title = file.replace(/\.md$/i, '')
284
+ let updated = ''
285
+ try {
286
+ const { content } = await readCapped(path)
287
+ const heading = content.split(/\r?\n/).find((line) => /^#\s+\S/.test(line.trim()))
288
+ const firstText = content.split(/\r?\n/).find((line) => line.trim().length > 0 && !line.trim().startsWith('#'))
289
+ title = (heading ? heading.replace(/^#\s+/, '') : firstText ?? title).trim().slice(0, 100)
290
+ updated = localTimestamp((await stat(path)).mtime)
291
+ } catch {
292
+ /* an unreadable note still gets an index row */
293
+ }
294
+ rows.push(`- [${title}](${encodeURI(file)})${updated ? ` — updated ${updated}` : ''}`)
295
+ }
296
+ const body = [
297
+ '# Workspace memory index',
298
+ '',
299
+ 'Durable notes kept by the workspace-scratch plugin. Every note lives next to this',
300
+ 'index inside the workspace `.dsh` directory, so the workspace itself stays clean.',
301
+ '',
302
+ rows.length > 0 ? rows.join('\n') : '_No notes yet._',
303
+ '',
304
+ ].join('\n')
305
+ await writeFile(join(layout.memory, MEMORY_INDEX), body, { encoding: 'utf8', mode: 0o644 })
306
+ }
307
+
308
+ /** Model-facing guidance about where scratch and memory files belong. */
309
+ function guidanceText(cfg, withTools) {
310
+ const base = cfg.dirName
311
+ const scratch = `${base}/${cfg.tmpDirName}/<session>`
312
+ const memory = `${base}/${cfg.memoryDirName}`
313
+ const lines = [
314
+ `Keep this workspace clean: temporary files and memory notes live under the workspace's \`${base}\` directory, never in the workspace root or its source directories.`,
315
+ '',
316
+ `- Temporary files — scripts, generated samples, intermediate output, downloads, logs, screenshots — belong in \`${scratch}/\`.`,
317
+ `- Durable notes that should survive this session — user preferences, project facts, decisions, useful commands — belong in \`${memory}/\`.`,
318
+ '- When a command must write a file, point it into the session scratch directory instead of the workspace root.',
319
+ `- \`${base}\` is hidden from git; do not add it to version control and do not remove it.`,
320
+ ]
321
+ if (withTools) {
322
+ lines.push(
323
+ '',
324
+ 'Use the `scratch` tool for temporary files and the `memory` tool for durable notes. Both take paths relative to their own directory, keep the workspace clean automatically, and are the only supported way to write there.',
325
+ )
326
+ }
327
+ return lines.join('\n')
328
+ }
329
+
330
+ /** Runtime-context line naming the two directories of the current session. */
331
+ function contextText(ctx, cfg, agent) {
332
+ if (!agent) return ''
333
+ let layout
334
+ try {
335
+ layout = layoutFor(ctx, cfg, agent, 'default')
336
+ } catch {
337
+ return ''
338
+ }
339
+ return `Session scratch directory: ${JSON.stringify(layout.scratch)}. Workspace memory directory: ${JSON.stringify(layout.memory)}.`
340
+ }
341
+
342
+ /** Minimal tool-definition builder; equivalent in shape to DSH's `defineTool`. */
343
+ function defineTool(definition) {
344
+ return {
345
+ name: definition.name,
346
+ description: definition.description,
347
+ parameters: definition.parameters,
348
+ output: { schema: definition.output.schema, render: definition.output.render },
349
+ ...(definition.isConcurrencySafe === undefined ? {} : { isConcurrencySafe: definition.isConcurrencySafe }),
350
+ execute: (args, exec) => definition.execute(args, exec),
351
+ }
352
+ }
353
+
354
+ /** A single string result rendered as one text block. */
355
+ const TEXT_OUTPUT = {
356
+ schema: { type: 'string' },
357
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
358
+ }
359
+
360
+ /** Resolve the layout a tool call works on, creating it when missing. */
361
+ async function toolLayout(ctx, cfg, exec) {
362
+ const layout = layoutFor(ctx, cfg, exec?.agent, 'default')
363
+ await mkdir(layout.scratch, { recursive: true, mode: 0o755 })
364
+ await mkdir(layout.memory, { recursive: true, mode: 0o755 })
365
+ return layout
366
+ }
367
+
368
+ /** Build the `scratch` tool: temporary files under `.dsh/tmp/<session>/`. */
369
+ function scratchTool(ctx, cfg) {
370
+ return defineTool({
371
+ name: 'scratch',
372
+ description: `Create, read, list and delete temporary files in this session's scratch directory (${cfg.dirName}/${cfg.tmpDirName}/<session>/). Use it for scripts, intermediate output, downloads, logs and generated samples so the workspace root stays clean. Paths are relative to the scratch directory.`,
373
+ parameters: {
374
+ type: 'object',
375
+ additionalProperties: false,
376
+ required: ['action'],
377
+ properties: {
378
+ action: {
379
+ type: 'string',
380
+ enum: ['write', 'read', 'list', 'delete'],
381
+ description: 'write a file, read a file, list the scratch tree, or delete a file or directory.',
382
+ },
383
+ path: { type: 'string', description: 'Path relative to the scratch directory; required for write, read and delete.' },
384
+ content: { type: 'string', description: 'Text to write; required for write.' },
385
+ append: { type: 'boolean', description: 'Append instead of replacing the file (write only).' },
386
+ },
387
+ },
388
+ output: TEXT_OUTPUT,
389
+ isConcurrencySafe: () => true,
390
+ async execute(args, exec) {
391
+ const layout = await toolLayout(ctx, cfg, exec)
392
+ const action = args?.action
393
+ const signal = exec?.signal
394
+ if (action === 'write') {
395
+ const path = resolveInside(layout.scratch, args?.path, 'path')
396
+ if (typeof args?.content !== 'string') throw new Error('workspace-scratch: content must be a string when action is "write"')
397
+ await mkdir(dirname(path), { recursive: true, mode: 0o755 })
398
+ if (args.append === true) {
399
+ await appendFile(path, args.content, { encoding: 'utf8' })
400
+ } else {
401
+ await writeFile(path, args.content, { encoding: 'utf8', mode: 0o644 })
402
+ }
403
+ const bytes = Buffer.byteLength(args.content, 'utf8')
404
+ signal?.throwIfAborted?.()
405
+ return `${args.append === true ? 'appended' : 'wrote'} ${displayPath(layout.root, path)} (${formatBytes(bytes)})`
406
+ }
407
+ if (action === 'read') {
408
+ const path = resolveInside(layout.scratch, args?.path, 'path')
409
+ const { content, truncated, totalBytes } = await readCapped(path)
410
+ signal?.throwIfAborted?.()
411
+ const header = `${displayPath(layout.root, path)}${truncated ? ` (truncated at ${formatBytes(READ_MAX_BYTES)} of ${formatBytes(totalBytes)})` : ''}`
412
+ return `${header}\n${content}`
413
+ }
414
+ if (action === 'list') {
415
+ const entries = await walk(layout.scratch)
416
+ if (entries.length === 0) return `${displayPath(layout.root, layout.scratch)} is empty.`
417
+ const lines = [`${displayPath(layout.root, layout.scratch)}:`]
418
+ for (const entry of entries) {
419
+ const relative = displayPath(layout.scratch, entry.path)
420
+ if (entry.directory) {
421
+ lines.push(` ${relative}/`)
422
+ continue
423
+ }
424
+ let size = 0
425
+ try {
426
+ size = (await stat(entry.path)).size
427
+ } catch {
428
+ /* a file may vanish between readdir and stat */
429
+ }
430
+ lines.push(` ${relative} (${formatBytes(size)})`)
431
+ }
432
+ if (entries.length >= LIST_MAX_ENTRIES) lines.push(`(listing truncated at ${LIST_MAX_ENTRIES} entries)`)
433
+ return lines.join('\n')
434
+ }
435
+ if (action === 'delete') {
436
+ const path = resolveInside(layout.scratch, args?.path, 'path')
437
+ if (path === layout.scratch) throw new Error('workspace-scratch: refusing to delete the session scratch directory itself')
438
+ await rm(path, { recursive: true, force: true })
439
+ return `deleted ${displayPath(layout.root, path)}`
440
+ }
441
+ throw new Error(`workspace-scratch: unknown action ${JSON.stringify(action)}; expected write, read, list or delete`)
442
+ },
443
+ })
444
+ }
445
+
446
+ /** Build the `memory` tool: durable notes under `.dsh/memory/`. */
447
+ function memoryTool(ctx, cfg) {
448
+ return defineTool({
449
+ name: 'memory',
450
+ description: `Save, read, list, search and delete durable workspace notes stored in the workspace's memory directory (${cfg.dirName}/${cfg.memoryDirName}/). Notes survive across sessions and keep the workspace clean; ${MEMORY_INDEX} is maintained automatically as their index.`,
451
+ parameters: {
452
+ type: 'object',
453
+ additionalProperties: false,
454
+ required: ['action'],
455
+ properties: {
456
+ action: {
457
+ type: 'string',
458
+ enum: ['save', 'read', 'list', 'search', 'delete'],
459
+ description: 'save a note, read one, list the index, search every note, or delete one.',
460
+ },
461
+ name: { type: 'string', description: 'Note name; required for save, read and delete. The ".md" suffix is optional.' },
462
+ content: { type: 'string', description: 'Markdown body of the note; required for save. The first heading or line becomes its index title.' },
463
+ append: { type: 'boolean', description: 'Append to an existing note instead of replacing it (save only).' },
464
+ query: { type: 'string', description: 'Case-insensitive text to look for in every note (search only).' },
465
+ },
466
+ },
467
+ output: TEXT_OUTPUT,
468
+ isConcurrencySafe: () => true,
469
+ async execute(args, exec) {
470
+ const layout = await toolLayout(ctx, cfg, exec)
471
+ const action = args?.action
472
+ const signal = exec?.signal
473
+ if (action === 'save') {
474
+ if (typeof args?.content !== 'string') throw new Error('workspace-scratch: content must be a string when action is "save"')
475
+ const file = memoryFileName(args?.name)
476
+ const path = join(layout.memory, file)
477
+ await mkdir(layout.memory, { recursive: true, mode: 0o755 })
478
+ if (args.append === true) {
479
+ const separator = await stat(path)
480
+ .then((info) => (info.size > 0 ? '\n' : ''))
481
+ .catch(() => '')
482
+ await appendFile(path, separator + args.content, { encoding: 'utf8' })
483
+ } else {
484
+ await writeFile(path, args.content, { encoding: 'utf8', mode: 0o644 })
485
+ }
486
+ await rebuildMemoryIndex(layout)
487
+ signal?.throwIfAborted?.()
488
+ return `${args.append === true ? 'appended to' : 'saved'} ${displayPath(layout.root, path)}; ${MEMORY_INDEX} updated.`
489
+ }
490
+ if (action === 'read') {
491
+ const file = memoryFileName(args?.name)
492
+ const path = join(layout.memory, file)
493
+ const { content, truncated, totalBytes } = await readCapped(path)
494
+ signal?.throwIfAborted?.()
495
+ const header = `${displayPath(layout.root, path)}${truncated ? ` (truncated at ${formatBytes(READ_MAX_BYTES)} of ${formatBytes(totalBytes)})` : ''}`
496
+ return `${header}\n${content}`
497
+ }
498
+ if (action === 'list') {
499
+ try {
500
+ return (await readCapped(join(layout.memory, MEMORY_INDEX))).content
501
+ } catch {
502
+ const notes = (await readdir(layout.memory, { withFileTypes: true }).catch(() => [])).filter(isNoteFile)
503
+ return notes.length === 0 ? 'No memory notes yet.' : notes.map((entry) => entry.name).join('\n')
504
+ }
505
+ }
506
+ if (action === 'search') {
507
+ const query = typeof args?.query === 'string' ? args.query.trim() : ''
508
+ if (query.length === 0) throw new Error('workspace-scratch: query must be a non-empty string when action is "search"')
509
+ const needle = query.toLowerCase()
510
+ const entries = await readdir(layout.memory, { withFileTypes: true }).catch(() => [])
511
+ const files = entries.filter(isNoteFile).map((entry) => entry.name).sort()
512
+ const hits = []
513
+ for (const file of files) {
514
+ let content = ''
515
+ try {
516
+ content = (await readCapped(join(layout.memory, file))).content
517
+ } catch {
518
+ continue
519
+ }
520
+ content.split(/\r?\n/).forEach((line, index) => {
521
+ if (hits.length < 60 && line.toLowerCase().includes(needle)) hits.push(`${file}:${index + 1}: ${line.trim().slice(0, 200)}`)
522
+ })
523
+ }
524
+ if (hits.length === 0) return `No memory note matches ${JSON.stringify(query)}.`
525
+ return [`Matches for ${JSON.stringify(query)}:`, ...hits].join('\n')
526
+ }
527
+ if (action === 'delete') {
528
+ const file = memoryFileName(args?.name)
529
+ const path = join(layout.memory, file)
530
+ await rm(path, { force: true })
531
+ await rebuildMemoryIndex(layout)
532
+ signal?.throwIfAborted?.()
533
+ return `deleted ${displayPath(layout.root, path)}; ${MEMORY_INDEX} updated.`
534
+ }
535
+ throw new Error(`workspace-scratch: unknown action ${JSON.stringify(action)}; expected save, read, list, search or delete`)
536
+ },
537
+ })
538
+ }
539
+
540
+ /**
541
+ * Register the `.dsh` layout for every live and future agent, the prompt
542
+ * guidance, both tools, and the settings page's HTTP API.
543
+ *
544
+ * The live config object `cfg` is mutated in place when the settings page
545
+ * saves, because every prompt section and tool closes over that same object —
546
+ * so a change applies to the next step without re-registering anything. The
547
+ * tools are always registered and hidden per step through `when`, which is
548
+ * what makes their toggles live too.
549
+ *
550
+ * @param ctx - owning plugin context.
551
+ * @param rawConfig - the composition row's `config` block, validated here.
552
+ */
553
+ export async function apply(ctx, rawConfig) {
554
+ // Layer 2: the hand-edited row config. Layer 3 (`stored`) is read below.
555
+ const rowLayer = validateLayer(rawConfig, 'config')
556
+ let storedLayer = {}
557
+ const loadWarnings = []
558
+ try {
559
+ storedLayer = await readSettings()
560
+ } catch (error) {
561
+ // A corrupt settings file must not stop the plugin: fall back to the row
562
+ // config and surface the problem in the settings page instead.
563
+ loadWarnings.push(error instanceof Error ? error.message : String(error))
564
+ }
565
+
566
+ /** The single object tools and prompts read; mutated in place on reload. */
567
+ const cfg = composeConfig(rowLayer, storedLayer)
568
+
569
+ /** Recompute the effective config from the current layers. */
570
+ const reload = async () => {
571
+ const stored = await readSettings()
572
+ mirrorConfig(cfg, composeConfig(rowLayer, stored))
573
+ }
574
+
575
+ /** Create one agent's layout, logging instead of failing agent creation. */
576
+ const prepare = async (agent) => {
577
+ try {
578
+ return await ensureLayout(ctx, cfg, agent)
579
+ } catch (error) {
580
+ warn(ctx, `could not prepare the .dsh layout for ${JSON.stringify(workspaceRootOf(ctx, agent))}: ${String(error)}`)
581
+ return undefined
582
+ }
583
+ }
584
+
585
+ ctx.on('agent/created', async ({ agent }) => {
586
+ await prepare(agent)
587
+ })
588
+ for (const agent of ctx.agents.list()) await prepare(agent)
589
+
590
+ ctx.systemPrompt.section({
591
+ name: 'workspace-scratch:guidance',
592
+ order: SECTION_ORDER,
593
+ interpolate: false,
594
+ text: () => (cfg.promptGuidance ? guidanceText(cfg, cfg.tools && (cfg.scratchTool || cfg.memoryTool)) : ''),
595
+ })
596
+ ctx.systemPrompt.context({
597
+ name: 'workspace-scratch:paths',
598
+ order: CONTEXT_ORDER,
599
+ interpolate: false,
600
+ text: (context) => (cfg.promptGuidance ? contextText(ctx, cfg, context.agent) : ''),
601
+ })
602
+
603
+ const toolsEnabled = () => cfg.tools === true
604
+ ctx.tools.register(scratchTool(ctx, cfg), { when: () => toolsEnabled() && cfg.scratchTool === true })
605
+ ctx.tools.register(memoryTool(ctx, cfg), { when: () => toolsEnabled() && cfg.memoryTool === true })
606
+
607
+ // The webserver row activates after `webStartup` resolves, so the service is
608
+ // absent at apply time. Register the routes once it appears.
609
+ if (typeof ctx.inject === 'function') {
610
+ ctx.inject(['webServer'], (httpCtx) => {
611
+ const webServer = httpCtx.get('webServer')
612
+ if (!webServer) return
613
+ const routes = createApiRoutes({
614
+ // Reuse the GUI's own admission gate (`connection.requestRejection`),
615
+ // so these routes are no easier to reach than the official /api/* ones.
616
+ // Compositions without an auth service simply have no gate to apply.
617
+ rejectRequest: (request) => {
618
+ const connection = httpCtx.get('connection')
619
+ if (connection === undefined) return undefined
620
+ try {
621
+ return connection.requestRejection(request)
622
+ } catch {
623
+ return 401
624
+ }
625
+ },
626
+ effective: () => cfg,
627
+ rowLayer: () => rowLayer,
628
+ readStored: () => readSettings(),
629
+ writeStored: (values) => writeSettings(values),
630
+ clearStored: () => removeSettings(),
631
+ settingsFile: () => settingsFile(),
632
+ warnings: () => [...loadWarnings],
633
+ reload,
634
+ })
635
+ for (const route of routes) httpCtx.effect(() => webServer.register(route), { label: `workspace-scratch: ${route.path}` })
636
+ })
637
+ }
638
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Workspace scratch and memory",
4
+ "description": "Gives every session a hidden .dsh directory in the workspace root for scratch files and memory notes, with scratch and memory tools, so the workspace itself stays clean."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "工作区临时文件与记忆",
4
+ "description": "每次会话在工作区根目录建立隐藏的 .dsh 目录,把临时文件和记忆文件都收进去,并提供 scratch / memory 工具,让工作区保持干净。"
5
+ }
6
+ }