@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,117 @@
1
+ /** Patch parsing and target identity shared by preflight and sequential commits. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { FsError } from '@deepseek-ai/dsh-fs'
4
+ import type { FsTarget, FsTargetKey, FsVersion, FsWriteIntent } from '@deepseek-ai/dsh-fs'
5
+ import { parsePatch } from '@deepseek-ai/dsh-fs-patch'
6
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
7
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
8
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
9
+ import { remediateFsError } from '../error.ts'
10
+ import type { FsSandboxController } from '../sandbox.ts'
11
+ import { sessionResolveOptions } from '../session-cwd.ts'
12
+ import type { PatchExecutionRequest, PatchFailure, PatchOperationRecord, PatchPlan, PlannedOperation } from './types.ts'
13
+
14
+ /**
15
+ * Resolve every operation without dropping repeated aliases or splitting moves.
16
+ * @param ctx - filesystem service owner.
17
+ * @param sandbox - filesystem diagnostic mapper.
18
+ * @param exec - session cwd and execution signal.
19
+ * @param request - raw patch and resolved per-call policy.
20
+ * @returns resolved operations sharing one target per canonical key, plus resolution refusals.
21
+ */
22
+ export async function planPatch(
23
+ ctx: Context, sandbox: FsSandboxController, exec: ToolExecution, request: PatchExecutionRequest,
24
+ ): Promise<PatchPlan> {
25
+ const parsed = parsePatch(request.patch)
26
+ const targets = new Map<FsTargetKey, FsTarget>()
27
+ const resolve = async (path: string): Promise<FsTarget> => {
28
+ const target = await ctx.fs.resolve(path, await sessionResolveOptions(ctx, exec))
29
+ const prior = targets.get(target.targetKey)
30
+ if (prior) return prior
31
+ targets.set(target.targetKey, target)
32
+ return target
33
+ }
34
+ const result: PatchPlan = { operations: [], refusals: [] }
35
+ for (const [index, operation] of parsed.entries()) {
36
+ const moveTo = operation.kind === 'update' ? operation.moveTo : undefined
37
+ const record: PatchOperationRecord = {
38
+ index, kind: moveTo === undefined ? operation.kind : 'move', path: operation.path, patchLine: operation.lineNumber,
39
+ ...(moveTo === undefined ? {} : { destination: moveTo }),
40
+ }
41
+ let failurePath = operation.path
42
+ try {
43
+ const target = await resolve(operation.path)
44
+ record.path = target.displayPath
45
+ const base = { target, rawPath: operation.path, record }
46
+ switch (operation.kind) {
47
+ case 'add': result.operations.push({ ...base, kind: 'add', content: operation.content }); break
48
+ case 'delete': result.operations.push({ ...base, kind: 'delete' }); break
49
+ case 'update': {
50
+ if (operation.moveTo === undefined) result.operations.push({ ...base, kind: 'update', hunks: operation.hunks })
51
+ else {
52
+ failurePath = operation.moveTo
53
+ const destination = await resolve(operation.moveTo)
54
+ record.destination = destination.displayPath
55
+ result.operations.push({ ...base, kind: 'move', destination, hunks: operation.hunks })
56
+ }
57
+ break
58
+ }
59
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
60
+ default: assertNever(operation)
61
+ }
62
+ } catch (error) {
63
+ if (!(error instanceof FsError)) throw error
64
+ result.refusals.push({ operation: record, failure: patchFailure(sandbox, request.sandboxPolicy, error, failurePath) })
65
+ }
66
+ }
67
+ return result
68
+ }
69
+
70
+ /**
71
+ * Obtain a source guard without recording an observation.
72
+ * @param ctx - intent dispatcher.
73
+ * @param exec - opaque observation actor.
74
+ * @param target - resolved source.
75
+ * @param kind - deletion or edit-family source policy.
76
+ * @returns the observed version, or undefined for a bare provider.
77
+ */
78
+ export function sourceIntent(ctx: Context, exec: ToolExecution, target: FsTarget, kind: 'delete' | 'edit'): Promise<{ version: FsVersion } | undefined> {
79
+ return kind === 'delete'
80
+ ? ctx.waterfall('fs/delete-intent', target, exec, () => undefined)
81
+ : ctx.waterfall('fs/edit-intent', target, exec, () => undefined)
82
+ }
83
+
84
+ /**
85
+ * Obtain a write guard without recording an observation.
86
+ * @param ctx - intent dispatcher.
87
+ * @param exec - opaque observation actor.
88
+ * @param target - resolved write destination.
89
+ * @returns the observed write intent, or undefined for a bare provider.
90
+ */
91
+ export function destinationIntent(ctx: Context, exec: ToolExecution, target: FsTarget): Promise<FsWriteIntent | undefined> {
92
+ return ctx.waterfall('fs/write-intent', target, exec, () => undefined)
93
+ }
94
+
95
+ /**
96
+ * Preserve filesystem codes while applying the existing model-facing error policy.
97
+ * @param sandbox - shared denial mapper.
98
+ * @param policy - policy supplied by the request.
99
+ * @param error - expected filesystem failure.
100
+ * @param path - display path whose operation failed.
101
+ * @returns the remediated code and message; unexpected mapper defects reject.
102
+ */
103
+ export function patchFailure(
104
+ sandbox: FsSandboxController, policy: SandboxExecutionPolicy | undefined, error: FsError, path: string,
105
+ ): PatchFailure {
106
+ const mapped = remediateFsError(sandbox.mapError(error, policy), path)
107
+ return { code: mapped.code, message: mapped.message }
108
+ }
109
+
110
+ /**
111
+ * List all targets the operation can mutate, with destination first for a move.
112
+ * @param operation - resolved operation.
113
+ * @returns targets whose versions the uncertainty comparison records.
114
+ */
115
+ export function mutationTargets(operation: PlannedOperation): FsTarget[] {
116
+ return operation.kind === 'move' ? [operation.destination, operation.target] : [operation.target]
117
+ }
@@ -0,0 +1,157 @@
1
+ /** Read-only simulation of patch effects; no internal read establishes model observation. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { FsError } from '@deepseek-ai/dsh-fs'
4
+ import type { FsInfo, FsTarget, FsTargetKey } from '@deepseek-ai/dsh-fs'
5
+ import { applyHunks } from '@deepseek-ai/dsh-fs-patch'
6
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
7
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
8
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
9
+ import type { FsSandboxController } from '../sandbox.ts'
10
+ import { sessionResolveOptions } from '../session-cwd.ts'
11
+ import { destinationIntent, patchFailure, sourceIntent } from './plan.ts'
12
+ import type { PatchFailure, PatchRefusal, PlannedOperation } from './types.ts'
13
+
14
+ interface SimulatedFile {
15
+ exists: boolean
16
+ info: FsInfo | undefined
17
+ content?: string
18
+ touched: boolean
19
+ }
20
+
21
+ class Preflight {
22
+ private failurePath = ''
23
+ private readonly states = new Map<FsTargetKey, SimulatedFile>()
24
+
25
+ constructor(
26
+ private readonly ctx: Context, private readonly sandbox: FsSandboxController, private readonly exec: ToolExecution,
27
+ private readonly policy: SandboxExecutionPolicy | undefined,
28
+ ) {}
29
+
30
+ private async state(target: FsTarget): Promise<SimulatedFile> {
31
+ const known = this.states.get(target.targetKey)
32
+ if (known) return known
33
+ const info = await this.ctx.fs.stat(target, this.exec.signal)
34
+ const state = { exists: info !== undefined, info, touched: false }
35
+ this.states.set(target.targetKey, state)
36
+ return state
37
+ }
38
+
39
+ private regular(state: SimulatedFile, target: FsTarget): void {
40
+ if (state.info !== undefined && state.info.type !== 'file') {
41
+ throw new FsError(`cannot modify "${target.displayPath}": not a regular file`, 'FS_NOT_REGULAR_FILE')
42
+ }
43
+ }
44
+
45
+ private async source(state: SimulatedFile, target: FsTarget, kind: 'delete' | 'edit' | 'move'): Promise<void> {
46
+ const intent = state.touched ? undefined : await sourceIntent(this.ctx, this.exec, target, kind === 'delete' ? 'delete' : 'edit')
47
+ if (!state.exists) throw new FsError(`cannot ${kind} "${target.displayPath}": not found`, 'FS_NOT_FOUND')
48
+ this.regular(state, target)
49
+ if (intent !== undefined && intent.version !== state.info?.version) {
50
+ throw new FsError(`cannot ${kind} "${target.displayPath}": file changed since it was read`, 'FS_STALE_VERSION')
51
+ }
52
+ }
53
+
54
+ private async destination(state: SimulatedFile, target: FsTarget): Promise<void> {
55
+ const intent = state.touched ? undefined : await destinationIntent(this.ctx, this.exec, target)
56
+ this.regular(state, target)
57
+ if (intent?.kind === 'createIfAbsent' && state.exists) {
58
+ throw new FsError(`cannot overwrite existing "${target.displayPath}" without reading it first`, 'FS_NOT_OBSERVED')
59
+ }
60
+ if (intent?.kind === 'replaceIfVersion' && (!state.exists || state.info?.version !== intent.version)) {
61
+ throw new FsError(`cannot write "${target.displayPath}": file changed since it was read`, 'FS_STALE_VERSION')
62
+ }
63
+ }
64
+
65
+ private async content(state: SimulatedFile, target: FsTarget): Promise<string> {
66
+ if (state.content === undefined) {
67
+ const text = await this.ctx.fs.readText(target, this.exec.signal)
68
+ // readText samples only a prefix for NUL bytes; the mutation path rejects any NUL.
69
+ if (text.includes('\0')) throw new FsError(`cannot patch "${target.displayPath}": binary file`, 'FS_NOT_TEXT')
70
+ state.content = text.replace(/\r\n/g, '\n')
71
+ }
72
+ return state.content
73
+ }
74
+
75
+ private publish(target: FsTarget, content?: string): void {
76
+ this.states.set(target.targetKey, { exists: content !== undefined, info: undefined, touched: true,
77
+ ...(content === undefined ? {} : { content }) })
78
+ }
79
+
80
+ /** Simulate one operation; a filesystem refusal becomes the operation's failure. */
81
+ async check(operation: PlannedOperation): Promise<PatchFailure | undefined> {
82
+ this.failurePath = operation.target.displayPath
83
+ try { return await this.simulate(operation) } catch (error) {
84
+ if (!(error instanceof FsError)) throw error
85
+ return patchFailure(this.sandbox, this.policy, error, this.failurePath)
86
+ }
87
+ }
88
+
89
+ private async simulate(operation: PlannedOperation): Promise<PatchFailure | undefined> {
90
+ if (operation.kind === 'move' && operation.target.targetKey === operation.destination.targetKey) {
91
+ throw new FsError(`cannot move "${operation.target.displayPath}" to itself`, 'FS_SAME_TARGET')
92
+ }
93
+ if (operation.kind === 'delete' || operation.kind === 'move') {
94
+ const info = await this.ctx.fs.lstat(operation.rawPath, await sessionResolveOptions(this.ctx, this.exec))
95
+ if (info?.type === 'symlink') return { code: 'PATCH_SYMLINK_SOURCE',
96
+ message: `cannot ${operation.kind} "${operation.target.displayPath}": path is a symbolic link — operate on its target path instead` }
97
+ }
98
+ const state = await this.state(operation.target)
99
+ switch (operation.kind) {
100
+ case 'add':
101
+ await this.destination(state, operation.target)
102
+ this.publish(operation.target, operation.content)
103
+ return
104
+ case 'delete':
105
+ await this.source(state, operation.target, 'delete')
106
+ this.publish(operation.target)
107
+ return
108
+ case 'update':
109
+ case 'move': {
110
+ await this.source(state, operation.target, operation.kind === 'move' ? 'move' : 'edit')
111
+ if (operation.kind === 'move') {
112
+ this.failurePath = operation.destination.displayPath
113
+ await this.destination(await this.state(operation.destination), operation.destination)
114
+ this.failurePath = operation.target.displayPath
115
+ }
116
+ const result = applyHunks(await this.content(state, operation.target), operation.hunks)
117
+ if (!result.ok) {
118
+ const first = result.failure.pattern.slice(0, 1).join('')
119
+ const characters = Array.from(first)
120
+ const preview = characters.length > 80 ? `${characters.slice(0, 80).join('')}…` : first
121
+ return { code: 'FS_PATCH_MISMATCH', hunkLine: result.failure.hunkLineNumber,
122
+ message: `cannot patch "${operation.target.displayPath}": hunk at patch line ${result.failure.hunkLineNumber} (${result.failure.stage}) does not match — ${preview}` }
123
+ }
124
+ if (operation.kind === 'move') {
125
+ this.publish(operation.destination, result.after)
126
+ this.publish(operation.target)
127
+ } else this.publish(operation.target, result.after)
128
+ return
129
+ }
130
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
131
+ default: return assertNever(operation)
132
+ }
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Collect every independent preflight refusal while simulating only admitted operations.
138
+ * Sandbox containment is the provider's decision at commit, as for write and edit.
139
+ * @param ctx - filesystem service owner; reads never emit observations.
140
+ * @param sandbox - model-facing denial mapper.
141
+ * @param exec - observation actor and cancellation signal.
142
+ * @param policy - resolved confinement policy used to label refusals.
143
+ * @param operations - complete resolved operation plan.
144
+ * @returns refused operations in patch order; any refusal forbids the commit phase.
145
+ */
146
+ export async function preflightPatch(
147
+ ctx: Context, sandbox: FsSandboxController, exec: ToolExecution, policy: SandboxExecutionPolicy | undefined,
148
+ operations: readonly PlannedOperation[],
149
+ ): Promise<PatchRefusal[]> {
150
+ const preflight = new Preflight(ctx, sandbox, exec, policy)
151
+ const refusals: PatchRefusal[] = []
152
+ for (const operation of operations) {
153
+ const failure = await preflight.check(operation)
154
+ if (failure !== undefined) refusals.push({ operation: operation.record, failure })
155
+ }
156
+ return refusals
157
+ }
@@ -0,0 +1,88 @@
1
+ /** Internal patch outcomes, failure diagnostics, and operation-local plans. */
2
+ import type { FsErrorCode, FsTarget } from '@deepseek-ai/dsh-fs'
3
+ import type { PatchHunk } from '@deepseek-ai/dsh-fs-patch'
4
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
5
+
6
+ /** One request after the caller resolves its per-call sandbox policy. */
7
+ export interface PatchExecutionRequest {
8
+ /** Raw patch text from the model. */
9
+ patch: string
10
+ /** Resolved per-call policy; undefined under an unconfined backend. */
11
+ sandboxPolicy: SandboxExecutionPolicy | undefined
12
+ }
13
+
14
+ /** One file operation; unresolved paths retain their original patch spelling on resolution failure. */
15
+ export interface PatchOperationRecord {
16
+ /** Zero-based position in the patch. */
17
+ index: number
18
+ /** File effect represented by this operation. */
19
+ kind: 'add' | 'update' | 'delete' | 'move'
20
+ /** Source display path (created path for add), or raw patch path if resolution failed. */
21
+ path: string
22
+ /** Move destination display path, or raw patch path if it could not be resolved. */
23
+ destination?: string
24
+ /** One-based patch line of the operation header. */
25
+ patchLine: number
26
+ }
27
+
28
+ /** LF text before and after one effect; null means absence or an unavailable provider basis. */
29
+ export interface PatchFileChange {
30
+ /** Canonical absolute process path that changed. */
31
+ path: string
32
+ /** Previous text, or null for absence or an unavailable basis. */
33
+ before: string | null
34
+ /** Published text, or null after deletion. */
35
+ after: string | null
36
+ }
37
+
38
+ /** Filesystem failures plus syntax and disallowed symlink-source diagnostics. */
39
+ export type PatchFailureCode = FsErrorCode | 'PATCH_SYNTAX' | 'PATCH_SYMLINK_SOURCE'
40
+
41
+ /** Actionable diagnostic ready for model output. */
42
+ export interface PatchFailure {
43
+ /** Stable machine-readable reason. */
44
+ code: PatchFailureCode
45
+ /** Message after sandbox denial mapping and filesystem remediation. */
46
+ message: string
47
+ /** Patch line of an unmatched hunk. */
48
+ hunkLine?: number
49
+ }
50
+
51
+ /** One operation refused before any write. */
52
+ export interface PatchRefusal {
53
+ operation: PatchOperationRecord
54
+ failure: PatchFailure
55
+ }
56
+
57
+ /** Each operation retains completed effects even when a move fails halfway. */
58
+ export type PatchOperationOutcome =
59
+ | { status: 'completed'; operation: PatchOperationRecord; changes: PatchFileChange[] }
60
+ | { status: 'failed'; operation: PatchOperationRecord; failure: PatchFailure; changes: PatchFileChange[] }
61
+ | { status: 'unknown'; operation: PatchOperationRecord; failure: PatchFailure }
62
+ | { status: 'skipped'; operation: PatchOperationRecord }
63
+
64
+ /** Syntax and preflight refusals prevent all writes; a commit failure stops later operations. */
65
+ export type PatchExecutionReport =
66
+ | { phase: 'syntax'; failure: PatchFailure }
67
+ | { phase: 'preflight'; refusals: [PatchRefusal, ...PatchRefusal[]] }
68
+ | { phase: 'commit'; outcomes: PatchOperationOutcome[]; affectedPaths: string[]; cancelled: boolean }
69
+
70
+ /** Resolved operation with raw source spelling retained for no-follow inspection. */
71
+ export type PlannedOperation = {
72
+ record: PatchOperationRecord
73
+ target: FsTarget
74
+ rawPath: string
75
+ } & (
76
+ | { kind: 'add'; content: string }
77
+ | { kind: 'update'; hunks: readonly PatchHunk[] }
78
+ | { kind: 'delete' }
79
+ | { kind: 'move'; destination: FsTarget; hunks: readonly PatchHunk[] }
80
+ )
81
+
82
+ /** Resolved operations and path-resolution refusals in one parsed patch. */
83
+ export interface PatchPlan {
84
+ /** Resolved operations in patch order. */
85
+ operations: PlannedOperation[]
86
+ /** Resolution refusals; unresolvable paths retain their raw patch spelling. */
87
+ refusals: PatchRefusal[]
88
+ }