@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
package/src/diff.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Result-time contextual diff presentation for write and edit. Storage returns before/after
3
+ * text; this model-facing layer derives one three-line-context card per applied hunk.
4
+ * @module @deepseek-ai/dsh-tool-fs/src/diff
5
+ */
6
+
7
+ import { structuredPatch } from 'diff'
8
+ import type { FileDiff } from '@deepseek-ai/dsh-tools'
9
+
10
+ /** Context lines shown on each side of an applied hunk. */
11
+ export const DIFF_CONTEXT = 3
12
+
13
+ /**
14
+ * The `write`/`edit` tools' private `tool/result` `meta` payload: the applied
15
+ * contextual-diff hunks, and for `write` whether the call created or updated
16
+ * the file, which tells an empty hunk list of a create from one of an
17
+ * unchanged overwrite. Attached opaquely (as `unknown`) on the tool result and
18
+ * persisted with the session log — it must be JSON-serializable (the session
19
+ * validates this at `append`), so `presentResult` reproduces the diff card on
20
+ * replay. The producing tool owns and narrows this opaque shape.
21
+ */
22
+ export type FsDiffMeta = { diffs: FileDiff[]; operation?: 'create' | 'update' }
23
+
24
+ /**
25
+ * Compute one {@link FileDiff} per hunk between `before` and `after`, each carrying the
26
+ * applied change plus {@link DIFF_CONTEXT} context lines. Pure insertions use `oldText: null`,
27
+ * patch-only no-newline markers are omitted, and scattered replacements remain separate hunks.
28
+ *
29
+ * @param path - the path stamped on every produced diff (the model-facing `file_path`; the
30
+ * bridge relativizes it).
31
+ * @param before - the file text before the change (the backend's LF-normalized diff basis).
32
+ * @param after - the file text after the change, on the same basis.
33
+ * @returns one diff per applied hunk, in file order; empty when the texts are identical.
34
+ */
35
+ export function computeHunkDiffs(path: string, before: string, after: string): FileDiff[] {
36
+ const patch = structuredPatch('', '', before, after, undefined, undefined, { context: DIFF_CONTEXT })
37
+ const diffs: FileDiff[] = []
38
+ for (const hunk of patch.hunks) {
39
+ const oldLines: string[] = []
40
+ const newLines: string[] = []
41
+ for (const line of hunk.lines) {
42
+ // The unified-diff marker for a missing trailing newline annotates the
43
+ // patch, not the content — skip it so it never leaks into a diff block.
44
+ if (line.startsWith('\\')) continue
45
+ const text = line.slice(1)
46
+ if (line.startsWith('-')) {
47
+ oldLines.push(text)
48
+ } else if (line.startsWith('+')) {
49
+ newLines.push(text)
50
+ } else {
51
+ // A context (unchanged) line appears on both sides.
52
+ oldLines.push(text)
53
+ newLines.push(text)
54
+ }
55
+ }
56
+ diffs.push({ path, oldText: oldLines.length > 0 ? oldLines.join('\n') : null, newText: newLines.join('\n') })
57
+ }
58
+ return diffs
59
+ }
60
+
61
+ /** Whether `value` is a valid {@link FileDiff} (defensive narrowing from opaque `meta`). */
62
+ function isFileDiff(value: unknown): value is FileDiff {
63
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
64
+ const { path, oldText, newText } = value as Record<string, unknown>
65
+ return typeof path === 'string'
66
+ && (oldText === null || typeof oldText === 'string')
67
+ && typeof newText === 'string'
68
+ }
69
+
70
+ /**
71
+ * Narrow opaque live or replayed result metadata to non-empty file diffs. Malformed metadata
72
+ * returns `undefined` so presentation can fall back instead of throwing during replay.
73
+ * @param meta - result metadata.
74
+ * @returns validated hunks, or `undefined` for absent or malformed data.
75
+ */
76
+ export function diffsFromMeta(meta: unknown): FileDiff[] | undefined {
77
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined
78
+ const diffs = (meta as Record<string, unknown>).diffs
79
+ if (!Array.isArray(diffs) || diffs.length === 0 || !diffs.every(isFileDiff)) return undefined
80
+ return diffs
81
+ }
82
+
83
+ /**
84
+ * Narrow the patch tool's optional stopped flag from persisted metadata.
85
+ * @param meta - opaque live or replayed result metadata.
86
+ * @returns true only for an explicit stopped flag.
87
+ */
88
+ export function stoppedFromMeta(meta: unknown): boolean {
89
+ return typeof meta === 'object' && meta !== null && !Array.isArray(meta)
90
+ && (meta as Record<string, unknown>).stopped === true
91
+ }
92
+
93
+ /**
94
+ * Read the operation's file path even when the applied diff is empty.
95
+ * @param meta - opaque persisted result metadata.
96
+ * @returns the recorded path, or undefined for old or malformed metadata.
97
+ */
98
+ export function pathFromMeta(meta: unknown): string | undefined {
99
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined
100
+ const path = (meta as Record<string, unknown>).path
101
+ return typeof path === 'string' && path.length > 0 ? path : undefined
102
+ }
package/src/edit.ts ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Model-facing literal edit, unique-match by default. It obtains an optional guard from the
3
+ * single intent slot, calls `ctx.fs.editText` without a separate stat, then records the observed
4
+ * version; no policy means an unconditional atomic edit.
5
+ * @module @deepseek-ai/dsh-tool-fs/src/edit
6
+ */
7
+
8
+ import type { Context } from '@deepseek-ai/cordis'
9
+ import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools'
10
+ import type { DiffCallView, DiffResultView, ToolResult } from '@deepseek-ai/dsh-tools'
11
+ import type {} from '@deepseek-ai/dsh-fs'
12
+ import { computeHunkDiffs, diffsFromMeta } from './diff.ts'
13
+ import { remediateFsError } from './error.ts'
14
+ import { mutationResult } from './mutation-result.ts'
15
+ import { sessionResolveOptions } from './session-cwd.ts'
16
+ import type { FsSandboxController } from './sandbox.ts'
17
+
18
+ /** Validated `edit` arguments after defaulting. */
19
+ interface EditInput {
20
+ filePath: string
21
+ oldString: string
22
+ newString: string
23
+ replaceAll: boolean
24
+ }
25
+
26
+ /**
27
+ * The `edit` tool's validated arguments: the base parameters plus the two
28
+ * escalation fields, advertised only under a confining `ctx.fs` (absent from
29
+ * the schema otherwise, so the validator rejects them before `execute`).
30
+ */
31
+ interface EditToolArgs {
32
+ file_path: string
33
+ old_string: string
34
+ new_string: string
35
+ replace_all?: boolean
36
+ sandbox_permissions?: string
37
+ justification?: string
38
+ }
39
+
40
+ /**
41
+ * Validate value constraints the schema DSL can't express: a non-blank
42
+ * `file_path`, a non-empty `old_string`, and `old_string !== new_string`
43
+ * (an equal pair would be a guaranteed no-op edit).
44
+ * @param args - the schema-validated raw tool arguments.
45
+ * @returns the camelCased input with `replace_all` defaulted to false.
46
+ */
47
+ export function parseEditArgs(args: { file_path: string; old_string: string; new_string: string; replace_all?: boolean }): EditInput {
48
+ if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string'])
49
+ if (args.old_string.length === 0) throw new ToolArgsError(['old_string must be a non-empty string'])
50
+ if (args.old_string === args.new_string) throw new ToolArgsError(['old_string and new_string must differ'])
51
+ return {
52
+ filePath: args.file_path,
53
+ oldString: args.old_string,
54
+ newString: args.new_string,
55
+ replaceAll: args.replace_all ?? false,
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Format an edit success (single-match or replace-all) as a Claude-style model-facing message.
61
+ * @param displayPath - the backend-resolved path shown to the model.
62
+ * @param replaceAll - selects the all-occurrences wording over the single-replacement one.
63
+ * @returns the confirmation sentence the model sees as the tool result.
64
+ */
65
+ export function formatEditOutput(displayPath: string, replaceAll: boolean): string {
66
+ return replaceAll
67
+ ? `The file ${displayPath} has been updated. All occurrences were successfully replaced.`
68
+ : `The file ${displayPath} has been updated successfully.`
69
+ }
70
+
71
+ /**
72
+ * Register the `edit` tool and its scope-aware system-prompt guidance.
73
+ * @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
74
+ * @param sandbox - the shared sandbox-escalation API (advertisement, mode stamping, denial mapping).
75
+ */
76
+ export function applyEditTool(ctx: Context, sandbox: FsSandboxController): void {
77
+ ctx.systemPrompt.section({
78
+ name: 'tool:edit',
79
+ order: ctx.systemPrompt.getSectionOrder('TOOL_EDIT'),
80
+ text: ({ scope }) => ctx.tools.get('edit', scope) === undefined
81
+ ? ''
82
+ : 'Read a file before editing it unless you just created or edited it in this session.',
83
+ })
84
+
85
+ ctx.tools.register(defineTool({
86
+ name: 'edit',
87
+ description: 'Edit an existing UTF-8 text file by replacing literal text.',
88
+ parameters: {
89
+ file_path: {
90
+ type: 'string', required: true,
91
+ description: 'Path to edit, resolved by the filesystem backend. '
92
+ + 'Provide `file_path` before `old_string` and `new_string` in the arguments.',
93
+ },
94
+ old_string: { type: 'string', required: true, description: 'Literal text to replace.' },
95
+ new_string: { type: 'string', required: true, description: 'Literal replacement text. Use an empty string to delete the match.' },
96
+ replace_all: { type: 'boolean', description: 'Replace all matches. Defaults to false; when false, old_string must appear exactly once.' },
97
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {},
98
+ },
99
+ output: {
100
+ schema: {
101
+ type: 'object',
102
+ additionalProperties: false,
103
+ properties: {
104
+ path: { type: 'string', required: true, description: 'Canonical absolute path in the filesystem execution world.' },
105
+ before: { type: 'string', required: true },
106
+ after: { type: 'string', required: true },
107
+ },
108
+ },
109
+ render: (args, value) => [{
110
+ type: 'text',
111
+ text: formatEditOutput(value.path, args.replace_all ?? false),
112
+ }],
113
+ presentationMeta: (_args, value) => ({
114
+ path: value.path,
115
+ diffs: computeHunkDiffs(value.path, value.before, value.after)
116
+ .map(({ path, oldText, newText }) => ({ path, oldText, newText })),
117
+ }),
118
+ },
119
+ async execute(args: EditToolArgs, exec) {
120
+ const input = parseEditArgs(args)
121
+ // Resolve the per-call sandbox policy (approved mode > session override
122
+ // > backend default, plus the session cwd root) BEFORE anything executes.
123
+ const sandboxPolicy = await sandbox.resolvePolicy('edit', args, exec)
124
+ const target = await ctx.fs.resolve(input.filePath, await sessionResolveOptions(ctx, exec))
125
+ // Single-slot decision: the policy plugin returns { version: vObserved } or
126
+ // throws FS_NOT_OBSERVED; the bare default is undefined (unconditional edit).
127
+ // No stat — the bare default never manufactures a version basis. The intent
128
+ // slot itself can throw FS_NOT_OBSERVED for an unread target, so it sits
129
+ // inside the try: both that refusal and the provider's guarded-mutation
130
+ // failure get the model-facing remedy below.
131
+ let outcome
132
+ try {
133
+ const intent = await ctx.waterfall('fs/edit-intent', target, exec, () => undefined)
134
+ outcome = await ctx.fs.editText(
135
+ target,
136
+ { oldString: input.oldString, newString: input.newString, replaceAll: input.replaceAll },
137
+ intent,
138
+ exec.signal,
139
+ sandboxPolicy,
140
+ )
141
+ } catch (error: unknown) {
142
+ // A sandbox denial becomes the shared [sandbox: …] marker (the model
143
+ // recognizes it from bash); guarded mutation failures receive their
144
+ // stable model-facing diagnostic; anything else passes through.
145
+ throw remediateFsError(sandbox.mapError(error, sandboxPolicy), target.displayPath)
146
+ }
147
+ return mutationResult(ctx, target, outcome, exec)
148
+ },
149
+ // Pure display: a diff card of the literal replacement (old_string → new_string), derived
150
+ // from the call args. `oldText: old_string || null` matches claude-agent-acp's Edit arm;
151
+ // new_string is a required arg here, so it maps straight to newText.
152
+ presentCall(args): DiffCallView {
153
+ return {
154
+ card: 'diff',
155
+ title: `Edit ${args.file_path}`,
156
+ diffs: [{ path: args.file_path, oldText: args.old_string || null, newText: args.new_string }],
157
+ locations: [{ path: args.file_path }],
158
+ }
159
+ },
160
+ // Applied metadata replaces the call-time snippet; errors or malformed replay metadata use
161
+ // the generic result rendering.
162
+ presentResult(args, result: ToolResult): DiffResultView | undefined {
163
+ if (result.isError) return undefined
164
+ const diffs = diffsFromMeta(result.meta)
165
+ if (diffs === undefined) return undefined
166
+ return { card: 'diff', title: `Edit ${args.file_path}`, diffs }
167
+ },
168
+ }))
169
+ }
package/src/error.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Model-facing diagnostics for guarded-mutation failures. Providers and
3
+ * policies retain operation-specific causes, while this package owns the
4
+ * stable message shown to the model.
5
+ * @module @deepseek-ai/dsh-tool-fs/src/error
6
+ */
7
+
8
+ import { FsError } from '@deepseek-ai/dsh-fs'
9
+
10
+ /**
11
+ * Render the stable model-facing diagnostic for a guarded-mutation failure.
12
+ * `FS_STALE_VERSION` keeps the provider's reason and appends its re-read
13
+ * remedy. `FS_NOT_OBSERVED` replaces operation-specific policy/provider text
14
+ * with one path-aware reason and read remedy. The original error remains the
15
+ * cause, and both diagnostics preserve its code for machine routing. Anything
16
+ * else passes through untouched.
17
+ * @param error - the caught value from a write/edit execution.
18
+ * @param displayPath - the resolved target path shown to the model.
19
+ * @returns a remediated `FsError` for the two guarded-mutation codes, else the original value.
20
+ */
21
+ export function remediateFsError(error: FsError, displayPath: string): FsError
22
+ /**
23
+ * Remediate a caught value, preserving non-filesystem failures.
24
+ * @param error - value thrown by an execution.
25
+ * @param displayPath - resolved target path shown to the model.
26
+ * @returns a remediated filesystem error, or the unchanged caught value.
27
+ */
28
+ export function remediateFsError(error: unknown, displayPath: string): unknown
29
+ export function remediateFsError(error: unknown, displayPath: string): unknown {
30
+ if (!(error instanceof FsError)) return error
31
+ if (error.code === 'FS_NOT_OBSERVED') {
32
+ return new FsError(
33
+ `cannot modify "${displayPath}": file has not been read — read the file, then retry`,
34
+ error.code,
35
+ { cause: error },
36
+ )
37
+ }
38
+ if (error.code === 'FS_STALE_VERSION') {
39
+ return new FsError(`${error.message} — re-read the file, then retry`, error.code, { cause: error })
40
+ }
41
+ return error
42
+ }
@@ -0,0 +1,36 @@
1
+ /** Typed `read_image` failures. @module @deepseek-ai/dsh-tool-fs/src/image-error */
2
+
3
+ import { HarnessError } from '@deepseek-ai/dsh-error'
4
+
5
+ /**
6
+ * Every `read_image` failure the tool classifies itself, before the attachment store sees the bytes:
7
+ *
8
+ * - `IMAGE_UNSUPPORTED_MODEL`: the calling route does not declare image input; switch to an image-capable model.
9
+ * - `IMAGE_UNSUPPORTED_FORMAT`: the extension, the file signature, or the deployment's accepted media types
10
+ * exclude the format; convert the file to an accepted format or read another file.
11
+ *
12
+ * Failures the attachment store classifies keep their `AttachmentError` codes.
13
+ */
14
+ export const IMAGE_INPUT_ERROR_CODES = [
15
+ 'IMAGE_UNSUPPORTED_MODEL',
16
+ 'IMAGE_UNSUPPORTED_FORMAT',
17
+ ] as const
18
+
19
+ /** One `read_image` failure code. */
20
+ export type ImageInputErrorCode = typeof IMAGE_INPUT_ERROR_CODES[number]
21
+
22
+ /** Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. */
23
+ export class ImageInputError extends HarnessError {
24
+ override readonly code: ImageInputErrorCode
25
+
26
+ /**
27
+ * @param message - model-facing refusal naming the path and the safe next step.
28
+ * @param code - stable failure code.
29
+ * @param options - standard `cause` chaining.
30
+ */
31
+ constructor(message: string, code: ImageInputErrorCode, options?: ErrorOptions) {
32
+ super(message, code, options)
33
+ this.name = 'ImageInputError'
34
+ this.code = code
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Model-facing read, read_image, write, edit, and apply_patch tools over `ctx.fs`. This package owns schemas, validation,
3
+ * read windows, formatting, and observation events, never a concrete provider. An optional
4
+ * event policy supplies mutation guards; without one the tools use unconditional provider calls.
5
+ * @module @deepseek-ai/dsh-tool-fs
6
+ */
7
+
8
+ import type {} from '@deepseek-ai/dsh-working-directory'
9
+ import type { Context } from '@deepseek-ai/cordis'
10
+ import z from '@deepseek-ai/schemastery'
11
+ import type {} from '@deepseek-ai/dsh-user-approval'
12
+ import { applyReadTool, READ_LIMIT, STREAM_MIN_SIZE } from './read.ts'
13
+ import { applyWriteTool } from './write.ts'
14
+ import { applyApplyPatchTool } from './apply-patch.ts'
15
+ import { applyEditTool } from './edit.ts'
16
+ import { applyReadImageTool } from './read-image.ts'
17
+ import { READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from './read-render.ts'
18
+ import { FsSandboxController } from './sandbox.ts'
19
+
20
+ /** Cordis plugin name used by loader diagnostics. */
21
+ export const name = 'tool-fs'
22
+
23
+ /** Services required by the filesystem tool suite. */
24
+ export const inject = ['tools', 'fs', 'systemPrompt', 'workingDirectory']
25
+
26
+ /** Plugin config (all optional — `Config` supplies the defaults). */
27
+ export interface Config {
28
+ /** Register `read` and its guidance. Defaults to true. */
29
+ read?: boolean
30
+ /** Register `read_image` while an attachment store is mounted. Defaults to true. */
31
+ readImage?: boolean
32
+ /** Register `write` and its guidance. Defaults to true. */
33
+ write?: boolean
34
+ /** Register `edit` and its guidance. Defaults to true. */
35
+ edit?: boolean
36
+ /** Register `apply_patch` and its guidance beside `edit`. Defaults to false; shipped compositions set it on their `tool-fs` rows. */
37
+ applyPatch?: boolean
38
+ /** Default and maximum number of lines returned by one `read` call. */
39
+ readLimit?: number
40
+ /** Maximum characters returned for a single line before truncation. */
41
+ readMaxLineLength?: number
42
+ /** Maximum bytes returned for the selected lines of one `read` call. */
43
+ readMaxBytes?: number
44
+ /** Files at or above this size stream instead of loading whole into memory. */
45
+ readStreamMinSize?: number
46
+ }
47
+
48
+ export const Config: z<Config> = z.object({
49
+ read: z.boolean().default(true),
50
+ readImage: z.boolean().default(true),
51
+ write: z.boolean().default(true),
52
+ edit: z.boolean().default(true),
53
+ applyPatch: z.boolean().default(false),
54
+ readLimit: z.number().default(READ_LIMIT),
55
+ readMaxLineLength: z.number().default(READ_MAX_LINE_LENGTH),
56
+ readMaxBytes: z.number().default(READ_MAX_BYTES),
57
+ readStreamMinSize: z.number().default(STREAM_MIN_SIZE),
58
+ })
59
+
60
+ /** Configuration after schemastery applied the defaults. */
61
+ type ResolvedConfig = Required<Config>
62
+
63
+ /** Every read cap counts lines/chars/bytes — a positive integer, or windowing arithmetic misbehaves silently. */
64
+ function assertPositiveInteger(name: string, value: number): void {
65
+ if (!Number.isInteger(value) || value < 1) {
66
+ throw new Error(`tool-fs: ${name} must be a positive integer`)
67
+ }
68
+ }
69
+
70
+ /** Register the selected filesystem tools; `read_image` additionally requires a mounted attachment store. */
71
+ export function apply(ctx: Context, config: Config): void {
72
+ // schemastery (Config) has already filled every defaulted field.
73
+ const resolved = config as ResolvedConfig
74
+ assertPositiveInteger('readLimit', resolved.readLimit)
75
+ assertPositiveInteger('readMaxLineLength', resolved.readMaxLineLength)
76
+ assertPositiveInteger('readMaxBytes', resolved.readMaxBytes)
77
+ assertPositiveInteger('readStreamMinSize', resolved.readStreamMinSize)
78
+ if (resolved.read) {
79
+ applyReadTool(ctx, {
80
+ limit: resolved.readLimit,
81
+ maxLineLength: resolved.readMaxLineLength,
82
+ maxBytes: resolved.readMaxBytes,
83
+ streamMinSize: resolved.readStreamMinSize,
84
+ })
85
+ }
86
+ // read_image is composition-conditional: without a mounted attachment store
87
+ // the deployment cannot durably commit image bytes, so the tool never
88
+ // registers; the execute body keeps a defensive re-check for direct callers.
89
+ if (resolved.readImage) {
90
+ ctx.inject(['attachments'], (imageCtx) => {
91
+ applyReadImageTool(imageCtx)
92
+ })
93
+ }
94
+ // One escalation API shared by the mutating tools: advertisement gating,
95
+ // per-call policy resolution, and denial-marker mapping, all keyed off whether
96
+ // the mounted ctx.fs confines (ctx.fs.sandboxMode).
97
+ if (resolved.write || resolved.edit || resolved.applyPatch) {
98
+ const sandbox = new FsSandboxController(ctx)
99
+ if (resolved.write) applyWriteTool(ctx, sandbox)
100
+ if (resolved.edit) applyEditTool(ctx, sandbox)
101
+ if (resolved.applyPatch) applyApplyPatchTool(ctx, sandbox)
102
+ }
103
+ }
@@ -0,0 +1,21 @@
1
+ /** Shared observation and result fields for successful file mutations. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { FsTarget, FsVersion } from '@deepseek-ai/dsh-fs'
5
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
6
+
7
+ /**
8
+ * Record the new file version and expose the mutation result with its canonical path.
9
+ * @param ctx - filesystem and observation event owner.
10
+ * @param target - resolved file that was mutated.
11
+ * @param outcome - successful provider result; its version stays in the observation event.
12
+ * @param exec - calling tool execution.
13
+ * @returns the provider's result fields without the version, plus the canonical absolute path.
14
+ */
15
+ export function mutationResult<T extends { version: FsVersion }>(
16
+ ctx: Context, target: FsTarget, outcome: T, exec: ToolExecution,
17
+ ): Omit<T, 'version'> & { path: string } {
18
+ const { version, ...result } = outcome
19
+ ctx.emit('fs/observed', target, { kind: 'present', version }, exec)
20
+ return { path: ctx.fs.processPath(target), ...result }
21
+ }
@@ -0,0 +1,121 @@
1
+ /** Sequential provider commits with truthful partial results and uncertainty checks. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { FsError } from '@deepseek-ai/dsh-fs'
4
+ import type { FsInfo, FsTarget } from '@deepseek-ai/dsh-fs'
5
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
6
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
7
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
8
+ import type { FsSandboxController } from '../sandbox.ts'
9
+ import { destinationIntent, mutationTargets, patchFailure, sourceIntent } from './plan.ts'
10
+ import type { PatchExecutionReport, PatchOperationOutcome, PlannedOperation } from './types.ts'
11
+
12
+ interface BeforeTarget {
13
+ target: FsTarget
14
+ info: FsInfo | undefined
15
+ }
16
+
17
+ async function unchanged(ctx: Context, before: readonly BeforeTarget[]): Promise<boolean> {
18
+ try {
19
+ for (const entry of before) {
20
+ // An aborted tool signal must not cancel the independent outcome check.
21
+ const after = await ctx.fs.stat(entry.target)
22
+ if (after?.version !== entry.info?.version) return false
23
+ }
24
+ return true
25
+ } catch (error) {
26
+ if (!(error instanceof FsError)) throw error
27
+ return false
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Commit a fully admitted plan; the first failure stops later operations without rollback.
33
+ * @param ctx - provider and observation dispatcher.
34
+ * @param sandbox - existing model-facing denial mapper.
35
+ * @param exec - session actor and cancellation signal.
36
+ * @param policy - request's resolved confinement policy.
37
+ * @param operations - operations that all passed preflight.
38
+ * @returns known changes, failed or unknown effects, and skipped successors in patch order.
39
+ */
40
+ export async function commitPatch(
41
+ ctx: Context, sandbox: FsSandboxController, exec: ToolExecution, policy: SandboxExecutionPolicy | undefined,
42
+ operations: readonly PlannedOperation[],
43
+ ): Promise<PatchExecutionReport> {
44
+ const outcomes: PatchOperationOutcome[] = operations.map(operation => ({ status: 'skipped', operation: operation.record }))
45
+ let cancelled = false
46
+ for (const [index, operation] of operations.entries()) {
47
+ if (exec.signal.aborted) { cancelled = true; break }
48
+ let started = false
49
+ let before: BeforeTarget[] = []
50
+ let failurePath = operation.target.displayPath
51
+ const target = operation.target
52
+ const record = operation.record
53
+ let outcome: PatchOperationOutcome
54
+ try {
55
+ before = await Promise.all(mutationTargets(operation).map(async target => ({ target, info: await ctx.fs.stat(target, exec.signal) })))
56
+ switch (operation.kind) {
57
+ case 'add': {
58
+ const intent = await destinationIntent(ctx, exec, target)
59
+ started = true
60
+ const result = await ctx.fs.writeText(target, operation.content, intent, exec.signal, policy)
61
+ ctx.emit('fs/observed', target, { kind: 'present', version: result.version }, exec)
62
+ outcome = { status: 'completed', operation: record, changes: [{ path: ctx.fs.processPath(target), before: result.before, after: result.after }] }
63
+ break
64
+ }
65
+ case 'update': {
66
+ const intent = await sourceIntent(ctx, exec, target, 'edit')
67
+ started = true
68
+ const result = await ctx.fs.patchText(target, operation.hunks, intent, exec.signal, policy)
69
+ ctx.emit('fs/observed', target, { kind: 'present', version: result.version }, exec)
70
+ outcome = { status: 'completed', operation: record, changes: [{ path: ctx.fs.processPath(target), before: result.before, after: result.after }] }
71
+ break
72
+ }
73
+ case 'delete': {
74
+ const intent = await sourceIntent(ctx, exec, target, 'delete')
75
+ started = true
76
+ const result = await ctx.fs.deleteFile(target, intent, exec.signal, policy)
77
+ ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
78
+ outcome = { status: 'completed', operation: record, changes: [{ path: ctx.fs.processPath(target), before: result.before, after: null }] }
79
+ break
80
+ }
81
+ case 'move': {
82
+ const expectedSource = await sourceIntent(ctx, exec, target, 'edit')
83
+ failurePath = operation.destination.displayPath
84
+ const expectedDestination = await destinationIntent(ctx, exec, operation.destination)
85
+ started = true
86
+ const result = await ctx.fs.moveFile(target, operation.destination, {
87
+ hunks: operation.hunks,
88
+ ...(expectedSource === undefined ? {} : { expectedSource }),
89
+ ...(expectedDestination === undefined ? {} : { expectedDestination }),
90
+ }, exec.signal, policy)
91
+ const changes = [{ path: ctx.fs.processPath(operation.destination),
92
+ before: result.destination.before, after: result.destination.after }]
93
+ ctx.emit('fs/observed', operation.destination, { kind: 'present', version: result.destination.version }, exec)
94
+ if (result.sourceDeleted) {
95
+ ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
96
+ outcome = { status: 'completed', operation: record, changes: [...changes, { path: ctx.fs.processPath(target), before: result.sourceBefore, after: null }] }
97
+ } else {
98
+ const error = new FsError(result.sourceFailure.message, result.sourceFailure.code)
99
+ outcome = { status: 'failed', operation: record, failure: patchFailure(sandbox, policy, error, target.displayPath), changes }
100
+ }
101
+ break
102
+ }
103
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
104
+ default: assertNever(operation)
105
+ }
106
+ } catch (error) {
107
+ if (!(error instanceof FsError)) throw error
108
+ const failure = patchFailure(sandbox, policy, error, failurePath)
109
+ // A cancelled remote request rejects while the provider may still be writing, so no
110
+ // stat can settle an aborted mutation; an I/O failure is settled by unchanged versions.
111
+ const uncertain = started && (error.code === 'FS_ABORTED' || (error.code === 'FS_IO_ERROR' && !await unchanged(ctx, before)))
112
+ outcome = uncertain
113
+ ? { status: 'unknown', operation: record, failure: { ...failure, message: `${failure.message} — re-read the affected files before retrying` } }
114
+ : { status: 'failed', operation: record, failure, changes: [] }
115
+ }
116
+ outcomes[index] = outcome
117
+ if (outcome.status !== 'completed') { cancelled = exec.signal.aborted; break }
118
+ }
119
+ const affectedPaths = [...new Set(outcomes.flatMap(outcome => 'changes' in outcome ? outcome.changes.map(change => change.path) : []))]
120
+ return { phase: 'commit', outcomes, affectedPaths, cancelled }
121
+ }
@@ -0,0 +1,36 @@
1
+ /** Internal patch executor; tool registration and persisted result metadata are owned by its caller. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { PatchParseError } from '@deepseek-ai/dsh-fs-patch'
4
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
5
+ import type { FsSandboxController } from '../sandbox.ts'
6
+ import { commitPatch } from './execute.ts'
7
+ import { planPatch } from './plan.ts'
8
+ import { preflightPatch } from './preflight.ts'
9
+ import type { PatchExecutionReport, PatchExecutionRequest } from './types.ts'
10
+
11
+ export type { PatchExecutionReport, PatchExecutionRequest, PatchFailure, PatchFailureCode, PatchFileChange, PatchOperationOutcome, PatchOperationRecord, PatchRefusal } from './types.ts'
12
+
13
+ /**
14
+ * Preflight a whole patch before sequential guarded mutations; business failures become records.
15
+ * @param ctx - mounted filesystem and observation-policy events.
16
+ * @param sandbox - denial mapper shared with existing filesystem tools.
17
+ * @param exec - session cwd, observation actor, and cancellation signal.
18
+ * @param request - raw patch and policy already resolved by the caller.
19
+ * @returns the syntax failure, the preflight refusals, or ordered commit outcomes.
20
+ * @throws unexpected programming defects without starting further operations.
21
+ */
22
+ export async function executePatch(
23
+ ctx: Context, sandbox: FsSandboxController, exec: ToolExecution, request: PatchExecutionRequest,
24
+ ): Promise<PatchExecutionReport> {
25
+ let plan
26
+ try { plan = await planPatch(ctx, sandbox, exec, request) } catch (error) {
27
+ if (!(error instanceof PatchParseError)) throw error
28
+ return { phase: 'syntax', failure: { code: 'PATCH_SYNTAX', message: error.message } }
29
+ }
30
+ const [first, ...rest] = [
31
+ ...plan.refusals,
32
+ ...await preflightPatch(ctx, sandbox, exec, request.sandboxPolicy, plan.operations),
33
+ ].sort((left, right) => left.operation.index - right.operation.index)
34
+ if (first !== undefined) return { phase: 'preflight', refusals: [first, ...rest] }
35
+ return commitPatch(ctx, sandbox, exec, request.sandboxPolicy, plan.operations)
36
+ }