@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.
- package/README.i18n.yaml +10 -10
- package/README.md +8 -5
- package/README.zh.md +8 -5
- package/lib/index.js +85 -28
- package/lib/types/apply-patch-output.d.ts.map +1 -0
- package/lib/types/apply-patch-output.js.map +1 -0
- package/lib/types/apply-patch-presentation.d.ts.map +1 -0
- package/lib/types/apply-patch-presentation.js.map +1 -0
- package/lib/types/apply-patch.d.ts +1 -1
- package/lib/types/apply-patch.d.ts.map +1 -0
- package/lib/types/apply-patch.js.map +1 -0
- package/lib/types/diff.d.ts.map +1 -0
- package/lib/types/diff.js.map +1 -0
- package/lib/types/edit.d.ts.map +1 -0
- package/lib/types/edit.js.map +1 -0
- package/lib/types/error.d.ts.map +1 -0
- package/lib/types/error.js.map +1 -0
- package/lib/types/image-error.d.ts +25 -0
- package/lib/types/image-error.d.ts.map +1 -0
- package/lib/types/image-error.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/mutation-result.d.ts.map +1 -0
- package/lib/types/mutation-result.js.map +1 -0
- package/lib/types/patch/execute.d.ts.map +1 -0
- package/lib/types/patch/execute.js.map +1 -0
- package/lib/types/patch/index.d.ts.map +1 -0
- package/lib/types/patch/index.js.map +1 -0
- package/lib/types/patch/plan.d.ts.map +1 -0
- package/lib/types/patch/plan.js.map +1 -0
- package/lib/types/patch/preflight.d.ts.map +1 -0
- package/lib/types/patch/preflight.js.map +1 -0
- package/lib/types/patch/types.d.ts.map +1 -0
- package/lib/types/patch/types.js.map +1 -0
- package/lib/types/read-image.d.ts +2 -0
- package/lib/types/read-image.d.ts.map +1 -0
- package/lib/types/read-image.js.map +1 -0
- package/lib/types/read-render.d.ts.map +1 -0
- package/lib/types/read-render.js.map +1 -0
- package/lib/types/read-target.d.ts.map +1 -0
- package/lib/types/read-target.js.map +1 -0
- package/lib/types/read.d.ts.map +1 -0
- package/lib/types/read.js.map +1 -0
- package/lib/types/sandbox.d.ts.map +1 -0
- package/lib/types/sandbox.js.map +1 -0
- package/lib/types/session-cwd.d.ts.map +1 -0
- package/lib/types/session-cwd.js.map +1 -0
- package/lib/types/write.d.ts.map +1 -0
- package/lib/types/write.js.map +1 -0
- package/package.json +47 -42
- package/src/apply-patch-output.ts +149 -0
- package/src/apply-patch-presentation.ts +47 -0
- package/src/apply-patch.ts +52 -0
- package/src/diff.ts +102 -0
- package/src/edit.ts +169 -0
- package/src/error.ts +42 -0
- package/src/image-error.ts +36 -0
- package/src/index.ts +103 -0
- package/src/mutation-result.ts +21 -0
- package/src/patch/execute.ts +121 -0
- package/src/patch/index.ts +36 -0
- package/src/patch/plan.ts +117 -0
- package/src/patch/preflight.ts +157 -0
- package/src/patch/types.ts +88 -0
- package/src/read-image.ts +391 -0
- package/src/read-render.ts +244 -0
- package/src/read-target.ts +34 -0
- package/src/read.ts +210 -0
- package/src/sandbox.ts +145 -0
- package/src/session-cwd.ts +25 -0
- package/src/write.ts +153 -0
package/src/read.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing UTF-8 read. It performs one provider stat for type, routing, and observed version,
|
|
3
|
+
* streams large or size-unknown files, renders a bounded window, then emits the observation.
|
|
4
|
+
* @module @deepseek-ai/dsh-tool-fs/src/read
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
8
|
+
import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools'
|
|
9
|
+
import type { GenericCallView, ReadResultView, ToolResult } from '@deepseek-ai/dsh-tools'
|
|
10
|
+
import type {} from '@deepseek-ai/dsh-fs'
|
|
11
|
+
import { buildWindow, formatReadOutput, langFromPath, readMetaFromMeta } from './read-render.ts'
|
|
12
|
+
import { resolveRegularReadTarget } from './read-target.ts'
|
|
13
|
+
|
|
14
|
+
/** Default and maximum number of lines returned by one `read` call (the `readLimit` config). */
|
|
15
|
+
export const READ_LIMIT = 2000
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Default streaming threshold (the `readStreamMinSize` config): files at or
|
|
19
|
+
* above this size stream; smaller files read whole into memory.
|
|
20
|
+
*/
|
|
21
|
+
export const STREAM_MIN_SIZE = 10 * 1024 * 1024
|
|
22
|
+
|
|
23
|
+
/** Resolved read-tool caps — plugin config after defaulting (see `Config` in index.ts). */
|
|
24
|
+
export interface ReadToolCaps {
|
|
25
|
+
/** Default and maximum number of lines returned by one call. */
|
|
26
|
+
limit: number
|
|
27
|
+
/** Maximum characters returned for a single line. */
|
|
28
|
+
maxLineLength: number
|
|
29
|
+
/** Maximum bytes returned for selected file lines. */
|
|
30
|
+
maxBytes: number
|
|
31
|
+
/** Files at or above this size stream; smaller files read whole into memory. */
|
|
32
|
+
streamMinSize: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Validated `read` arguments after defaulting. */
|
|
36
|
+
interface ReadInput {
|
|
37
|
+
filePath: string
|
|
38
|
+
offset: number
|
|
39
|
+
limit: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parsePositiveInteger(value: number, name: string): number {
|
|
43
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) {
|
|
44
|
+
throw new ToolArgsError([`${name} must be a positive integer`])
|
|
45
|
+
}
|
|
46
|
+
return value
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Validate value constraints the schema DSL can't express. `maxLimit` is the deployment's line cap.
|
|
51
|
+
* @param args - the schema-validated raw tool arguments; `offset`/`limit` must be positive integers when given.
|
|
52
|
+
* @param maxLimit - the configured line cap: both the default `limit` and the largest one accepted.
|
|
53
|
+
* @returns the validated input with `offset` defaulted to 1 and `limit` to `maxLimit`.
|
|
54
|
+
*/
|
|
55
|
+
export function parseReadArgs(args: { file_path: string; offset?: number; limit?: number }, maxLimit: number): ReadInput {
|
|
56
|
+
if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string'])
|
|
57
|
+
const offset = args.offset === undefined ? 1 : parsePositiveInteger(args.offset, 'offset')
|
|
58
|
+
const limit = args.limit === undefined ? maxLimit : parsePositiveInteger(args.limit, 'limit')
|
|
59
|
+
if (limit > maxLimit) throw new ToolArgsError([`limit must be less than or equal to ${maxLimit}`])
|
|
60
|
+
return { filePath: args.file_path, offset, limit }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Register the `read` tool and its scope-aware system-prompt guidance.
|
|
65
|
+
* @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
|
|
66
|
+
* @param caps - the deployment's resolved read caps (plugin config after defaulting).
|
|
67
|
+
*/
|
|
68
|
+
export function applyReadTool(ctx: Context, caps: ReadToolCaps): void {
|
|
69
|
+
ctx.systemPrompt.section({
|
|
70
|
+
name: 'tool:read',
|
|
71
|
+
order: ctx.systemPrompt.getSectionOrder('TOOL_READ'),
|
|
72
|
+
text: ({ scope }) => ctx.tools.get('read', scope) === undefined
|
|
73
|
+
? ''
|
|
74
|
+
: 'Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.',
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
ctx.tools.register(defineTool({
|
|
78
|
+
name: 'read',
|
|
79
|
+
description: 'Read a UTF-8 text file and return line-numbered content.',
|
|
80
|
+
parameters: {
|
|
81
|
+
file_path: { type: 'string', required: true, description: 'Path to read, resolved by the filesystem backend.' },
|
|
82
|
+
offset: { type: 'number', description: '1-based first line to return. Defaults to 1.' },
|
|
83
|
+
limit: { type: 'number', description: `Maximum number of lines to return. Defaults to ${caps.limit}.` },
|
|
84
|
+
},
|
|
85
|
+
output: {
|
|
86
|
+
schema: {
|
|
87
|
+
type: 'object',
|
|
88
|
+
additionalProperties: false,
|
|
89
|
+
properties: {
|
|
90
|
+
path: { type: 'string', required: true, description: 'Canonical absolute path in the filesystem execution world.' },
|
|
91
|
+
offset: { type: 'integer', required: true },
|
|
92
|
+
lines: {
|
|
93
|
+
type: 'array',
|
|
94
|
+
required: true,
|
|
95
|
+
items: {
|
|
96
|
+
type: 'object',
|
|
97
|
+
additionalProperties: false,
|
|
98
|
+
properties: {
|
|
99
|
+
number: { type: 'integer', required: true },
|
|
100
|
+
text: { type: 'string', required: true },
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
totalLines: { type: 'integer', required: true },
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
render: (args, value) => {
|
|
108
|
+
const input = parseReadArgs(args, caps.limit)
|
|
109
|
+
const endLine = value.lines.at(-1)?.number ?? Math.max(0, value.offset - 1)
|
|
110
|
+
const truncatedByBytes = value.lines.length < input.limit && endLine < value.totalLines
|
|
111
|
+
return [{
|
|
112
|
+
type: 'text',
|
|
113
|
+
text: formatReadOutput(value.path, {
|
|
114
|
+
offset: value.offset,
|
|
115
|
+
lines: value.lines,
|
|
116
|
+
totalLines: value.totalLines,
|
|
117
|
+
...truncatedByBytes ? { truncatedByBytes: true } : {},
|
|
118
|
+
}),
|
|
119
|
+
}]
|
|
120
|
+
},
|
|
121
|
+
// Project the structured window into persisted `meta` so a UI's read card
|
|
122
|
+
// survives replay: the raw canonical output object is not on the wire, only
|
|
123
|
+
// the model-facing text, from which the line/lang data cannot be recovered.
|
|
124
|
+
presentationMeta: (_args, value) => {
|
|
125
|
+
const lang = langFromPath(value.path)
|
|
126
|
+
return {
|
|
127
|
+
path: value.path,
|
|
128
|
+
offset: value.offset,
|
|
129
|
+
lines: value.lines.map(({ number, text }) => ({ number, text })),
|
|
130
|
+
totalLines: value.totalLines,
|
|
131
|
+
...lang === undefined ? {} : { lang },
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
// Observation races fail closed because guarded mutations re-check the version in-lock.
|
|
136
|
+
isConcurrencySafe: () => true,
|
|
137
|
+
async execute(args, exec) {
|
|
138
|
+
const input = parseReadArgs(args, caps.limit)
|
|
139
|
+
// One stat: absence observation OR type check + size routing + present version.
|
|
140
|
+
// A concurrent write can only make a later guarded mutation fail stale and require reread.
|
|
141
|
+
const { target, info } = await resolveRegularReadTarget(ctx, exec, input.filePath)
|
|
142
|
+
|
|
143
|
+
// Stream when the file is large OR size is unknown, so a size-less backend
|
|
144
|
+
// never buffers an arbitrarily large file.
|
|
145
|
+
const chunks = info.size === undefined || info.size >= caps.streamMinSize
|
|
146
|
+
? await ctx.fs.streamText(target, exec.signal)
|
|
147
|
+
: [await ctx.fs.readText(target, exec.signal)]
|
|
148
|
+
const window = await buildWindow(
|
|
149
|
+
chunks,
|
|
150
|
+
{ offset: input.offset, limit: input.limit, maxLineLength: caps.maxLineLength, maxBytes: caps.maxBytes },
|
|
151
|
+
target.displayPath,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
const outcome = {
|
|
155
|
+
path: ctx.fs.processPath(target),
|
|
156
|
+
offset: input.offset,
|
|
157
|
+
lines: window.lines,
|
|
158
|
+
totalLines: window.totalLines,
|
|
159
|
+
}
|
|
160
|
+
// Record the present observation (a no-op when no policy plugin listens). The
|
|
161
|
+
// read already succeeded; an fs/observed listener is contractually a
|
|
162
|
+
// synchronous, side-effect-only recorder.
|
|
163
|
+
ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec)
|
|
164
|
+
return outcome
|
|
165
|
+
},
|
|
166
|
+
// Result-time display: a `read` card carrying the structured line window a
|
|
167
|
+
// capable UI renders as a line-numbered, syntax-highlighted view. The
|
|
168
|
+
// structured data is narrowed from the persisted `meta` (replay-safe); the
|
|
169
|
+
// envelope-stripped model-facing text rides along as `content` so a UI without
|
|
170
|
+
// the read capability still shows the file text. A malformed or absent meta,
|
|
171
|
+
// or a result whose text is not the read envelope, declines to `undefined`
|
|
172
|
+
// (the generic fallback), never throwing on replay of obsolete logged output.
|
|
173
|
+
presentResult(_args, result: ToolResult): ReadResultView | undefined {
|
|
174
|
+
if (result.isError) return undefined
|
|
175
|
+
const meta = readMetaFromMeta(result.meta)
|
|
176
|
+
if (meta === undefined) return undefined
|
|
177
|
+
const only = result.content.length === 1 ? result.content[0] : undefined
|
|
178
|
+
const text = only?.type === 'text' ? only.text : undefined
|
|
179
|
+
if (text === undefined) return undefined
|
|
180
|
+
// Group 1 always captures (possibly empty) when the envelope matches.
|
|
181
|
+
const body = /^<path>[^\n]*<\/path>\n<type>file<\/type>\n<content>\n([\s\S]*)\n<\/content>$/u.exec(text)?.[1]
|
|
182
|
+
if (body === undefined) return undefined
|
|
183
|
+
return {
|
|
184
|
+
card: 'read',
|
|
185
|
+
path: meta.path,
|
|
186
|
+
offset: meta.offset,
|
|
187
|
+
lines: meta.lines,
|
|
188
|
+
totalLines: meta.totalLines,
|
|
189
|
+
...meta.lang === undefined ? {} : { lang: meta.lang },
|
|
190
|
+
content: [{ type: 'text', text: body }],
|
|
191
|
+
}
|
|
192
|
+
},
|
|
193
|
+
// Pure display: a generic card titled by the file with the read window appended (`Read
|
|
194
|
+
// foo.txt (5 - 8)`), `read` kind (icon), and a follow-along location whose line is the
|
|
195
|
+
// read's offset (defaulting to 1). The window reflects raw args, so an omitted limit keeps
|
|
196
|
+
// the title bare instead of smuggling config into this pure presenter.
|
|
197
|
+
presentCall(args): GenericCallView {
|
|
198
|
+
const { offset, limit } = args
|
|
199
|
+
const window = limit !== undefined && limit > 0
|
|
200
|
+
? ` (${offset ?? 1} - ${(offset ?? 1) + limit - 1})`
|
|
201
|
+
: offset !== undefined ? ` (from line ${offset})` : ''
|
|
202
|
+
return {
|
|
203
|
+
card: 'generic',
|
|
204
|
+
title: `Read ${args.file_path}${window}`,
|
|
205
|
+
kind: 'read',
|
|
206
|
+
locations: [{ path: args.file_path, line: offset ?? 1 }],
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
}))
|
|
210
|
+
}
|
package/src/sandbox.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sandbox-escalation API shared by the `write` and `edit` tools: the
|
|
3
|
+
* per-call policy resolution, the advertised escalation fields, and the denial-marker
|
|
4
|
+
* mapping — all delegating the vocabulary and the fail-closed approval
|
|
5
|
+
* sequence to `@deepseek-ai/dsh-sandbox` (the same pieces `@deepseek-ai/dsh-tool-bash`
|
|
6
|
+
* uses), so bash and fs escalate identically. Built ONCE per plugin from
|
|
7
|
+
* `ctx.fs.sandboxMode` (the capability fact — is a confining backend mounted?)
|
|
8
|
+
* and shared by both mutating tools.
|
|
9
|
+
*
|
|
10
|
+
* @module @deepseek-ai/dsh-tool-fs/sandbox
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
14
|
+
import { ToolArgsError } from '@deepseek-ai/dsh-tools'
|
|
15
|
+
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
|
|
16
|
+
import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
|
17
|
+
import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
|
|
18
|
+
import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
|
|
19
|
+
import { FsError } from '@deepseek-ai/dsh-fs'
|
|
20
|
+
|
|
21
|
+
/** The two escalation arguments a mutating tool may carry (advertised only under a confining backend). */
|
|
22
|
+
export interface FsEscalationArgs {
|
|
23
|
+
sandbox_permissions?: string
|
|
24
|
+
justification?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The schema fields for the escalation arguments, spread into a tool's `parameters` when a confining backend is mounted. */
|
|
28
|
+
export interface EscalationSchemaFields {
|
|
29
|
+
sandbox_permissions: { type: 'string'; enum: string[]; description: string }
|
|
30
|
+
justification: { type: 'string'; description: string }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The filesystem escalation API: advertisement gating, per-call policy
|
|
35
|
+
* resolution, the one-approved wider retry, and denial-marker mapping. A pure
|
|
36
|
+
* product of `ctx` at plugin apply time.
|
|
37
|
+
*/
|
|
38
|
+
export class FsSandboxController {
|
|
39
|
+
/** The escalation targets this composition advertises (`[]` when no confining backend is mounted). */
|
|
40
|
+
readonly escalationModes: readonly SandboxMode[]
|
|
41
|
+
/** Shared per-session policy resolver, required by a confining backend. */
|
|
42
|
+
private readonly policy: SandboxPolicyService | undefined
|
|
43
|
+
|
|
44
|
+
constructor(private readonly ctx: Context) {
|
|
45
|
+
const defaultMode = ctx.fs.sandboxMode
|
|
46
|
+
this.escalationModes = defaultMode === undefined ? [] : ESCALATION_TARGETS
|
|
47
|
+
this.policy = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy')
|
|
48
|
+
if (defaultMode !== undefined && this.policy === undefined) {
|
|
49
|
+
throw new Error('tool-fs: the mounted filesystem confines but ctx.sandboxPolicy is missing')
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The escalation schema fields for a mutating tool's `parameters`. Call it
|
|
55
|
+
* only under a confining backend (guard on {@link escalationModes}); the
|
|
56
|
+
* enum pins the closed target vocabulary, the strict-wider check happens per
|
|
57
|
+
* call at execution.
|
|
58
|
+
* @returns the two escalation parameter specs.
|
|
59
|
+
*/
|
|
60
|
+
schemaFields(): EscalationSchemaFields {
|
|
61
|
+
return {
|
|
62
|
+
sandbox_permissions: {
|
|
63
|
+
type: 'string',
|
|
64
|
+
enum: [...this.escalationModes],
|
|
65
|
+
description: sandboxPermissionsDescription('operation'),
|
|
66
|
+
},
|
|
67
|
+
justification: {
|
|
68
|
+
type: 'string',
|
|
69
|
+
description: 'Required with sandbox_permissions: one sentence for the user explaining '
|
|
70
|
+
+ 'why this exact file operation needs the wider access. Use the language of the user’s current request.',
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The policy to stamp onto this mutation: an approved escalation grant (a
|
|
77
|
+
* strictly wider retry resolved through `ctx.approval` before anything
|
|
78
|
+
* executes), else the Session's standing mode. An omitted or repeated mode
|
|
79
|
+
* permits an omitted or blank justification; repeating the mode needs no
|
|
80
|
+
* approval. A different mode requires a non-empty justification, and a
|
|
81
|
+
* non-empty justification without a mode is rejected. The workspace root is
|
|
82
|
+
* the original Session directory, or the deployment fallback when absent.
|
|
83
|
+
* @param toolName - the mutating tool's name, for the approval audit trail.
|
|
84
|
+
* @param args - the call's escalation arguments.
|
|
85
|
+
* @param exec - the tool-execution context (agent, callId, signal).
|
|
86
|
+
* @returns the policy to pass to the mutation, or undefined for an
|
|
87
|
+
* unsandboxed backend.
|
|
88
|
+
*/
|
|
89
|
+
async resolvePolicy(toolName: string, args: FsEscalationArgs, exec: ToolExecution): Promise<SandboxExecutionPolicy | undefined> {
|
|
90
|
+
const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} })
|
|
91
|
+
if (args.sandbox_permissions !== undefined && args.sandbox_permissions === standingPolicy?.mode) return standingPolicy
|
|
92
|
+
const justification = args.sandbox_permissions === undefined && args.justification?.trim() === ''
|
|
93
|
+
? undefined
|
|
94
|
+
: args.justification
|
|
95
|
+
validateEscalationArgs(args.sandbox_permissions, justification)
|
|
96
|
+
if (args.sandbox_permissions === undefined || args.justification === undefined) {
|
|
97
|
+
return standingPolicy
|
|
98
|
+
}
|
|
99
|
+
if (this.escalationModes.length === 0) {
|
|
100
|
+
throw new ToolArgsError(['sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)'])
|
|
101
|
+
}
|
|
102
|
+
const policy = standingPolicy as SandboxExecutionPolicy
|
|
103
|
+
const approvedMode = await approveEscalation(
|
|
104
|
+
{ requestedMode: args.sandbox_permissions, justification: args.justification, effectiveMode: policy.mode, subject: 'operation' },
|
|
105
|
+
{
|
|
106
|
+
approver: this.ctx.get('approval'),
|
|
107
|
+
agent: exec.agent,
|
|
108
|
+
callId: exec.callId,
|
|
109
|
+
toolName,
|
|
110
|
+
signal: exec.signal,
|
|
111
|
+
},
|
|
112
|
+
)
|
|
113
|
+
return { ...policy, mode: approvedMode }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes a
|
|
118
|
+
* `FsError` whose text is the shared `[sandbox: …]` denial marker plus the
|
|
119
|
+
* same-turn escalation hint, so a policy denial reads identically to bash's
|
|
120
|
+
* WHILE keeping the structured `FS_SANDBOX_DENIED` code — `ToolRuntime`
|
|
121
|
+
* populates `result.error` only for `HarnessError` instances, so a plain
|
|
122
|
+
* `Error` would strip the code retry/observers key off. Any other error
|
|
123
|
+
* passes through unchanged. A `FS_SANDBOX_DENIED` only arises under a
|
|
124
|
+
* confining backend, which always advertises the escalation fields, so the
|
|
125
|
+
* hint always applies here.
|
|
126
|
+
* @param error - the error thrown by the mutation.
|
|
127
|
+
* @param policy - the policy stamped onto the call (names the mode in the marker).
|
|
128
|
+
* @returns the error to throw — the marker `FsError` for a sandbox denial, else the original.
|
|
129
|
+
*/
|
|
130
|
+
mapError(error: FsError, policy: SandboxExecutionPolicy | undefined): FsError
|
|
131
|
+
/**
|
|
132
|
+
* Map a caught value, preserving failures other than sandbox denials.
|
|
133
|
+
* @param error - value thrown by a mutation.
|
|
134
|
+
* @param policy - policy stamped onto the call, when applicable.
|
|
135
|
+
* @returns the denial marker error, or the unchanged caught value.
|
|
136
|
+
*/
|
|
137
|
+
mapError(error: unknown, policy: SandboxExecutionPolicy | undefined): unknown
|
|
138
|
+
mapError(error: unknown, policy: SandboxExecutionPolicy | undefined): unknown {
|
|
139
|
+
if (!(error instanceof FsError) || error.code !== 'FS_SANDBOX_DENIED') return error
|
|
140
|
+
// A FS_SANDBOX_DENIED only arises under a confining backend, whose tool
|
|
141
|
+
// path always resolves a policy before mutation.
|
|
142
|
+
const mode = (policy as SandboxExecutionPolicy).mode
|
|
143
|
+
return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker('operation')}`, 'FS_SANDBOX_DENIED', { cause: error })
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolution options for filesystem calls in the Session's current directory.
|
|
3
|
+
* Non-agent calls leave directory defaults to the filesystem provider.
|
|
4
|
+
* @module @deepseek-ai/dsh-tool-fs/session-cwd
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
8
|
+
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
|
|
9
|
+
import type {} from '@deepseek-ai/dsh-working-directory'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Resolve the current directory and cancellation for a filesystem call.
|
|
13
|
+
* @param ctx - context containing the working-directory service.
|
|
14
|
+
* @param exec - tool execution supplying the agent and cancellation.
|
|
15
|
+
* @returns filesystem resolution options for this call.
|
|
16
|
+
*/
|
|
17
|
+
export async function sessionResolveOptions(
|
|
18
|
+
ctx: Context,
|
|
19
|
+
exec: ToolExecution,
|
|
20
|
+
): Promise<{ cwd?: string; signal?: AbortSignal }> {
|
|
21
|
+
const cwd = exec.agent === undefined
|
|
22
|
+
? undefined
|
|
23
|
+
: await ctx.workingDirectory.ensure(exec.agent, exec.signal)
|
|
24
|
+
return { ...cwd !== undefined ? { cwd } : {}, signal: exec.signal }
|
|
25
|
+
}
|
package/src/write.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing full-file write. It obtains an optional intent from the single policy slot, calls
|
|
3
|
+
* `ctx.fs.writeText` without a stat, then records the resulting version; no policy means an
|
|
4
|
+
* unconditional atomic create-or-overwrite.
|
|
5
|
+
* @module @deepseek-ai/dsh-tool-fs/src/write
|
|
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 { FsWriteOutcome } from '@deepseek-ai/dsh-fs'
|
|
12
|
+
import type {} from '@deepseek-ai/dsh-fs'
|
|
13
|
+
import { computeHunkDiffs, diffsFromMeta, pathFromMeta } from './diff.ts'
|
|
14
|
+
import { remediateFsError } from './error.ts'
|
|
15
|
+
import { mutationResult } from './mutation-result.ts'
|
|
16
|
+
import { sessionResolveOptions } from './session-cwd.ts'
|
|
17
|
+
import type { FsSandboxController } from './sandbox.ts'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Validate value constraints the schema DSL can't express: only a non-blank
|
|
21
|
+
* `file_path` — an empty `content` is legitimate (it writes an empty file).
|
|
22
|
+
* @param args - the schema-validated raw tool arguments.
|
|
23
|
+
* @returns the camelCased input; `content` passes through untouched.
|
|
24
|
+
*/
|
|
25
|
+
export function parseWriteArgs(args: { file_path: string; content: string }): { filePath: string; content: string } {
|
|
26
|
+
if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string'])
|
|
27
|
+
return { filePath: args.file_path, content: args.content }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Format a write outcome as one model-facing text block body.
|
|
32
|
+
* @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
|
|
33
|
+
* @param outcome - the write outcome; its `operation` selects the Created/Updated wording.
|
|
34
|
+
* @returns the model-facing confirmation envelope (no file content is echoed back).
|
|
35
|
+
*/
|
|
36
|
+
export function formatWriteOutput(displayPath: string, outcome: Pick<FsWriteOutcome, 'operation'>): string {
|
|
37
|
+
const verb = outcome.operation === 'create' ? 'Created' : 'Updated'
|
|
38
|
+
return `<path>${displayPath}</path>
|
|
39
|
+
<type>file</type>
|
|
40
|
+
<content>
|
|
41
|
+
${verb} file
|
|
42
|
+
</content>`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The `write` tool's validated arguments: the base parameters plus the
|
|
47
|
+
* two escalation fields, advertised only under a confining `ctx.fs` (absent
|
|
48
|
+
* from the schema otherwise, so the validator rejects them before `execute`).
|
|
49
|
+
*/
|
|
50
|
+
interface WriteToolArgs {
|
|
51
|
+
file_path: string
|
|
52
|
+
content: string
|
|
53
|
+
sandbox_permissions?: string
|
|
54
|
+
justification?: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Register the `write` tool and its scope-aware system-prompt guidance.
|
|
59
|
+
* @param ctx - the plugin context; registrations are effects scoped to it, and execution uses its `fs` service.
|
|
60
|
+
* @param sandbox - the shared sandbox-escalation API (advertisement, mode stamping, denial mapping).
|
|
61
|
+
*/
|
|
62
|
+
export function applyWriteTool(ctx: Context, sandbox: FsSandboxController): void {
|
|
63
|
+
ctx.systemPrompt.section({
|
|
64
|
+
name: 'tool:write',
|
|
65
|
+
order: ctx.systemPrompt.getSectionOrder('TOOL_WRITE'),
|
|
66
|
+
text: ({ scope }) => ctx.tools.get('write', scope) === undefined
|
|
67
|
+
? ''
|
|
68
|
+
: 'Read an existing file before overwriting it with write'
|
|
69
|
+
+ (ctx.tools.get('edit', scope) === undefined ? '' : ' and prefer edit for targeted changes')
|
|
70
|
+
+ '.',
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
ctx.tools.register(defineTool({
|
|
74
|
+
name: 'write',
|
|
75
|
+
description: 'Create or fully replace a UTF-8 text file.',
|
|
76
|
+
parameters: {
|
|
77
|
+
file_path: {
|
|
78
|
+
type: 'string', required: true,
|
|
79
|
+
description: 'Path to write, resolved by the filesystem backend. '
|
|
80
|
+
+ 'Provide `file_path` before `content` in the arguments.',
|
|
81
|
+
},
|
|
82
|
+
content: { type: 'string', required: true, description: 'Full UTF-8 text content to write.' },
|
|
83
|
+
...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {},
|
|
84
|
+
},
|
|
85
|
+
output: {
|
|
86
|
+
schema: {
|
|
87
|
+
type: 'object',
|
|
88
|
+
additionalProperties: false,
|
|
89
|
+
properties: {
|
|
90
|
+
path: { type: 'string', required: true, description: 'Canonical absolute path in the filesystem execution world.' },
|
|
91
|
+
operation: { type: 'string', required: true, enum: ['create', 'update'] },
|
|
92
|
+
before: {
|
|
93
|
+
required: true,
|
|
94
|
+
oneOf: [
|
|
95
|
+
{ type: 'string' },
|
|
96
|
+
{ type: 'null' },
|
|
97
|
+
],
|
|
98
|
+
},
|
|
99
|
+
after: { type: 'string', required: true },
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
render: (_args, value) => [{ type: 'text', text: formatWriteOutput(value.path, value) }],
|
|
103
|
+
presentationMeta: (_args, value) => ({
|
|
104
|
+
operation: value.operation,
|
|
105
|
+
path: value.path,
|
|
106
|
+
diffs: value.before === null
|
|
107
|
+
? []
|
|
108
|
+
: computeHunkDiffs(value.path, value.before, value.after)
|
|
109
|
+
.map(({ path, oldText, newText }) => ({ path, oldText, newText })),
|
|
110
|
+
}),
|
|
111
|
+
},
|
|
112
|
+
async execute(args: WriteToolArgs, exec) {
|
|
113
|
+
const input = parseWriteArgs(args)
|
|
114
|
+
// Resolve the per-call sandbox policy (approved mode > session override
|
|
115
|
+
// > backend default, plus the session cwd root) BEFORE anything executes;
|
|
116
|
+
// an escalating call throws its distinct text on any non-grant.
|
|
117
|
+
const sandboxPolicy = await sandbox.resolvePolicy('write', args, exec)
|
|
118
|
+
const target = await ctx.fs.resolve(input.filePath, await sessionResolveOptions(ctx, exec))
|
|
119
|
+
// Single-slot decision: the policy plugin produces createIfAbsent/
|
|
120
|
+
// replaceIfVersion; the bare default is undefined (unconditional). No stat.
|
|
121
|
+
const intent = await ctx.waterfall('fs/write-intent', target, exec, () => undefined)
|
|
122
|
+
let outcome: FsWriteOutcome
|
|
123
|
+
try {
|
|
124
|
+
outcome = await ctx.fs.writeText(target, input.content, intent, exec.signal, sandboxPolicy)
|
|
125
|
+
} catch (error: unknown) {
|
|
126
|
+
// A sandbox denial becomes the shared [sandbox: …] marker (the model
|
|
127
|
+
// recognizes it from bash); guarded mutation failures receive their
|
|
128
|
+
// stable model-facing diagnostic; anything else passes through.
|
|
129
|
+
throw remediateFsError(sandbox.mapError(error, sandboxPolicy), target.displayPath)
|
|
130
|
+
}
|
|
131
|
+
return mutationResult(ctx, target, outcome, exec)
|
|
132
|
+
},
|
|
133
|
+
// Pure display: a diff card. A call-time presenter has no access to prior
|
|
134
|
+
// file content, so `oldText: null` also represents an overwrite here.
|
|
135
|
+
presentCall(args): DiffCallView {
|
|
136
|
+
return {
|
|
137
|
+
card: 'diff',
|
|
138
|
+
title: `Write ${args.file_path}`,
|
|
139
|
+
diffs: [{ path: args.file_path, oldText: null, newText: args.content }],
|
|
140
|
+
locations: [{ path: args.file_path }],
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
// Result-time display repeats the diff because completed views replace the
|
|
144
|
+
// pending view. Overwrites use applied metadata; creates and identical
|
|
145
|
+
// overwrites use the replay-safe args fallback.
|
|
146
|
+
presentResult(args, result: ToolResult): DiffResultView | undefined {
|
|
147
|
+
if (result.isError) return undefined
|
|
148
|
+
const diffs = diffsFromMeta(result.meta)
|
|
149
|
+
?? [{ path: pathFromMeta(result.meta) ?? args.file_path, oldText: null, newText: args.content }]
|
|
150
|
+
return { card: 'diff', title: `Write ${args.file_path}`, diffs }
|
|
151
|
+
},
|
|
152
|
+
}))
|
|
153
|
+
}
|