@d0nj/dsh-native-tools 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,88 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { type FileSystem } from '@deepseek-ai/dsh-fs';
3
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
4
+ export declare const READ_LIMIT = 2000;
5
+ export declare const READ_MAX_LINE_LENGTH = 2000;
6
+ export declare const READ_MAX_BYTES: number;
7
+ export interface ReadToolCaps {
8
+ readonly limit: number;
9
+ readonly maxLineLength: number;
10
+ readonly maxBytes: number;
11
+ }
12
+ export interface ReadToolDeps {
13
+ readonly ctx: Context;
14
+ readonly fs: FileSystem;
15
+ readonly workdir: (signal: AbortSignal) => Promise<string>;
16
+ readonly caps: ReadToolCaps;
17
+ readonly summary?: {
18
+ readonly minLines: number;
19
+ readonly minBodyLines: number;
20
+ } | undefined;
21
+ readonly grammar?: {
22
+ readonly idForPath: (path: string) => string | undefined;
23
+ readonly ensure: (id: string, signal: AbortSignal) => Promise<{
24
+ installed: boolean;
25
+ reason?: string;
26
+ }>;
27
+ } | undefined;
28
+ readonly timeoutMs: number;
29
+ }
30
+ export type ElidedRange = {
31
+ startLine: number;
32
+ endLine: number;
33
+ label: string;
34
+ };
35
+ export interface ReadValue {
36
+ path: string;
37
+ offset: number;
38
+ lines: Array<{
39
+ number: number;
40
+ text: string;
41
+ }>;
42
+ totalLines: number;
43
+ elided: ElidedRange[];
44
+ }
45
+ export interface ReadInput {
46
+ filePath: string;
47
+ offset: number;
48
+ limit: number;
49
+ summarize: boolean;
50
+ }
51
+ export interface ReadWindowOutcome {
52
+ offset: number;
53
+ lines: Array<{
54
+ number: number;
55
+ text: string;
56
+ }>;
57
+ totalLines: number;
58
+ truncatedByBytes?: true;
59
+ elided?: ElidedRange[];
60
+ }
61
+ export interface ReadMeta {
62
+ path: string;
63
+ offset: number;
64
+ lines: Array<{
65
+ number: number;
66
+ text: string;
67
+ }>;
68
+ totalLines: number;
69
+ lang?: string;
70
+ }
71
+ export declare function parseReadArgs(args: {
72
+ file_path: string;
73
+ offset?: number;
74
+ limit?: number;
75
+ summarize?: boolean;
76
+ }, maxLimit: number): ReadInput;
77
+ export declare function endLineOf(lines: ReadonlyArray<{
78
+ number: number;
79
+ }>, offset: number): number;
80
+ export declare function cappedByBytes(value: ReadValue, limit: number): boolean;
81
+ export declare function renderReadBody(lines: ReadonlyArray<{
82
+ number: number;
83
+ text: string;
84
+ }>, elided: ReadonlyArray<ElidedRange>): string;
85
+ export declare function formatReadOutput(displayPath: string, outcome: ReadWindowOutcome): string;
86
+ export declare function readMetaFromMeta(meta: unknown): ReadMeta | undefined;
87
+ export declare function createReadTool(deps: ReadToolDeps): ToolDefinition;
88
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1,247 @@
1
+ import { FsError } from '@deepseek-ai/dsh-fs';
2
+ import { defineTool, ToolArgsError, } from '@deepseek-ai/dsh-tools';
3
+ import { cancellable, loadNative } from '../native.js';
4
+ export const READ_LIMIT = 2000;
5
+ export const READ_MAX_LINE_LENGTH = 2000;
6
+ export const READ_MAX_BYTES = 50 * 1024;
7
+ const READ_ENVELOPE = /^<path>[^\n]*<\/path>\n<type>file<\/type>\n<content>\n([\s\S]*)\n<\/content>$/u;
8
+ function parsePositiveInteger(value, name) {
9
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) {
10
+ throw new ToolArgsError([`${name} must be a positive integer`]);
11
+ }
12
+ return value;
13
+ }
14
+ export function parseReadArgs(args, maxLimit) {
15
+ if (args.file_path.trim().length === 0)
16
+ throw new ToolArgsError(['file_path must be a non-empty string']);
17
+ const offset = args.offset === undefined ? 1 : parsePositiveInteger(args.offset, 'offset');
18
+ const limit = args.limit === undefined ? maxLimit : parsePositiveInteger(args.limit, 'limit');
19
+ if (limit > maxLimit)
20
+ throw new ToolArgsError([`limit must be less than or equal to ${maxLimit}`]);
21
+ return { filePath: args.file_path, offset, limit, summarize: args.summarize === true };
22
+ }
23
+ export function endLineOf(lines, offset) {
24
+ return lines.at(-1)?.number ?? Math.max(0, offset - 1);
25
+ }
26
+ export function cappedByBytes(value, limit) {
27
+ return value.lines.length < limit && endLineOf(value.lines, value.offset) < value.totalLines;
28
+ }
29
+ export function renderReadBody(lines, elided) {
30
+ if (elided.length === 0)
31
+ return lines.map((line) => `${line.number}: ${line.text}`).join('\n');
32
+ const rendered = [];
33
+ for (const line of lines) {
34
+ const range = elided.find((entry) => line.number >= entry.startLine && line.number <= entry.endLine);
35
+ if (range === undefined) {
36
+ rendered.push(`${line.number}: ${line.text}`);
37
+ continue;
38
+ }
39
+ if (line.number === range.startLine) {
40
+ rendered.push(`… +${range.endLine - range.startLine + 1} lines (${range.label})`);
41
+ }
42
+ }
43
+ return rendered.join('\n');
44
+ }
45
+ export function formatReadOutput(displayPath, outcome) {
46
+ const endLine = endLineOf(outcome.lines, outcome.offset);
47
+ const footer = outcome.truncatedByBytes === true
48
+ ? `(Output capped. Showing lines ${outcome.offset}-${endLine}. Use offset=${endLine + 1} to continue.)`
49
+ : endLine < outcome.totalLines
50
+ ? `(Showing lines ${outcome.offset}-${endLine} of ${outcome.totalLines}. Use offset=${endLine + 1} to continue.)`
51
+ : `(End of file - total ${outcome.totalLines} lines)`;
52
+ const body = outcome.lines.length > 0
53
+ ? `${renderReadBody(outcome.lines, outcome.elided ?? [])}\n\n${footer}`
54
+ : footer;
55
+ return `<path>${displayPath}</path>\n<type>file</type>\n<content>\n${body}\n</content>`;
56
+ }
57
+ function isFileTextLine(value) {
58
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
59
+ return false;
60
+ const { number, text } = value;
61
+ return typeof number === 'number' && Number.isInteger(number) && number >= 1 && typeof text === 'string';
62
+ }
63
+ export function readMetaFromMeta(meta) {
64
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta))
65
+ return undefined;
66
+ const { path, offset, lines, totalLines, lang } = meta;
67
+ if (typeof path !== 'string' || typeof offset !== 'number' || typeof totalLines !== 'number')
68
+ return undefined;
69
+ if (!Number.isInteger(offset) || offset < 1)
70
+ return undefined;
71
+ if (!Number.isInteger(totalLines) || totalLines < 0)
72
+ return undefined;
73
+ if (!Array.isArray(lines) || !lines.every(isFileTextLine))
74
+ return undefined;
75
+ if (lang !== undefined && typeof lang !== 'string')
76
+ return undefined;
77
+ let previous = offset - 1;
78
+ for (const { number } of lines) {
79
+ if (number <= previous || number > totalLines)
80
+ return undefined;
81
+ previous = number;
82
+ }
83
+ return { path, offset, lines, totalLines, ...lang === undefined ? {} : { lang } };
84
+ }
85
+ export function createReadTool(deps) {
86
+ return defineTool({
87
+ name: 'read',
88
+ description: 'Read a UTF-8 text file and return line-numbered content.',
89
+ parameters: {
90
+ file_path: { type: 'string', required: true, description: 'Path to read, resolved by the filesystem backend.' },
91
+ offset: { type: 'number', description: '1-based first line to return. Defaults to 1.' },
92
+ limit: { type: 'number', description: `Maximum number of lines to return. Defaults to ${deps.caps.limit}.` },
93
+ summarize: {
94
+ type: 'boolean',
95
+ description: 'Replace the bodies of long functions with an elision marker so a large file stays readable in one call. Defaults to false.',
96
+ },
97
+ },
98
+ output: {
99
+ schema: {
100
+ type: 'object',
101
+ additionalProperties: false,
102
+ properties: {
103
+ path: { type: 'string', required: true },
104
+ offset: { type: 'integer', required: true },
105
+ lines: {
106
+ type: 'array',
107
+ required: true,
108
+ items: {
109
+ type: 'object',
110
+ additionalProperties: false,
111
+ properties: {
112
+ number: { type: 'integer', required: true },
113
+ text: { type: 'string', required: true },
114
+ },
115
+ },
116
+ },
117
+ totalLines: { type: 'integer', required: true },
118
+ elided: {
119
+ type: 'array',
120
+ required: true,
121
+ items: {
122
+ type: 'object',
123
+ additionalProperties: false,
124
+ properties: {
125
+ startLine: { type: 'integer', required: true },
126
+ endLine: { type: 'integer', required: true },
127
+ label: { type: 'string', required: true },
128
+ },
129
+ },
130
+ },
131
+ },
132
+ },
133
+ render: (args, value) => {
134
+ const input = parseReadArgs(args, deps.caps.limit);
135
+ return [{
136
+ type: 'text',
137
+ text: formatReadOutput(value.path, {
138
+ offset: value.offset,
139
+ lines: value.lines,
140
+ totalLines: value.totalLines,
141
+ elided: value.elided,
142
+ ...(cappedByBytes(value, input.limit) ? { truncatedByBytes: true } : {}),
143
+ }),
144
+ }];
145
+ },
146
+ presentationMeta: (_args, value) => ({
147
+ path: value.path,
148
+ offset: value.offset,
149
+ lines: value.lines.map(({ number, text }) => ({ number, text })),
150
+ totalLines: value.totalLines,
151
+ }),
152
+ },
153
+ timeoutMs: deps.timeoutMs,
154
+ isConcurrencySafe: () => true,
155
+ presentCall: (args) => {
156
+ const { offset, limit } = args;
157
+ const first = offset ?? 1;
158
+ const window = limit !== undefined && limit > 0
159
+ ? ` (${first} - ${first + limit - 1})`
160
+ : offset !== undefined ? ` (from line ${offset})` : '';
161
+ return {
162
+ card: 'generic',
163
+ title: `Read ${args.file_path}${window}`,
164
+ kind: 'read',
165
+ locations: [{ path: args.file_path, line: first }],
166
+ };
167
+ },
168
+ presentResult(_args, result) {
169
+ if (result.isError)
170
+ return undefined;
171
+ const meta = readMetaFromMeta(result.meta);
172
+ if (meta === undefined)
173
+ return undefined;
174
+ const only = result.content.length === 1 ? result.content[0] : undefined;
175
+ const text = only?.type === 'text' ? only.text : undefined;
176
+ if (text === undefined)
177
+ return undefined;
178
+ const body = READ_ENVELOPE.exec(text)?.[1];
179
+ if (body === undefined)
180
+ return undefined;
181
+ return {
182
+ card: 'read',
183
+ path: meta.path,
184
+ offset: meta.offset,
185
+ lines: meta.lines,
186
+ totalLines: meta.totalLines,
187
+ ...meta.lang === undefined ? {} : { lang: meta.lang },
188
+ content: [{ type: 'text', text: body }],
189
+ };
190
+ },
191
+ async execute(args, exec) {
192
+ const input = parseReadArgs(args, deps.caps.limit);
193
+ const cwd = await deps.workdir(exec.signal);
194
+ const target = await deps.fs.resolve(input.filePath, { cwd, signal: exec.signal });
195
+ const info = await deps.fs.stat(target, exec.signal);
196
+ if (info === undefined) {
197
+ deps.ctx.emit('fs/observed', target, { kind: 'absent' }, exec);
198
+ throw new FsError(`cannot read "${target.displayPath}": not found`, 'FS_NOT_FOUND');
199
+ }
200
+ if (info.type !== 'file') {
201
+ throw new FsError(`cannot read "${target.displayPath}": not a regular file`, 'FS_NOT_REGULAR_FILE');
202
+ }
203
+ const content = await deps.fs.readText(target, exec.signal);
204
+ const window = await cancellable(exec.signal, (cancel) => loadNative().readWindow({
205
+ content,
206
+ offset: input.offset,
207
+ limit: input.limit,
208
+ maxLineLength: deps.caps.maxLineLength,
209
+ maxBytes: deps.caps.maxBytes,
210
+ cancel,
211
+ }));
212
+ const value = {
213
+ path: deps.fs.processPath(target),
214
+ offset: input.offset,
215
+ lines: window.lines,
216
+ totalLines: window.totalLines,
217
+ elided: [],
218
+ };
219
+ if (deps.summary !== undefined && input.summarize && value.totalLines >= deps.summary.minLines) {
220
+ const wasmId = deps.grammar?.idForPath(input.filePath);
221
+ if (wasmId !== undefined) {
222
+ const ready = await deps.grammar?.ensure(wasmId, exec.signal);
223
+ if (ready?.installed !== true) {
224
+ return value;
225
+ }
226
+ }
227
+ const summarized = await cancellable(exec.signal, (cancel) => loadNative().summarizeCode({
228
+ text: content,
229
+ minBodyLines: deps.summary?.minBodyLines ?? 6,
230
+ unfoldUntilLines: deps.summary?.minLines ?? 200,
231
+ cancel,
232
+ ...(wasmId === undefined ? { path: input.filePath } : { lang: wasmId }),
233
+ }));
234
+ value.elided = summarized.segments
235
+ .filter((segment) => segment.kind === 'elided')
236
+ .map((segment) => ({ startLine: segment.startLine, endLine: segment.endLine, label: segment.label }));
237
+ }
238
+ if (!cappedByBytes(value, input.limit) && input.offset > value.totalLines
239
+ && !(value.totalLines === 0 && input.offset === 1)) {
240
+ throw new FsError(`offset ${input.offset} is out of range for "${target.displayPath}" (${value.totalLines} lines)`, 'FS_NOT_FOUND');
241
+ }
242
+ deps.ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec);
243
+ return value;
244
+ },
245
+ });
246
+ }
247
+ //# sourceMappingURL=read.js.map
@@ -0,0 +1,25 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { FileSystem } from '@deepseek-ai/dsh-fs';
3
+ import type { FileDiff } from '@deepseek-ai/dsh-tools';
4
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
5
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox';
6
+ export declare const DIFF_CONTEXT = 3;
7
+ export interface WriteToolDeps {
8
+ readonly ctx: Context;
9
+ readonly fs: FileSystem;
10
+ readonly workdir: (signal: AbortSignal) => Promise<string>;
11
+ readonly policy?: ((exec: {
12
+ readonly agent?: unknown;
13
+ }) => SandboxExecutionPolicy | undefined) | undefined;
14
+ readonly timeoutMs: number;
15
+ }
16
+ export interface WriteValue {
17
+ path: string;
18
+ operation: 'create' | 'update';
19
+ before: string | null;
20
+ after: string;
21
+ }
22
+ export declare function hunkDiffs(path: string, before: string | null, after: string): FileDiff[];
23
+ export declare function formatWriteOutput(operation: 'create' | 'update'): string;
24
+ export declare function createWriteTool(deps: WriteToolDeps): ToolDefinition;
25
+ //# sourceMappingURL=write.d.ts.map
@@ -0,0 +1,86 @@
1
+ import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools';
2
+ import { loadNative } from '../native.js';
3
+ export const DIFF_CONTEXT = 3;
4
+ export function hunkDiffs(path, before, after) {
5
+ if (before === null || before === after)
6
+ return [];
7
+ const hunks = loadNative().diffHunks(before, after, DIFF_CONTEXT);
8
+ return hunks.map((hunk) => ({ path, oldText: hunk.oldText, newText: hunk.newText }));
9
+ }
10
+ export function formatWriteOutput(operation) {
11
+ return `<path>__PATH__</path>\n<type>file</type>\n<content>\n${operation === 'create' ? 'Created' : 'Updated'} file\n</content>`;
12
+ }
13
+ export function createWriteTool(deps) {
14
+ return defineTool({
15
+ name: 'write',
16
+ description: 'Write a UTF-8 text file, creating it or replacing its whole contents. Read a file before overwriting it.',
17
+ parameters: {
18
+ file_path: {
19
+ type: 'string',
20
+ required: true,
21
+ description: 'Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments.',
22
+ },
23
+ content: { type: 'string', required: true, description: 'Full UTF-8 text content to write.' },
24
+ },
25
+ output: {
26
+ schema: {
27
+ type: 'object',
28
+ additionalProperties: false,
29
+ properties: {
30
+ path: { type: 'string', required: true },
31
+ operation: { type: 'string', required: true, enum: ['create', 'update'] },
32
+ before: { oneOf: [{ type: 'string' }, { type: 'null' }], required: true },
33
+ after: { type: 'string', required: true },
34
+ },
35
+ },
36
+ render: (_args, value) => [
37
+ {
38
+ type: 'text',
39
+ text: formatWriteOutput(value.operation).replace('__PATH__', value.path),
40
+ },
41
+ ],
42
+ presentationMeta: (_args, value) => ({
43
+ operation: value.operation,
44
+ path: value.path,
45
+ diffs: hunkDiffs(value.path, value.before, value.after).map((diff) => ({
46
+ path: diff.path,
47
+ oldText: diff.oldText,
48
+ newText: diff.newText,
49
+ })),
50
+ }),
51
+ },
52
+ timeoutMs: deps.timeoutMs,
53
+ presentCall: (args) => ({
54
+ card: 'diff',
55
+ title: `Write ${args.file_path}`,
56
+ diffs: [{ path: args.file_path, oldText: null, newText: args.content }],
57
+ locations: [{ path: args.file_path }],
58
+ }),
59
+ presentResult(args, result) {
60
+ if (result.isError)
61
+ return undefined;
62
+ const meta = result.meta;
63
+ const diffs = meta?.diffs;
64
+ if (!Array.isArray(diffs)) {
65
+ return { card: 'diff', title: `Write ${args.file_path}`, diffs: [{ path: args.file_path, oldText: null, newText: args.content }] };
66
+ }
67
+ return { card: 'diff', title: `Write ${args.file_path}`, diffs: diffs };
68
+ },
69
+ async execute(args, exec) {
70
+ if (args.file_path.trim().length === 0)
71
+ throw new ToolArgsError(['file_path must be a non-empty string']);
72
+ const cwd = await deps.workdir(exec.signal);
73
+ const target = await deps.fs.resolve(args.file_path, { cwd, signal: exec.signal });
74
+ const intent = await deps.ctx.waterfall('fs/write-intent', target, exec, () => undefined);
75
+ const written = await deps.fs.writeText(target, args.content, intent, exec.signal, deps.policy?.(exec));
76
+ deps.ctx.emit('fs/observed', target, { kind: 'present', version: written.version }, exec);
77
+ return {
78
+ path: deps.fs.processPath(target),
79
+ operation: written.operation,
80
+ before: written.before ?? null,
81
+ after: written.after,
82
+ };
83
+ },
84
+ });
85
+ }
86
+ //# sourceMappingURL=write.js.map