@deepseek-ai/dsh-tool-fs 0.0.1-rc.1

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/lib/index.js ADDED
@@ -0,0 +1,979 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { FsError } from "@deepseek-ai/dsh-fs";
4
+ import { ESCALATION_TARGETS, approveEscalation, canonicalPath, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
5
+ import { structuredPatch } from "diff";
6
+ //#region lib/types/read-render.js
7
+ /**
8
+ * Pure read presentation: turn provider-decoded text into a bounded, line-numbered window and
9
+ * model-facing envelope. Chunk scanning caps the current line, so even one newline-free giant
10
+ * line cannot grow memory without bound.
11
+ * @module @deepseek-ai/dsh-tool-fs/read-render
12
+ */
13
+ /** Default maximum characters returned for a single line (the `readMaxLineLength` config). */
14
+ const READ_MAX_LINE_LENGTH = 2e3;
15
+ /** Default maximum bytes returned for selected file lines (the `readMaxBytes` config). */
16
+ const READ_MAX_BYTES = 50 * 1024;
17
+ function newAccumulator() {
18
+ return {
19
+ lines: [],
20
+ totalLines: 0,
21
+ outputBytes: 0,
22
+ truncatedByBytes: false
23
+ };
24
+ }
25
+ function truncateLine(line, maxLineLength) {
26
+ return line.length > maxLineLength ? `${line.substring(0, maxLineLength)}... (line truncated to ${maxLineLength} chars)` : line;
27
+ }
28
+ function lineByteSize(line, currentLineCount) {
29
+ return Buffer.byteLength(line, "utf8") + (currentLineCount > 0 ? 1 : 0);
30
+ }
31
+ function consumeLine(acc, rawLine, request) {
32
+ acc.totalLines += 1;
33
+ if (acc.truncatedByBytes || acc.totalLines < request.offset || acc.lines.length >= request.limit) return;
34
+ const text = truncateLine(rawLine, request.maxLineLength);
35
+ const bytes = lineByteSize(text, acc.lines.length);
36
+ if (acc.outputBytes + bytes > request.maxBytes) {
37
+ acc.truncatedByBytes = true;
38
+ return;
39
+ }
40
+ acc.outputBytes += bytes;
41
+ acc.lines.push({
42
+ number: acc.totalLines,
43
+ text
44
+ });
45
+ }
46
+ function stripCarriageReturn(line) {
47
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
48
+ }
49
+ function finish(acc, request, displayPath) {
50
+ if (!acc.truncatedByBytes && request.offset > acc.totalLines && !(acc.totalLines === 0 && request.offset === 1)) throw new FsError(`offset ${request.offset} is out of range for "${displayPath}" (${acc.totalLines} lines)`, "FS_NOT_FOUND");
51
+ return {
52
+ lines: acc.lines,
53
+ totalLines: acc.totalLines,
54
+ truncatedByBytes: acc.truncatedByBytes
55
+ };
56
+ }
57
+ /**
58
+ * Build one window from streamed or whole-file chunks, enforcing line and byte caps while still
59
+ * scanning to an exact total line count, and throwing `FS_NOT_FOUND` when the requested offset is
60
+ * past EOF.
61
+ * @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning.
62
+ * @param request - the resolved window; the caller has already applied its defaults and caps.
63
+ * @param displayPath - the caller-facing path used in the offset-out-of-range error.
64
+ * @returns the numbered window lines, the total line count seen, and the byte-cap truncation flag.
65
+ */
66
+ async function buildWindow(chunks, request, displayPath) {
67
+ const acc = newAccumulator();
68
+ const lineBufferCap = request.maxLineLength + 1;
69
+ let lineBuffer = "";
70
+ function appendToLineBuffer(segment) {
71
+ if (lineBuffer.length >= lineBufferCap) return;
72
+ lineBuffer += segment;
73
+ if (lineBuffer.length > lineBufferCap) lineBuffer = lineBuffer.slice(0, lineBufferCap);
74
+ }
75
+ function flushLine() {
76
+ consumeLine(acc, stripCarriageReturn(lineBuffer), request);
77
+ lineBuffer = "";
78
+ }
79
+ for await (const chunk of chunks) {
80
+ let startPos = 0;
81
+ let newlinePos;
82
+ while ((newlinePos = chunk.indexOf("\n", startPos)) !== -1) {
83
+ appendToLineBuffer(chunk.slice(startPos, newlinePos));
84
+ flushLine();
85
+ startPos = newlinePos + 1;
86
+ }
87
+ appendToLineBuffer(chunk.slice(startPos));
88
+ }
89
+ if (lineBuffer.length > 0) flushLine();
90
+ return finish(acc, request, displayPath);
91
+ }
92
+ /**
93
+ * Format a read outcome as one OpenCode-style line-numbered text block body.
94
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
95
+ * @param outcome - the windowed read to render.
96
+ * @returns the model-facing envelope: numbered lines plus a continuation or end-of-file footer.
97
+ */
98
+ function formatReadOutput(displayPath, outcome) {
99
+ const endLine = outcome.lines.at(-1)?.number ?? Math.max(0, outcome.offset - 1);
100
+ let footer;
101
+ if (outcome.truncatedByBytes) footer = `(Output capped. Showing lines ${outcome.offset}-${endLine}. Use offset=${endLine + 1} to continue.)`;
102
+ else if (endLine < outcome.totalLines) footer = `(Showing lines ${outcome.offset}-${endLine} of ${outcome.totalLines}. Use offset=${endLine + 1} to continue.)`;
103
+ else footer = `(End of file - total ${outcome.totalLines} lines)`;
104
+ return `<path>${displayPath}</path>
105
+ <type>file</type>
106
+ <content>
107
+ ${outcome.lines.length > 0 ? `${outcome.lines.map((line) => `${line.number}: ${line.text}`).join("\n")}\n\n${footer}` : footer}
108
+ </content>`;
109
+ }
110
+ /**
111
+ * Lowercased file-extension to syntax-highlighting language hint. Keys are the
112
+ * extension without its dot; a UI treats an absent key as plain text. The map is
113
+ * intentionally small — common source, config, and markup extensions a
114
+ * line-numbered code view benefits from highlighting — not an exhaustive registry.
115
+ */
116
+ const LANG_BY_EXTENSION = {
117
+ ts: "ts",
118
+ tsx: "tsx",
119
+ mts: "ts",
120
+ cts: "ts",
121
+ js: "js",
122
+ jsx: "jsx",
123
+ mjs: "js",
124
+ cjs: "js",
125
+ json: "json",
126
+ jsonc: "json",
127
+ py: "py",
128
+ rb: "rb",
129
+ go: "go",
130
+ rs: "rs",
131
+ java: "java",
132
+ c: "c",
133
+ h: "c",
134
+ cc: "cpp",
135
+ cpp: "cpp",
136
+ hpp: "cpp",
137
+ cxx: "cpp",
138
+ cs: "cs",
139
+ kt: "kotlin",
140
+ swift: "swift",
141
+ php: "php",
142
+ sh: "sh",
143
+ bash: "sh",
144
+ zsh: "sh",
145
+ yaml: "yaml",
146
+ yml: "yaml",
147
+ toml: "toml",
148
+ ini: "ini",
149
+ md: "md",
150
+ markdown: "md",
151
+ mdx: "mdx",
152
+ html: "html",
153
+ htm: "html",
154
+ css: "css",
155
+ scss: "scss",
156
+ less: "less",
157
+ sql: "sql",
158
+ xml: "xml",
159
+ lua: "lua"
160
+ };
161
+ /**
162
+ * Derive a syntax-highlighting language hint from a read path's file extension.
163
+ * Pure and case-insensitive on the extension; a dotfile with no extension
164
+ * (`.gitignore`) and an unknown extension both yield `undefined`.
165
+ * @param path - the model-facing path the read reported.
166
+ * @returns the language hint for {@link LANG_BY_EXTENSION}, or `undefined` when the extension maps to none.
167
+ */
168
+ function langFromPath(path) {
169
+ const base = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
170
+ const dot = base.lastIndexOf(".");
171
+ if (dot <= 0) return void 0;
172
+ const ext = base.slice(dot + 1).toLowerCase();
173
+ return Object.hasOwn(LANG_BY_EXTENSION, ext) ? LANG_BY_EXTENSION[ext] : void 0;
174
+ }
175
+ /**
176
+ * Whether `value` is a valid {@link FileTextLine} (defensive narrowing from
177
+ * opaque `meta`). `number` must be a 1-based integer line number, since a card
178
+ * rendered from a zero, fractional, or non-finite line number would violate the
179
+ * 1-based numbering contract the read window promises.
180
+ */
181
+ function isFileTextLine(value) {
182
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
183
+ const { number, text } = value;
184
+ return typeof number === "number" && Number.isInteger(number) && number >= 1 && typeof text === "string";
185
+ }
186
+ /**
187
+ * Narrow opaque live or replayed result metadata to a structured read window.
188
+ * Malformed metadata returns `undefined` so presentation can fall back to the
189
+ * generic text card instead of throwing during replay. Beyond shape, the
190
+ * semantic contract of a read window is enforced against replayed JSON that is
191
+ * well-typed but out of range: `offset` must be a 1-based integer, `totalLines`
192
+ * must be a non-negative integer, each line number must be a 1-based integer no
193
+ * less than `offset`, the line numbers must strictly increase, and no line number
194
+ * may exceed `totalLines`. Any violation declines to the generic fallback rather
195
+ * than emitting a card that misnumbers or overcounts.
196
+ * @param meta - result metadata.
197
+ * @returns the validated read window, or `undefined` for absent, malformed, or semantically invalid data.
198
+ */
199
+ function readMetaFromMeta(meta) {
200
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return void 0;
201
+ const { path, offset, lines, totalLines, lang } = meta;
202
+ if (typeof path !== "string" || typeof totalLines !== "number" || typeof offset !== "number") return void 0;
203
+ if (!Number.isInteger(offset) || offset < 1) return void 0;
204
+ if (!Number.isInteger(totalLines) || totalLines < 0) return void 0;
205
+ if (!Array.isArray(lines) || !lines.every(isFileTextLine)) return void 0;
206
+ if (lang !== void 0 && typeof lang !== "string") return void 0;
207
+ let previous = offset - 1;
208
+ for (const { number } of lines) {
209
+ if (number <= previous || number > totalLines) return void 0;
210
+ previous = number;
211
+ }
212
+ return {
213
+ path,
214
+ offset,
215
+ lines,
216
+ totalLines,
217
+ ...lang === void 0 ? {} : { lang }
218
+ };
219
+ }
220
+ //#endregion
221
+ //#region lib/types/session-cwd.js
222
+ /**
223
+ * Derive the working directory a filesystem tool resolves relative paths against: the calling
224
+ * agent's per-session workspace (`exec.agent.session.header.cwd`), so each session's
225
+ * `read`/`write`/`edit` act on ITS workspace, not the server's launch dir — mirroring how
226
+ * `dsh-tool-bash` defaults a bash `workdir` to the session cwd.
227
+ * Non-agent calls return `undefined`, leaving the fallback in the provider rather than reading
228
+ * `process.cwd()` at the tool boundary.
229
+ * @module @deepseek-ai/dsh-tool-fs/session-cwd
230
+ */
231
+ const PARENT_PATH_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
232
+ /**
233
+ * The session workspace cwd for this call, or `undefined` when none applies.
234
+ * @param exec - the tool-execution context; only its optional `agent` is read.
235
+ * @param requestedPath - the path the provider will resolve; parent traversal
236
+ * makes a symlinked cwd's filesystem identity observable.
237
+ * @returns the calling agent's session cwd, or undefined for a non-agent caller (the backend then applies its own default).
238
+ */
239
+ function sessionCwd(exec, requestedPath) {
240
+ const cwd = exec.agent?.session.header.cwd;
241
+ if (cwd === void 0 || !PARENT_PATH_SEGMENT.test(cwd) && !PARENT_PATH_SEGMENT.test(requestedPath)) return cwd;
242
+ return canonicalPath(cwd);
243
+ }
244
+ /**
245
+ * Resolution options shared by all model-facing filesystem tools.
246
+ * @param exec - the tool-execution context supplying session cwd and cancellation.
247
+ * @param requestedPath - the path the provider will resolve.
248
+ * @param policyWorkspaceRoot - resolved per-call root, when a mutation carries sandbox policy.
249
+ * @returns provider resolution options for the current tool call.
250
+ */
251
+ function sessionResolveOptions(exec, requestedPath, policyWorkspaceRoot) {
252
+ const cwd = policyWorkspaceRoot ?? sessionCwd(exec, requestedPath);
253
+ return {
254
+ ...cwd !== void 0 ? { cwd } : {},
255
+ signal: exec.signal
256
+ };
257
+ }
258
+ //#endregion
259
+ //#region lib/types/read.js
260
+ /**
261
+ * Model-facing UTF-8 read. It performs one provider stat for type, routing, and observed version,
262
+ * streams large or size-unknown files, renders a bounded window, then emits the observation.
263
+ * @module @deepseek-ai/dsh-tool-fs/src/read
264
+ */
265
+ /** Default and maximum number of lines returned by one `read` call (the `readLimit` config). */
266
+ const READ_LIMIT = 2e3;
267
+ /**
268
+ * Default streaming threshold (the `readStreamMinSize` config): files at or
269
+ * above this size stream; smaller files read whole into memory.
270
+ */
271
+ const STREAM_MIN_SIZE = 10 * 1024 * 1024;
272
+ function parsePositiveInteger(value, name) {
273
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
274
+ return value;
275
+ }
276
+ /**
277
+ * Validate value constraints the schema DSL can't express. `maxLimit` is the deployment's line cap.
278
+ * @param args - the schema-validated raw tool arguments; `offset`/`limit` must be positive integers when given.
279
+ * @param maxLimit - the configured line cap: both the default `limit` and the largest one accepted.
280
+ * @returns the validated input with `offset` defaulted to 1 and `limit` to `maxLimit`.
281
+ */
282
+ function parseReadArgs(args, maxLimit) {
283
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
284
+ const offset = args.offset === void 0 ? 1 : parsePositiveInteger(args.offset, "offset");
285
+ const limit = args.limit === void 0 ? maxLimit : parsePositiveInteger(args.limit, "limit");
286
+ if (limit > maxLimit) throw new Error(`limit must be less than or equal to ${maxLimit}`);
287
+ return {
288
+ filePath: args.file_path,
289
+ offset,
290
+ limit
291
+ };
292
+ }
293
+ /**
294
+ * Register the `read` tool and its system-prompt guidance.
295
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
296
+ * @param caps - the deployment's resolved read caps (plugin config after defaulting).
297
+ */
298
+ function applyReadTool(ctx, caps) {
299
+ ctx.systemPrompt.section({
300
+ name: "tool:read",
301
+ order: 100,
302
+ text: "Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files."
303
+ });
304
+ ctx.tools.register(defineTool({
305
+ name: "read",
306
+ description: "Read a UTF-8 text file and return line-numbered content.",
307
+ parameters: {
308
+ file_path: {
309
+ type: "string",
310
+ required: true,
311
+ description: "Path to read, resolved by the filesystem backend."
312
+ },
313
+ offset: {
314
+ type: "number",
315
+ description: "1-based first line to return. Defaults to 1."
316
+ },
317
+ limit: {
318
+ type: "number",
319
+ description: `Maximum number of lines to return. Defaults to ${caps.limit}.`
320
+ }
321
+ },
322
+ output: {
323
+ schema: {
324
+ type: "object",
325
+ additionalProperties: false,
326
+ properties: {
327
+ path: {
328
+ type: "string",
329
+ required: true
330
+ },
331
+ offset: {
332
+ type: "integer",
333
+ required: true
334
+ },
335
+ lines: {
336
+ type: "array",
337
+ required: true,
338
+ items: {
339
+ type: "object",
340
+ additionalProperties: false,
341
+ properties: {
342
+ number: {
343
+ type: "integer",
344
+ required: true
345
+ },
346
+ text: {
347
+ type: "string",
348
+ required: true
349
+ }
350
+ }
351
+ }
352
+ },
353
+ totalLines: {
354
+ type: "integer",
355
+ required: true
356
+ }
357
+ }
358
+ },
359
+ render: (args, value) => {
360
+ const input = parseReadArgs(args, caps.limit);
361
+ const endLine = value.lines.at(-1)?.number ?? Math.max(0, value.offset - 1);
362
+ const truncatedByBytes = value.lines.length < input.limit && endLine < value.totalLines;
363
+ return [{
364
+ type: "text",
365
+ text: formatReadOutput(value.path, {
366
+ offset: value.offset,
367
+ lines: value.lines,
368
+ totalLines: value.totalLines,
369
+ ...truncatedByBytes ? { truncatedByBytes: true } : {}
370
+ })
371
+ }];
372
+ },
373
+ presentationMeta: (_args, value) => {
374
+ const lang = langFromPath(value.path);
375
+ return {
376
+ path: value.path,
377
+ offset: value.offset,
378
+ lines: value.lines.map(({ number, text }) => ({
379
+ number,
380
+ text
381
+ })),
382
+ totalLines: value.totalLines,
383
+ ...lang === void 0 ? {} : { lang }
384
+ };
385
+ }
386
+ },
387
+ isConcurrencySafe: () => true,
388
+ async execute(args, exec) {
389
+ const input = parseReadArgs(args, caps.limit);
390
+ const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, input.filePath));
391
+ const info = await ctx.fs.stat(target, exec.signal);
392
+ if (!info) {
393
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
394
+ throw new FsError(`cannot read "${target.displayPath}": not found`, "FS_NOT_FOUND");
395
+ }
396
+ if (info.type !== "file") throw new FsError(`cannot read "${target.displayPath}": not a regular file`, "FS_NOT_REGULAR_FILE");
397
+ const window = await buildWindow(info.size === void 0 || info.size >= caps.streamMinSize ? await ctx.fs.streamText(target, exec.signal) : [await ctx.fs.readText(target, exec.signal)], {
398
+ offset: input.offset,
399
+ limit: input.limit,
400
+ maxLineLength: caps.maxLineLength,
401
+ maxBytes: caps.maxBytes
402
+ }, target.displayPath);
403
+ const outcome = {
404
+ path: target.displayPath,
405
+ offset: input.offset,
406
+ lines: window.lines,
407
+ totalLines: window.totalLines
408
+ };
409
+ ctx.emit("fs/observed", target, {
410
+ kind: "present",
411
+ version: info.version
412
+ }, exec);
413
+ return outcome;
414
+ },
415
+ presentResult(_args, result) {
416
+ if (result.isError) return void 0;
417
+ const meta = readMetaFromMeta(result.meta);
418
+ if (meta === void 0) return void 0;
419
+ const only = result.content.length === 1 ? result.content[0] : void 0;
420
+ const text = only?.type === "text" ? only.text : void 0;
421
+ if (text === void 0) return void 0;
422
+ const body = /^<path>[^\n]*<\/path>\n<type>file<\/type>\n<content>\n([\s\S]*)\n<\/content>$/u.exec(text)?.[1];
423
+ if (body === void 0) return void 0;
424
+ return {
425
+ card: "read",
426
+ path: meta.path,
427
+ offset: meta.offset,
428
+ lines: meta.lines,
429
+ totalLines: meta.totalLines,
430
+ ...meta.lang === void 0 ? {} : { lang: meta.lang },
431
+ content: [{
432
+ type: "text",
433
+ text: body
434
+ }]
435
+ };
436
+ },
437
+ presentCall(args) {
438
+ const { offset, limit } = args;
439
+ const window = limit !== void 0 && limit > 0 ? ` (${offset ?? 1} - ${(offset ?? 1) + limit - 1})` : offset !== void 0 ? ` (from line ${offset})` : "";
440
+ return {
441
+ card: "generic",
442
+ title: `Read ${args.file_path}${window}`,
443
+ kind: "read",
444
+ locations: [{
445
+ path: args.file_path,
446
+ line: offset ?? 1
447
+ }]
448
+ };
449
+ }
450
+ }));
451
+ }
452
+ /**
453
+ * Compute one {@link FileDiff} per hunk between `before` and `after`, each carrying the
454
+ * applied change plus {@link DIFF_CONTEXT} context lines. Pure insertions use `oldText: null`,
455
+ * patch-only no-newline markers are omitted, and scattered replacements remain separate hunks.
456
+ *
457
+ * @param path - the path stamped on every produced diff (the model-facing `file_path`; the
458
+ * bridge relativizes it).
459
+ * @param before - the file text before the change (the backend's LF-normalized diff basis).
460
+ * @param after - the file text after the change, on the same basis.
461
+ * @returns one diff per applied hunk, in file order; empty when the texts are identical.
462
+ */
463
+ function computeHunkDiffs(path, before, after) {
464
+ const patch = structuredPatch("", "", before, after, void 0, void 0, { context: 3 });
465
+ const diffs = [];
466
+ for (const hunk of patch.hunks) {
467
+ const oldLines = [];
468
+ const newLines = [];
469
+ for (const line of hunk.lines) {
470
+ if (line.startsWith("\\")) continue;
471
+ const text = line.slice(1);
472
+ if (line.startsWith("-")) oldLines.push(text);
473
+ else if (line.startsWith("+")) newLines.push(text);
474
+ else {
475
+ oldLines.push(text);
476
+ newLines.push(text);
477
+ }
478
+ }
479
+ diffs.push({
480
+ path,
481
+ oldText: oldLines.length > 0 ? oldLines.join("\n") : null,
482
+ newText: newLines.join("\n")
483
+ });
484
+ }
485
+ return diffs;
486
+ }
487
+ /** Whether `value` is a valid {@link FileDiff} (defensive narrowing from opaque `meta`). */
488
+ function isFileDiff(value) {
489
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
490
+ const { path, oldText, newText } = value;
491
+ return typeof path === "string" && (oldText === null || typeof oldText === "string") && typeof newText === "string";
492
+ }
493
+ /**
494
+ * Narrow opaque live or replayed result metadata to non-empty file diffs. Malformed metadata
495
+ * returns `undefined` so presentation can fall back instead of throwing during replay.
496
+ * @param meta - result metadata.
497
+ * @returns validated hunks, or `undefined` for absent or malformed data.
498
+ */
499
+ function diffsFromMeta(meta) {
500
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return void 0;
501
+ const diffs = meta.diffs;
502
+ if (!Array.isArray(diffs) || diffs.length === 0 || !diffs.every(isFileDiff)) return void 0;
503
+ return diffs;
504
+ }
505
+ //#endregion
506
+ //#region lib/types/error.js
507
+ /**
508
+ * Model-facing remediation for guarded-mutation failures. The provider's
509
+ * `FS_STALE_VERSION` and `FS_NOT_OBSERVED` messages state the condition but
510
+ * not the only correct recovery (re-read / read the file), so this package
511
+ * appends the remedy at the model boundary; provider messages stay
512
+ * machine-oriented and unchanged.
513
+ * @module @deepseek-ai/dsh-tool-fs/src/error
514
+ */
515
+ /** The remedy appended to each remediable failure code's message. */
516
+ const REMEDIES = {
517
+ FS_STALE_VERSION: "re-read the file, then retry",
518
+ FS_NOT_OBSERVED: "read the file, then retry"
519
+ };
520
+ /**
521
+ * Append the correct recovery instruction to a guarded-mutation failure's
522
+ * message. `FS_STALE_VERSION` (the file changed since this session's last
523
+ * observation, including a missing target) recovers only by re-reading;
524
+ * `FS_NOT_OBSERVED` (no prior read by this session) by reading. The `FsError`
525
+ * code is preserved so retry/permission/UI layers keep routing on it, and the
526
+ * original error chains as `cause`. Anything else passes through untouched.
527
+ * @param error - the caught value from a write/edit execution.
528
+ * @returns a remediated `FsError` for the two guarded-mutation codes, else the original value.
529
+ */
530
+ function remediateFsError(error) {
531
+ if (!(error instanceof FsError)) return error;
532
+ const remedy = REMEDIES[error.code];
533
+ if (!remedy) return error;
534
+ return new FsError(`${error.message} — ${remedy}`, error.code, { cause: error });
535
+ }
536
+ //#endregion
537
+ //#region lib/types/write.js
538
+ /**
539
+ * Model-facing full-file write. It obtains an optional intent from the single policy slot, calls
540
+ * `ctx.fs.writeText` without a stat, then records the resulting version; no policy means an
541
+ * unconditional atomic create-or-overwrite.
542
+ * @module @deepseek-ai/dsh-tool-fs/src/write
543
+ */
544
+ /**
545
+ * Validate value constraints the schema DSL can't express: only a non-blank
546
+ * `file_path` — an empty `content` is legitimate (it writes an empty file).
547
+ * @param args - the schema-validated raw tool arguments.
548
+ * @returns the camelCased input; `content` passes through untouched.
549
+ */
550
+ function parseWriteArgs(args) {
551
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
552
+ return {
553
+ filePath: args.file_path,
554
+ content: args.content
555
+ };
556
+ }
557
+ /**
558
+ * Format a write outcome as one model-facing text block body.
559
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
560
+ * @param outcome - the write outcome; its `operation` selects the Created/Updated wording.
561
+ * @returns the model-facing confirmation envelope (no file content is echoed back).
562
+ */
563
+ function formatWriteOutput(displayPath, outcome) {
564
+ return `<path>${displayPath}</path>
565
+ <type>file</type>
566
+ <content>
567
+ ${outcome.operation === "create" ? "Created" : "Updated"} file
568
+ </content>`;
569
+ }
570
+ /**
571
+ * Register the `write` tool and its system-prompt guidance.
572
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
573
+ * @param sandbox - the shared sandbox-escalation surface (advertisement, mode stamping, denial mapping).
574
+ */
575
+ function applyWriteTool(ctx, sandbox) {
576
+ ctx.systemPrompt.section({
577
+ name: "tool:write",
578
+ order: 101,
579
+ text: "Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes."
580
+ });
581
+ ctx.tools.register(defineTool({
582
+ name: "write",
583
+ description: "Create or fully replace a UTF-8 text file.",
584
+ parameters: {
585
+ file_path: {
586
+ type: "string",
587
+ required: true,
588
+ description: "Path to write, resolved by the filesystem backend."
589
+ },
590
+ content: {
591
+ type: "string",
592
+ required: true,
593
+ description: "Full UTF-8 text content to write."
594
+ },
595
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}
596
+ },
597
+ output: {
598
+ schema: {
599
+ type: "object",
600
+ additionalProperties: false,
601
+ properties: {
602
+ path: {
603
+ type: "string",
604
+ required: true
605
+ },
606
+ operation: {
607
+ type: "string",
608
+ required: true,
609
+ enum: ["create", "update"]
610
+ },
611
+ before: {
612
+ required: true,
613
+ oneOf: [{ type: "string" }, { type: "null" }]
614
+ },
615
+ after: {
616
+ type: "string",
617
+ required: true
618
+ }
619
+ }
620
+ },
621
+ render: (_args, value) => [{
622
+ type: "text",
623
+ text: formatWriteOutput(value.path, value)
624
+ }],
625
+ presentationMeta: (args, value) => ({ diffs: value.before === null ? [] : computeHunkDiffs(args.file_path, value.before, value.after).map(({ path, oldText, newText }) => ({
626
+ path,
627
+ oldText,
628
+ newText
629
+ })) })
630
+ },
631
+ async execute(args, exec) {
632
+ const input = parseWriteArgs(args);
633
+ const sandboxPolicy = await sandbox.resolvePolicy("write", args, exec);
634
+ const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, input.filePath, sandboxPolicy?.workspaceRoot));
635
+ const intent = await ctx.waterfall("fs/write-intent", target, exec, () => void 0);
636
+ let outcome;
637
+ try {
638
+ outcome = await ctx.fs.writeText(target, input.content, intent, exec.signal, sandboxPolicy);
639
+ } catch (error) {
640
+ throw remediateFsError(sandbox.mapError(error, sandboxPolicy));
641
+ }
642
+ ctx.emit("fs/observed", target, {
643
+ kind: "present",
644
+ version: outcome.version
645
+ }, exec);
646
+ return {
647
+ path: target.displayPath,
648
+ operation: outcome.operation,
649
+ before: outcome.before,
650
+ after: outcome.after
651
+ };
652
+ },
653
+ presentCall(args) {
654
+ return {
655
+ card: "diff",
656
+ title: `Write ${args.file_path}`,
657
+ diffs: [{
658
+ path: args.file_path,
659
+ oldText: null,
660
+ newText: args.content
661
+ }],
662
+ locations: [{ path: args.file_path }]
663
+ };
664
+ },
665
+ presentResult(args, result) {
666
+ if (result.isError) return void 0;
667
+ const diffs = diffsFromMeta(result.meta) ?? [{
668
+ path: args.file_path,
669
+ oldText: null,
670
+ newText: args.content
671
+ }];
672
+ return {
673
+ card: "diff",
674
+ title: `Write ${args.file_path}`,
675
+ diffs
676
+ };
677
+ }
678
+ }));
679
+ }
680
+ //#endregion
681
+ //#region lib/types/edit.js
682
+ /**
683
+ * Model-facing literal edit, unique-match by default. It obtains an optional guard from the
684
+ * single intent slot, calls `ctx.fs.editText` without a separate stat, then records the observed
685
+ * version; no policy means an unconditional atomic edit.
686
+ * @module @deepseek-ai/dsh-tool-fs/src/edit
687
+ */
688
+ /**
689
+ * Validate value constraints the schema DSL can't express: a non-blank
690
+ * `file_path`, a non-empty `old_string`, and `old_string !== new_string`
691
+ * (an equal pair would be a guaranteed no-op edit).
692
+ * @param args - the schema-validated raw tool arguments.
693
+ * @returns the camelCased input with `replace_all` defaulted to false.
694
+ */
695
+ function parseEditArgs(args) {
696
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
697
+ if (args.old_string.length === 0) throw new Error("old_string must be a non-empty string");
698
+ if (args.old_string === args.new_string) throw new Error("old_string and new_string must differ");
699
+ return {
700
+ filePath: args.file_path,
701
+ oldString: args.old_string,
702
+ newString: args.new_string,
703
+ replaceAll: args.replace_all ?? false
704
+ };
705
+ }
706
+ /**
707
+ * Format an edit success (single-match or replace-all) as a Claude-style model-facing message.
708
+ * @param displayPath - the backend-resolved path shown to the model.
709
+ * @param replaceAll - selects the all-occurrences wording over the single-replacement one.
710
+ * @returns the confirmation sentence the model sees as the tool result.
711
+ */
712
+ function formatEditOutput(displayPath, replaceAll) {
713
+ return replaceAll ? `The file ${displayPath} has been updated. All occurrences were successfully replaced.` : `The file ${displayPath} has been updated successfully.`;
714
+ }
715
+ /**
716
+ * Register the `edit` tool and its system-prompt guidance.
717
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
718
+ * @param sandbox - the shared sandbox-escalation surface (advertisement, mode stamping, denial mapping).
719
+ */
720
+ function applyEditTool(ctx, sandbox) {
721
+ ctx.systemPrompt.section({
722
+ name: "tool:edit",
723
+ order: 102,
724
+ text: "Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session."
725
+ });
726
+ ctx.tools.register(defineTool({
727
+ name: "edit",
728
+ description: "Edit an existing UTF-8 text file by replacing literal text.",
729
+ parameters: {
730
+ file_path: {
731
+ type: "string",
732
+ required: true,
733
+ description: "Path to edit, resolved by the filesystem backend."
734
+ },
735
+ old_string: {
736
+ type: "string",
737
+ required: true,
738
+ description: "Literal text to replace. Must match exactly."
739
+ },
740
+ new_string: {
741
+ type: "string",
742
+ required: true,
743
+ description: "Literal replacement text. Use an empty string to delete the match."
744
+ },
745
+ replace_all: {
746
+ type: "boolean",
747
+ description: "Replace all matches. Defaults to false; when false, old_string must appear exactly once."
748
+ },
749
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}
750
+ },
751
+ output: {
752
+ schema: {
753
+ type: "object",
754
+ additionalProperties: false,
755
+ properties: {
756
+ path: {
757
+ type: "string",
758
+ required: true
759
+ },
760
+ before: {
761
+ type: "string",
762
+ required: true
763
+ },
764
+ after: {
765
+ type: "string",
766
+ required: true
767
+ }
768
+ }
769
+ },
770
+ render: (args, value) => [{
771
+ type: "text",
772
+ text: formatEditOutput(value.path, args.replace_all ?? false)
773
+ }],
774
+ presentationMeta: (args, value) => ({ diffs: computeHunkDiffs(args.file_path, value.before, value.after).map(({ path, oldText, newText }) => ({
775
+ path,
776
+ oldText,
777
+ newText
778
+ })) })
779
+ },
780
+ async execute(args, exec) {
781
+ const input = parseEditArgs(args);
782
+ const sandboxPolicy = await sandbox.resolvePolicy("edit", args, exec);
783
+ const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, input.filePath, sandboxPolicy?.workspaceRoot));
784
+ let outcome;
785
+ try {
786
+ const intent = await ctx.waterfall("fs/edit-intent", target, exec, () => void 0);
787
+ outcome = await ctx.fs.editText(target, {
788
+ oldString: input.oldString,
789
+ newString: input.newString,
790
+ replaceAll: input.replaceAll
791
+ }, intent, exec.signal, sandboxPolicy);
792
+ } catch (error) {
793
+ throw remediateFsError(sandbox.mapError(error, sandboxPolicy));
794
+ }
795
+ ctx.emit("fs/observed", target, {
796
+ kind: "present",
797
+ version: outcome.version
798
+ }, exec);
799
+ return {
800
+ path: target.displayPath,
801
+ before: outcome.before,
802
+ after: outcome.after
803
+ };
804
+ },
805
+ presentCall(args) {
806
+ return {
807
+ card: "diff",
808
+ title: `Edit ${args.file_path}`,
809
+ diffs: [{
810
+ path: args.file_path,
811
+ oldText: args.old_string || null,
812
+ newText: args.new_string
813
+ }],
814
+ locations: [{ path: args.file_path }]
815
+ };
816
+ },
817
+ presentResult(args, result) {
818
+ if (result.isError) return void 0;
819
+ const diffs = diffsFromMeta(result.meta);
820
+ if (diffs === void 0) return void 0;
821
+ return {
822
+ card: "diff",
823
+ title: `Edit ${args.file_path}`,
824
+ diffs
825
+ };
826
+ }
827
+ }));
828
+ }
829
+ //#endregion
830
+ //#region lib/types/sandbox.js
831
+ /**
832
+ * The sandbox-escalation surface shared by the `write` and `edit` tools: the
833
+ * per-call policy resolution, the advertised escalation fields, and the denial-marker
834
+ * mapping — all delegating the vocabulary and the fail-closed approval
835
+ * sequence to `@deepseek-ai/dsh-sandbox` (the same pieces `@deepseek-ai/dsh-tool-bash`
836
+ * uses), so bash and fs escalate identically. Built ONCE per plugin from
837
+ * `ctx.fs.sandboxMode` (the capability fact — is a confining backend mounted?)
838
+ * and shared by both mutating tools.
839
+ *
840
+ * @module @deepseek-ai/dsh-tool-fs/sandbox
841
+ */
842
+ /**
843
+ * The filesystem escalation surface: advertisement gating, per-call policy
844
+ * resolution, the one-approved wider retry, and denial-marker mapping. A pure
845
+ * product of `ctx` at plugin apply time.
846
+ */
847
+ var FsSandboxSurface = class {
848
+ ctx;
849
+ /** The escalation targets this composition advertises (`[]` when no confining backend is mounted). */
850
+ escalationModes;
851
+ /** Shared per-session policy resolver, required by a confining backend. */
852
+ policy;
853
+ constructor(ctx) {
854
+ this.ctx = ctx;
855
+ const defaultMode = ctx.fs.sandboxMode;
856
+ this.escalationModes = defaultMode === void 0 ? [] : ESCALATION_TARGETS;
857
+ this.policy = defaultMode === void 0 ? void 0 : ctx.get("sandboxPolicy");
858
+ if (defaultMode !== void 0 && this.policy === void 0) throw new Error("tool-fs: the mounted filesystem confines but ctx.sandboxPolicy is missing");
859
+ }
860
+ /**
861
+ * The escalation schema fields for a mutating tool's `parameters`. Call it
862
+ * only under a confining backend (guard on {@link escalationModes}); the
863
+ * enum pins the closed target vocabulary, the strict-wider check happens per
864
+ * call at execution.
865
+ * @returns the two escalation parameter specs.
866
+ */
867
+ schemaFields() {
868
+ return {
869
+ sandbox_permissions: {
870
+ type: "string",
871
+ enum: [...this.escalationModes],
872
+ description: "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval."
873
+ },
874
+ justification: {
875
+ type: "string",
876
+ description: "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access."
877
+ }
878
+ };
879
+ }
880
+ /**
881
+ * The policy to stamp onto this mutation: an approved escalation grant (a
882
+ * strictly wider retry resolved through `ctx.approval` before anything
883
+ * executes), else the session's standing mode. The calling session's cwd is
884
+ * always carried as the workspace root. Validates the escalation argument
885
+ * pairing first.
886
+ * @param toolName - the mutating tool's name, for the approval audit trail.
887
+ * @param args - the call's escalation arguments.
888
+ * @param exec - the tool-execution context (agent, callId, signal).
889
+ * @returns the policy to pass to the mutation, or undefined for an
890
+ * unsandboxed backend.
891
+ */
892
+ async resolvePolicy(toolName, args, exec) {
893
+ validateEscalationArgs(args.sandbox_permissions, args.justification);
894
+ const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} });
895
+ if (args.sandbox_permissions === void 0 || args.justification === void 0) return standingPolicy;
896
+ if (this.escalationModes.length === 0) throw new Error("sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)");
897
+ const policy = standingPolicy;
898
+ const approvedMode = await approveEscalation({
899
+ requestedMode: args.sandbox_permissions,
900
+ justification: args.justification,
901
+ effectiveMode: policy.mode,
902
+ subject: "operation"
903
+ }, {
904
+ approver: this.ctx.get("approval"),
905
+ agent: exec.agent,
906
+ callId: exec.callId,
907
+ toolName,
908
+ signal: exec.signal
909
+ });
910
+ return {
911
+ ...policy,
912
+ mode: approvedMode
913
+ };
914
+ }
915
+ /**
916
+ * Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes a
917
+ * `FsError` whose text is the shared `[sandbox: …]` denial marker plus the
918
+ * same-turn escalation hint, so a policy denial reads identically to bash's
919
+ * WHILE keeping the structured `FS_SANDBOX_DENIED` code — `ToolRegistry`
920
+ * populates `result.error` only for `HarnessError` instances, so a plain
921
+ * `Error` would strip the code retry/observers key off. Any other error
922
+ * passes through unchanged. A `FS_SANDBOX_DENIED` only arises under a
923
+ * confining backend, which always advertises the escalation fields, so the
924
+ * hint always applies here.
925
+ * @param error - the error thrown by the mutation.
926
+ * @param policy - the policy stamped onto the call (names the mode in the marker).
927
+ * @returns the error to throw — the marker `FsError` for a sandbox denial, else the original.
928
+ */
929
+ mapError(error, policy) {
930
+ if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED") return error;
931
+ const mode = policy.mode;
932
+ return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker("operation")}`, "FS_SANDBOX_DENIED", { cause: error });
933
+ }
934
+ };
935
+ //#endregion
936
+ //#region lib/types/index.js
937
+ /**
938
+ * Model-facing read, write, and edit tools over `ctx.fs`. This package owns schemas, validation,
939
+ * read windows, formatting, and observation events, never a concrete provider. An optional
940
+ * event policy supplies mutation guards; without one the tools use unconditional provider calls.
941
+ * @module @deepseek-ai/dsh-tool-fs
942
+ */
943
+ /** Cordis plugin name used by loader diagnostics. */
944
+ const name = "tool-fs";
945
+ /** Services required by the filesystem tool suite. */
946
+ const inject = [
947
+ "tools",
948
+ "fs",
949
+ "systemPrompt"
950
+ ];
951
+ const Config = z.object({
952
+ readLimit: z.number().default(READ_LIMIT),
953
+ readMaxLineLength: z.number().default(READ_MAX_LINE_LENGTH),
954
+ readMaxBytes: z.number().default(READ_MAX_BYTES),
955
+ readStreamMinSize: z.number().default(STREAM_MIN_SIZE)
956
+ });
957
+ /** Every read cap counts lines/chars/bytes — a positive integer, or windowing arithmetic misbehaves silently. */
958
+ function assertPositiveInteger(name, value) {
959
+ if (!Number.isInteger(value) || value < 1) throw new Error(`tool-fs: ${name} must be a positive integer`);
960
+ }
961
+ /** Register the full `read`/`write`/`edit` filesystem tool suite. */
962
+ function apply(ctx, config) {
963
+ const resolved = config;
964
+ assertPositiveInteger("readLimit", resolved.readLimit);
965
+ assertPositiveInteger("readMaxLineLength", resolved.readMaxLineLength);
966
+ assertPositiveInteger("readMaxBytes", resolved.readMaxBytes);
967
+ assertPositiveInteger("readStreamMinSize", resolved.readStreamMinSize);
968
+ applyReadTool(ctx, {
969
+ limit: resolved.readLimit,
970
+ maxLineLength: resolved.readMaxLineLength,
971
+ maxBytes: resolved.readMaxBytes,
972
+ streamMinSize: resolved.readStreamMinSize
973
+ });
974
+ const sandbox = new FsSandboxSurface(ctx);
975
+ applyWriteTool(ctx, sandbox);
976
+ applyEditTool(ctx, sandbox);
977
+ }
978
+ //#endregion
979
+ export { Config, apply, inject, name };