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