@deepseek-ai/dsh-tool-fs 0.2.2-alpha.3 → 0.2.2-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.
Files changed (71) hide show
  1. package/README.i18n.yaml +10 -10
  2. package/README.md +8 -5
  3. package/README.zh.md +8 -5
  4. package/lib/index.js +85 -28
  5. package/lib/types/apply-patch-output.d.ts.map +1 -0
  6. package/lib/types/apply-patch-output.js.map +1 -0
  7. package/lib/types/apply-patch-presentation.d.ts.map +1 -0
  8. package/lib/types/apply-patch-presentation.js.map +1 -0
  9. package/lib/types/apply-patch.d.ts +1 -1
  10. package/lib/types/apply-patch.d.ts.map +1 -0
  11. package/lib/types/apply-patch.js.map +1 -0
  12. package/lib/types/diff.d.ts.map +1 -0
  13. package/lib/types/diff.js.map +1 -0
  14. package/lib/types/edit.d.ts.map +1 -0
  15. package/lib/types/edit.js.map +1 -0
  16. package/lib/types/error.d.ts.map +1 -0
  17. package/lib/types/error.js.map +1 -0
  18. package/lib/types/image-error.d.ts +25 -0
  19. package/lib/types/image-error.d.ts.map +1 -0
  20. package/lib/types/image-error.js.map +1 -0
  21. package/lib/types/index.d.ts.map +1 -0
  22. package/lib/types/index.js.map +1 -0
  23. package/lib/types/mutation-result.d.ts.map +1 -0
  24. package/lib/types/mutation-result.js.map +1 -0
  25. package/lib/types/patch/execute.d.ts.map +1 -0
  26. package/lib/types/patch/execute.js.map +1 -0
  27. package/lib/types/patch/index.d.ts.map +1 -0
  28. package/lib/types/patch/index.js.map +1 -0
  29. package/lib/types/patch/plan.d.ts.map +1 -0
  30. package/lib/types/patch/plan.js.map +1 -0
  31. package/lib/types/patch/preflight.d.ts.map +1 -0
  32. package/lib/types/patch/preflight.js.map +1 -0
  33. package/lib/types/patch/types.d.ts.map +1 -0
  34. package/lib/types/patch/types.js.map +1 -0
  35. package/lib/types/read-image.d.ts +2 -0
  36. package/lib/types/read-image.d.ts.map +1 -0
  37. package/lib/types/read-image.js.map +1 -0
  38. package/lib/types/read-render.d.ts.map +1 -0
  39. package/lib/types/read-render.js.map +1 -0
  40. package/lib/types/read-target.d.ts.map +1 -0
  41. package/lib/types/read-target.js.map +1 -0
  42. package/lib/types/read.d.ts.map +1 -0
  43. package/lib/types/read.js.map +1 -0
  44. package/lib/types/sandbox.d.ts.map +1 -0
  45. package/lib/types/sandbox.js.map +1 -0
  46. package/lib/types/session-cwd.d.ts.map +1 -0
  47. package/lib/types/session-cwd.js.map +1 -0
  48. package/lib/types/write.d.ts.map +1 -0
  49. package/lib/types/write.js.map +1 -0
  50. package/package.json +47 -42
  51. package/src/apply-patch-output.ts +149 -0
  52. package/src/apply-patch-presentation.ts +47 -0
  53. package/src/apply-patch.ts +52 -0
  54. package/src/diff.ts +102 -0
  55. package/src/edit.ts +169 -0
  56. package/src/error.ts +42 -0
  57. package/src/image-error.ts +36 -0
  58. package/src/index.ts +103 -0
  59. package/src/mutation-result.ts +21 -0
  60. package/src/patch/execute.ts +121 -0
  61. package/src/patch/index.ts +36 -0
  62. package/src/patch/plan.ts +117 -0
  63. package/src/patch/preflight.ts +157 -0
  64. package/src/patch/types.ts +88 -0
  65. package/src/read-image.ts +391 -0
  66. package/src/read-render.ts +244 -0
  67. package/src/read-target.ts +34 -0
  68. package/src/read.ts +210 -0
  69. package/src/sandbox.ts +145 -0
  70. package/src/session-cwd.ts +25 -0
  71. package/src/write.ts +153 -0
@@ -0,0 +1,391 @@
1
+ /**
2
+ * The model-facing `read_image` tool commits a PNG/JPEG/WebP/GIF file. A path
3
+ * without a file extension is identified from its file signature, while the
4
+ * attachment service's full decode stays authoritative. The mounted `ctx.fs`
5
+ * backend owns path resolution and read access; names only declare media type.
6
+ *
7
+ * The route gate is deliberately stricter than the host upload preflight. An
8
+ * image-reading tool is useful only when the exact calling route can inspect
9
+ * its result, so unknown capability refuses instead of relying on an adapter
10
+ * failure after filesystem and attachment work.
11
+ * @module @deepseek-ai/dsh-tool-fs/src/read-image
12
+ */
13
+
14
+ import { basename, extname } from 'node:path'
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment'
17
+ import type { AttachmentStore, ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment'
18
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
19
+ import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
20
+ import type { GenericCallView, ToolExecution } from '@deepseek-ai/dsh-tools'
21
+ import type {} from '@deepseek-ai/dsh-fs'
22
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
23
+ import { ImageInputError } from './image-error.ts'
24
+ import { resolveRegularReadTarget } from './read-target.ts'
25
+
26
+ /** Extensions `read_image` accepts; magic-byte validation at the attachment service stays authoritative. */
27
+ const IMAGE_EXTENSIONS: Readonly<Record<string, ImageMediaType>> = {
28
+ '.png': 'image/png',
29
+ '.jpg': 'image/jpeg',
30
+ '.jpeg': 'image/jpeg',
31
+ '.webp': 'image/webp',
32
+ '.gif': 'image/gif',
33
+ }
34
+
35
+ const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const
36
+ const JPEG_SIGNATURE = [0xff, 0xd8, 0xff] as const
37
+
38
+ function matchesBytes(data: Uint8Array, offset: number, expected: readonly number[]): boolean {
39
+ if (data.byteLength < offset + expected.length) return false
40
+ return expected.every((byte, index) => data[offset + index] === byte)
41
+ }
42
+
43
+ function matchesAscii(data: Uint8Array, offset: number, value: string): boolean {
44
+ if (data.byteLength < offset + value.length) return false
45
+ for (let index = 0; index < value.length; index += 1) {
46
+ if (data[offset + index] !== value.charCodeAt(index)) return false
47
+ }
48
+ return true
49
+ }
50
+
51
+ /**
52
+ * Identify the media type declared by a supported image file signature.
53
+ * @param data - file bytes read through the current filesystem backend.
54
+ * @returns the detected supported media type, or undefined for other bytes.
55
+ */
56
+ export function sniffImageMediaType(data: Uint8Array): ImageMediaType | undefined {
57
+ if (matchesBytes(data, 0, PNG_SIGNATURE)) return 'image/png'
58
+ if (matchesBytes(data, 0, JPEG_SIGNATURE)) return 'image/jpeg'
59
+ if (matchesAscii(data, 0, 'GIF87a') || matchesAscii(data, 0, 'GIF89a')) return 'image/gif'
60
+ if (matchesAscii(data, 0, 'RIFF') && matchesAscii(data, 8, 'WEBP')) return 'image/webp'
61
+ return undefined
62
+ }
63
+
64
+ const IMAGE_VALUE_SCHEMA = {
65
+ type: 'object',
66
+ additionalProperties: false,
67
+ required: true,
68
+ properties: {
69
+ attachmentId: { type: 'string', required: true },
70
+ mediaType: { type: 'string', enum: ['image/png', 'image/jpeg', 'image/webp', 'image/gif'], required: true },
71
+ bytes: { type: 'integer', required: true },
72
+ width: { type: 'integer', required: true },
73
+ height: { type: 'integer', required: true },
74
+ name: { type: 'string' },
75
+ originalDimensions: {
76
+ type: 'object',
77
+ additionalProperties: false,
78
+ properties: {
79
+ width: { type: 'integer', required: true },
80
+ height: { type: 'integer', required: true },
81
+ },
82
+ },
83
+ },
84
+ } as const
85
+
86
+ /** The structured outcome declared by the `read_image` output schema. */
87
+ export interface ImageReadValue {
88
+ /** Canonical absolute path in the filesystem provider's execution world. */
89
+ path: string
90
+ image: {
91
+ attachmentId: string
92
+ mediaType: ImageMediaType
93
+ bytes: number
94
+ width: number
95
+ height: number
96
+ name?: string
97
+ /** Orientation-applied file dimensions before normalization; present only when storage reduced it. */
98
+ originalDimensions?: {
99
+ width: number
100
+ height: number
101
+ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Map a model-supplied path to its declared image media type by extension.
107
+ * @param filePath - the raw `file_path` argument (not yet resolved).
108
+ * @returns the declared media type, or undefined when the path does not claim an image.
109
+ */
110
+ export function imageMediaTypeForPath(filePath: string): ImageMediaType | undefined {
111
+ return IMAGE_EXTENSIONS[extname(filePath).toLowerCase()]
112
+ }
113
+
114
+ /**
115
+ * Enforce the strict image-capability gate for the calling route. Resolves the
116
+ * session's latest routed provider/model (request header config, then agent
117
+ * options) and requires the exact resolved route to declare `image` input explicitly.
118
+ * @param ctx - the plugin context used to resolve the optional `llm` service.
119
+ * @param exec - the tool-execution context supplying the calling agent.
120
+ * @param requestedPath - the raw, not-yet-resolved path rendered in refusal messages.
121
+ * @throws ToolContextUnavailableError when no Agent route or `llm` service is available.
122
+ * @throws ImageInputError `IMAGE_UNSUPPORTED_MODEL` when the route does not declare image input.
123
+ */
124
+ export async function assertImageCapableRoute(ctx: Context, exec: ToolExecution, requestedPath: string): Promise<void> {
125
+ const routed = exec.agent?.session.requestHeader()?.config
126
+ const provider = routed?.provider ?? exec.agent?.options.provider
127
+ const model = routed?.model ?? exec.agent?.options.model
128
+ const llm = ctx.get('llm')
129
+ if (provider === undefined || model === undefined || llm === undefined) {
130
+ throw new ToolContextUnavailableError(`cannot read "${requestedPath}" as an image: the current model route could not be resolved`)
131
+ }
132
+ const active = await llm.resolveModelInfo(provider, model, exec.signal)
133
+ if (active.inputModalities === undefined || !active.inputModalities.includes('image')) {
134
+ throw new ImageInputError(
135
+ `cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`,
136
+ 'IMAGE_UNSUPPORTED_MODEL',
137
+ )
138
+ }
139
+ }
140
+
141
+ /** Refuse a media type outside the deployment's accepted set, naming the offending path. */
142
+ function assertDeploymentAccepts(attachments: AttachmentStore, mediaType: ImageMediaType, displayPath: string): void {
143
+ if (!attachments.imageLimits.mediaTypes.includes(mediaType)) {
144
+ throw new ImageInputError(`cannot read "${displayPath}": ${mediaType} images are not accepted by this deployment`, 'IMAGE_UNSUPPORTED_FORMAT')
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Re-brand a structured image outcome into the durable attachment reference an
150
+ * `ImageBlock` carries.
151
+ * @param image - the image metadata from the output schema.
152
+ * @returns the branded attachment reference.
153
+ */
154
+ export function imageRefFromValue(image: ImageReadValue['image']): ImageAttachmentRef {
155
+ return {
156
+ attachmentId: AttachmentId(image.attachmentId),
157
+ mediaType: image.mediaType,
158
+ bytes: image.bytes,
159
+ width: image.width,
160
+ height: image.height,
161
+ ...image.name === undefined ? {} : { name: image.name },
162
+ ...image.originalDimensions === undefined ? {} : {
163
+ originalDimensions: { ...image.originalDimensions },
164
+ },
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Format an image read as the model-facing envelope beside its image block.
170
+ * A downscaled read names the on-disk dimensions and the multiplier that maps
171
+ * coordinates measured on the attached image back onto the original file.
172
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
173
+ * @param image - the image metadata to summarize.
174
+ * @returns the model-facing envelope; the image itself rides the adjacent image block.
175
+ */
176
+ export function formatImageReadOutput(displayPath: string, image: ImageReadValue['image']): string {
177
+ let scaled = ''
178
+ if (image.originalDimensions !== undefined) {
179
+ // Integer rounding can give the two axes slightly different ratios, so the
180
+ // advice names one multiplier only when both round to the same value.
181
+ const x = (image.originalDimensions.width / image.width).toFixed(2)
182
+ const y = (image.originalDimensions.height / image.height).toFixed(2)
183
+ const advice = x === y
184
+ ? `multiply coordinates by ${x}`
185
+ : `multiply x coordinates by ${x} and y coordinates by ${y}`
186
+ scaled = ` (downscaled from ${image.originalDimensions.width}x${image.originalDimensions.height} px; ${advice} to locate features in the original file)`
187
+ }
188
+ return `<path>${displayPath}</path>
189
+ <type>image</type>
190
+ <content>
191
+ ${image.mediaType} image, ${image.width}x${image.height} px, ${image.bytes} bytes${scaled}
192
+ </content>`
193
+ }
194
+
195
+ /**
196
+ * Project one structured image read into its model-facing envelope and image.
197
+ * @param value - the image-read outcome.
198
+ * @returns the two content blocks used by native and nested dispatches.
199
+ */
200
+ function imageReadContent(value: ImageReadValue): ContentBlock[] {
201
+ return [
202
+ { type: 'text', text: formatImageReadOutput(value.path, value.image) },
203
+ { type: 'image', attachment: imageRefFromValue(value.image) },
204
+ ]
205
+ }
206
+
207
+ /** Facts about one image read that a save-failure report names. */
208
+ interface SaveFailureFacts {
209
+ displayPath: string
210
+ /** Lower-cased path extension; empty for an extension-less path. */
211
+ extension: string
212
+ mediaType: ImageMediaType
213
+ /** Whether `mediaType` came from the file signature instead of the extension. */
214
+ sniffed: boolean
215
+ }
216
+
217
+ /**
218
+ * Add the read path and the next step to one `saveImage` rejection. The attachment store
219
+ * classifies its own failures, so an `AttachmentError` keeps its `name` and `code` and only
220
+ * gains a message naming the file and remedy, with the original as `cause`; a code without
221
+ * a remedy, and any value that is not an `AttachmentError`, passes through unchanged.
222
+ * @param error - the value `saveImage` rejected with.
223
+ * @param attachments - the store whose limits the message names.
224
+ * @param facts - the path and media-type facts the message names.
225
+ * @returns the error to throw from the tool body.
226
+ */
227
+ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFailureFacts): unknown {
228
+ if (!(error instanceof AttachmentError)) return error
229
+ const detail = saveFailureDetail(error, attachments, facts)
230
+ return detail === undefined
231
+ ? error
232
+ : new AttachmentError(`cannot read "${facts.displayPath}": ${detail}`, error.code, { cause: error })
233
+ }
234
+
235
+ /** The model-facing remedy for one attachment rejection, or undefined when the store message stands. */
236
+ function saveFailureDetail(error: AttachmentError, attachments: AttachmentStore, facts: SaveFailureFacts): string | undefined {
237
+ const { extension, mediaType, sniffed } = facts
238
+ // Size refusals stay recoverable tool errors: an oversized image must never
239
+ // enter durable history, where it would ride every later model request past
240
+ // provider-side dimension rejections.
241
+ switch (error.code) {
242
+ case 'IMAGE_DIMENSION_TOO_LARGE':
243
+ return `at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`
244
+ case 'IMAGE_TOO_MANY_PIXELS':
245
+ return `the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`
246
+ case 'IMAGE_TOO_LARGE':
247
+ case 'IMAGES_TOO_LARGE':
248
+ return 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'
249
+ case 'UNSUPPORTED_IMAGE_TYPE':
250
+ return `${mediaType} images are not accepted by this deployment`
251
+ case 'INVALID_IMAGE':
252
+ return 'the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt'
253
+ case 'IMAGE_TYPE_MISMATCH':
254
+ return sniffed
255
+ ? `the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`
256
+ : `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`
257
+ case 'ATTACHMENT_WRITE_FAILED':
258
+ return /16-bit PNG/iu.test(error.message)
259
+ ? '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'
260
+ : undefined
261
+ case 'TOO_MANY_IMAGES':
262
+ case 'INVALID_IMAGE_BASE64':
263
+ case 'INVALID_FILE_BASE64':
264
+ case 'INVALID_ATTACHMENT_REF':
265
+ case 'ATTACHMENT_CORRUPT':
266
+ case 'ATTACHMENT_NOT_FOUND':
267
+ case 'ATTACHMENT_READ_FAILED':
268
+ case 'ATTACHMENT_PROJECTION_UNSUPPORTED':
269
+ case 'ATTACHMENT_FILES_UNSUPPORTED':
270
+ return undefined
271
+ /* v8 ignore next -- Closed AttachmentErrorCode union; assertNever checks exhaustiveness at compile time. */
272
+ default:
273
+ return assertNever(error.code)
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Register the `read_image` tool into the given context. The composing plugin
279
+ * owns the attachments gate: `src/index.ts` calls this inside
280
+ * `ctx.inject(['attachments'], …)` so the tool exists only while a durable
281
+ * store is mounted. Execution still re-checks `ctx.get('attachments')` for
282
+ * direct callers and gates on the calling route's declared image input.
283
+ * @param ctx - the registration scope; execution uses its `fs` service plus
284
+ * the optional `attachments`/`llm` services.
285
+ */
286
+ export function applyReadImageTool(ctx: Context): void {
287
+ ctx.tools.register(defineTool({
288
+ name: 'read_image',
289
+ description: 'Read a PNG/JPEG/WebP/GIF file and return the image itself. '
290
+ + 'Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.',
291
+ parameters: {
292
+ file_path: { type: 'string', required: true, description: 'Path to the image file, resolved by the filesystem backend.' },
293
+ },
294
+ output: {
295
+ schema: {
296
+ type: 'object',
297
+ additionalProperties: false,
298
+ properties: {
299
+ path: { type: 'string', required: true, description: 'Canonical absolute path in the filesystem execution world.' },
300
+ image: IMAGE_VALUE_SCHEMA,
301
+ },
302
+ },
303
+ render: (_args, value) => imageReadContent(value),
304
+ // Persist the resolved path only. The attachment reference is NOT copied
305
+ // here: the settled `content` already carries the image block with the
306
+ // complete reference, so a second copy would keep two records of one fact —
307
+ // and a `tools/post-execute` hook that legitimately replaces the content
308
+ // would leave the stale copy behind, showing an image the result no longer
309
+ // returns. The path needs its own structured record because the content
310
+ // carries it only as model-facing envelope text, which the client does not
311
+ // parse.
312
+ presentationMeta: (_args, value) => ({ path: value.path }),
313
+ },
314
+ // Content-addressed attachment writes are idempotent, so concurrent reads
315
+ // of the same file cannot conflict.
316
+ isConcurrencySafe: () => true,
317
+ async execute(args, exec) {
318
+ if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string'])
319
+
320
+ // Every pre-read gate runs before any filesystem I/O so a refusal never
321
+ // leaks partial reads or attachment writes. An extension-less path
322
+ // declares no format, so only its format and deployment media-type
323
+ // checks wait for the bytes.
324
+ const extension = extname(args.file_path).toLowerCase()
325
+ const declared = imageMediaTypeForPath(args.file_path)
326
+ if (declared === undefined && extension !== '') {
327
+ throw new ImageInputError(
328
+ `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`,
329
+ 'IMAGE_UNSUPPORTED_FORMAT',
330
+ )
331
+ }
332
+ const attachments = ctx.get('attachments')
333
+ if (attachments === undefined) {
334
+ throw new ToolContextUnavailableError(`cannot read "${args.file_path}" as an image: no attachment service is mounted`)
335
+ }
336
+ if (declared !== undefined) assertDeploymentAccepts(attachments, declared, args.file_path)
337
+ await assertImageCapableRoute(ctx, exec, args.file_path)
338
+
339
+ const { target, info } = await resolveRegularReadTarget(ctx, exec, args.file_path)
340
+
341
+ // The tool result is one message carrying one image, so the per-message
342
+ // aggregate bound applies beside the per-image bound.
343
+ const byteCap = Math.min(attachments.imageLimits.maxImageBytes, attachments.imageLimits.maxMessageImageBytes)
344
+ const data = await ctx.fs.readBytes(target, exec.signal, byteCap)
345
+ const mediaType = declared ?? sniffImageMediaType(data)
346
+ if (mediaType === undefined) {
347
+ throw new ImageInputError(
348
+ `cannot read "${target.displayPath}": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`,
349
+ 'IMAGE_UNSUPPORTED_FORMAT',
350
+ )
351
+ }
352
+ if (declared === undefined) assertDeploymentAccepts(attachments, mediaType, target.displayPath)
353
+ // Persist before returning: the image block must reference a durably
354
+ // committed object by the time the tool/result event is appended.
355
+ let ref: ImageAttachmentRef
356
+ try {
357
+ ref = await attachments.saveImage({ data, mediaType, name: basename(target.displayPath) })
358
+ } catch (error: unknown) {
359
+ throw saveFailure(error, attachments, {
360
+ displayPath: target.displayPath, extension, mediaType, sniffed: declared === undefined,
361
+ })
362
+ }
363
+ ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec)
364
+ const value: ImageReadValue = {
365
+ path: ctx.fs.processPath(target),
366
+ image: {
367
+ attachmentId: ref.attachmentId,
368
+ mediaType: ref.mediaType,
369
+ bytes: ref.bytes,
370
+ width: ref.width,
371
+ height: ref.height,
372
+ ...ref.name === undefined ? {} : { name: ref.name },
373
+ ...ref.originalDimensions === undefined ? {} : {
374
+ originalDimensions: { ...ref.originalDimensions },
375
+ },
376
+ },
377
+ }
378
+ return value
379
+ },
380
+ // Pure display: a generic card in the read family with a follow-along
381
+ // location on the image file.
382
+ presentCall(args): GenericCallView {
383
+ return {
384
+ card: 'generic',
385
+ title: `Read image ${args.file_path}`,
386
+ kind: 'read',
387
+ locations: [{ path: args.file_path }],
388
+ }
389
+ },
390
+ }))
391
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Pure read presentation: turn provider-decoded text into a bounded, line-numbered window and
3
+ * model-facing envelope. Chunk scanning caps the current line, so even one newline-free giant
4
+ * line cannot grow memory without bound.
5
+ * @module @deepseek-ai/dsh-tool-fs/read-render
6
+ */
7
+
8
+ import { FsError } from '@deepseek-ai/dsh-fs'
9
+
10
+ /** Default maximum characters returned for a single line (the `readMaxLineLength` config). */
11
+ export const READ_MAX_LINE_LENGTH = 2000
12
+
13
+ /** Default maximum bytes returned for selected file lines (the `readMaxBytes` config). */
14
+ export const READ_MAX_BYTES = 50 * 1024
15
+
16
+ /** Resolved read window. The consumer applies its defaults/caps before calling. */
17
+ export interface ReadWindow {
18
+ /** 1-based first line to return. */
19
+ offset: number
20
+ /** Maximum number of lines to return. */
21
+ limit: number
22
+ /** Maximum characters returned for a single line; overflow is truncated with a suffix. */
23
+ maxLineLength: number
24
+ /** Maximum bytes of selected output; overflow stops the scan and marks `truncatedByBytes`. */
25
+ maxBytes: number
26
+ }
27
+
28
+ /** One line returned from a text file. */
29
+ export interface FileTextLine {
30
+ /** 1-based line number in the file. */
31
+ number: number
32
+ /** Line text without its trailing newline. */
33
+ text: string
34
+ }
35
+
36
+ /** The windowed result {@link buildWindow} produces from a file's decoded text. */
37
+ export interface WindowResult {
38
+ /** Returned lines, already numbered. */
39
+ lines: FileTextLine[]
40
+ /** Exact total line count in the file. */
41
+ totalLines: number
42
+ /** Whether selected output hit the byte cap. */
43
+ truncatedByBytes: boolean
44
+ }
45
+
46
+ /** Outcome of a bounded text read — what {@link formatReadOutput} renders. */
47
+ export interface FileReadOutcome {
48
+ /** 1-based first line requested. */
49
+ offset: number
50
+ /** Returned lines, already numbered. */
51
+ lines: FileTextLine[]
52
+ /** Exact total line count in the file. */
53
+ totalLines: number
54
+ /** Whether selected output hit the byte cap. */
55
+ truncatedByBytes?: true
56
+ }
57
+
58
+ interface WindowAccumulator {
59
+ lines: FileTextLine[]
60
+ totalLines: number
61
+ outputBytes: number
62
+ truncatedByBytes: boolean
63
+ }
64
+
65
+ function newAccumulator(): WindowAccumulator {
66
+ return { lines: [], totalLines: 0, outputBytes: 0, truncatedByBytes: false }
67
+ }
68
+
69
+ function truncateLine(line: string, maxLineLength: number): string {
70
+ return line.length > maxLineLength ? `${line.substring(0, maxLineLength)}... (line truncated to ${maxLineLength} chars)` : line
71
+ }
72
+
73
+ function lineByteSize(line: string, currentLineCount: number): number {
74
+ return Buffer.byteLength(line, 'utf8') + (currentLineCount > 0 ? 1 : 0)
75
+ }
76
+
77
+ function consumeLine(acc: WindowAccumulator, rawLine: string, request: ReadWindow): void {
78
+ acc.totalLines += 1
79
+ if (acc.truncatedByBytes || acc.totalLines < request.offset || acc.lines.length >= request.limit) return
80
+
81
+ const text = truncateLine(rawLine, request.maxLineLength)
82
+ const bytes = lineByteSize(text, acc.lines.length)
83
+ if (acc.outputBytes + bytes > request.maxBytes) {
84
+ acc.truncatedByBytes = true
85
+ return
86
+ }
87
+ acc.outputBytes += bytes
88
+ acc.lines.push({ number: acc.totalLines, text })
89
+ }
90
+
91
+ function stripCarriageReturn(line: string): string {
92
+ return line.endsWith('\r') ? line.slice(0, -1) : line
93
+ }
94
+
95
+ function finish(acc: WindowAccumulator, request: ReadWindow, displayPath: string): WindowResult {
96
+ if (!acc.truncatedByBytes && request.offset > acc.totalLines && !(acc.totalLines === 0 && request.offset === 1)) {
97
+ throw new FsError(`offset ${request.offset} is out of range for "${displayPath}" (${acc.totalLines} lines)`, 'FS_NOT_FOUND')
98
+ }
99
+ return { lines: acc.lines, totalLines: acc.totalLines, truncatedByBytes: acc.truncatedByBytes }
100
+ }
101
+
102
+ /**
103
+ * Build one window from streamed or whole-file chunks, enforcing line and byte caps while still
104
+ * scanning to an exact total line count, and throwing `FS_NOT_FOUND` when the requested offset is
105
+ * past EOF.
106
+ * @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning.
107
+ * @param request - the resolved window; the caller has already applied its defaults and caps.
108
+ * @param displayPath - the caller-facing path used in the offset-out-of-range error.
109
+ * @returns the numbered window lines, the total line count seen, and the byte-cap truncation flag.
110
+ */
111
+ export async function buildWindow(
112
+ chunks: AsyncIterable<string> | Iterable<string>,
113
+ request: ReadWindow,
114
+ displayPath: string,
115
+ ): Promise<WindowResult> {
116
+ const acc = newAccumulator()
117
+ // One char past the truncation point is enough to prove a line overflows.
118
+ const lineBufferCap = request.maxLineLength + 1
119
+ let lineBuffer = ''
120
+
121
+ function appendToLineBuffer(segment: string): void {
122
+ if (lineBuffer.length >= lineBufferCap) return
123
+ lineBuffer += segment
124
+ if (lineBuffer.length > lineBufferCap) lineBuffer = lineBuffer.slice(0, lineBufferCap)
125
+ }
126
+
127
+ function flushLine(): void {
128
+ consumeLine(acc, stripCarriageReturn(lineBuffer), request)
129
+ lineBuffer = ''
130
+ }
131
+
132
+ for await (const chunk of chunks) {
133
+ let startPos = 0
134
+ let newlinePos: number
135
+ while ((newlinePos = chunk.indexOf('\n', startPos)) !== -1) {
136
+ appendToLineBuffer(chunk.slice(startPos, newlinePos))
137
+ flushLine()
138
+ startPos = newlinePos + 1
139
+ }
140
+ appendToLineBuffer(chunk.slice(startPos))
141
+ }
142
+ if (lineBuffer.length > 0) flushLine()
143
+ return finish(acc, request, displayPath)
144
+ }
145
+
146
+ /**
147
+ * Format a read outcome as one OpenCode-style line-numbered text block body.
148
+ * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
149
+ * @param outcome - the windowed read to render.
150
+ * @returns the model-facing envelope: numbered lines plus a continuation or end-of-file footer.
151
+ */
152
+ export function formatReadOutput(displayPath: string, outcome: FileReadOutcome): string {
153
+ const endLine = outcome.lines.at(-1)?.number ?? Math.max(0, outcome.offset - 1)
154
+ let footer: string
155
+ if (outcome.truncatedByBytes) {
156
+ footer = `(Output capped. Showing lines ${outcome.offset}-${endLine}. Use offset=${endLine + 1} to continue.)`
157
+ } else if (endLine < outcome.totalLines) {
158
+ footer = `(Showing lines ${outcome.offset}-${endLine} of ${outcome.totalLines}. Use offset=${endLine + 1} to continue.)`
159
+ } else {
160
+ footer = `(End of file - total ${outcome.totalLines} lines)`
161
+ }
162
+ const body = outcome.lines.length > 0
163
+ ? `${outcome.lines.map(line => `${line.number}: ${line.text}`).join('\n')}\n\n${footer}`
164
+ : footer
165
+ return `<path>${displayPath}</path>
166
+ <type>file</type>
167
+ <content>
168
+ ${body}
169
+ </content>`
170
+ }
171
+
172
+ /**
173
+ * Derive the persisted `lang` hint from a read path's file extension. The shared
174
+ * table in `@deepseek-ai/dsh-util-code-language` owns the recognized suffixes and
175
+ * the path rules (both separators, a leading dot as the extension separator, and
176
+ * prototype-key safety); `readLangHintForPath` projects the read card's short ids
177
+ * over it, so a suffix whose value a recorded session already holds keeps it
178
+ * byte-identical while every other suffix uses its language's short name.
179
+ * @param path - the model-facing path the read reported.
180
+ * @returns the persisted language hint, or `undefined` when the extension maps to none.
181
+ */
182
+ export { readLangHintForPath as langFromPath } from '@deepseek-ai/dsh-util-code-language'
183
+
184
+ /**
185
+ * The `read` tool's private `tool/result` `meta` payload: the structured
186
+ * line-numbered window a capable UI renders as a code view. Attached opaquely (as
187
+ * `unknown`) on the tool result and persisted with the session log — it must be
188
+ * JSON-serializable (the session validates this at `append`), so `presentResult`
189
+ * reproduces the read card on replay when the raw structured output is no longer
190
+ * on the wire. The producing tool owns and narrows this opaque shape.
191
+ */
192
+ export interface FsReadMeta {
193
+ /** The read file's model-facing path. */
194
+ path: string
195
+ /** The 1-based first line the window requested, kept even when `lines` is empty. */
196
+ offset: number
197
+ /** The returned window's lines, each keeping its file line number. */
198
+ lines: FileTextLine[]
199
+ /** Exact total line count in the file. */
200
+ totalLines: number
201
+ /** Syntax-highlighting language hint from the extension, or omitted for plain text. */
202
+ lang?: string
203
+ }
204
+
205
+ /**
206
+ * Whether `value` is a valid {@link FileTextLine} (defensive narrowing from
207
+ * opaque `meta`). `number` must be a 1-based integer line number, since a card
208
+ * rendered from a zero, fractional, or non-finite line number would violate the
209
+ * 1-based numbering contract the read window promises.
210
+ */
211
+ function isFileTextLine(value: unknown): value is FileTextLine {
212
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
213
+ const { number, text } = value as Record<string, unknown>
214
+ return typeof number === 'number' && Number.isInteger(number) && number >= 1 && typeof text === 'string'
215
+ }
216
+
217
+ /**
218
+ * Narrow opaque live or replayed result metadata to a structured read window.
219
+ * Malformed metadata returns `undefined` so presentation can fall back to the
220
+ * generic text card instead of throwing during replay. Beyond shape, the
221
+ * semantic contract of a read window is enforced against replayed JSON that is
222
+ * well-typed but out of range: `offset` must be a 1-based integer, `totalLines`
223
+ * must be a non-negative integer, each line number must be a 1-based integer no
224
+ * less than `offset`, the line numbers must strictly increase, and no line number
225
+ * may exceed `totalLines`. Any violation declines to the generic fallback rather
226
+ * than emitting a card that misnumbers or overcounts.
227
+ * @param meta - result metadata.
228
+ * @returns the validated read window, or `undefined` for absent, malformed, or semantically invalid data.
229
+ */
230
+ export function readMetaFromMeta(meta: unknown): FsReadMeta | undefined {
231
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined
232
+ const { path, offset, lines, totalLines, lang } = meta as Record<string, unknown>
233
+ if (typeof path !== 'string' || typeof totalLines !== 'number' || typeof offset !== 'number') return undefined
234
+ if (!Number.isInteger(offset) || offset < 1) return undefined
235
+ if (!Number.isInteger(totalLines) || totalLines < 0) return undefined
236
+ if (!Array.isArray(lines) || !lines.every(isFileTextLine)) return undefined
237
+ if (lang !== undefined && typeof lang !== 'string') return undefined
238
+ let previous = offset - 1
239
+ for (const { number } of lines) {
240
+ if (number <= previous || number > totalLines) return undefined
241
+ previous = number
242
+ }
243
+ return { path, offset, lines, totalLines, ...lang === undefined ? {} : { lang } }
244
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Shared path resolution and regular-file validation for model-facing read tools.
3
+ * @module @deepseek-ai/dsh-tool-fs/src/read-target
4
+ */
5
+
6
+ import type { Context } from '@deepseek-ai/cordis'
7
+ import { FsError } from '@deepseek-ai/dsh-fs'
8
+ import type { FsInfo, FsTarget } from '@deepseek-ai/dsh-fs'
9
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
10
+ import { sessionResolveOptions } from './session-cwd.ts'
11
+
12
+ /**
13
+ * Resolve a model-supplied path, observe absence, and require a regular file.
14
+ * @param ctx - the plugin context providing filesystem resolution and observation events.
15
+ * @param exec - the current tool execution, including the owning Agent and cancellation.
16
+ * @param requestedPath - the raw path supplied to the tool.
17
+ * @returns the resolved target and its single stat result.
18
+ */
19
+ export async function resolveRegularReadTarget(
20
+ ctx: Context,
21
+ exec: ToolExecution,
22
+ requestedPath: string,
23
+ ): Promise<{ target: FsTarget; info: FsInfo }> {
24
+ const target = await ctx.fs.resolve(requestedPath, await sessionResolveOptions(ctx, exec))
25
+ const info = await ctx.fs.stat(target, exec.signal)
26
+ if (info === undefined) {
27
+ ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
28
+ throw new FsError(`cannot read "${target.displayPath}": not found`, 'FS_NOT_FOUND')
29
+ }
30
+ if (info.type !== 'file') {
31
+ throw new FsError(`cannot read "${target.displayPath}": not a regular file`, 'FS_NOT_REGULAR_FILE')
32
+ }
33
+ return { target, info }
34
+ }