@x1a0f3n9/dsh-tool-fs 0.1.5-rc.2

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,1278 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { defineTool } from "@x1a0f3n9/dsh-tools";
3
+ import { FsError } from "@x1a0f3n9/dsh-fs";
4
+ import { ESCALATION_TARGETS, approveEscalation, canonicalPath, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs } from "@x1a0f3n9/dsh-sandbox";
5
+ import { structuredPatch } from "diff";
6
+ import { basename, extname } from "node:path";
7
+ import { AttachmentError, AttachmentId } from "@x1a0f3n9/dsh-attachment";
8
+ //#region lib/types/read-render.js
9
+ /**
10
+ * Pure read presentation: turn provider-decoded text into a bounded, line-numbered window and
11
+ * model-facing envelope. Chunk scanning caps the current line, so even one newline-free giant
12
+ * line cannot grow memory without bound.
13
+ * @module @x1a0f3n9/dsh-tool-fs/read-render
14
+ */
15
+ /** Default maximum characters returned for a single line (the `readMaxLineLength` config). */
16
+ const READ_MAX_LINE_LENGTH = 2e3;
17
+ /** Default maximum bytes returned for selected file lines (the `readMaxBytes` config). */
18
+ const READ_MAX_BYTES = 50 * 1024;
19
+ function newAccumulator() {
20
+ return {
21
+ lines: [],
22
+ totalLines: 0,
23
+ outputBytes: 0,
24
+ truncatedByBytes: false
25
+ };
26
+ }
27
+ function truncateLine(line, maxLineLength) {
28
+ return line.length > maxLineLength ? `${line.substring(0, maxLineLength)}... (line truncated to ${maxLineLength} chars)` : line;
29
+ }
30
+ function lineByteSize(line, currentLineCount) {
31
+ return Buffer.byteLength(line, "utf8") + (currentLineCount > 0 ? 1 : 0);
32
+ }
33
+ function consumeLine(acc, rawLine, request) {
34
+ acc.totalLines += 1;
35
+ if (acc.truncatedByBytes || acc.totalLines < request.offset || acc.lines.length >= request.limit) return;
36
+ const text = truncateLine(rawLine, request.maxLineLength);
37
+ const bytes = lineByteSize(text, acc.lines.length);
38
+ if (acc.outputBytes + bytes > request.maxBytes) {
39
+ acc.truncatedByBytes = true;
40
+ return;
41
+ }
42
+ acc.outputBytes += bytes;
43
+ acc.lines.push({
44
+ number: acc.totalLines,
45
+ text
46
+ });
47
+ }
48
+ function stripCarriageReturn(line) {
49
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
50
+ }
51
+ function finish(acc, request, displayPath) {
52
+ 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");
53
+ return {
54
+ lines: acc.lines,
55
+ totalLines: acc.totalLines,
56
+ truncatedByBytes: acc.truncatedByBytes
57
+ };
58
+ }
59
+ /**
60
+ * Build one window from streamed or whole-file chunks, enforcing line and byte caps while still
61
+ * scanning to an exact total line count, and throwing `FS_NOT_FOUND` when the requested offset is
62
+ * past EOF.
63
+ * @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning.
64
+ * @param request - the resolved window; the caller has already applied its defaults and caps.
65
+ * @param displayPath - the caller-facing path used in the offset-out-of-range error.
66
+ * @returns the numbered window lines, the total line count seen, and the byte-cap truncation flag.
67
+ */
68
+ async function buildWindow(chunks, request, displayPath) {
69
+ const acc = newAccumulator();
70
+ const lineBufferCap = request.maxLineLength + 1;
71
+ let lineBuffer = "";
72
+ function appendToLineBuffer(segment) {
73
+ if (lineBuffer.length >= lineBufferCap) return;
74
+ lineBuffer += segment;
75
+ if (lineBuffer.length > lineBufferCap) lineBuffer = lineBuffer.slice(0, lineBufferCap);
76
+ }
77
+ function flushLine() {
78
+ consumeLine(acc, stripCarriageReturn(lineBuffer), request);
79
+ lineBuffer = "";
80
+ }
81
+ for await (const chunk of chunks) {
82
+ let startPos = 0;
83
+ let newlinePos;
84
+ while ((newlinePos = chunk.indexOf("\n", startPos)) !== -1) {
85
+ appendToLineBuffer(chunk.slice(startPos, newlinePos));
86
+ flushLine();
87
+ startPos = newlinePos + 1;
88
+ }
89
+ appendToLineBuffer(chunk.slice(startPos));
90
+ }
91
+ if (lineBuffer.length > 0) flushLine();
92
+ return finish(acc, request, displayPath);
93
+ }
94
+ /**
95
+ * Format a read outcome as one OpenCode-style line-numbered text block body.
96
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
97
+ * @param outcome - the windowed read to render.
98
+ * @returns the model-facing envelope: numbered lines plus a continuation or end-of-file footer.
99
+ */
100
+ function formatReadOutput(displayPath, outcome) {
101
+ const endLine = outcome.lines.at(-1)?.number ?? Math.max(0, outcome.offset - 1);
102
+ let footer;
103
+ if (outcome.truncatedByBytes) footer = `(Output capped. Showing lines ${outcome.offset}-${endLine}. Use offset=${endLine + 1} to continue.)`;
104
+ else if (endLine < outcome.totalLines) footer = `(Showing lines ${outcome.offset}-${endLine} of ${outcome.totalLines}. Use offset=${endLine + 1} to continue.)`;
105
+ else footer = `(End of file - total ${outcome.totalLines} lines)`;
106
+ return `<path>${displayPath}</path>
107
+ <type>file</type>
108
+ <content>
109
+ ${outcome.lines.length > 0 ? `${outcome.lines.map((line) => `${line.number}: ${line.text}`).join("\n")}\n\n${footer}` : footer}
110
+ </content>`;
111
+ }
112
+ /**
113
+ * Lowercased file-extension to syntax-highlighting language hint. Keys are the
114
+ * extension without its dot; a UI treats an absent key as plain text. The map is
115
+ * intentionally small — common source, config, and markup extensions a
116
+ * line-numbered code view benefits from highlighting — not an exhaustive registry.
117
+ */
118
+ const LANG_BY_EXTENSION = {
119
+ ts: "ts",
120
+ tsx: "tsx",
121
+ mts: "ts",
122
+ cts: "ts",
123
+ js: "js",
124
+ jsx: "jsx",
125
+ mjs: "js",
126
+ cjs: "js",
127
+ json: "json",
128
+ jsonc: "json",
129
+ py: "py",
130
+ rb: "rb",
131
+ go: "go",
132
+ rs: "rs",
133
+ java: "java",
134
+ c: "c",
135
+ h: "c",
136
+ cc: "cpp",
137
+ cpp: "cpp",
138
+ hpp: "cpp",
139
+ cxx: "cpp",
140
+ cs: "cs",
141
+ kt: "kotlin",
142
+ swift: "swift",
143
+ php: "php",
144
+ sh: "sh",
145
+ bash: "sh",
146
+ zsh: "sh",
147
+ yaml: "yaml",
148
+ yml: "yaml",
149
+ toml: "toml",
150
+ ini: "ini",
151
+ md: "md",
152
+ markdown: "md",
153
+ mdx: "mdx",
154
+ html: "html",
155
+ htm: "html",
156
+ css: "css",
157
+ scss: "scss",
158
+ less: "less",
159
+ sql: "sql",
160
+ xml: "xml",
161
+ lua: "lua"
162
+ };
163
+ /**
164
+ * Derive a syntax-highlighting language hint from a read path's file extension.
165
+ * Pure and case-insensitive on the extension; a dotfile with no extension
166
+ * (`.gitignore`) and an unknown extension both yield `undefined`.
167
+ * @param path - the model-facing path the read reported.
168
+ * @returns the language hint for {@link LANG_BY_EXTENSION}, or `undefined` when the extension maps to none.
169
+ */
170
+ function langFromPath(path) {
171
+ const base = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
172
+ const dot = base.lastIndexOf(".");
173
+ if (dot <= 0) return void 0;
174
+ const ext = base.slice(dot + 1).toLowerCase();
175
+ return Object.hasOwn(LANG_BY_EXTENSION, ext) ? LANG_BY_EXTENSION[ext] : void 0;
176
+ }
177
+ /**
178
+ * Whether `value` is a valid {@link FileTextLine} (defensive narrowing from
179
+ * opaque `meta`). `number` must be a 1-based integer line number, since a card
180
+ * rendered from a zero, fractional, or non-finite line number would violate the
181
+ * 1-based numbering contract the read window promises.
182
+ */
183
+ function isFileTextLine(value) {
184
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
185
+ const { number, text } = value;
186
+ return typeof number === "number" && Number.isInteger(number) && number >= 1 && typeof text === "string";
187
+ }
188
+ /**
189
+ * Narrow opaque live or replayed result metadata to a structured read window.
190
+ * Malformed metadata returns `undefined` so presentation can fall back to the
191
+ * generic text card instead of throwing during replay. Beyond shape, the
192
+ * semantic contract of a read window is enforced against replayed JSON that is
193
+ * well-typed but out of range: `offset` must be a 1-based integer, `totalLines`
194
+ * must be a non-negative integer, each line number must be a 1-based integer no
195
+ * less than `offset`, the line numbers must strictly increase, and no line number
196
+ * may exceed `totalLines`. Any violation declines to the generic fallback rather
197
+ * than emitting a card that misnumbers or overcounts.
198
+ * @param meta - result metadata.
199
+ * @returns the validated read window, or `undefined` for absent, malformed, or semantically invalid data.
200
+ */
201
+ function readMetaFromMeta(meta) {
202
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return void 0;
203
+ const { path, offset, lines, totalLines, lang } = meta;
204
+ if (typeof path !== "string" || typeof totalLines !== "number" || typeof offset !== "number") return void 0;
205
+ if (!Number.isInteger(offset) || offset < 1) return void 0;
206
+ if (!Number.isInteger(totalLines) || totalLines < 0) return void 0;
207
+ if (!Array.isArray(lines) || !lines.every(isFileTextLine)) return void 0;
208
+ if (lang !== void 0 && typeof lang !== "string") return void 0;
209
+ let previous = offset - 1;
210
+ for (const { number } of lines) {
211
+ if (number <= previous || number > totalLines) return void 0;
212
+ previous = number;
213
+ }
214
+ return {
215
+ path,
216
+ offset,
217
+ lines,
218
+ totalLines,
219
+ ...lang === void 0 ? {} : { lang }
220
+ };
221
+ }
222
+ //#endregion
223
+ //#region lib/types/session-cwd.js
224
+ /**
225
+ * Derive the working directory a filesystem tool resolves relative paths against: the calling
226
+ * agent's per-session workspace (`exec.agent.session.header.cwd`), so each session's
227
+ * `read`/`write`/`edit` act on its workspace, not the server's launch directory.
228
+ * Non-agent calls return `undefined`, leaving the fallback in the provider rather than reading
229
+ * `process.cwd()` at the tool boundary.
230
+ * @module @x1a0f3n9/dsh-tool-fs/session-cwd
231
+ */
232
+ const PARENT_PATH_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
233
+ /**
234
+ * The session workspace cwd for this call, or `undefined` when none applies.
235
+ * @param exec - the tool-execution context; only its optional `agent` is read.
236
+ * @param requestedPath - the path the provider will resolve; parent traversal
237
+ * makes a symlinked cwd's filesystem identity observable.
238
+ * @returns the calling agent's session cwd, or undefined for a non-agent caller (the backend then applies its own default).
239
+ */
240
+ function sessionCwd(exec, requestedPath) {
241
+ const cwd = exec.agent?.session.header.cwd;
242
+ if (cwd === void 0 || !PARENT_PATH_SEGMENT.test(cwd) && !PARENT_PATH_SEGMENT.test(requestedPath)) return cwd;
243
+ return canonicalPath(cwd);
244
+ }
245
+ /**
246
+ * Resolution options shared by all model-facing filesystem tools.
247
+ * @param exec - the tool-execution context supplying session cwd and cancellation.
248
+ * @param requestedPath - the path the provider will resolve.
249
+ * @param policyWorkspaceRoot - resolved per-call root, when a mutation carries sandbox policy.
250
+ * @returns provider resolution options for the current tool call.
251
+ */
252
+ function sessionResolveOptions(exec, requestedPath, policyWorkspaceRoot) {
253
+ const cwd = policyWorkspaceRoot ?? sessionCwd(exec, requestedPath);
254
+ return {
255
+ ...cwd !== void 0 ? { cwd } : {},
256
+ signal: exec.signal
257
+ };
258
+ }
259
+ //#endregion
260
+ //#region lib/types/read-target.js
261
+ /**
262
+ * Shared path resolution and regular-file validation for model-facing read tools.
263
+ * @module @x1a0f3n9/dsh-tool-fs/src/read-target
264
+ */
265
+ /**
266
+ * Resolve a model-supplied path, observe absence, and require a regular file.
267
+ * @param ctx - the plugin context providing filesystem resolution and observation events.
268
+ * @param exec - the current tool execution, including session cwd and cancellation.
269
+ * @param requestedPath - the raw path supplied to the tool.
270
+ * @returns the resolved target and its single stat result.
271
+ */
272
+ async function resolveRegularReadTarget(ctx, exec, requestedPath) {
273
+ const target = await ctx.fs.resolve(requestedPath, sessionResolveOptions(exec, requestedPath));
274
+ const info = await ctx.fs.stat(target, exec.signal);
275
+ if (info === void 0) {
276
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
277
+ throw new FsError(`cannot read "${target.displayPath}": not found`, "FS_NOT_FOUND");
278
+ }
279
+ if (info.type !== "file") throw new FsError(`cannot read "${target.displayPath}": not a regular file`, "FS_NOT_REGULAR_FILE");
280
+ return {
281
+ target,
282
+ info
283
+ };
284
+ }
285
+ //#endregion
286
+ //#region lib/types/read.js
287
+ /**
288
+ * Model-facing UTF-8 read. It performs one provider stat for type, routing, and observed version,
289
+ * streams large or size-unknown files, renders a bounded window, then emits the observation.
290
+ * @module @x1a0f3n9/dsh-tool-fs/src/read
291
+ */
292
+ /** Default and maximum number of lines returned by one `read` call (the `readLimit` config). */
293
+ const READ_LIMIT = 2e3;
294
+ /**
295
+ * Default streaming threshold (the `readStreamMinSize` config): files at or
296
+ * above this size stream; smaller files read whole into memory.
297
+ */
298
+ const STREAM_MIN_SIZE = 10 * 1024 * 1024;
299
+ function parsePositiveInteger(value, name) {
300
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
301
+ return value;
302
+ }
303
+ /**
304
+ * Validate value constraints the schema DSL can't express. `maxLimit` is the deployment's line cap.
305
+ * @param args - the schema-validated raw tool arguments; `offset`/`limit` must be positive integers when given.
306
+ * @param maxLimit - the configured line cap: both the default `limit` and the largest one accepted.
307
+ * @returns the validated input with `offset` defaulted to 1 and `limit` to `maxLimit`.
308
+ */
309
+ function parseReadArgs(args, maxLimit) {
310
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
311
+ const offset = args.offset === void 0 ? 1 : parsePositiveInteger(args.offset, "offset");
312
+ const limit = args.limit === void 0 ? maxLimit : parsePositiveInteger(args.limit, "limit");
313
+ if (limit > maxLimit) throw new Error(`limit must be less than or equal to ${maxLimit}`);
314
+ return {
315
+ filePath: args.file_path,
316
+ offset,
317
+ limit
318
+ };
319
+ }
320
+ /**
321
+ * Register the `read` tool and its scope-aware system-prompt guidance.
322
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
323
+ * @param caps - the deployment's resolved read caps (plugin config after defaulting).
324
+ */
325
+ function applyReadTool(ctx, caps) {
326
+ ctx.systemPrompt.section({
327
+ name: "tool:read",
328
+ order: ctx.systemPrompt.getSectionOrder("TOOL_READ"),
329
+ text: ({ scope }) => ctx.tools.get("read", scope) === void 0 ? "" : "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."
330
+ });
331
+ ctx.tools.register(defineTool({
332
+ name: "read",
333
+ description: "Read a UTF-8 text file and return line-numbered content.",
334
+ parameters: {
335
+ file_path: {
336
+ type: "string",
337
+ required: true,
338
+ description: "Path to read, resolved by the filesystem backend."
339
+ },
340
+ offset: {
341
+ type: "number",
342
+ description: "1-based first line to return. Defaults to 1."
343
+ },
344
+ limit: {
345
+ type: "number",
346
+ description: `Maximum number of lines to return. Defaults to ${caps.limit}.`
347
+ }
348
+ },
349
+ output: {
350
+ schema: {
351
+ type: "object",
352
+ additionalProperties: false,
353
+ properties: {
354
+ path: {
355
+ type: "string",
356
+ required: true
357
+ },
358
+ offset: {
359
+ type: "integer",
360
+ required: true
361
+ },
362
+ lines: {
363
+ type: "array",
364
+ required: true,
365
+ items: {
366
+ type: "object",
367
+ additionalProperties: false,
368
+ properties: {
369
+ number: {
370
+ type: "integer",
371
+ required: true
372
+ },
373
+ text: {
374
+ type: "string",
375
+ required: true
376
+ }
377
+ }
378
+ }
379
+ },
380
+ totalLines: {
381
+ type: "integer",
382
+ required: true
383
+ }
384
+ }
385
+ },
386
+ render: (args, value) => {
387
+ const input = parseReadArgs(args, caps.limit);
388
+ const endLine = value.lines.at(-1)?.number ?? Math.max(0, value.offset - 1);
389
+ const truncatedByBytes = value.lines.length < input.limit && endLine < value.totalLines;
390
+ return [{
391
+ type: "text",
392
+ text: formatReadOutput(value.path, {
393
+ offset: value.offset,
394
+ lines: value.lines,
395
+ totalLines: value.totalLines,
396
+ ...truncatedByBytes ? { truncatedByBytes: true } : {}
397
+ })
398
+ }];
399
+ },
400
+ presentationMeta: (_args, value) => {
401
+ const lang = langFromPath(value.path);
402
+ return {
403
+ path: value.path,
404
+ offset: value.offset,
405
+ lines: value.lines.map(({ number, text }) => ({
406
+ number,
407
+ text
408
+ })),
409
+ totalLines: value.totalLines,
410
+ ...lang === void 0 ? {} : { lang }
411
+ };
412
+ }
413
+ },
414
+ isConcurrencySafe: () => true,
415
+ async execute(args, exec) {
416
+ const input = parseReadArgs(args, caps.limit);
417
+ const { target, info } = await resolveRegularReadTarget(ctx, exec, input.filePath);
418
+ 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)], {
419
+ offset: input.offset,
420
+ limit: input.limit,
421
+ maxLineLength: caps.maxLineLength,
422
+ maxBytes: caps.maxBytes
423
+ }, target.displayPath);
424
+ const outcome = {
425
+ path: target.displayPath,
426
+ offset: input.offset,
427
+ lines: window.lines,
428
+ totalLines: window.totalLines
429
+ };
430
+ ctx.emit("fs/observed", target, {
431
+ kind: "present",
432
+ version: info.version
433
+ }, exec);
434
+ return outcome;
435
+ },
436
+ presentResult(_args, result) {
437
+ if (result.isError) return void 0;
438
+ const meta = readMetaFromMeta(result.meta);
439
+ if (meta === void 0) return void 0;
440
+ const only = result.content.length === 1 ? result.content[0] : void 0;
441
+ const text = only?.type === "text" ? only.text : void 0;
442
+ if (text === void 0) return void 0;
443
+ const body = /^<path>[^\n]*<\/path>\n<type>file<\/type>\n<content>\n([\s\S]*)\n<\/content>$/u.exec(text)?.[1];
444
+ if (body === void 0) return void 0;
445
+ return {
446
+ card: "read",
447
+ path: meta.path,
448
+ offset: meta.offset,
449
+ lines: meta.lines,
450
+ totalLines: meta.totalLines,
451
+ ...meta.lang === void 0 ? {} : { lang: meta.lang },
452
+ content: [{
453
+ type: "text",
454
+ text: body
455
+ }]
456
+ };
457
+ },
458
+ presentCall(args) {
459
+ const { offset, limit } = args;
460
+ const window = limit !== void 0 && limit > 0 ? ` (${offset ?? 1} - ${(offset ?? 1) + limit - 1})` : offset !== void 0 ? ` (from line ${offset})` : "";
461
+ return {
462
+ card: "generic",
463
+ title: `Read ${args.file_path}${window}`,
464
+ kind: "read",
465
+ locations: [{
466
+ path: args.file_path,
467
+ line: offset ?? 1
468
+ }]
469
+ };
470
+ }
471
+ }));
472
+ }
473
+ /**
474
+ * Compute one {@link FileDiff} per hunk between `before` and `after`, each carrying the
475
+ * applied change plus {@link DIFF_CONTEXT} context lines. Pure insertions use `oldText: null`,
476
+ * patch-only no-newline markers are omitted, and scattered replacements remain separate hunks.
477
+ *
478
+ * @param path - the path stamped on every produced diff (the model-facing `file_path`; the
479
+ * bridge relativizes it).
480
+ * @param before - the file text before the change (the backend's LF-normalized diff basis).
481
+ * @param after - the file text after the change, on the same basis.
482
+ * @returns one diff per applied hunk, in file order; empty when the texts are identical.
483
+ */
484
+ function computeHunkDiffs(path, before, after) {
485
+ const patch = structuredPatch("", "", before, after, void 0, void 0, { context: 3 });
486
+ const diffs = [];
487
+ for (const hunk of patch.hunks) {
488
+ const oldLines = [];
489
+ const newLines = [];
490
+ for (const line of hunk.lines) {
491
+ if (line.startsWith("\\")) continue;
492
+ const text = line.slice(1);
493
+ if (line.startsWith("-")) oldLines.push(text);
494
+ else if (line.startsWith("+")) newLines.push(text);
495
+ else {
496
+ oldLines.push(text);
497
+ newLines.push(text);
498
+ }
499
+ }
500
+ diffs.push({
501
+ path,
502
+ oldText: oldLines.length > 0 ? oldLines.join("\n") : null,
503
+ newText: newLines.join("\n")
504
+ });
505
+ }
506
+ return diffs;
507
+ }
508
+ /** Whether `value` is a valid {@link FileDiff} (defensive narrowing from opaque `meta`). */
509
+ function isFileDiff(value) {
510
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
511
+ const { path, oldText, newText } = value;
512
+ return typeof path === "string" && (oldText === null || typeof oldText === "string") && typeof newText === "string";
513
+ }
514
+ /**
515
+ * Narrow opaque live or replayed result metadata to non-empty file diffs. Malformed metadata
516
+ * returns `undefined` so presentation can fall back instead of throwing during replay.
517
+ * @param meta - result metadata.
518
+ * @returns validated hunks, or `undefined` for absent or malformed data.
519
+ */
520
+ function diffsFromMeta(meta) {
521
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return void 0;
522
+ const diffs = meta.diffs;
523
+ if (!Array.isArray(diffs) || diffs.length === 0 || !diffs.every(isFileDiff)) return void 0;
524
+ return diffs;
525
+ }
526
+ //#endregion
527
+ //#region lib/types/error.js
528
+ /**
529
+ * Model-facing diagnostics for guarded-mutation failures. Providers and
530
+ * policies retain operation-specific causes, while this package owns the
531
+ * stable message shown to the model.
532
+ * @module @x1a0f3n9/dsh-tool-fs/src/error
533
+ */
534
+ /**
535
+ * Render the stable model-facing diagnostic for a guarded-mutation failure.
536
+ * `FS_STALE_VERSION` keeps the provider's reason and appends its re-read
537
+ * remedy. `FS_NOT_OBSERVED` replaces operation-specific policy/provider text
538
+ * with one path-aware reason and read remedy. The original error remains the
539
+ * cause, and both diagnostics preserve its code for machine routing. Anything
540
+ * else passes through untouched.
541
+ * @param error - the caught value from a write/edit execution.
542
+ * @param displayPath - the resolved target path shown to the model.
543
+ * @returns a remediated `FsError` for the two guarded-mutation codes, else the original value.
544
+ */
545
+ function remediateFsError(error, displayPath) {
546
+ if (!(error instanceof FsError)) return error;
547
+ if (error.code === "FS_NOT_OBSERVED") return new FsError(`cannot modify "${displayPath}": file has not been read — read the file, then retry`, error.code, { cause: error });
548
+ if (error.code === "FS_STALE_VERSION") return new FsError(`${error.message} — re-read the file, then retry`, error.code, { cause: error });
549
+ return error;
550
+ }
551
+ //#endregion
552
+ //#region lib/types/write.js
553
+ /**
554
+ * Model-facing full-file write. It obtains an optional intent from the single policy slot, calls
555
+ * `ctx.fs.writeText` without a stat, then records the resulting version; no policy means an
556
+ * unconditional atomic create-or-overwrite.
557
+ * @module @x1a0f3n9/dsh-tool-fs/src/write
558
+ */
559
+ /**
560
+ * Validate value constraints the schema DSL can't express: only a non-blank
561
+ * `file_path` — an empty `content` is legitimate (it writes an empty file).
562
+ * @param args - the schema-validated raw tool arguments.
563
+ * @returns the camelCased input; `content` passes through untouched.
564
+ */
565
+ function parseWriteArgs(args) {
566
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
567
+ return {
568
+ filePath: args.file_path,
569
+ content: args.content
570
+ };
571
+ }
572
+ /**
573
+ * Format a write outcome as one model-facing text block body.
574
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
575
+ * @param outcome - the write outcome; its `operation` selects the Created/Updated wording.
576
+ * @returns the model-facing confirmation envelope (no file content is echoed back).
577
+ */
578
+ function formatWriteOutput(displayPath, outcome) {
579
+ return `<path>${displayPath}</path>
580
+ <type>file</type>
581
+ <content>
582
+ ${outcome.operation === "create" ? "Created" : "Updated"} file
583
+ </content>`;
584
+ }
585
+ /**
586
+ * Register the `write` tool and its scope-aware system-prompt guidance.
587
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
588
+ * @param sandbox - the shared sandbox-escalation API (advertisement, mode stamping, denial mapping).
589
+ */
590
+ function applyWriteTool(ctx, sandbox) {
591
+ ctx.systemPrompt.section({
592
+ name: "tool:write",
593
+ order: ctx.systemPrompt.getSectionOrder("TOOL_WRITE"),
594
+ text: ({ scope }) => ctx.tools.get("write", scope) === void 0 ? "" : "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-observation-policy requires it)" + (ctx.tools.get("edit", scope) === void 0 ? "" : " and prefer edit for targeted changes") + "."
595
+ });
596
+ ctx.tools.register(defineTool({
597
+ name: "write",
598
+ description: "Create or fully replace a UTF-8 text file.",
599
+ parameters: {
600
+ file_path: {
601
+ type: "string",
602
+ required: true,
603
+ description: "Path to write, resolved by the filesystem backend."
604
+ },
605
+ content: {
606
+ type: "string",
607
+ required: true,
608
+ description: "Full UTF-8 text content to write."
609
+ },
610
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}
611
+ },
612
+ output: {
613
+ schema: {
614
+ type: "object",
615
+ additionalProperties: false,
616
+ properties: {
617
+ path: {
618
+ type: "string",
619
+ required: true
620
+ },
621
+ operation: {
622
+ type: "string",
623
+ required: true,
624
+ enum: ["create", "update"]
625
+ },
626
+ before: {
627
+ required: true,
628
+ oneOf: [{ type: "string" }, { type: "null" }]
629
+ },
630
+ after: {
631
+ type: "string",
632
+ required: true
633
+ }
634
+ }
635
+ },
636
+ render: (_args, value) => [{
637
+ type: "text",
638
+ text: formatWriteOutput(value.path, value)
639
+ }],
640
+ presentationMeta: (args, value) => ({ diffs: value.before === null ? [] : computeHunkDiffs(args.file_path, value.before, value.after).map(({ path, oldText, newText }) => ({
641
+ path,
642
+ oldText,
643
+ newText
644
+ })) })
645
+ },
646
+ async execute(args, exec) {
647
+ const input = parseWriteArgs(args);
648
+ const sandboxPolicy = await sandbox.resolvePolicy("write", args, exec);
649
+ const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, input.filePath, sandboxPolicy?.workspaceRoot));
650
+ const intent = await ctx.waterfall("fs/write-intent", target, exec, () => void 0);
651
+ let outcome;
652
+ try {
653
+ outcome = await ctx.fs.writeText(target, input.content, intent, exec.signal, sandboxPolicy);
654
+ } catch (error) {
655
+ throw remediateFsError(sandbox.mapError(error, sandboxPolicy), target.displayPath);
656
+ }
657
+ ctx.emit("fs/observed", target, {
658
+ kind: "present",
659
+ version: outcome.version
660
+ }, exec);
661
+ return {
662
+ path: target.displayPath,
663
+ operation: outcome.operation,
664
+ before: outcome.before,
665
+ after: outcome.after
666
+ };
667
+ },
668
+ presentCall(args) {
669
+ return {
670
+ card: "diff",
671
+ title: `Write ${args.file_path}`,
672
+ diffs: [{
673
+ path: args.file_path,
674
+ oldText: null,
675
+ newText: args.content
676
+ }],
677
+ locations: [{ path: args.file_path }]
678
+ };
679
+ },
680
+ presentResult(args, result) {
681
+ if (result.isError) return void 0;
682
+ const diffs = diffsFromMeta(result.meta) ?? [{
683
+ path: args.file_path,
684
+ oldText: null,
685
+ newText: args.content
686
+ }];
687
+ return {
688
+ card: "diff",
689
+ title: `Write ${args.file_path}`,
690
+ diffs
691
+ };
692
+ }
693
+ }));
694
+ }
695
+ //#endregion
696
+ //#region lib/types/edit.js
697
+ /**
698
+ * Model-facing literal edit, unique-match by default. It obtains an optional guard from the
699
+ * single intent slot, calls `ctx.fs.editText` without a separate stat, then records the observed
700
+ * version; no policy means an unconditional atomic edit.
701
+ * @module @x1a0f3n9/dsh-tool-fs/src/edit
702
+ */
703
+ /**
704
+ * Validate value constraints the schema DSL can't express: a non-blank
705
+ * `file_path`, a non-empty `old_string`, and `old_string !== new_string`
706
+ * (an equal pair would be a guaranteed no-op edit).
707
+ * @param args - the schema-validated raw tool arguments.
708
+ * @returns the camelCased input with `replace_all` defaulted to false.
709
+ */
710
+ function parseEditArgs(args) {
711
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
712
+ if (args.old_string.length === 0) throw new Error("old_string must be a non-empty string");
713
+ if (args.old_string === args.new_string) throw new Error("old_string and new_string must differ");
714
+ return {
715
+ filePath: args.file_path,
716
+ oldString: args.old_string,
717
+ newString: args.new_string,
718
+ replaceAll: args.replace_all ?? false
719
+ };
720
+ }
721
+ /**
722
+ * Format an edit success (single-match or replace-all) as a Claude-style model-facing message.
723
+ * @param displayPath - the backend-resolved path shown to the model.
724
+ * @param replaceAll - selects the all-occurrences wording over the single-replacement one.
725
+ * @returns the confirmation sentence the model sees as the tool result.
726
+ */
727
+ function formatEditOutput(displayPath, replaceAll) {
728
+ return replaceAll ? `The file ${displayPath} has been updated. All occurrences were successfully replaced.` : `The file ${displayPath} has been updated successfully.`;
729
+ }
730
+ /**
731
+ * Register the `edit` tool and its scope-aware system-prompt guidance.
732
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
733
+ * @param sandbox - the shared sandbox-escalation API (advertisement, mode stamping, denial mapping).
734
+ */
735
+ function applyEditTool(ctx, sandbox) {
736
+ ctx.systemPrompt.section({
737
+ name: "tool:edit",
738
+ order: ctx.systemPrompt.getSectionOrder("TOOL_EDIT"),
739
+ text: ({ scope }) => ctx.tools.get("edit", scope) === void 0 ? "" : "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-observation-policy requires it), unless you just created or edited it in this session."
740
+ });
741
+ ctx.tools.register(defineTool({
742
+ name: "edit",
743
+ description: "Edit an existing UTF-8 text file by replacing literal text.",
744
+ parameters: {
745
+ file_path: {
746
+ type: "string",
747
+ required: true,
748
+ description: "Path to edit, resolved by the filesystem backend."
749
+ },
750
+ old_string: {
751
+ type: "string",
752
+ required: true,
753
+ description: "Literal text to replace. Must match exactly."
754
+ },
755
+ new_string: {
756
+ type: "string",
757
+ required: true,
758
+ description: "Literal replacement text. Use an empty string to delete the match."
759
+ },
760
+ replace_all: {
761
+ type: "boolean",
762
+ description: "Replace all matches. Defaults to false; when false, old_string must appear exactly once."
763
+ },
764
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}
765
+ },
766
+ output: {
767
+ schema: {
768
+ type: "object",
769
+ additionalProperties: false,
770
+ properties: {
771
+ path: {
772
+ type: "string",
773
+ required: true
774
+ },
775
+ before: {
776
+ type: "string",
777
+ required: true
778
+ },
779
+ after: {
780
+ type: "string",
781
+ required: true
782
+ }
783
+ }
784
+ },
785
+ render: (args, value) => [{
786
+ type: "text",
787
+ text: formatEditOutput(value.path, args.replace_all ?? false)
788
+ }],
789
+ presentationMeta: (args, value) => ({ diffs: computeHunkDiffs(args.file_path, value.before, value.after).map(({ path, oldText, newText }) => ({
790
+ path,
791
+ oldText,
792
+ newText
793
+ })) })
794
+ },
795
+ async execute(args, exec) {
796
+ const input = parseEditArgs(args);
797
+ const sandboxPolicy = await sandbox.resolvePolicy("edit", args, exec);
798
+ const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, input.filePath, sandboxPolicy?.workspaceRoot));
799
+ let outcome;
800
+ try {
801
+ const intent = await ctx.waterfall("fs/edit-intent", target, exec, () => void 0);
802
+ outcome = await ctx.fs.editText(target, {
803
+ oldString: input.oldString,
804
+ newString: input.newString,
805
+ replaceAll: input.replaceAll
806
+ }, intent, exec.signal, sandboxPolicy);
807
+ } catch (error) {
808
+ throw remediateFsError(sandbox.mapError(error, sandboxPolicy), target.displayPath);
809
+ }
810
+ ctx.emit("fs/observed", target, {
811
+ kind: "present",
812
+ version: outcome.version
813
+ }, exec);
814
+ return {
815
+ path: target.displayPath,
816
+ before: outcome.before,
817
+ after: outcome.after
818
+ };
819
+ },
820
+ presentCall(args) {
821
+ return {
822
+ card: "diff",
823
+ title: `Edit ${args.file_path}`,
824
+ diffs: [{
825
+ path: args.file_path,
826
+ oldText: args.old_string || null,
827
+ newText: args.new_string
828
+ }],
829
+ locations: [{ path: args.file_path }]
830
+ };
831
+ },
832
+ presentResult(args, result) {
833
+ if (result.isError) return void 0;
834
+ const diffs = diffsFromMeta(result.meta);
835
+ if (diffs === void 0) return void 0;
836
+ return {
837
+ card: "diff",
838
+ title: `Edit ${args.file_path}`,
839
+ diffs
840
+ };
841
+ }
842
+ }));
843
+ }
844
+ //#endregion
845
+ //#region lib/types/read-image.js
846
+ /**
847
+ * The model-facing `read_image` tool commits a PNG/JPEG/WebP/GIF file. A path
848
+ * without a file extension is identified from its file signature, while the
849
+ * attachment service's full decode stays authoritative. The mounted `ctx.fs`
850
+ * backend owns path resolution and read access; names only declare media type.
851
+ *
852
+ * The route gate is deliberately stricter than the host upload preflight. An
853
+ * image-reading tool is useful only when the exact calling route can inspect
854
+ * its result, so unknown capability refuses instead of relying on an adapter
855
+ * failure after filesystem and attachment work.
856
+ * @module @x1a0f3n9/dsh-tool-fs/src/read-image
857
+ */
858
+ /** Extensions `read_image` accepts; magic-byte validation at the attachment service stays authoritative. */
859
+ const IMAGE_EXTENSIONS = {
860
+ ".png": "image/png",
861
+ ".jpg": "image/jpeg",
862
+ ".jpeg": "image/jpeg",
863
+ ".webp": "image/webp",
864
+ ".gif": "image/gif"
865
+ };
866
+ const PNG_SIGNATURE = [
867
+ 137,
868
+ 80,
869
+ 78,
870
+ 71,
871
+ 13,
872
+ 10,
873
+ 26,
874
+ 10
875
+ ];
876
+ const JPEG_SIGNATURE = [
877
+ 255,
878
+ 216,
879
+ 255
880
+ ];
881
+ function matchesBytes(data, offset, expected) {
882
+ if (data.byteLength < offset + expected.length) return false;
883
+ return expected.every((byte, index) => data[offset + index] === byte);
884
+ }
885
+ function matchesAscii(data, offset, value) {
886
+ if (data.byteLength < offset + value.length) return false;
887
+ for (let index = 0; index < value.length; index += 1) if (data[offset + index] !== value.charCodeAt(index)) return false;
888
+ return true;
889
+ }
890
+ /**
891
+ * Identify the media type declared by a supported image file signature.
892
+ * @param data - file bytes read through the current filesystem backend.
893
+ * @returns the detected supported media type, or undefined for other bytes.
894
+ */
895
+ function sniffImageMediaType(data) {
896
+ if (matchesBytes(data, 0, PNG_SIGNATURE)) return "image/png";
897
+ if (matchesBytes(data, 0, JPEG_SIGNATURE)) return "image/jpeg";
898
+ if (matchesAscii(data, 0, "GIF87a") || matchesAscii(data, 0, "GIF89a")) return "image/gif";
899
+ if (matchesAscii(data, 0, "RIFF") && matchesAscii(data, 8, "WEBP")) return "image/webp";
900
+ }
901
+ const IMAGE_VALUE_SCHEMA = {
902
+ type: "object",
903
+ additionalProperties: false,
904
+ required: true,
905
+ properties: {
906
+ attachmentId: {
907
+ type: "string",
908
+ required: true
909
+ },
910
+ mediaType: {
911
+ type: "string",
912
+ enum: [
913
+ "image/png",
914
+ "image/jpeg",
915
+ "image/webp",
916
+ "image/gif"
917
+ ],
918
+ required: true
919
+ },
920
+ bytes: {
921
+ type: "integer",
922
+ required: true
923
+ },
924
+ width: {
925
+ type: "integer",
926
+ required: true
927
+ },
928
+ height: {
929
+ type: "integer",
930
+ required: true
931
+ },
932
+ name: { type: "string" },
933
+ originalDimensions: {
934
+ type: "object",
935
+ additionalProperties: false,
936
+ properties: {
937
+ width: {
938
+ type: "integer",
939
+ required: true
940
+ },
941
+ height: {
942
+ type: "integer",
943
+ required: true
944
+ }
945
+ }
946
+ }
947
+ }
948
+ };
949
+ /**
950
+ * Map a model-supplied path to its declared image media type by extension.
951
+ * @param filePath - the raw `file_path` argument (not yet resolved).
952
+ * @returns the declared media type, or undefined when the path does not claim an image.
953
+ */
954
+ function imageMediaTypeForPath(filePath) {
955
+ return IMAGE_EXTENSIONS[extname(filePath).toLowerCase()];
956
+ }
957
+ /**
958
+ * Enforce the strict image-capability gate for the calling route. Resolves the
959
+ * session's latest routed provider/model (request header config, then agent
960
+ * options) and requires the exact resolved route to declare `image` input explicitly.
961
+ * @param ctx - the plugin context used to resolve the optional `llm` service.
962
+ * @param exec - the tool-execution context supplying the calling agent.
963
+ * @param requestedPath - the raw, not-yet-resolved path rendered in refusal messages.
964
+ */
965
+ async function assertImageCapableRoute(ctx, exec, requestedPath) {
966
+ const routed = exec.agent?.session.requestHeader()?.config;
967
+ const provider = routed?.provider ?? exec.agent?.options.provider;
968
+ const model = routed?.model ?? exec.agent?.options.model;
969
+ const llm = ctx.get("llm");
970
+ if (provider === void 0 || model === void 0 || llm === void 0) throw new Error(`cannot read "${requestedPath}" as an image: the current model route could not be resolved`);
971
+ const active = await llm.resolveModelInfo(provider, model, exec.signal);
972
+ if (active.inputModalities === void 0 || !active.inputModalities.includes("image")) throw new Error(`cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`);
973
+ }
974
+ /** Refuse a media type outside the deployment's accepted set, naming the offending path. */
975
+ function assertDeploymentAccepts(attachments, mediaType, displayPath) {
976
+ if (!attachments.imageLimits.mediaTypes.includes(mediaType)) throw new Error(`cannot read "${displayPath}": ${mediaType} images are not accepted by this deployment`);
977
+ }
978
+ /**
979
+ * Re-brand a structured image outcome into the durable attachment reference an
980
+ * `ImageBlock` carries.
981
+ * @param image - the image metadata from the output schema.
982
+ * @returns the branded attachment reference.
983
+ */
984
+ function imageRefFromValue(image) {
985
+ return {
986
+ attachmentId: AttachmentId(image.attachmentId),
987
+ mediaType: image.mediaType,
988
+ bytes: image.bytes,
989
+ width: image.width,
990
+ height: image.height,
991
+ ...image.name === void 0 ? {} : { name: image.name },
992
+ ...image.originalDimensions === void 0 ? {} : { originalDimensions: { ...image.originalDimensions } }
993
+ };
994
+ }
995
+ /**
996
+ * Format an image read as the model-facing envelope beside its image block.
997
+ * A downscaled read names the on-disk dimensions and the multiplier that maps
998
+ * coordinates measured on the attached image back onto the original file.
999
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
1000
+ * @param image - the image metadata to summarize.
1001
+ * @returns the model-facing envelope; the image itself rides the adjacent image block.
1002
+ */
1003
+ function formatImageReadOutput(displayPath, image) {
1004
+ let scaled = "";
1005
+ if (image.originalDimensions !== void 0) {
1006
+ const x = (image.originalDimensions.width / image.width).toFixed(2);
1007
+ const y = (image.originalDimensions.height / image.height).toFixed(2);
1008
+ const advice = x === y ? `multiply coordinates by ${x}` : `multiply x coordinates by ${x} and y coordinates by ${y}`;
1009
+ scaled = ` (downscaled from ${image.originalDimensions.width}x${image.originalDimensions.height} px; ${advice} to locate features in the original file)`;
1010
+ }
1011
+ return `<path>${displayPath}</path>
1012
+ <type>image</type>
1013
+ <content>
1014
+ ${image.mediaType} image, ${image.width}x${image.height} px, ${image.bytes} bytes${scaled}
1015
+ </content>`;
1016
+ }
1017
+ /**
1018
+ * Project one structured image read into its model-facing envelope and image.
1019
+ * @param value - the image-read outcome.
1020
+ * @returns the two content blocks used by native and nested dispatches.
1021
+ */
1022
+ function imageReadContent(value) {
1023
+ return [{
1024
+ type: "text",
1025
+ text: formatImageReadOutput(value.path, value.image)
1026
+ }, {
1027
+ type: "image",
1028
+ attachment: imageRefFromValue(value.image)
1029
+ }];
1030
+ }
1031
+ /**
1032
+ * Register the `read_image` tool into the given context. The composing plugin
1033
+ * owns the attachments gate: `src/index.ts` calls this inside
1034
+ * `ctx.inject(['attachments'], …)` so the tool exists only while a durable
1035
+ * store is mounted. Execution still re-checks `ctx.get('attachments')` for
1036
+ * direct callers and gates on the calling route's declared image input.
1037
+ * @param ctx - the registration scope; execution uses its `fs` service plus
1038
+ * the optional `attachments`/`llm` services.
1039
+ */
1040
+ function applyReadImageTool(ctx) {
1041
+ ctx.tools.register(defineTool({
1042
+ name: "read_image",
1043
+ description: "Read a PNG/JPEG/WebP/GIF file and return the image itself. A path without a file extension is accepted; the format is detected from the file content, so normalized attachment paths can be passed directly without copying or renaming. Harness validates and downscales large supported images before the next model request, so use this tool directly instead of installing image libraries or creating thumbnails merely to inspect an image. Independent files may be read concurrently in small batches. Requires the current model to accept image input.",
1044
+ parameters: { file_path: {
1045
+ type: "string",
1046
+ required: true,
1047
+ description: "Path to the image file, resolved by the filesystem backend."
1048
+ } },
1049
+ output: {
1050
+ schema: {
1051
+ type: "object",
1052
+ additionalProperties: false,
1053
+ properties: {
1054
+ path: {
1055
+ type: "string",
1056
+ required: true
1057
+ },
1058
+ image: IMAGE_VALUE_SCHEMA
1059
+ }
1060
+ },
1061
+ render: (_args, value) => imageReadContent(value),
1062
+ presentationMeta: (_args, value) => ({ path: value.path })
1063
+ },
1064
+ isConcurrencySafe: () => true,
1065
+ async execute(args, exec) {
1066
+ if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
1067
+ const extension = extname(args.file_path).toLowerCase();
1068
+ const declared = imageMediaTypeForPath(args.file_path);
1069
+ if (declared === void 0 && extension !== "") throw new Error(`cannot read "${args.file_path}": the ${extension} extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`);
1070
+ const attachments = ctx.get("attachments");
1071
+ if (attachments === void 0) throw new Error(`cannot read "${args.file_path}" as an image: no attachment service is mounted`);
1072
+ if (declared !== void 0) assertDeploymentAccepts(attachments, declared, args.file_path);
1073
+ await assertImageCapableRoute(ctx, exec, args.file_path);
1074
+ const { target, info } = await resolveRegularReadTarget(ctx, exec, args.file_path);
1075
+ const byteCap = Math.min(attachments.imageLimits.maxImageBytes, attachments.imageLimits.maxMessageImageBytes);
1076
+ const data = await ctx.fs.readBytes(target, exec.signal, byteCap);
1077
+ const mediaType = declared ?? sniffImageMediaType(data);
1078
+ if (mediaType === void 0) throw new Error(`cannot read "${target.displayPath}": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`);
1079
+ if (declared === void 0) assertDeploymentAccepts(attachments, mediaType, target.displayPath);
1080
+ let ref;
1081
+ try {
1082
+ ref = await attachments.saveImage({
1083
+ data,
1084
+ mediaType,
1085
+ name: basename(target.displayPath)
1086
+ });
1087
+ } catch (error) {
1088
+ if (!(error instanceof AttachmentError)) throw error;
1089
+ if (error.code === "IMAGE_DIMENSION_TOO_LARGE") throw new Error(`cannot read "${target.displayPath}": at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`, { cause: error });
1090
+ if (error.code === "IMAGE_TOO_MANY_PIXELS") throw new Error(`cannot read "${target.displayPath}": the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`, { cause: error });
1091
+ if (error.code === "IMAGE_TOO_LARGE") throw new Error(`cannot read "${target.displayPath}": the image cannot be stored within the deployment's byte limits; downscale the image and read the smaller copy`, { cause: error });
1092
+ if (error.code === "ATTACHMENT_WRITE_FAILED" && /16-bit PNG/iu.test(error.message)) throw new Error(`cannot read "${target.displayPath}": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`, { cause: error });
1093
+ if (error.code === "INVALID_IMAGE" && declared === void 0) throw new Error(`cannot read "${target.displayPath}": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`, { cause: error });
1094
+ if (error.code !== "IMAGE_TYPE_MISMATCH") throw error;
1095
+ if (declared === void 0) throw new Error(`cannot read "${target.displayPath}": the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`, { cause: error });
1096
+ throw new Error(`cannot read "${target.displayPath}": the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`, { cause: error });
1097
+ }
1098
+ ctx.emit("fs/observed", target, {
1099
+ kind: "present",
1100
+ version: info.version
1101
+ }, exec);
1102
+ return {
1103
+ path: target.displayPath,
1104
+ image: {
1105
+ attachmentId: ref.attachmentId,
1106
+ mediaType: ref.mediaType,
1107
+ bytes: ref.bytes,
1108
+ width: ref.width,
1109
+ height: ref.height,
1110
+ ...ref.name === void 0 ? {} : { name: ref.name },
1111
+ ...ref.originalDimensions === void 0 ? {} : { originalDimensions: { ...ref.originalDimensions } }
1112
+ }
1113
+ };
1114
+ },
1115
+ presentCall(args) {
1116
+ return {
1117
+ card: "generic",
1118
+ title: `Read image ${args.file_path}`,
1119
+ kind: "read",
1120
+ locations: [{ path: args.file_path }]
1121
+ };
1122
+ }
1123
+ }));
1124
+ }
1125
+ //#endregion
1126
+ //#region lib/types/sandbox.js
1127
+ /**
1128
+ * The sandbox-escalation API shared by the `write` and `edit` tools: the
1129
+ * per-call policy resolution, the advertised escalation fields, and the denial-marker
1130
+ * mapping — all delegating the vocabulary and the fail-closed approval
1131
+ * sequence to `@x1a0f3n9/dsh-sandbox` (the same pieces `@x1a0f3n9/dsh-tool-bash`
1132
+ * uses), so bash and fs escalate identically. Built ONCE per plugin from
1133
+ * `ctx.fs.sandboxMode` (the capability fact — is a confining backend mounted?)
1134
+ * and shared by both mutating tools.
1135
+ *
1136
+ * @module @x1a0f3n9/dsh-tool-fs/sandbox
1137
+ */
1138
+ /**
1139
+ * The filesystem escalation API: advertisement gating, per-call policy
1140
+ * resolution, the one-approved wider retry, and denial-marker mapping. A pure
1141
+ * product of `ctx` at plugin apply time.
1142
+ */
1143
+ var FsSandboxController = class {
1144
+ ctx;
1145
+ /** The escalation targets this composition advertises (`[]` when no confining backend is mounted). */
1146
+ escalationModes;
1147
+ /** Shared per-session policy resolver, required by a confining backend. */
1148
+ policy;
1149
+ constructor(ctx) {
1150
+ this.ctx = ctx;
1151
+ const defaultMode = ctx.fs.sandboxMode;
1152
+ this.escalationModes = defaultMode === void 0 ? [] : ESCALATION_TARGETS;
1153
+ this.policy = defaultMode === void 0 ? void 0 : ctx.get("sandboxPolicy");
1154
+ if (defaultMode !== void 0 && this.policy === void 0) throw new Error("tool-fs: the mounted filesystem confines but ctx.sandboxPolicy is missing");
1155
+ }
1156
+ /**
1157
+ * The escalation schema fields for a mutating tool's `parameters`. Call it
1158
+ * only under a confining backend (guard on {@link escalationModes}); the
1159
+ * enum pins the closed target vocabulary, the strict-wider check happens per
1160
+ * call at execution.
1161
+ * @returns the two escalation parameter specs.
1162
+ */
1163
+ schemaFields() {
1164
+ return {
1165
+ sandbox_permissions: {
1166
+ type: "string",
1167
+ enum: [...this.escalationModes],
1168
+ 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."
1169
+ },
1170
+ justification: {
1171
+ type: "string",
1172
+ description: "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access."
1173
+ }
1174
+ };
1175
+ }
1176
+ /**
1177
+ * The policy to stamp onto this mutation: an approved escalation grant (a
1178
+ * strictly wider retry resolved through `ctx.approval` before anything
1179
+ * executes), else the session's standing mode. The calling session's cwd is
1180
+ * always carried as the workspace root. Validates the escalation argument
1181
+ * pairing first.
1182
+ * @param toolName - the mutating tool's name, for the approval audit trail.
1183
+ * @param args - the call's escalation arguments.
1184
+ * @param exec - the tool-execution context (agent, callId, signal).
1185
+ * @returns the policy to pass to the mutation, or undefined for an
1186
+ * unsandboxed backend.
1187
+ */
1188
+ async resolvePolicy(toolName, args, exec) {
1189
+ validateEscalationArgs(args.sandbox_permissions, args.justification);
1190
+ const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} });
1191
+ if (args.sandbox_permissions === void 0 || args.justification === void 0) return standingPolicy;
1192
+ if (this.escalationModes.length === 0) throw new Error("sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)");
1193
+ const policy = standingPolicy;
1194
+ const approvedMode = await approveEscalation({
1195
+ requestedMode: args.sandbox_permissions,
1196
+ justification: args.justification,
1197
+ effectiveMode: policy.mode,
1198
+ subject: "operation"
1199
+ }, {
1200
+ approver: this.ctx.get("approval"),
1201
+ agent: exec.agent,
1202
+ callId: exec.callId,
1203
+ toolName,
1204
+ signal: exec.signal
1205
+ });
1206
+ return {
1207
+ ...policy,
1208
+ mode: approvedMode
1209
+ };
1210
+ }
1211
+ /**
1212
+ * Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes a
1213
+ * `FsError` whose text is the shared `[sandbox: …]` denial marker plus the
1214
+ * same-turn escalation hint, so a policy denial reads identically to bash's
1215
+ * WHILE keeping the structured `FS_SANDBOX_DENIED` code — `ToolRuntime`
1216
+ * populates `result.error` only for `HarnessError` instances, so a plain
1217
+ * `Error` would strip the code retry/observers key off. Any other error
1218
+ * passes through unchanged. A `FS_SANDBOX_DENIED` only arises under a
1219
+ * confining backend, which always advertises the escalation fields, so the
1220
+ * hint always applies here.
1221
+ * @param error - the error thrown by the mutation.
1222
+ * @param policy - the policy stamped onto the call (names the mode in the marker).
1223
+ * @returns the error to throw — the marker `FsError` for a sandbox denial, else the original.
1224
+ */
1225
+ mapError(error, policy) {
1226
+ if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED") return error;
1227
+ const mode = policy.mode;
1228
+ return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker("operation")}`, "FS_SANDBOX_DENIED", { cause: error });
1229
+ }
1230
+ };
1231
+ //#endregion
1232
+ //#region lib/types/index.js
1233
+ /**
1234
+ * Model-facing read, read_image, write, and edit tools over `ctx.fs`. This package owns schemas, validation,
1235
+ * read windows, formatting, and observation events, never a concrete provider. An optional
1236
+ * event policy supplies mutation guards; without one the tools use unconditional provider calls.
1237
+ * @module @x1a0f3n9/dsh-tool-fs
1238
+ */
1239
+ /** Cordis plugin name used by loader diagnostics. */
1240
+ const name = "tool-fs";
1241
+ /** Services required by the filesystem tool suite. */
1242
+ const inject = [
1243
+ "tools",
1244
+ "fs",
1245
+ "systemPrompt"
1246
+ ];
1247
+ const Config = z.object({
1248
+ readLimit: z.number().default(READ_LIMIT),
1249
+ readMaxLineLength: z.number().default(READ_MAX_LINE_LENGTH),
1250
+ readMaxBytes: z.number().default(READ_MAX_BYTES),
1251
+ readStreamMinSize: z.number().default(STREAM_MIN_SIZE)
1252
+ });
1253
+ /** Every read cap counts lines/chars/bytes — a positive integer, or windowing arithmetic misbehaves silently. */
1254
+ function assertPositiveInteger(name, value) {
1255
+ if (!Number.isInteger(value) || value < 1) throw new Error(`tool-fs: ${name} must be a positive integer`);
1256
+ }
1257
+ /** Register the full `read`/`write`/`edit` filesystem tool suite, plus `read_image` while `attachments` is mounted. */
1258
+ function apply(ctx, config) {
1259
+ const resolved = config;
1260
+ assertPositiveInteger("readLimit", resolved.readLimit);
1261
+ assertPositiveInteger("readMaxLineLength", resolved.readMaxLineLength);
1262
+ assertPositiveInteger("readMaxBytes", resolved.readMaxBytes);
1263
+ assertPositiveInteger("readStreamMinSize", resolved.readStreamMinSize);
1264
+ applyReadTool(ctx, {
1265
+ limit: resolved.readLimit,
1266
+ maxLineLength: resolved.readMaxLineLength,
1267
+ maxBytes: resolved.readMaxBytes,
1268
+ streamMinSize: resolved.readStreamMinSize
1269
+ });
1270
+ ctx.inject(["attachments"], (imageCtx) => {
1271
+ applyReadImageTool(imageCtx);
1272
+ });
1273
+ const sandbox = new FsSandboxController(ctx);
1274
+ applyWriteTool(ctx, sandbox);
1275
+ applyEditTool(ctx, sandbox);
1276
+ }
1277
+ //#endregion
1278
+ export { Config, apply, inject, name };