Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
551 lines (518 loc) · 24.9 KB
/
Copy pathindex.ts
File metadata and controls
551 lines (518 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/**
* Workspace file service: read-only file previews, workspace directory
* listings, workspace-wide name and path search, and the
* filesystem-observation change feed, exposed as `workspaceFiles`.
*
* File reads follow the composed filesystem's read access, including paths
* outside the workspace. The selected Session's workspace root supplies the
* base for relative paths, with the header directory and then the sandbox
* policy root as fallbacks, not a read-containment restriction. Directory
* listings, searches, and change observations remain workspace-scoped; a
* search reports workspace-relative paths. File-kind checks and configured read caps apply to
* every preview; this service exposes no mutations.
*
* A page is cut from `streamText`, which decodes and rejects non-UTF-8 as it
* goes, so the file is read only up to the first character past the page and
* never held whole in memory; the NUL scan runs on the page itself.
*
* This is NOT modelled on `session.openWorkspacePath`. That endpoint hands a
* path to the local opener and leaves the effect on the machine; this one sends
* file content across the wire, which is a different level of exposure.
*/
import { posix, win32 } from 'node:path'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type {} from '@deepseek-ai/dsh-fs'
import type { FsDirEntry, FsInfo, FsPathInfo, FsTarget } from '@deepseek-ai/dsh-fs'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import type {} from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-session-persistence'
import type {} from '@deepseek-ai/dsh-session-projection-cache'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { Remote, RemoteError, TypertRemoteService, type TypertLookup } from '@deepseek-ai/dsh-typert-protocol'
import type {} from '@deepseek-ai/dsh-working-directory'
import { WorkspaceChangeFeed } from './changes.ts'
import { searchWorkspace, type SearchLimits } from './search.ts'
import type {
WorkspaceByteRange,
WorkspaceByteReadOptions,
WorkspaceDirectoryEntry,
WorkspaceDirectoryListing,
WorkspaceFileBytes,
WorkspaceFileRange,
WorkspaceFileSearchRequest,
WorkspaceFileSearchResult,
WorkspaceFileStat,
WorkspaceFileText,
WorkspaceFileWatchFrame,
} from './types.ts'
export type * from './types.ts'
declare module '@deepseek-ai/cordis' {
interface Context {
/** Host owner of the `workspaceFiles` Remote namespace. */
workspaceFiles: WorkspaceFiles
}
}
/** Header-derived file resolution context for one Session identity. */
export interface WorkspaceFileScope {
/** Session identity received on the wire. */
readonly sessionId: SessionId
/**
* Session workspace root: for a live Session the root the sandbox policy
* bounds it by; for a stored one its directory in the projection cache, else
* its header directory, else the deployment fallback.
*/
readonly workspaceRoot: string
}
/**
* Resolve the workspace root a Session's file views and directory listings
* use, without loading its event body or activating an Agent.
* @param ctx - Host context carrying the Session store and the sandbox policy, and optionally persistence
* and the projection cache.
* @param sessionId - Session identity received on the wire.
* @param signal - cancellation for the persistence read of a stored Session.
* @returns the scope, or undefined when no live or stored Session has that identity.
*/
async function workspaceFileScopeOf(
ctx: Context, sessionId: SessionId, signal?: AbortSignal,
): Promise<WorkspaceFileScope | undefined> {
const live = ctx.get('sessions')?.get(sessionId)
if (live !== undefined) return { sessionId, workspaceRoot: ctx.sandboxPolicy.resolve({ session: live }).workspaceRoot }
const stored = await ctx.get('sessionPersistence')?.stat(sessionId, signal === undefined ? undefined : { signal })
if (stored === undefined) return undefined
const cached = ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header, ['workingDirectory'])?.values.workingDirectory
return { sessionId, workspaceRoot: cached ?? stored.header.cwd ?? ctx.sandboxPolicy.workspaceRoot }
}
declare module '@deepseek-ai/dsh-typert-protocol' {
interface TypertLookupMap {
/** Resolve a Session id to its workspace root without loading its event body or activating an Agent. */
workspaceFileScope: TypertLookup<WorkspaceFileScope, SessionId>
}
}
/** Deployment caps on one page, one listing, or one search. */
export interface Config {
/**
* Inclusive byte cap on one page's text and on one byte window.
*
* A page above this fails; it is not shortened, because a silently cut page
* reads as the whole page. A byte window asking for more is refused the same
* way. The file itself has no size cap: a caller pages through it.
*/
readonly maxBytes: number
/** Inclusive byte cap on a complete-file read; larger files are refused, never truncated. */
readonly maxFileBytes: number
/** Default and largest page size in lines; a request asking for more is refused. */
readonly maxLines: number
/** Cap on returned directory entries; the rest is dropped and reported cut. */
readonly maxEntries: number
/** Budgets on one search's matches, listed files, deadline and ripgrep process. */
readonly search: SearchLimits
}
/** One page cut from a decoded text stream. */
interface Page {
readonly text: string
/** Lines in `text`; `0` for a page past the last line. */
readonly lines: number
readonly eof: boolean
}
/** The byte text never carries: its presence marks a page as binary. */
const NUL = String.fromCharCode(0)
/** Refuse anything the wire schema admits as a number but a window cannot use: only safe integers index a file. */
function integerAtLeast(value: number, min: number, name: string): number {
if (!Number.isSafeInteger(value) || value < min) {
throw new RemoteError('gateway/bad-request', `${name} must be a safe integer of at least ${min}`, {})
}
return value
}
/**
* Cut lines `offset` through `offset + limit - 1` from decoded chunks, stopping
* at the first character past the page so the rest of the file is never read.
* Lines before the page are counted, not kept, and the page is refused the
* moment its bytes exceed `maxBytes`, so one giant line cannot grow memory past
* the cap either.
*/
async function cutPage(
chunks: AsyncIterable<string>,
offset: number,
limit: number,
maxBytes: number,
path: string,
): Promise<Page> {
const last = offset + limit - 1
const lines: string[] = []
let current = ''
let bytes = 0
let lineNumber = 1
const admit = (size: number): void => {
bytes += size
if (bytes > maxBytes) {
throw new RemoteError(
'workspace-file/too-large',
`lines ${offset}-${last} of "${path}" exceed the ${maxBytes} byte cap`,
{ path, limit: maxBytes },
)
}
}
const complete = (): void => {
if (lines.length > 0) admit(1)
lines.push(current)
current = ''
}
for await (const chunk of chunks) {
let position = 0
while (position < chunk.length) {
if (lineNumber > last) return { text: lines.join('\n'), lines: lines.length, eof: false }
const newline = chunk.indexOf('\n', position)
const segment = newline === -1 ? chunk.slice(position) : chunk.slice(position, newline)
if (lineNumber >= offset) {
admit(Buffer.byteLength(segment, 'utf8'))
current += segment
}
if (newline === -1) break
if (lineNumber >= offset) complete()
lineNumber += 1
position = newline + 1
}
}
// Only an in-page line can be pending here: earlier lines were never kept,
// and a character past the page returned above.
if (current.length > 0) complete()
return { text: lines.join('\n'), lines: lines.length, eof: true }
}
/**
* Workspace path of `target` relative to `root`, derived from the two canonical
* `file:` URIs so the answer is `/`-joined on every platform. Empty for the root.
*/
function workspacePathOf(rootUrl: string, targetUrl: string): string {
const root = new URL(rootUrl).pathname.replace(/\/+$/, '')
const target = new URL(targetUrl).pathname
if (target === root) return ''
return target.slice(root.length + 1).split('/').map(decodeURIComponent).join('/')
}
/** Strip the resolved child target: the wire carries names and metadata only. */
function directoryEntry(child: FsDirEntry): WorkspaceDirectoryEntry {
return {
name: child.name,
type: child.type,
...child.size === undefined ? {} : { size: child.size },
}
}
/** Host Remote file reads and workspace directory observations over the composed filesystem. */
export class WorkspaceFiles extends TypertRemoteService {
static inject = ['fs', 'sandboxPolicy', 'sessions', 'typert']
static Config: z<Config> = z.object({
maxBytes: z.number().step(1).min(1).default(2 * 1024 * 1024),
maxFileBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER - 1).default(32 * 1024 * 1024),
maxLines: z.number().step(1).min(1).default(5000),
maxEntries: z.number().step(1).min(1).default(2000),
search: z.object({
maxResults: z.number().step(1).min(1).default(512),
maxEntries: z.number().step(1).min(1).default(100000),
graceMs: z.number().step(1).min(1).max(2147483647).default(3000),
timeoutMs: z.number().step(1).min(1).max(2147483647).default(30000),
stderrMaxBytes: z.number().step(1).min(1).default(65536),
}),
})
private readonly feed: WorkspaceChangeFeed
/**
* @param ctx - Host context carrying the filesystem and the sandbox policy.
* @param config - deployment caps on one page, one listing, or one search.
*/
constructor(ctx: Context, private readonly config: Config) {
super(ctx, 'workspaceFiles')
this.feed = new WorkspaceChangeFeed(ctx)
ctx.inject(['sessions', 'typert'], (scope) => {
scope.typert.lookups.register('workspaceFileScope', {
parameter: 'workspaceFileScope',
wire: 'workspaceFileScopeId',
resource: 'session',
hostTypeSymbol: '@deepseek-ai/dsh-api-workspace-files#WorkspaceFileScope',
wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId',
resolve: sessionId => workspaceFileScopeOf(scope, sessionId),
})
})
}
/**
* Resolve the scope other Host services use to open the same `session/<id>/<path>` addresses:
* a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory.
* @param sessionId - Session identity received on the wire.
* @param signal - cancellation for the persistence read of a stored Session.
* @returns the scope, or undefined when no live or stored Session has that identity.
*/
scopeOf(sessionId: SessionId, signal?: AbortSignal): Promise<WorkspaceFileScope | undefined> {
return workspaceFileScopeOf(this.ctx, sessionId, signal)
}
/**
* Read one page of lines from a UTF-8 file readable by the filesystem backend.
* @param workspaceFileScope - header-derived workspace root for the Session identity on the wire.
* @param path - absolute path or path relative to the workspace root; files outside it are allowed.
* @param range - the line window; omitted fields take the page defaults.
* @param signal - caller cancellation.
* @returns the page, the file's version at the stat before it, and whether it reaches the last line.
*/
@Remote
async read(
workspaceFileScope: WorkspaceFileScope,
path: string,
range: WorkspaceFileRange,
signal: AbortSignal,
): Promise<WorkspaceFileText> {
const { offset, limit } = this.resolvePage(range)
const { target, info } = await this.locateFile(workspaceFileScope, path, signal)
const page = await this.cutPage(target, offset, limit, signal, path)
if (page.text.includes(NUL)) {
throw new RemoteError('workspace-file/not-text', `"${path}" contains NUL bytes`, { path })
}
return { ...this.statOf(target, info), offset, text: page.text, lines: page.lines, eof: page.eof }
}
/**
* Read a complete regular file or one byte range without text decoding.
* @param workspaceFileScope - header-derived workspace root for the Session identity on the wire.
* @param path - target path, absolute or workspace-relative; relative to the base file's directory when provided.
* @param options - optional base file and range; without a range the complete-file cap applies.
* @param signal - caller cancellation.
* @returns native bytes with the file's version and size at the preceding stat, byte offset, and EOF marker.
*/
@Remote
async readBytes(
workspaceFileScope: WorkspaceFileScope,
path: string,
options: WorkspaceByteReadOptions,
signal: AbortSignal,
): Promise<WorkspaceFileBytes> {
const window = options.range === undefined ? undefined : this.resolveWindow(options.range, path)
const resolved = options.baseFile === undefined ? path : await this.relativePath(workspaceFileScope, options.baseFile, path, signal)
const { target, info } = await this.locateFile(workspaceFileScope, resolved, signal)
if (window !== undefined) {
const { offset, length } = window
const data = await this.ctx.fs.readByteRange(target, window, signal)
const eof = info.size === undefined ? data.length < length : offset + data.length >= info.size
return { ...this.statOf(target, info), offset, data, eof }
}
const limit = this.config.maxFileBytes
const data = await this.ctx.fs.readBytes(target, signal, limit).catch((cause: unknown) => {
if (typeof cause === 'object' && cause !== null && 'code' in cause && cause.code === 'FS_TOO_LARGE') {
throw new RemoteError('workspace-file/too-large', `"${path}" exceeds the ${limit} byte full-file cap`, { path, limit }, { cause })
}
throw cause
})
return { ...this.statOf(target, info), offset: 0, data, eof: true }
}
/**
* Report one regular file's identity, version, and size without its content.
* @param workspaceFileScope - header-derived workspace root for the Session identity on the wire.
* @param path - absolute path or path relative to the workspace root; files outside it are allowed.
* @param signal - caller cancellation.
* @returns the file's absolute path, current version, and byte size.
*/
@Remote
async stat(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): Promise<WorkspaceFileStat> {
const { target, info } = await this.locateFile(workspaceFileScope, path, signal)
return this.statOf(target, info)
}
/**
* List the direct children of one directory inside the Session's workspace.
* @param workspaceFileScope - header-derived workspace root for the Session identity on the wire.
* @param path - workspace path, absolute or relative to the workspace root.
* @param signal - caller cancellation.
* @returns the directory's children in the backend's stable name order, bounded by the entry cap.
*/
@Remote
async list(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): Promise<WorkspaceDirectoryListing> {
const { root, workspaceRoot, entry } = await this.inspect(workspaceFileScope, path, signal)
// A final link — a Windows junction or a symlink — is listed through the
// directory it resolves to, matching the child type `listDir` reports for
// that entry; `read` keeps its own no-follow gate on the final component.
if (entry.type !== 'directory' && entry.type !== 'symlink') {
throw new RemoteError(
'workspace-file/not-directory',
`"${path}" is a ${entry.type}`,
{ path, kind: entry.type },
)
}
const target = await this.confine(root, workspaceRoot, path, signal)
if (entry.type === 'symlink') {
const info = await this.ctx.fs.stat(target, signal)
if (info?.type !== 'directory') {
throw new RemoteError('workspace-file/not-directory', `"${path}" does not resolve to a directory`, { path, kind: 'symlink' })
}
}
const children = await this.ctx.fs.listDir(target, signal)
return {
path: workspacePathOf(this.ctx.fs.fileUrl(root), this.ctx.fs.fileUrl(target)),
entries: children.slice(0, this.config.maxEntries).map(directoryEntry),
truncated: children.length > this.config.maxEntries,
}
}
/**
* Search files and their inferred ancestor directories with packaged ripgrep.
* Native ignore rules apply unless disabled; VCS metadata, symlinks and empty
* directories are absent. Within the bounded set of listed files, matches
* sort by depth, then workspace-relative path.
* @param workspaceFileScope - header-derived workspace root for the Session identity on the wire.
* @param request - the query, literal exclusions, and hidden/ignore switches.
* @param signal - caller cancellation, forwarded to the subprocess; rejection preserves its reason.
* @returns matches capped by search.maxResults; incomplete marks excess rg files or exit 2.
* @throws RemoteError `gateway/bad-request`: the query is blank.
* @throws RemoteError `workspace-file/not-found`: the workspace root does not exist.
* @throws RemoteError `workspace-file/not-directory`: the workspace root is not a directory.
* @throws RemoteError `workspace-file/search-failed`: subprocess is missing, rg cannot launch or execute, or the search times out.
*/
@Remote
async search(
workspaceFileScope: WorkspaceFileScope,
request: WorkspaceFileSearchRequest,
signal: AbortSignal,
): Promise<WorkspaceFileSearchResult> {
const query = request.query.trim()
if (query.length === 0) throw new RemoteError('gateway/bad-request', 'query must not be blank', {})
signal.throwIfAborted()
const { workspaceRoot } = workspaceFileScope
const root = await this.ctx.fs.resolve(workspaceRoot, { signal })
const info = await this.ctx.fs.stat(root, signal)
if (info === undefined) {
throw new RemoteError('workspace-file/not-found', `no entry at "${workspaceRoot}"`, { path: workspaceRoot })
}
if (info.type !== 'directory') {
throw new RemoteError('workspace-file/not-directory', `"${workspaceRoot}" is a ${info.type}`, { path: workspaceRoot, kind: info.type })
}
const subprocess = this.ctx.get('subprocess')
if (subprocess === undefined) {
throw new RemoteError('workspace-file/search-failed', 'Workspace file search requires a subprocess provider', {})
}
return searchWorkspace(subprocess, {
cwd: this.ctx.fs.processPath(root),
query,
excludedPaths: request.excludedPaths,
includeHidden: request.includeHidden,
respectGitignore: request.respectGitignore,
...this.config.search,
}, signal)
}
/**
* Watch one file or a directory's direct entries in the Session's filesystem.
* Files use the backend's read authority; directories remain workspace-scoped.
* @param workspaceFileScope - header-derived workspace root for the Session identity on the wire.
* @param path - target path; the Host determines its type and confines directories to the workspace.
* @param signal - generation cancellation.
* @returns `ready` once the target watch is active, then current metadata for queued and live invalidations.
* @throws RemoteError when watching is unavailable or a directory is outside the workspace.
*/
@Remote({ mode: 'stream' })
changes(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): AsyncIterable<WorkspaceFileWatchFrame> {
return this.feed.follow(workspaceFileScope.workspaceRoot, path, signal)
}
private async relativePath(scope: WorkspaceFileScope, baseFile: string, path: string, signal: AbortSignal): Promise<string> {
const relative = path.replace(/\\/g, '/')
if (relative.length === 0 || relative.startsWith('/') || /^[a-z][a-z\d+.-]*:/iu.test(relative) || relative.includes(NUL)) {
throw new RemoteError('gateway/bad-request', 'path must be relative when baseFile is provided', {})
}
const { target } = await this.locateFile(scope, baseFile, signal)
const absolute = this.ctx.fs.processPath(target)
const paths = absolute.startsWith('/') ? posix : win32
return paths.resolve(paths.dirname(absolute), relative)
}
/** Apply the page defaults and caps here, so the request never carries them implicitly. */
private resolvePage(range: WorkspaceFileRange): { offset: number; limit: number } {
const offset = range.offset === undefined ? 1 : integerAtLeast(range.offset, 1, 'offset')
const limit = range.limit === undefined ? this.config.maxLines : integerAtLeast(range.limit, 1, 'limit')
if (limit > this.config.maxLines) {
throw new RemoteError('gateway/bad-request', `limit must be at most ${this.config.maxLines}`, {})
}
return { offset, limit }
}
/** Apply the byte-window defaults and cap; a window above the cap is refused, not shortened. */
private resolveWindow(range: WorkspaceByteRange, path: string): { offset: number; length: number } {
const offset = range.offset === undefined ? 0 : integerAtLeast(range.offset, 0, 'offset')
const length = range.length === undefined ? this.config.maxBytes : integerAtLeast(range.length, 1, 'length')
if (offset + length > Number.MAX_SAFE_INTEGER) {
throw new RemoteError('gateway/bad-request', 'offset plus length must stay a safe integer', {})
}
if (length > this.config.maxBytes) {
throw new RemoteError(
'workspace-file/too-large',
`${length} bytes of "${path}" exceed the ${this.config.maxBytes} byte cap`,
{ path, limit: this.config.maxBytes },
)
}
return { offset, length }
}
/**
* Inspect the requested path itself before resolution follows its final
* component. Directory containment is checked separately by `list`.
*/
private async inspect(
workspaceFileScope: WorkspaceFileScope,
path: string,
signal: AbortSignal,
): Promise<{ root: FsTarget; workspaceRoot: string; entry: FsPathInfo }> {
if (path.length === 0) throw new RemoteError('gateway/bad-request', 'path is required', {})
const { workspaceRoot } = workspaceFileScope
const root = await this.ctx.fs.resolve(workspaceRoot, { signal })
// Gate on the path itself before anything follows it.
const entry = await this.ctx.fs.lstat(path, { cwd: workspaceRoot }, signal)
if (entry === undefined) {
throw new RemoteError('workspace-file/not-found', `no entry at "${path}"`, { path })
}
return { root, workspaceRoot, entry }
}
/** Resolve an inspected path and refuse it unless the workspace contains it. */
private async confine(root: FsTarget, workspaceRoot: string, path: string, signal: AbortSignal): Promise<FsTarget> {
const target = await this.ctx.fs.resolve(path, { cwd: workspaceRoot, signal })
if (!this.ctx.fs.contains(root, target)) {
throw new RemoteError('workspace-file/outside-workspace', `"${path}" is outside the workspace`, { path })
}
return target
}
/**
* All gates for a regular file, ending in the one stat that names its version
* and size. The stat re-checks what `lstat` saw: the file may have gone or
* changed kind in between.
*/
private async locateFile(
workspaceFileScope: WorkspaceFileScope,
path: string,
signal: AbortSignal,
): Promise<{ target: FsTarget; info: FsInfo }> {
const { workspaceRoot, entry } = await this.inspect(workspaceFileScope, path, signal)
if (entry.type !== 'file') {
throw new RemoteError('workspace-file/not-regular-file', `"${path}" is a ${entry.type}`, { path, kind: entry.type })
}
const target = await this.ctx.fs.resolve(path, { cwd: workspaceRoot, signal })
const info = await this.ctx.fs.stat(target, signal)
if (info === undefined) {
throw new RemoteError('workspace-file/not-found', `no entry at "${path}"`, { path })
}
if (info.type !== 'file') {
throw new RemoteError('workspace-file/not-regular-file', `"${path}" is a ${info.type}`, { path, kind: info.type })
}
return { target, info }
}
private statOf(target: FsTarget, info: FsInfo): WorkspaceFileStat {
return {
absolutePath: this.ctx.fs.processPath(target),
version: info.version,
...info.size === undefined ? {} : { bytes: info.size },
}
}
/** Stream the file as text and cut the page, classifying the backend's non-text refusal. */
private async cutPage(target: FsTarget, offset: number, limit: number, signal: AbortSignal, path: string): Promise<Page> {
try {
return await cutPage(await this.ctx.fs.streamText(target, signal), offset, limit, this.config.maxBytes, path)
} catch (error: unknown) {
if (isNotTextRefusal(error)) {
throw new RemoteError('workspace-file/not-text', `"${path}" is not UTF-8 text`, { path }, { cause: error })
}
throw error
}
}
}
/**
* The backend's non-text refusal, recognized by its code alone: the error class
* belongs to whichever `dsh-fs` instance the provider loaded, so no class
* identity is shared across the package boundary.
*/
function isNotTextRefusal(error: unknown): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === 'FS_NOT_TEXT'
}
export default WorkspaceFiles