@saturn-universe/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.
- package/LICENSE +661 -0
- package/dist/container-sandbox.d.ts +168 -0
- package/dist/container-sandbox.js +1241 -0
- package/dist/counter.d.ts +5 -0
- package/dist/counter.js +82 -0
- package/dist/data-review.d.ts +4 -0
- package/dist/data-review.js +146 -0
- package/dist/execution-backend.d.ts +55 -0
- package/dist/execution-backend.js +339 -0
- package/dist/executor.d.ts +25 -0
- package/dist/executor.js +978 -0
- package/dist/file-window.d.ts +3 -0
- package/dist/file-window.js +12 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +17 -0
- package/dist/mcp-headers.d.ts +3 -0
- package/dist/mcp-headers.js +51 -0
- package/dist/mcp-http.d.ts +3 -0
- package/dist/mcp-http.js +253 -0
- package/dist/mcp-stdio.d.ts +2 -0
- package/dist/mcp-stdio.js +147 -0
- package/dist/mcp-wire.d.ts +33 -0
- package/dist/mcp-wire.js +85 -0
- package/dist/mcp.d.ts +19 -0
- package/dist/mcp.js +325 -0
- package/dist/path-containment.d.ts +3 -0
- package/dist/path-containment.js +11 -0
- package/dist/planner.d.ts +3 -0
- package/dist/planner.js +162 -0
- package/dist/process-manager.d.ts +67 -0
- package/dist/process-manager.js +423 -0
- package/dist/process-output.d.ts +34 -0
- package/dist/process-output.js +162 -0
- package/dist/process-worker.d.ts +1 -0
- package/dist/process-worker.js +202 -0
- package/dist/registry.d.ts +33 -0
- package/dist/registry.js +227 -0
- package/dist/search.d.ts +9 -0
- package/dist/search.js +96 -0
- package/dist/team.d.ts +36 -0
- package/dist/team.js +284 -0
- package/dist/text-patch.d.ts +15 -0
- package/dist/text-patch.js +81 -0
- package/dist/todo.d.ts +3 -0
- package/dist/todo.js +105 -0
- package/dist/workspace-discovery.d.ts +42 -0
- package/dist/workspace-discovery.js +404 -0
- package/dist/workspace-snapshot.d.ts +28 -0
- package/dist/workspace-snapshot.js +371 -0
- package/dist/workspace.d.ts +22 -0
- package/dist/workspace.js +1819 -0
- package/package.json +16 -3
- package/README.md +0 -3
|
@@ -0,0 +1,1819 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants as fsConstants } from 'node:fs';
|
|
3
|
+
import { access, link, lstat, mkdir, open, opendir, realpath, rename, stat, unlink } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
6
|
+
import { assertSandboxPathContained, createHostExecutionBackend } from './execution-backend.js';
|
|
7
|
+
import { readFileWindow } from './file-window.js';
|
|
8
|
+
import { isContainedPath, relativePathWithin } from './path-containment.js';
|
|
9
|
+
import { isManagedBranchWorkspace } from './workspace-snapshot.js';
|
|
10
|
+
import { createProcessManager, processEnvironment } from './process-manager.js';
|
|
11
|
+
import { applyTextPatch, parseTextPatch } from './text-patch.js';
|
|
12
|
+
import { isProcessOutputPath, ProcessOutput, maxProcessOutputBytes } from './process-output.js';
|
|
13
|
+
import { globWorkspace, grepText, grepWorkspace, isDiscoverablePath, maxContextLines, maxDiscoveryResults, } from './workspace-discovery.js';
|
|
14
|
+
const maxFileBytes = 256 * 1024;
|
|
15
|
+
const maxReadBytes = 8 * 1024;
|
|
16
|
+
const maxReadPageBytes = 32 * 1024;
|
|
17
|
+
export const processTimeoutMs = 30_000;
|
|
18
|
+
export const maxShellTimeoutMs = 300_000;
|
|
19
|
+
const defaultReadLines = 200;
|
|
20
|
+
const maxSearchBytes = 4 * 1024;
|
|
21
|
+
const maxMatches = 40;
|
|
22
|
+
const maxEntries = 2000;
|
|
23
|
+
const maxListedEntries = 100;
|
|
24
|
+
const maxListBytes = 4 * 1024;
|
|
25
|
+
const maxScannedBytes = 8 * 1024 * 1024;
|
|
26
|
+
const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
27
|
+
const pathSchema = { type: 'string', minLength: 1, maxLength: 1024 };
|
|
28
|
+
export const outsideWorkspacePrefix = 'outside_workspace:';
|
|
29
|
+
export const containerReadonlyPrefix = 'container_ro:';
|
|
30
|
+
export const readonlyCommandAllowlist = new Set([
|
|
31
|
+
'strings',
|
|
32
|
+
'objdump',
|
|
33
|
+
'readelf',
|
|
34
|
+
'nm',
|
|
35
|
+
'file',
|
|
36
|
+
'size',
|
|
37
|
+
'ldd',
|
|
38
|
+
'checksec',
|
|
39
|
+
'rg',
|
|
40
|
+
'grep',
|
|
41
|
+
'findstr',
|
|
42
|
+
'wc',
|
|
43
|
+
'head',
|
|
44
|
+
'tail',
|
|
45
|
+
'stat',
|
|
46
|
+
'ls',
|
|
47
|
+
'tree',
|
|
48
|
+
'where',
|
|
49
|
+
'which',
|
|
50
|
+
'git',
|
|
51
|
+
]);
|
|
52
|
+
const readonlyGitSubcommands = new Set([
|
|
53
|
+
'status',
|
|
54
|
+
'log',
|
|
55
|
+
'diff',
|
|
56
|
+
'show',
|
|
57
|
+
'branch',
|
|
58
|
+
'rev-parse',
|
|
59
|
+
'ls-files',
|
|
60
|
+
'ls-tree',
|
|
61
|
+
'describe',
|
|
62
|
+
'tag',
|
|
63
|
+
]);
|
|
64
|
+
const gitSafePreFlags = new Set([
|
|
65
|
+
'--no-pager',
|
|
66
|
+
'-P',
|
|
67
|
+
'--no-optional-locks',
|
|
68
|
+
'--literal-pathspecs',
|
|
69
|
+
'--noglob-pathspecs',
|
|
70
|
+
'--icase-pathspecs',
|
|
71
|
+
]);
|
|
72
|
+
// The local Host is the workspace owner. A process can modify several files, so its
|
|
73
|
+
// approved execution shares the same write queue as atomic file replacements.
|
|
74
|
+
const workspaceWriters = new Map();
|
|
75
|
+
async function withWorkspaceWrite(root, signal, run) {
|
|
76
|
+
const key = process.platform === 'win32' ? root.toLowerCase() : root;
|
|
77
|
+
const previous = workspaceWriters.get(key) ?? Promise.resolve();
|
|
78
|
+
let release;
|
|
79
|
+
const next = new Promise((resolve) => {
|
|
80
|
+
release = resolve;
|
|
81
|
+
});
|
|
82
|
+
workspaceWriters.set(key, next);
|
|
83
|
+
await previous;
|
|
84
|
+
try {
|
|
85
|
+
signal.throwIfAborted();
|
|
86
|
+
return await run();
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
release();
|
|
90
|
+
if (workspaceWriters.get(key) === next)
|
|
91
|
+
workspaceWriters.delete(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function createWorkspaceTools(root, versionedFiles = false, options = {}) {
|
|
95
|
+
const phase2 = options.phase2 === true;
|
|
96
|
+
const phase1 = phase2 || (options.phase1 ?? (!options.legacyProcessTools && !options.expandedProcessArgs));
|
|
97
|
+
let processManager = options.processManager;
|
|
98
|
+
const processes = () => (processManager ??= createProcessManager({ directory: path.join(root, '.saturn', 'processes') }));
|
|
99
|
+
const hostRootFor = (workingDirectory) => isManagedBranchWorkspace(root, workingDirectory) ? path.resolve(workingDirectory) : root;
|
|
100
|
+
const executionBackend = options.executionBackend ?? createHostExecutionBackend(hostRootFor);
|
|
101
|
+
const executionContext = (workingDirectory, target) => executionBackend.resolveContext(workingDirectory, target);
|
|
102
|
+
const sandboxRoot = (workingDirectory, target) => executionContext(workingDirectory, target).effectiveRoot;
|
|
103
|
+
const captureProcessOutput = (context) => new ProcessOutput(sandboxRoot(context.workingDirectory, targetFor(context)), [
|
|
104
|
+
context.executionKey,
|
|
105
|
+
context.attemptId,
|
|
106
|
+
]);
|
|
107
|
+
const resolveInputPath = (workingDirectory, supplied, ctx) => {
|
|
108
|
+
if (ctx.kind !== 'container')
|
|
109
|
+
return path.resolve(workingDirectory, supplied);
|
|
110
|
+
const containerRoot = path.posix.normalize(ctx.containerWorkDir ?? '/workspace');
|
|
111
|
+
if (supplied.startsWith('/')) {
|
|
112
|
+
const normalized = path.posix.normalize(supplied);
|
|
113
|
+
if (normalized === containerRoot)
|
|
114
|
+
return ctx.effectiveRoot;
|
|
115
|
+
if (normalized.startsWith(containerRoot + '/')) {
|
|
116
|
+
const rel = normalized.slice(containerRoot.length + 1);
|
|
117
|
+
return rel ? path.resolve(ctx.effectiveRoot, ...rel.split('/')) : ctx.effectiveRoot;
|
|
118
|
+
}
|
|
119
|
+
throw invalidPath();
|
|
120
|
+
}
|
|
121
|
+
return path.resolve(ctx.effectiveRoot, supplied);
|
|
122
|
+
};
|
|
123
|
+
const checkPath = (effectiveRoot, target, git = false, readSpill = false, strictContainment = false) => {
|
|
124
|
+
const relative = relativePathWithin(effectiveRoot, target);
|
|
125
|
+
if (!safePathSyntax(target) ||
|
|
126
|
+
(!readSpill && !unprotectedPath(relative ?? target, git)) ||
|
|
127
|
+
(relative === undefined && (strictContainment || isManagedBranchWorkspace(root, effectiveRoot))))
|
|
128
|
+
throw invalidPath();
|
|
129
|
+
};
|
|
130
|
+
const pathResources = async (cwd, paths, target) => {
|
|
131
|
+
const canonicalRoot = await realpath(sandboxRoot(cwd, target));
|
|
132
|
+
return paths.map((entry) => isContainedPath(canonicalRoot, entry) ? entry : outsideWorkspacePrefix + entry);
|
|
133
|
+
};
|
|
134
|
+
const workspacePath = async (workingDirectory, supplied, kind, git = false, readSpill = false, execTarget) => {
|
|
135
|
+
const ctx = executionContext(workingDirectory, execTarget);
|
|
136
|
+
const effectiveRoot = ctx.effectiveRoot;
|
|
137
|
+
const isContainer = ctx.kind === 'container';
|
|
138
|
+
let canonical;
|
|
139
|
+
let info;
|
|
140
|
+
try {
|
|
141
|
+
const target = resolveInputPath(workingDirectory, supplied, ctx);
|
|
142
|
+
if (!safePathSyntax(supplied))
|
|
143
|
+
throw invalidPath();
|
|
144
|
+
const canonicalRoot = await realpath(effectiveRoot);
|
|
145
|
+
const lexicalRoot = readSpill && !isContainedPath(effectiveRoot, target) ? canonicalRoot : effectiveRoot;
|
|
146
|
+
const relative = path.relative(lexicalRoot, target);
|
|
147
|
+
const spill = readSpill && isProcessOutputPath(relative);
|
|
148
|
+
checkPath(spill ? lexicalRoot : effectiveRoot, target, git, spill, isContainer);
|
|
149
|
+
if (isContainer) {
|
|
150
|
+
await assertSandboxPathContained(canonicalRoot, target);
|
|
151
|
+
}
|
|
152
|
+
canonical = await realpath(target);
|
|
153
|
+
if (spill && path.relative(path.join(canonicalRoot, relative), canonical))
|
|
154
|
+
throw invalidPath();
|
|
155
|
+
checkPath(canonicalRoot, canonical, git, spill, isContainer);
|
|
156
|
+
info = await lstat(canonical);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error instanceof RuntimeError && error.code === 'SANDBOX_SYMLINK_ESCAPE')
|
|
160
|
+
throw error;
|
|
161
|
+
throw invalidPath();
|
|
162
|
+
}
|
|
163
|
+
if (kind === 'file' && info.isDirectory())
|
|
164
|
+
throw new RuntimeError('WORKSPACE_PATH_INVALID', 'Target is a directory. Specify a file path.');
|
|
165
|
+
if (kind === 'directory' && info.isFile())
|
|
166
|
+
throw new RuntimeError('WORKSPACE_PATH_INVALID', 'Target is a file. Specify a directory path.');
|
|
167
|
+
if (!(kind !== 'file' && info.isDirectory()) &&
|
|
168
|
+
!(kind !== 'directory' && info.isFile() && info.nlink === 1))
|
|
169
|
+
throw invalidPath();
|
|
170
|
+
return canonical;
|
|
171
|
+
};
|
|
172
|
+
const resolveWritableFile = async (workingDirectory, supplied, execTarget) => {
|
|
173
|
+
const ctx = executionContext(workingDirectory, execTarget);
|
|
174
|
+
if (ctx.kind === 'container' && ctx.readonly) {
|
|
175
|
+
throw new RuntimeError('SANDBOX_READONLY', 'Write operation denied in read-only sandbox');
|
|
176
|
+
}
|
|
177
|
+
const effectiveRoot = ctx.effectiveRoot;
|
|
178
|
+
const isContainer = ctx.kind === 'container';
|
|
179
|
+
if (!supplied || /[\\/]$/.test(supplied) || !safePathSyntax(supplied))
|
|
180
|
+
throw invalidPath();
|
|
181
|
+
const target = resolveInputPath(workingDirectory, supplied, ctx);
|
|
182
|
+
checkPath(effectiveRoot, target, false, false, isContainer);
|
|
183
|
+
const canonicalRoot = await realpath(effectiveRoot);
|
|
184
|
+
if (isContainer) {
|
|
185
|
+
await assertSandboxPathContained(canonicalRoot, target);
|
|
186
|
+
}
|
|
187
|
+
const anchor = isContainedPath(effectiveRoot, target) ? effectiveRoot : path.parse(target).root;
|
|
188
|
+
const parts = path.relative(anchor, target).split(path.sep).filter(Boolean);
|
|
189
|
+
if (!parts.length)
|
|
190
|
+
throw invalidPath();
|
|
191
|
+
let canonicalParent = await realpath(anchor);
|
|
192
|
+
let current = anchor;
|
|
193
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
194
|
+
current = path.join(current, parts[i]);
|
|
195
|
+
let info;
|
|
196
|
+
try {
|
|
197
|
+
info = await lstat(current);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (error.code === 'ENOENT') {
|
|
201
|
+
const remaining = parts.slice(i);
|
|
202
|
+
return path.join(canonicalParent, ...remaining);
|
|
203
|
+
}
|
|
204
|
+
throw invalidPath();
|
|
205
|
+
}
|
|
206
|
+
let resolvedDir;
|
|
207
|
+
try {
|
|
208
|
+
resolvedDir = await realpath(current);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw isContainer
|
|
212
|
+
? new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory')
|
|
213
|
+
: invalidPath();
|
|
214
|
+
}
|
|
215
|
+
checkPath(canonicalRoot, resolvedDir, false, false, isContainer);
|
|
216
|
+
const dirInfo = info.isSymbolicLink() ? await lstat(resolvedDir) : info;
|
|
217
|
+
if (!dirInfo.isDirectory())
|
|
218
|
+
throw new RuntimeError('WORKSPACE_PATH_INVALID', 'Parent path is not a directory.');
|
|
219
|
+
canonicalParent = resolvedDir;
|
|
220
|
+
}
|
|
221
|
+
const finalTarget = path.join(canonicalParent, parts.at(-1));
|
|
222
|
+
let fileInfo;
|
|
223
|
+
try {
|
|
224
|
+
fileInfo = await lstat(finalTarget);
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
if (error.code !== 'ENOENT')
|
|
228
|
+
throw invalidPath();
|
|
229
|
+
}
|
|
230
|
+
if (!fileInfo)
|
|
231
|
+
return finalTarget;
|
|
232
|
+
if (fileInfo.isDirectory())
|
|
233
|
+
throw new RuntimeError('WORKSPACE_PATH_INVALID', 'Target is a directory. Specify a file path.');
|
|
234
|
+
if (fileInfo.isSymbolicLink()) {
|
|
235
|
+
let realTarget;
|
|
236
|
+
let realInfo;
|
|
237
|
+
try {
|
|
238
|
+
realTarget = await realpath(finalTarget);
|
|
239
|
+
checkPath(canonicalRoot, realTarget, false, false, isContainer);
|
|
240
|
+
realInfo = await lstat(realTarget);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
throw isContainer
|
|
244
|
+
? new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory')
|
|
245
|
+
: invalidPath();
|
|
246
|
+
}
|
|
247
|
+
if (!realInfo.isFile() || realInfo.nlink !== 1)
|
|
248
|
+
throw invalidPath();
|
|
249
|
+
return realTarget;
|
|
250
|
+
}
|
|
251
|
+
if (!fileInfo.isFile() || fileInfo.nlink !== 1)
|
|
252
|
+
throw invalidPath();
|
|
253
|
+
return finalTarget;
|
|
254
|
+
};
|
|
255
|
+
const fileResources = async (input, cwd, target) => pathResources(cwd, [await workspacePath(cwd, input.path, 'file', false, false, target)], target);
|
|
256
|
+
const readFileResources = async (input, cwd, target) => {
|
|
257
|
+
const ctx = executionContext(cwd, target);
|
|
258
|
+
if (ctx.kind === 'container' && input.path.startsWith('/')) {
|
|
259
|
+
const containerRoot = path.posix.normalize(ctx.containerWorkDir ?? '/workspace');
|
|
260
|
+
const normalized = path.posix.normalize(input.path);
|
|
261
|
+
if (normalized !== containerRoot && !normalized.startsWith(containerRoot + '/')) {
|
|
262
|
+
if (!safePathSyntax(input.path) || !unprotectedPath(normalized, false))
|
|
263
|
+
throw invalidPath();
|
|
264
|
+
return [containerReadonlyPrefix + normalized];
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return pathResources(cwd, [await workspacePath(cwd, input.path, 'file', false, true, target)], target);
|
|
268
|
+
};
|
|
269
|
+
const writableFileResources = async (input, cwd, target) => pathResources(cwd, [await resolveWritableFile(cwd, input.path, target)], target);
|
|
270
|
+
const directoryResources = async (input, cwd, target) => pathResources(cwd, [await workspacePath(cwd, input.path, 'directory', false, false, target)], target);
|
|
271
|
+
const discoveryResources = async (supplied, cwd, kind, execTarget) => {
|
|
272
|
+
const ctx = executionContext(cwd, execTarget);
|
|
273
|
+
const effectiveRoot = ctx.effectiveRoot;
|
|
274
|
+
const target = supplied === undefined ? effectiveRoot : resolveInputPath(cwd, supplied, ctx);
|
|
275
|
+
const relative = relativePathWithin(effectiveRoot, target);
|
|
276
|
+
if ((supplied !== undefined && !safePathSyntax(supplied)) ||
|
|
277
|
+
relative === undefined ||
|
|
278
|
+
!isDiscoverablePath(relative))
|
|
279
|
+
throw invalidPath();
|
|
280
|
+
const canonical = await workspacePath(cwd, supplied ?? '.', kind, false, false, execTarget);
|
|
281
|
+
const canonicalRoot = await realpath(effectiveRoot);
|
|
282
|
+
const canonicalRelative = relativePathWithin(canonicalRoot, canonical);
|
|
283
|
+
if (canonicalRelative === undefined || !isDiscoverablePath(canonicalRelative))
|
|
284
|
+
throw invalidPath();
|
|
285
|
+
return [canonical];
|
|
286
|
+
};
|
|
287
|
+
const isValidWindowsExe = (canonical, info) => info.isFile() && path.extname(canonical).toLowerCase() === '.exe' && /^[a-z]:[\\/]/i.test(canonical);
|
|
288
|
+
const resolveExecutableOnPath = async (program) => {
|
|
289
|
+
let candidateName = program;
|
|
290
|
+
if (process.platform === 'win32') {
|
|
291
|
+
const ext = path.extname(program).toLowerCase();
|
|
292
|
+
if (ext && ext !== '.exe') {
|
|
293
|
+
throw new RuntimeError('PROGRAM_INVALID', `Windows execution only supports .exe binaries directly (got "${program}").`);
|
|
294
|
+
}
|
|
295
|
+
candidateName = ext === '.exe' ? program : `${program}.exe`;
|
|
296
|
+
}
|
|
297
|
+
const rawPath = process.platform === 'win32' ? (process.env.PATH ?? process.env.Path ?? '') : (process.env.PATH ?? '');
|
|
298
|
+
const pathEntries = rawPath
|
|
299
|
+
.split(path.delimiter)
|
|
300
|
+
.map((entry) => entry.trim().replace(/^"(.*)"$/, '$1'))
|
|
301
|
+
.filter(Boolean);
|
|
302
|
+
for (const dir of pathEntries) {
|
|
303
|
+
const candidate = path.join(dir, candidateName);
|
|
304
|
+
try {
|
|
305
|
+
if (process.platform !== 'win32')
|
|
306
|
+
await access(candidate, fsConstants.X_OK);
|
|
307
|
+
const canonical = await realpath(candidate);
|
|
308
|
+
const info = await stat(canonical);
|
|
309
|
+
if (process.platform === 'win32') {
|
|
310
|
+
if (!isValidWindowsExe(canonical, info) || info.size <= 0)
|
|
311
|
+
continue;
|
|
312
|
+
await access(canonical, fsConstants.R_OK);
|
|
313
|
+
}
|
|
314
|
+
else if (!info.isFile()) {
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
return canonical;
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return undefined;
|
|
324
|
+
};
|
|
325
|
+
const processResources = async ({ program, args, cwd }, workingDirectory, target) => {
|
|
326
|
+
validateProcessArgs(args);
|
|
327
|
+
const git = /^git(?:\.exe)?$/i.test(path.basename(program));
|
|
328
|
+
const ctx = executionContext(workingDirectory, target);
|
|
329
|
+
const directory = await workspacePath(workingDirectory, cwd, 'directory', git, false, target);
|
|
330
|
+
const [directoryResource] = await pathResources(workingDirectory, [directory], target);
|
|
331
|
+
if (!program || !safePathSyntax(program) || program === '.' || program === '..')
|
|
332
|
+
throw new RuntimeError('PROGRAM_INVALID', 'Program path contains invalid characters');
|
|
333
|
+
if (ctx.kind === 'container') {
|
|
334
|
+
return [program, directoryResource, ...args];
|
|
335
|
+
}
|
|
336
|
+
if (path.isAbsolute(program)) {
|
|
337
|
+
if (!unprotectedPath(program))
|
|
338
|
+
throw invalidPath();
|
|
339
|
+
let canonical;
|
|
340
|
+
try {
|
|
341
|
+
canonical = await realpath(program);
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
const hint = process.platform === 'win32' && program.startsWith('/') && !/^[a-z]:/i.test(program)
|
|
345
|
+
? ` Running on Windows (win32); Linux/POSIX paths such as "${program}" do not exist. Use a Windows .exe path or a command name on PATH.`
|
|
346
|
+
: '';
|
|
347
|
+
throw new RuntimeError('PROGRAM_NOT_FOUND', `Executable "${program}" was not found.${hint}`);
|
|
348
|
+
}
|
|
349
|
+
if (!unprotectedPath(canonical))
|
|
350
|
+
throw invalidPath();
|
|
351
|
+
let info;
|
|
352
|
+
try {
|
|
353
|
+
info = await stat(canonical);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
throw new RuntimeError('PROGRAM_NOT_FOUND', `Executable "${program}" was not found.`);
|
|
357
|
+
}
|
|
358
|
+
if (process.platform === 'win32' ? !isValidWindowsExe(canonical, info) : !info.isFile()) {
|
|
359
|
+
throw new RuntimeError('PROGRAM_INVALID', process.platform === 'win32'
|
|
360
|
+
? `Windows run_process requires an existing local .exe file (got "${canonical}").`
|
|
361
|
+
: `Program "${canonical}" is not a regular file.`);
|
|
362
|
+
}
|
|
363
|
+
return [canonical, directoryResource, ...args];
|
|
364
|
+
}
|
|
365
|
+
if (!program.includes('/') && !program.includes('\\')) {
|
|
366
|
+
const fromPath = await resolveExecutableOnPath(program);
|
|
367
|
+
if (fromPath) {
|
|
368
|
+
if (!unprotectedPath(fromPath))
|
|
369
|
+
throw invalidPath();
|
|
370
|
+
return [fromPath, directoryResource, ...args];
|
|
371
|
+
}
|
|
372
|
+
const candidateName = process.platform === 'win32' && path.extname(program).toLowerCase() !== '.exe'
|
|
373
|
+
? `${program}.exe`
|
|
374
|
+
: program;
|
|
375
|
+
try {
|
|
376
|
+
const canonical = await workspacePath(workingDirectory, path.join(directory, candidateName), 'file');
|
|
377
|
+
const [programResource] = await pathResources(workingDirectory, [canonical]);
|
|
378
|
+
const info = await stat(canonical);
|
|
379
|
+
if (process.platform === 'win32') {
|
|
380
|
+
if (isValidWindowsExe(canonical, info)) {
|
|
381
|
+
await access(canonical, fsConstants.R_OK);
|
|
382
|
+
return [programResource, directoryResource, ...args];
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
else if (info.isFile()) {
|
|
386
|
+
await access(canonical, fsConstants.X_OK);
|
|
387
|
+
return [programResource, directoryResource, ...args];
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
// Fall through to PROGRAM_NOT_FOUND
|
|
392
|
+
}
|
|
393
|
+
throw new RuntimeError('PROGRAM_NOT_FOUND', `Executable "${program}" was not found on PATH or in workspace cwd (platform=${process.platform}). Use an available executable or built-in workspace tools (list_dir, read_file, search_files).`);
|
|
394
|
+
}
|
|
395
|
+
const canonical = await workspacePath(workingDirectory, path.resolve(directory, program), 'file');
|
|
396
|
+
const info = await stat(canonical);
|
|
397
|
+
if (process.platform === 'win32' ? !isValidWindowsExe(canonical, info) : !info.isFile()) {
|
|
398
|
+
throw new RuntimeError('PROGRAM_INVALID', process.platform === 'win32'
|
|
399
|
+
? `Windows run_process requires an existing local .exe file (got "${canonical}").`
|
|
400
|
+
: `Program "${canonical}" is not a regular file.`);
|
|
401
|
+
}
|
|
402
|
+
const [programResource] = await pathResources(workingDirectory, [canonical]);
|
|
403
|
+
return [programResource, directoryResource, ...args];
|
|
404
|
+
};
|
|
405
|
+
const readonlyCommandResources = async ({ program, args, cwd }, workingDirectory, execTarget) => {
|
|
406
|
+
validateProcessArgs(args);
|
|
407
|
+
if (!program ||
|
|
408
|
+
program.includes('/') ||
|
|
409
|
+
program.includes('\\') ||
|
|
410
|
+
path.isAbsolute(program) ||
|
|
411
|
+
!/^[a-zA-Z0-9_-]+(?:\.exe)?$/i.test(program)) {
|
|
412
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Read-only command must be a bare allowlisted command name (got "${program}")`);
|
|
413
|
+
}
|
|
414
|
+
const base = program.toLowerCase().replace(/\.exe$/i, '');
|
|
415
|
+
if (!readonlyCommandAllowlist.has(base)) {
|
|
416
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Command "${program}" is not in the read-only diagnostic allowlist`);
|
|
417
|
+
}
|
|
418
|
+
const git = base === 'git';
|
|
419
|
+
const ctx = executionContext(workingDirectory, execTarget);
|
|
420
|
+
const directory = await workspacePath(workingDirectory, cwd, 'directory', git, false, execTarget);
|
|
421
|
+
const effectiveRoot = ctx.effectiveRoot;
|
|
422
|
+
const canonicalRoot = await realpath(effectiveRoot);
|
|
423
|
+
if (ctx.kind === 'container') {
|
|
424
|
+
for (const operand of readonlyPathCandidates(base, args)) {
|
|
425
|
+
if (!unprotectedPath(operand, git))
|
|
426
|
+
throw invalidPath();
|
|
427
|
+
}
|
|
428
|
+
const [directoryResource] = await pathResources(workingDirectory, [directory], execTarget);
|
|
429
|
+
return [program, directoryResource, ...args];
|
|
430
|
+
}
|
|
431
|
+
const paths = [];
|
|
432
|
+
for (const operand of readonlyPathCandidates(base, args)) {
|
|
433
|
+
if (!unprotectedPath(operand, git))
|
|
434
|
+
throw invalidPath();
|
|
435
|
+
const target = path.resolve(directory, operand);
|
|
436
|
+
const explicitPath = /[\\/]/.test(operand) || operand === '..';
|
|
437
|
+
if (explicitPath)
|
|
438
|
+
checkPath(canonicalRoot, target, git);
|
|
439
|
+
const canonical = await realpath(target).catch(() => undefined);
|
|
440
|
+
if (canonical !== undefined)
|
|
441
|
+
checkPath(canonicalRoot, canonical, git);
|
|
442
|
+
const candidate = canonical ?? (explicitPath ? target : undefined);
|
|
443
|
+
if (candidate && !isContainedPath(canonicalRoot, candidate))
|
|
444
|
+
paths.push(candidate);
|
|
445
|
+
}
|
|
446
|
+
const resolved = await resolveExecutableOnPath(program);
|
|
447
|
+
if (!resolved) {
|
|
448
|
+
throw new RuntimeError('PROGRAM_NOT_FOUND', `Allowlisted read-only command "${program}" was not found on PATH (platform=${process.platform}).`);
|
|
449
|
+
}
|
|
450
|
+
if (!unprotectedPath(resolved))
|
|
451
|
+
throw invalidPath();
|
|
452
|
+
const [directoryResource, ...externalOperands] = await pathResources(workingDirectory, [
|
|
453
|
+
directory,
|
|
454
|
+
...new Set(paths),
|
|
455
|
+
]);
|
|
456
|
+
return [resolved, directoryResource, ...args, ...externalOperands];
|
|
457
|
+
};
|
|
458
|
+
const withProcessWrite = (input, context, resources, run) => withWorkspaceWrite(sandboxRoot(context.workingDirectory, targetFor(context)), context.signal, async () => {
|
|
459
|
+
if (JSON.stringify(await processResources(input, context.workingDirectory, targetFor(context))) !==
|
|
460
|
+
JSON.stringify(resources))
|
|
461
|
+
throw new RuntimeError('APPROVAL_SCOPE_CHANGED', 'Resolved process resources have changed');
|
|
462
|
+
return run();
|
|
463
|
+
});
|
|
464
|
+
const shellResources = async ({ command, cwd = '.', timeout_ms }, workingDirectory, target) => {
|
|
465
|
+
if (!command.trim() || command.includes('\0'))
|
|
466
|
+
throw new RuntimeError('INVALID_ARGUMENTS', 'command must contain text and cannot contain a NUL character');
|
|
467
|
+
if (timeout_ms !== undefined &&
|
|
468
|
+
(!Number.isInteger(timeout_ms) || timeout_ms < 1 || timeout_ms > maxShellTimeoutMs))
|
|
469
|
+
throw new RuntimeError('INVALID_ARGUMENTS', `timeout_ms must be an integer between 1 and ${maxShellTimeoutMs}`);
|
|
470
|
+
const ctx = executionContext(workingDirectory, target);
|
|
471
|
+
const effectiveRoot = ctx.effectiveRoot;
|
|
472
|
+
const resolvedInput = resolveInputPath(workingDirectory, cwd, ctx);
|
|
473
|
+
if (!isContainedPath(effectiveRoot, resolvedInput))
|
|
474
|
+
throw new RuntimeError('WORKSPACE_PATH_INVALID', 'cwd must stay inside the workspace');
|
|
475
|
+
const directory = await workspacePath(workingDirectory, cwd, 'directory', false, false, target);
|
|
476
|
+
if (!isContainedPath(await realpath(effectiveRoot), directory))
|
|
477
|
+
throw new RuntimeError('WORKSPACE_PATH_INVALID', 'cwd must stay inside the workspace');
|
|
478
|
+
return [directory];
|
|
479
|
+
};
|
|
480
|
+
const bindings = [
|
|
481
|
+
binding('read_file', versionedFiles
|
|
482
|
+
? 'Read a UTF-8 workspace file and its SHA-256 revision for edit_file. Edit limit: 256 KiB.'
|
|
483
|
+
: 'Read up to 8192 bytes of a UTF-8 workspace file. Use byte_offset to continue.', {
|
|
484
|
+
path: pathSchema,
|
|
485
|
+
byte_offset: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER - maxReadBytes },
|
|
486
|
+
}, ['path'], 'read', readFileResources, async ({ byte_offset: offset = 0 }, context, [resource]) => {
|
|
487
|
+
if (resource.startsWith(containerReadonlyPrefix)) {
|
|
488
|
+
return readContainerBytePage(executionBackend, resource.slice(containerReadonlyPrefix.length), offset, maxReadBytes, context.signal, targetFor(context));
|
|
489
|
+
}
|
|
490
|
+
return readBytePage(resolvedWorkspacePath(resource), offset, versionedFiles);
|
|
491
|
+
}),
|
|
492
|
+
binding('search_files', 'Find case-sensitive literal text in UTF-8 files below a workspace directory. Results are bounded.', { path: pathSchema, query: { type: 'string', minLength: 1, maxLength: 256 } }, ['path', 'query'], 'read', directoryResources, async ({ query }, context, [resource]) => {
|
|
493
|
+
const target = targetFor(context);
|
|
494
|
+
const directory = resolvedWorkspacePath(resource);
|
|
495
|
+
const effectiveRoot = await realpath(sandboxRoot(context.workingDirectory, target));
|
|
496
|
+
return search(isContainedPath(effectiveRoot, directory) ? effectiveRoot : directory, directory, query, context.signal, (_cwd, supplied, kind) => workspacePath(context.workingDirectory, supplied, kind, false, false, target));
|
|
497
|
+
}),
|
|
498
|
+
binding('edit_file', phase2
|
|
499
|
+
? 'Replace one exact, unique old_text in an existing UTF-8 file. Call read_file first. new_text is required; pass an empty string to delete the selected text.'
|
|
500
|
+
: versionedFiles
|
|
501
|
+
? 'Replace one exact, unique old_text after approval. Include the SHA-256 from read_file.'
|
|
502
|
+
: 'Replace one exact, unique old_text in an existing UTF-8 workspace file after approval.', {
|
|
503
|
+
path: pathSchema,
|
|
504
|
+
old_text: { type: 'string', minLength: 1, maxLength: maxReadBytes },
|
|
505
|
+
new_text: { type: 'string', maxLength: maxReadBytes },
|
|
506
|
+
...(!phase2 && versionedFiles
|
|
507
|
+
? { expected_sha256: { type: 'string', pattern: '^[0-9a-f]{64}$' } }
|
|
508
|
+
: {}),
|
|
509
|
+
}, ['path', 'old_text', 'new_text', ...(!phase2 && versionedFiles ? ['expected_sha256'] : [])], 'non_idempotent_write', phase2 ? writableFileResources : fileResources, async ({ path: supplied, old_text: before, new_text: after, expected_sha256: expected }, context, [resource]) => {
|
|
510
|
+
const target = targetFor(context);
|
|
511
|
+
const ctx = executionContext(context.workingDirectory, target);
|
|
512
|
+
if (ctx.kind === 'container' && ctx.readonly) {
|
|
513
|
+
throw new RuntimeError('SANDBOX_READONLY', 'Write operation denied in read-only sandbox');
|
|
514
|
+
}
|
|
515
|
+
const file = resolvedWorkspacePath(resource);
|
|
516
|
+
const effectiveRoot = ctx.effectiveRoot;
|
|
517
|
+
return withWorkspaceWrite(effectiveRoot, context.signal, async () => {
|
|
518
|
+
const currentResolved = phase2
|
|
519
|
+
? await resolveWritableFile(context.workingDirectory, supplied, target)
|
|
520
|
+
: await workspacePath(context.workingDirectory, supplied, 'file', false, false, target);
|
|
521
|
+
if (currentResolved !== file)
|
|
522
|
+
return failure('APPROVAL_SCOPE_CHANGED', 'Resolved tool resources have changed');
|
|
523
|
+
const snapshot = phase2
|
|
524
|
+
? requireFileSnapshot(context, file, await existingFileInfo(file))
|
|
525
|
+
: undefined;
|
|
526
|
+
const { bytes, more, info } = await readBytes(file, 0, maxFileBytes);
|
|
527
|
+
if (snapshot !== undefined &&
|
|
528
|
+
(snapshot.stat !== fileRevision(info) ||
|
|
529
|
+
(snapshot.sha256 !== undefined && snapshot.sha256 !== sha256Hex(bytes))))
|
|
530
|
+
throw staleFile();
|
|
531
|
+
if (more)
|
|
532
|
+
return failure('FILE_TOO_LARGE', 'File exceeds the edit limit');
|
|
533
|
+
if (!phase2 && versionedFiles && sha256Hex(bytes) !== expected)
|
|
534
|
+
return failure('FILE_VERSION_CONFLICT', 'File revision changed; read the file again before editing');
|
|
535
|
+
const original = decoder.decode(bytes);
|
|
536
|
+
const at = original.indexOf(before);
|
|
537
|
+
if (at < 0)
|
|
538
|
+
return failure(options.patchTools || phase2 ? 'EDIT_NOT_FOUND' : 'EDIT_MISMATCH', 'old_text was not found; read the current file and copy the exact text');
|
|
539
|
+
if (original.indexOf(before, at + 1) >= 0)
|
|
540
|
+
return failure(options.patchTools || phase2 ? 'EDIT_AMBIGUOUS' : 'EDIT_MISMATCH', 'old_text matches more than once; include surrounding context');
|
|
541
|
+
const changed = original.slice(0, at) + after + original.slice(at + before.length);
|
|
542
|
+
const changedBuffer = Buffer.from(changed, 'utf8');
|
|
543
|
+
if (changedBuffer.byteLength > maxFileBytes)
|
|
544
|
+
return failure('FILE_TOO_LARGE', 'Edit exceeds the file limit');
|
|
545
|
+
if (changed === original)
|
|
546
|
+
return success('File already has the requested content', 'none');
|
|
547
|
+
const temporary = path.join(path.dirname(file), '.saturn-edit-' + randomUUID());
|
|
548
|
+
const handle = await open(temporary, 'wx', info.mode & 0o777);
|
|
549
|
+
try {
|
|
550
|
+
try {
|
|
551
|
+
await handle.writeFile(changedBuffer);
|
|
552
|
+
}
|
|
553
|
+
finally {
|
|
554
|
+
await handle.close();
|
|
555
|
+
}
|
|
556
|
+
const prepared = phase2 || context.fileSnapshots ? await lstat(temporary) : undefined;
|
|
557
|
+
const current = phase2
|
|
558
|
+
? await resolveWritableFile(context.workingDirectory, supplied, target)
|
|
559
|
+
: await workspacePath(context.workingDirectory, supplied, 'file', false, false, target);
|
|
560
|
+
if (snapshot !== undefined &&
|
|
561
|
+
(current !== file || snapshot.stat !== fileRevision(await existingFileInfo(file))))
|
|
562
|
+
throw staleFile();
|
|
563
|
+
const check = await readBytes(current, 0, maxFileBytes);
|
|
564
|
+
if (current !== file ||
|
|
565
|
+
check.more ||
|
|
566
|
+
!check.bytes.equals(bytes) ||
|
|
567
|
+
(snapshot !== undefined && snapshot.stat !== fileRevision(await existingFileInfo(file)))) {
|
|
568
|
+
if (phase2)
|
|
569
|
+
throw staleFile();
|
|
570
|
+
return failure('EDIT_MISMATCH', 'File changed during the edit');
|
|
571
|
+
}
|
|
572
|
+
context.signal.throwIfAborted();
|
|
573
|
+
await rename(temporary, file);
|
|
574
|
+
if (prepared)
|
|
575
|
+
await recordReplacement(context, file, prepared, sha256Hex(changedBuffer));
|
|
576
|
+
return success('Replaced the requested text', 'applied');
|
|
577
|
+
}
|
|
578
|
+
finally {
|
|
579
|
+
await unlink(temporary).catch(() => { });
|
|
580
|
+
}
|
|
581
|
+
});
|
|
582
|
+
}),
|
|
583
|
+
binding('write_file', 'Create or overwrite a UTF-8 workspace file atomically after approval. Max size: 256 KiB. Missing parent directories inside the workspace are created safely.' +
|
|
584
|
+
(phase2 ? ' Call read_file before overwriting an existing file.' : ''), {
|
|
585
|
+
path: pathSchema,
|
|
586
|
+
content: { type: 'string', maxLength: maxFileBytes },
|
|
587
|
+
}, ['path', 'content'], 'non_idempotent_write', writableFileResources, async ({ path: suppliedPath, content }, context, [resource]) => {
|
|
588
|
+
const target = targetFor(context);
|
|
589
|
+
const file = resolvedWorkspacePath(resource);
|
|
590
|
+
const effectiveRoot = sandboxRoot(context.workingDirectory, target);
|
|
591
|
+
return withWorkspaceWrite(effectiveRoot, context.signal, async () => {
|
|
592
|
+
const byteLength = Buffer.byteLength(content, 'utf8');
|
|
593
|
+
if (byteLength > maxFileBytes)
|
|
594
|
+
return failure('FILE_TOO_LARGE', 'Content exceeds the 256 KiB file limit');
|
|
595
|
+
if ((await resolveWritableFile(context.workingDirectory, suppliedPath, target)) !== file)
|
|
596
|
+
return failure('APPROVAL_SCOPE_CHANGED', 'Resolved tool resources have changed');
|
|
597
|
+
const existing = await existingFileInfo(file);
|
|
598
|
+
if (existing) {
|
|
599
|
+
if (existing.isDirectory())
|
|
600
|
+
return failure('WORKSPACE_PATH_INVALID', 'Target is a directory. Specify a file path.');
|
|
601
|
+
if (!existing.isFile() || existing.nlink !== 1)
|
|
602
|
+
throw invalidPath();
|
|
603
|
+
}
|
|
604
|
+
const snapshot = phase2 && existing ? requireFileSnapshot(context, file, existing) : undefined;
|
|
605
|
+
if (snapshot?.sha256 !== undefined && existing && existing.size <= maxFileBytes) {
|
|
606
|
+
const currentBytes = await readBytes(file, 0, maxFileBytes);
|
|
607
|
+
if (currentBytes.more || sha256Hex(currentBytes.bytes) !== snapshot.sha256)
|
|
608
|
+
throw staleFile();
|
|
609
|
+
}
|
|
610
|
+
const mode = existing ? existing.mode & 0o777 : 0o644;
|
|
611
|
+
await ensureSafeDirectories(path.dirname(file), context.signal);
|
|
612
|
+
const temporary = path.join(path.dirname(file), '.saturn-write-' + randomUUID());
|
|
613
|
+
const handle = await open(temporary, 'wx', mode);
|
|
614
|
+
try {
|
|
615
|
+
const contentBuffer = Buffer.from(content, 'utf8');
|
|
616
|
+
const contentSha256 = sha256Hex(contentBuffer);
|
|
617
|
+
try {
|
|
618
|
+
await handle.writeFile(contentBuffer);
|
|
619
|
+
}
|
|
620
|
+
finally {
|
|
621
|
+
await handle.close();
|
|
622
|
+
}
|
|
623
|
+
const prepared = phase2 || context.fileSnapshots ? await lstat(temporary) : undefined;
|
|
624
|
+
if ((await resolveWritableFile(context.workingDirectory, suppliedPath, target)) !== file)
|
|
625
|
+
return failure('APPROVAL_SCOPE_CHANGED', 'Resolved tool resources have changed');
|
|
626
|
+
if (snapshot !== undefined && snapshot.stat !== fileRevision(await existingFileInfo(file)))
|
|
627
|
+
throw staleFile();
|
|
628
|
+
context.signal.throwIfAborted();
|
|
629
|
+
if (phase2 && !existing) {
|
|
630
|
+
try {
|
|
631
|
+
await link(temporary, file);
|
|
632
|
+
}
|
|
633
|
+
catch (error) {
|
|
634
|
+
if (error.code === 'EEXIST')
|
|
635
|
+
throw staleFile();
|
|
636
|
+
throw error;
|
|
637
|
+
}
|
|
638
|
+
await unlink(temporary).catch(() => { });
|
|
639
|
+
}
|
|
640
|
+
else
|
|
641
|
+
await rename(temporary, file);
|
|
642
|
+
if (prepared)
|
|
643
|
+
await recordReplacement(context, file, prepared, contentSha256);
|
|
644
|
+
return success(existing ? 'Overwrote file' : 'Created file', 'applied', {
|
|
645
|
+
path: path.relative(effectiveRoot, file),
|
|
646
|
+
bytes: byteLength,
|
|
647
|
+
created: !existing,
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
finally {
|
|
651
|
+
await unlink(temporary).catch(() => { });
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
}),
|
|
655
|
+
binding('run_process', 'Run an approved program directly with an argv array and workspace cwd. Specify a command name on PATH, its full path, or a path relative to cwd. Output is bounded to 64 KiB.', {
|
|
656
|
+
program: pathSchema,
|
|
657
|
+
args: { type: 'array', maxItems: 32, items: { type: 'string', maxLength: 1024 } },
|
|
658
|
+
cwd: pathSchema,
|
|
659
|
+
}, ['program', 'args', 'cwd'], 'non_idempotent_write', processResources, async (input, context, resources) => withProcessWrite(input, context, resources, () => {
|
|
660
|
+
const target = targetFor(context);
|
|
661
|
+
return executionContext(context.workingDirectory, target).backend.runCommand({
|
|
662
|
+
program: resolvedWorkspacePath(resources[0]),
|
|
663
|
+
args: input.args,
|
|
664
|
+
cwd: resolvedWorkspacePath(resources[1]),
|
|
665
|
+
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
|
|
666
|
+
timeoutMs: processTimeoutMs,
|
|
667
|
+
signal: context.signal,
|
|
668
|
+
output: captureProcessOutput(context),
|
|
669
|
+
effect: 'applied',
|
|
670
|
+
}, target);
|
|
671
|
+
}), processTimeoutMs),
|
|
672
|
+
binding('run_readonly_command', 'Run a strictly allowlisted read-only diagnostic command (e.g. strings, objdump, readelf, nm, file, size, ldd, checksec, rg, grep, findstr, wc, head, tail, stat, ls, tree, where, which, or read-only git subcommands) with shell=false inside workspace cwd. Output is bounded to 64 KiB.', {
|
|
673
|
+
program: pathSchema,
|
|
674
|
+
args: { type: 'array', maxItems: 32, items: { type: 'string', maxLength: 1024 } },
|
|
675
|
+
cwd: pathSchema,
|
|
676
|
+
}, ['program', 'args', 'cwd'], 'read', readonlyCommandResources, async (input, context, [program, cwd]) => {
|
|
677
|
+
const target = targetFor(context);
|
|
678
|
+
return executionContext(context.workingDirectory, target).backend.runCommand({
|
|
679
|
+
program: program,
|
|
680
|
+
args: input.args,
|
|
681
|
+
cwd: resolvedWorkspacePath(cwd),
|
|
682
|
+
timeoutMs: processTimeoutMs,
|
|
683
|
+
signal: context.signal,
|
|
684
|
+
output: captureProcessOutput(context),
|
|
685
|
+
effect: 'none',
|
|
686
|
+
}, target);
|
|
687
|
+
}, processTimeoutMs),
|
|
688
|
+
binding('list_dir', 'List the immediate entries of a workspace directory with their types. Use path "." to inspect the current directory before reading a file. The listing is bounded.', { path: pathSchema }, ['path'], 'read', directoryResources, async (_input, context, [resource]) => listDirectory(resolvedWorkspacePath(resource), context.signal)),
|
|
689
|
+
];
|
|
690
|
+
if (phase1 && !versionedFiles) {
|
|
691
|
+
const shell = binding('shell', 'Run a command string with PowerShell on Windows or sh on POSIX. cwd defaults to the current workspace directory. The timeout defaults to 30 seconds and can be set up to 300,000 ms with timeout_ms. Large output retains the first 8 KiB and last 56 KiB with a full output file for read_file.', {
|
|
692
|
+
command: { type: 'string', minLength: 1 },
|
|
693
|
+
cwd: pathSchema,
|
|
694
|
+
timeout_ms: { type: 'integer', minimum: 1, maximum: maxShellTimeoutMs },
|
|
695
|
+
description: { type: 'string' },
|
|
696
|
+
}, ['command'], 'non_idempotent_write', shellResources, async (input, context, [cwd]) => {
|
|
697
|
+
const target = targetFor(context);
|
|
698
|
+
const ctx = executionContext(context.workingDirectory, target);
|
|
699
|
+
return withWorkspaceWrite(ctx.effectiveRoot, context.signal, async () => {
|
|
700
|
+
if ((await shellResources(input, context.workingDirectory, target))[0] !== cwd)
|
|
701
|
+
return failure('APPROVAL_SCOPE_CHANGED', 'Resolved shell cwd has changed');
|
|
702
|
+
const invocation = ctx.backend.shellInvocation(input.command, target);
|
|
703
|
+
return ctx.backend.runCommand({
|
|
704
|
+
program: invocation.program,
|
|
705
|
+
args: invocation.args,
|
|
706
|
+
cwd: cwd,
|
|
707
|
+
timeoutMs: input.timeout_ms ?? processTimeoutMs,
|
|
708
|
+
signal: context.signal,
|
|
709
|
+
output: captureProcessOutput(context),
|
|
710
|
+
effect: 'applied',
|
|
711
|
+
}, target);
|
|
712
|
+
});
|
|
713
|
+
}, maxShellTimeoutMs);
|
|
714
|
+
bindings.push({ ...shell, definition: { ...shell.definition, abortGraceMs: 5000 } });
|
|
715
|
+
}
|
|
716
|
+
if (phase1) {
|
|
717
|
+
bindings[0] = binding('read_file', 'Read a UTF-8 workspace file with 1-based line numbers (offset defaults to 1, limit to 200). The text page is capped at 32 KiB. Continue from endLine + 1, or use next_byte_offset with byte_offset for a line longer than the page.' +
|
|
718
|
+
(phase2
|
|
719
|
+
? ' Records the file revision for later edit_file and write_file calls in the same Run.'
|
|
720
|
+
: versionedFiles
|
|
721
|
+
? ' Includes the SHA-256 revision for edit_file when the file is within the 256 KiB edit limit.'
|
|
722
|
+
: ''), {
|
|
723
|
+
path: pathSchema,
|
|
724
|
+
offset: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
|
|
725
|
+
limit: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
|
|
726
|
+
byte_offset: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER - maxReadPageBytes },
|
|
727
|
+
}, ['path'], 'read', readFileResources, async ({ byte_offset, offset, limit }, context, [resource]) => {
|
|
728
|
+
if (resource.startsWith(containerReadonlyPrefix)) {
|
|
729
|
+
const containerPath = resource.slice(containerReadonlyPrefix.length);
|
|
730
|
+
const target = targetFor(context);
|
|
731
|
+
if (byte_offset !== undefined) {
|
|
732
|
+
if (offset !== undefined || limit !== undefined)
|
|
733
|
+
return failure('INVALID_ARGUMENTS', 'Use byte_offset or line pagination (offset and limit)');
|
|
734
|
+
return readContainerBytePage(executionBackend, containerPath, byte_offset, maxReadPageBytes, context.signal, target);
|
|
735
|
+
}
|
|
736
|
+
return readContainerLinePage(executionBackend, containerPath, offset ?? 1, limit ?? defaultReadLines, context.signal, target);
|
|
737
|
+
}
|
|
738
|
+
const file = resolvedWorkspacePath(resource);
|
|
739
|
+
const record = phase2
|
|
740
|
+
? (info, sha256) => {
|
|
741
|
+
context.signal.throwIfAborted();
|
|
742
|
+
context.fileSnapshots?.set(snapshotKey(file), formatFileSnapshot(info, sha256));
|
|
743
|
+
}
|
|
744
|
+
: undefined;
|
|
745
|
+
if (byte_offset !== undefined) {
|
|
746
|
+
if (offset !== undefined || limit !== undefined)
|
|
747
|
+
return failure('INVALID_ARGUMENTS', 'Use byte_offset or line pagination (offset and limit)');
|
|
748
|
+
return readBytePage(file, byte_offset, !phase2 && versionedFiles, maxReadPageBytes, record);
|
|
749
|
+
}
|
|
750
|
+
return readLinePage(file, offset ?? 1, limit ?? defaultReadLines, !phase2 && versionedFiles, context.signal, record);
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
if (!options.legacyProcessTools) {
|
|
754
|
+
for (const [index, tool] of bindings.entries()) {
|
|
755
|
+
if (['run_process', 'run_readonly_command'].includes(tool.definition.name)) {
|
|
756
|
+
const isRunProcess = tool.definition.name === 'run_process';
|
|
757
|
+
const properties = isRunProcess &&
|
|
758
|
+
tool.definition.inputSchema.properties &&
|
|
759
|
+
typeof tool.definition.inputSchema.properties === 'object' &&
|
|
760
|
+
!Array.isArray(tool.definition.inputSchema.properties)
|
|
761
|
+
? {
|
|
762
|
+
...tool.definition.inputSchema.properties,
|
|
763
|
+
stdin: { type: 'string', maxLength: maxProcessOutputBytes },
|
|
764
|
+
}
|
|
765
|
+
: tool.definition.inputSchema.properties;
|
|
766
|
+
bindings[index] = {
|
|
767
|
+
...tool,
|
|
768
|
+
definition: {
|
|
769
|
+
...tool.definition,
|
|
770
|
+
version: '2',
|
|
771
|
+
abortGraceMs: 5000,
|
|
772
|
+
inputSchema: {
|
|
773
|
+
...tool.definition.inputSchema,
|
|
774
|
+
...(properties ? { properties } : {}),
|
|
775
|
+
},
|
|
776
|
+
description: isRunProcess
|
|
777
|
+
? 'Run an approved short command directly with argv and workspace cwd (supports python3, bash/sh on Linux/WSL, gcc, gdb, node, docker, builds, or tests). Optional stdin (up to 64 KiB) is piped then closed; otherwise stdin is closed. Output is bounded to 64 KiB; a 30-second hard wait stops the process tree and returns TIMEOUT with partial output. Use start_process for servers, interactive input and long-running work.'
|
|
778
|
+
: 'Run an allowlisted read-only diagnostic command (strings, objdump, readelf, nm, file, size, ldd, checksec, rg, grep, findstr, wc, head, tail, stat, ls, tree, where, which, or read-only git subcommands) with argv and workspace cwd, closed stdin and bounded 64 KiB output (30-second wait limit). For commands outside this allowlist (such as python, node, docker, wsl, builds, or tests), use run_process (<=30s) or start_process (>30s/interactive).',
|
|
779
|
+
},
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const startBase = binding('start_process', 'Start an approved long-running program and return its process_id without waiting for exit. Use read_process for output, write_process for input/EOF and stop_process for cleanup. Owned by this workspace, run and agent; default hard lifetime is 15 minutes, capped by the Run deadline.', {
|
|
784
|
+
program: pathSchema,
|
|
785
|
+
args: { type: 'array', maxItems: 32, items: { type: 'string', maxLength: 1024 } },
|
|
786
|
+
cwd: pathSchema,
|
|
787
|
+
timeout_ms: { type: 'integer', minimum: 1, maximum: 86400000 },
|
|
788
|
+
}, ['program', 'args', 'cwd'], 'non_idempotent_write', processResources, async (input, context, resources) => withProcessWrite(input, context, resources, async () => {
|
|
789
|
+
const target = targetFor(context);
|
|
790
|
+
const ctx = executionContext(context.workingDirectory, target);
|
|
791
|
+
const rawStart = {
|
|
792
|
+
program: resolvedWorkspacePath(resources[0]),
|
|
793
|
+
args: input.args,
|
|
794
|
+
cwd: resolvedWorkspacePath(resources[1]),
|
|
795
|
+
...(input.timeout_ms === undefined ? {} : { timeoutMs: input.timeout_ms }),
|
|
796
|
+
};
|
|
797
|
+
const startInput = ctx.backend.wrapStartProcess
|
|
798
|
+
? ctx.backend.wrapStartProcess(rawStart, target, context.executionKey)
|
|
799
|
+
: rawStart;
|
|
800
|
+
const value = await processes().start(startInput, processScope(context), context.executionKey, context.signal);
|
|
801
|
+
return processObservation(value, value.status === 'unknown' || value.status === 'starting'
|
|
802
|
+
? 'unknown'
|
|
803
|
+
: value.startError
|
|
804
|
+
? 'none'
|
|
805
|
+
: 'applied');
|
|
806
|
+
}));
|
|
807
|
+
const start = {
|
|
808
|
+
...startBase,
|
|
809
|
+
definition: {
|
|
810
|
+
...startBase.definition,
|
|
811
|
+
supportsIdempotencyKey: true,
|
|
812
|
+
supportsReconcile: true,
|
|
813
|
+
abortGraceMs: 2000,
|
|
814
|
+
},
|
|
815
|
+
};
|
|
816
|
+
start.handler.reconcile = async (key, context) => {
|
|
817
|
+
const value = await processes().reconcile(key, processScope(context));
|
|
818
|
+
const evidenceRef = `process:${value?.processId ?? key}`;
|
|
819
|
+
if (!value)
|
|
820
|
+
return { kind: 'not_applied', evidenceRef };
|
|
821
|
+
if (value.status === 'starting' || value.status === 'unknown')
|
|
822
|
+
throw new RuntimeError('PROCESS_OUTCOME_UNKNOWN', 'Supervisor identity could not be verified; process will not be restarted');
|
|
823
|
+
const observation = processObservation(value, value.startError ? 'none' : 'applied');
|
|
824
|
+
return {
|
|
825
|
+
kind: 'completed',
|
|
826
|
+
evidenceRef,
|
|
827
|
+
result: {
|
|
828
|
+
toolCallId: key.split(':').at(-1),
|
|
829
|
+
...observation,
|
|
830
|
+
},
|
|
831
|
+
};
|
|
832
|
+
};
|
|
833
|
+
const handleResources = async ({ process_id }) => [`process:${process_id}`];
|
|
834
|
+
const handleSchema = { type: 'string', pattern: '^[a-f0-9]{64}$' };
|
|
835
|
+
bindings.push(start, binding('read_process', 'Read bounded stdout/stderr and process status. Byte offsets resume output; wait_ms only waits for output and never stops the process.', {
|
|
836
|
+
process_id: handleSchema,
|
|
837
|
+
stdout_offset: { type: 'integer', minimum: 0 },
|
|
838
|
+
stderr_offset: { type: 'integer', minimum: 0 },
|
|
839
|
+
max_bytes: { type: 'integer', minimum: 1, maximum: 65536 },
|
|
840
|
+
wait_ms: { type: 'integer', minimum: 0, maximum: phase2 ? 30000 : 1000 },
|
|
841
|
+
}, ['process_id'], 'read', handleResources, async (input, context) => processObservation(await processes().read(input.process_id, processScope(context), {
|
|
842
|
+
...(input.stdout_offset === undefined ? {} : { stdoutOffset: input.stdout_offset }),
|
|
843
|
+
...(input.stderr_offset === undefined ? {} : { stderrOffset: input.stderr_offset }),
|
|
844
|
+
...(input.max_bytes === undefined ? {} : { maxBytes: input.max_bytes }),
|
|
845
|
+
...(input.wait_ms === undefined ? {} : { waitMs: input.wait_ms }),
|
|
846
|
+
}, context.signal), 'none'), phase2 ? 35000 : 10000), binding('write_process', 'Send up to 64 KiB of stdin to an owned process. Set eof:true explicitly to close stdin. A failed unconfirmed write must not be repeated with a new execution key.', { process_id: handleSchema, input: { type: 'string', maxLength: 65536 }, eof: { type: 'boolean' } }, ['process_id'], 'non_idempotent_write', handleResources, async (input, context) => {
|
|
847
|
+
try {
|
|
848
|
+
return processObservation(await processes().write(input.process_id, processScope(context), {
|
|
849
|
+
...(input.input === undefined ? {} : { input: input.input }),
|
|
850
|
+
...(input.eof === undefined ? {} : { eof: input.eof }),
|
|
851
|
+
}, context.executionKey), 'applied');
|
|
852
|
+
}
|
|
853
|
+
catch (error) {
|
|
854
|
+
if (error instanceof RuntimeError && error.code === 'PROCESS_INPUT_UNKNOWN')
|
|
855
|
+
return {
|
|
856
|
+
outcome: {
|
|
857
|
+
status: 'error',
|
|
858
|
+
error: { code: error.code, message: error.message, retryable: false },
|
|
859
|
+
},
|
|
860
|
+
effect: 'unknown',
|
|
861
|
+
};
|
|
862
|
+
throw error;
|
|
863
|
+
}
|
|
864
|
+
}), binding('stop_process', 'Stop an owned process and its verifiable descendants. Returns unknown when termination cannot be confirmed, including unverified WSL descendants.', { process_id: handleSchema }, ['process_id'], 'non_idempotent_write', handleResources, async (input, context) => {
|
|
865
|
+
const value = await processes().stop(input.process_id, processScope(context));
|
|
866
|
+
return value.terminationConfirmed || value.status === 'exited'
|
|
867
|
+
? processObservation(value, value.terminationConfirmed ? 'applied' : 'none')
|
|
868
|
+
: {
|
|
869
|
+
outcome: {
|
|
870
|
+
status: 'error',
|
|
871
|
+
error: {
|
|
872
|
+
code: 'PROCESS_STOP_UNCONFIRMED',
|
|
873
|
+
message: 'Process tree termination could not be confirmed',
|
|
874
|
+
retryable: false,
|
|
875
|
+
},
|
|
876
|
+
data: processData(value),
|
|
877
|
+
},
|
|
878
|
+
effect: 'unknown',
|
|
879
|
+
};
|
|
880
|
+
}));
|
|
881
|
+
}
|
|
882
|
+
if (options.patchTools && !versionedFiles) {
|
|
883
|
+
const resources = async ({ input }, cwd, target) => {
|
|
884
|
+
const files = await Promise.all(parseTextPatch(input).map((file) => file.operation === 'add'
|
|
885
|
+
? resolveWritableFile(cwd, file.path, target)
|
|
886
|
+
: workspacePath(cwd, file.path, 'file', false, false, target)));
|
|
887
|
+
if (new Set(files.map((file) => (process.platform === 'win32' ? file.toLowerCase() : file))).size !==
|
|
888
|
+
files.length)
|
|
889
|
+
throw new RuntimeError('INVALID_PATCH', 'Each file may appear only once');
|
|
890
|
+
return pathResources(cwd, files, target);
|
|
891
|
+
};
|
|
892
|
+
bindings.push(binding('apply_patch', 'Apply a UTF-8 workspace patch. Wrap it in *** Begin Patch and *** End Patch. Use *** Add File: path with + lines, or *** Update File: path with @@ hunks using space-prefixed context, + additions and - removals. Update hunks need unique original context. Read touched files before retrying a partial result.', { input: { type: 'string', minLength: 1, maxLength: maxFileBytes } }, ['input'], 'non_idempotent_write', resources, async (input, context, approvedTargets) => {
|
|
893
|
+
const target = targetFor(context);
|
|
894
|
+
const ctx = executionContext(context.workingDirectory, target);
|
|
895
|
+
if (ctx.kind === 'container' && ctx.readonly) {
|
|
896
|
+
throw new RuntimeError('SANDBOX_READONLY', 'Write operation denied in read-only sandbox');
|
|
897
|
+
}
|
|
898
|
+
return withWorkspaceWrite(ctx.effectiveRoot, context.signal, async () => {
|
|
899
|
+
const cwd = context.workingDirectory;
|
|
900
|
+
const patches = parseTextPatch(input.input);
|
|
901
|
+
const targets = approvedTargets.map(resolvedWorkspacePath);
|
|
902
|
+
const verifyTargets = async () => {
|
|
903
|
+
if (JSON.stringify(await resources(input, cwd, target)) !== JSON.stringify(approvedTargets))
|
|
904
|
+
throw new RuntimeError('APPROVAL_SCOPE_CHANGED', 'Resolved patch resources have changed');
|
|
905
|
+
};
|
|
906
|
+
await verifyTargets();
|
|
907
|
+
const changes = await Promise.all(patches.map(async (patch, index) => {
|
|
908
|
+
const file = targets[index];
|
|
909
|
+
const prior = patch.operation === 'update' ? await readBytes(file, 0, maxFileBytes) : undefined;
|
|
910
|
+
if (prior?.more)
|
|
911
|
+
throw new RuntimeError('FILE_TOO_LARGE', 'File exceeds the patch limit');
|
|
912
|
+
if (!prior)
|
|
913
|
+
await assertPatchFileAbsent(file);
|
|
914
|
+
const original = prior ? decoder.decode(prior.bytes) : undefined;
|
|
915
|
+
const text = original === undefined
|
|
916
|
+
? patch.added.length
|
|
917
|
+
? patch.added.join('\n') + '\n'
|
|
918
|
+
: ''
|
|
919
|
+
: applyTextPatch(patch, original);
|
|
920
|
+
if (Buffer.byteLength(text) > maxFileBytes)
|
|
921
|
+
throw new RuntimeError('FILE_TOO_LARGE', 'Patched file exceeds the file limit');
|
|
922
|
+
return { file, supplied: patch.path, prior, text, changed: original !== text };
|
|
923
|
+
}));
|
|
924
|
+
const written = [];
|
|
925
|
+
const unchanged = [];
|
|
926
|
+
for (const [index, change] of changes.entries()) {
|
|
927
|
+
if (!change.changed) {
|
|
928
|
+
unchanged.push(change.supplied);
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
931
|
+
const temporary = path.join(path.dirname(change.file), '.saturn-edit-' + randomUUID());
|
|
932
|
+
try {
|
|
933
|
+
context.signal.throwIfAborted();
|
|
934
|
+
if (!change.prior)
|
|
935
|
+
await ensureSafeDirectories(path.dirname(change.file), context.signal);
|
|
936
|
+
const handle = await open(temporary, 'wx', change.prior ? change.prior.mode & 0o777 : 0o644);
|
|
937
|
+
try {
|
|
938
|
+
await handle.writeFile(change.text, 'utf8');
|
|
939
|
+
}
|
|
940
|
+
finally {
|
|
941
|
+
await handle.close();
|
|
942
|
+
}
|
|
943
|
+
await verifyTargets();
|
|
944
|
+
if (change.prior) {
|
|
945
|
+
const current = await readBytes(change.file, 0, maxFileBytes);
|
|
946
|
+
if (current.more || !current.bytes.equals(change.prior.bytes))
|
|
947
|
+
throw new RuntimeError('FILE_VERSION_CONFLICT', 'File changed while applying the patch');
|
|
948
|
+
}
|
|
949
|
+
const prepared = context.fileSnapshots ? await lstat(temporary) : undefined;
|
|
950
|
+
context.signal.throwIfAborted();
|
|
951
|
+
if (change.prior)
|
|
952
|
+
await rename(temporary, change.file);
|
|
953
|
+
else {
|
|
954
|
+
await link(temporary, change.file);
|
|
955
|
+
await unlink(temporary).catch(() => { });
|
|
956
|
+
}
|
|
957
|
+
if (prepared) {
|
|
958
|
+
await recordReplacement(context, change.file, prepared, sha256Hex(Buffer.from(change.text, 'utf8')));
|
|
959
|
+
}
|
|
960
|
+
written.push(change.supplied);
|
|
961
|
+
}
|
|
962
|
+
catch (error) {
|
|
963
|
+
if (!written.length)
|
|
964
|
+
throw error;
|
|
965
|
+
return {
|
|
966
|
+
effect: 'applied',
|
|
967
|
+
outcome: {
|
|
968
|
+
status: 'error',
|
|
969
|
+
error: {
|
|
970
|
+
code: 'PATCH_PARTIAL',
|
|
971
|
+
message: 'Some files were written before the patch stopped. Re-read affected paths before retrying.',
|
|
972
|
+
retryable: false,
|
|
973
|
+
},
|
|
974
|
+
data: { written, unchanged, pending: changes.slice(index).map((item) => item.supplied) },
|
|
975
|
+
},
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
finally {
|
|
979
|
+
await unlink(temporary).catch(() => { });
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
return success('Patch applied', written.length ? 'applied' : 'none', { written, unchanged });
|
|
983
|
+
});
|
|
984
|
+
}));
|
|
985
|
+
}
|
|
986
|
+
if (phase2) {
|
|
987
|
+
const pattern = { type: 'string', minLength: 1, maxLength: 1024 };
|
|
988
|
+
const limit = { type: 'integer', minimum: 1, maximum: maxDiscoveryResults };
|
|
989
|
+
bindings.push(binding('glob', 'Find files by a glob relative to path. Use ** to recurse. Returns workspace-relative paths, newest first. Path defaults to the workspace root; limit defaults to 200.', { pattern, path: pathSchema, limit }, ['pattern'], 'read', (input, cwd, target) => discoveryResources(input.path, cwd, 'directory', target), async ({ pattern, limit = 200 }, context, [target]) => {
|
|
990
|
+
const ctx = executionContext(context.workingDirectory, targetFor(context));
|
|
991
|
+
const root = await realpath(ctx.effectiveRoot);
|
|
992
|
+
const result = await globWorkspace({ root, target: target, strictSymlinks: ctx.kind === 'container' }, pattern, limit, context.signal);
|
|
993
|
+
return success([
|
|
994
|
+
...(result.paths.length ? result.paths : ['No matching files']),
|
|
995
|
+
...(result.truncated
|
|
996
|
+
? [`Showing ${result.paths.length} of ${result.totalMatched} matches`]
|
|
997
|
+
: []),
|
|
998
|
+
].join('\n'), 'none', result);
|
|
999
|
+
}), binding('grep', 'Search UTF-8 files by line using a regular expression. Path defaults to the workspace root. An include glob without a slash matches basenames at every depth. Case-sensitive by default, with 0 context lines and a limit of 100 matching lines.', {
|
|
1000
|
+
pattern,
|
|
1001
|
+
path: pathSchema,
|
|
1002
|
+
include: pattern,
|
|
1003
|
+
ignore_case: { type: 'boolean' },
|
|
1004
|
+
context_lines: { type: 'integer', minimum: 0, maximum: maxContextLines },
|
|
1005
|
+
limit,
|
|
1006
|
+
}, ['pattern'], 'read', (input, cwd, target) => discoveryResources(input.path, cwd, 'either', target), async ({ pattern, include, ignore_case: ignoreCase = false, context_lines: contextLines = 0, limit = 100 }, context, [target]) => {
|
|
1007
|
+
const execTarget = targetFor(context);
|
|
1008
|
+
const ctx = executionContext(context.workingDirectory, execTarget);
|
|
1009
|
+
const root = await realpath(ctx.effectiveRoot);
|
|
1010
|
+
let rgProgram;
|
|
1011
|
+
if (ctx.kind === 'container' && ctx.backend.spawnRipgrep) {
|
|
1012
|
+
const containerWorkDir = path.posix.normalize(ctx.containerWorkDir ?? '/workspace');
|
|
1013
|
+
rgProgram = {
|
|
1014
|
+
filename: 'rg',
|
|
1015
|
+
env: processEnvironment(),
|
|
1016
|
+
spawn: (args, cwd, signal) => ctx.backend.spawnRipgrep(args, cwd, signal, execTarget),
|
|
1017
|
+
mapPath: (file) => {
|
|
1018
|
+
const rel = path.relative(root, file).split(path.sep).join('/');
|
|
1019
|
+
return rel ? path.posix.join(containerWorkDir, rel) : containerWorkDir;
|
|
1020
|
+
},
|
|
1021
|
+
unmapPath: (filename) => {
|
|
1022
|
+
const norm = path.posix.normalize(filename);
|
|
1023
|
+
const rel = norm.startsWith(containerWorkDir + '/')
|
|
1024
|
+
? norm.slice(containerWorkDir.length + 1)
|
|
1025
|
+
: norm;
|
|
1026
|
+
return path.resolve(root, ...rel.split('/'));
|
|
1027
|
+
},
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
else {
|
|
1031
|
+
const program = await resolveExecutableOnPath('rg');
|
|
1032
|
+
if (program)
|
|
1033
|
+
rgProgram = { filename: program, env: processEnvironment() };
|
|
1034
|
+
}
|
|
1035
|
+
const result = await grepWorkspace({
|
|
1036
|
+
root,
|
|
1037
|
+
target: target,
|
|
1038
|
+
strictSymlinks: ctx.kind === 'container',
|
|
1039
|
+
pattern,
|
|
1040
|
+
...(include === undefined ? {} : { include }),
|
|
1041
|
+
ignoreCase,
|
|
1042
|
+
contextLines,
|
|
1043
|
+
limit,
|
|
1044
|
+
}, context.signal, rgProgram);
|
|
1045
|
+
return success(grepText(result), 'none', {
|
|
1046
|
+
...result,
|
|
1047
|
+
lines: result.lines.map((row) => ({ ...row })),
|
|
1048
|
+
});
|
|
1049
|
+
}));
|
|
1050
|
+
const versions = new Map([
|
|
1051
|
+
['read_file', '5'],
|
|
1052
|
+
['edit_file', '5'],
|
|
1053
|
+
['write_file', '2'],
|
|
1054
|
+
['read_process', '2'],
|
|
1055
|
+
]);
|
|
1056
|
+
return bindings.map((item) => {
|
|
1057
|
+
const version = versions.get(item.definition.name);
|
|
1058
|
+
return version
|
|
1059
|
+
? { ...item, definition: { ...item.definition, version } }
|
|
1060
|
+
: expandProcessArgs(item, true);
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
if (options.patchTools) {
|
|
1064
|
+
const index = bindings.findIndex(({ definition }) => definition.name === 'edit_file');
|
|
1065
|
+
const edit = bindings[index];
|
|
1066
|
+
bindings[index] = {
|
|
1067
|
+
...edit,
|
|
1068
|
+
definition: {
|
|
1069
|
+
...edit.definition,
|
|
1070
|
+
description: edit.definition.description +
|
|
1071
|
+
' new_text is required; pass an empty string to delete the selected text.',
|
|
1072
|
+
},
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
if (!versionedFiles) {
|
|
1076
|
+
return bindings.map((item) => {
|
|
1077
|
+
if (options.patchTools && item.definition.name === 'edit_file')
|
|
1078
|
+
return { ...item, definition: { ...item.definition, version: '3' } };
|
|
1079
|
+
if (phase1 && item.definition.name === 'read_file')
|
|
1080
|
+
return { ...item, definition: { ...item.definition, version: '3' } };
|
|
1081
|
+
if ((phase1 || options.expandedProcessArgs) && !options.legacyProcessTools)
|
|
1082
|
+
return expandProcessArgs(item, phase1);
|
|
1083
|
+
return item;
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
return bindings
|
|
1087
|
+
.filter((b) => ['read_file', 'edit_file'].includes(b.definition.name))
|
|
1088
|
+
.map((b) => ({
|
|
1089
|
+
...b,
|
|
1090
|
+
definition: {
|
|
1091
|
+
...b.definition,
|
|
1092
|
+
version: (phase1 && b.definition.name === 'read_file') ||
|
|
1093
|
+
(options.patchTools && b.definition.name === 'edit_file')
|
|
1094
|
+
? '4'
|
|
1095
|
+
: '2',
|
|
1096
|
+
},
|
|
1097
|
+
}));
|
|
1098
|
+
}
|
|
1099
|
+
async function assertPatchFileAbsent(file) {
|
|
1100
|
+
try {
|
|
1101
|
+
await lstat(file);
|
|
1102
|
+
}
|
|
1103
|
+
catch (error) {
|
|
1104
|
+
if (error.code === 'ENOENT')
|
|
1105
|
+
return;
|
|
1106
|
+
throw error;
|
|
1107
|
+
}
|
|
1108
|
+
throw new RuntimeError('FILE_VERSION_CONFLICT', 'Add File target already exists');
|
|
1109
|
+
}
|
|
1110
|
+
function resolvedWorkspacePath(resource) {
|
|
1111
|
+
return resource.startsWith(outsideWorkspacePrefix)
|
|
1112
|
+
? resource.slice(outsideWorkspacePrefix.length)
|
|
1113
|
+
: resource;
|
|
1114
|
+
}
|
|
1115
|
+
function expandProcessArgs(binding, unlimitedLength) {
|
|
1116
|
+
const { definition } = binding;
|
|
1117
|
+
const version = { run_process: '3', run_readonly_command: '3', start_process: '2' }[definition.name];
|
|
1118
|
+
if (!version)
|
|
1119
|
+
return binding;
|
|
1120
|
+
const properties = definition.inputSchema.properties;
|
|
1121
|
+
return {
|
|
1122
|
+
...binding,
|
|
1123
|
+
definition: {
|
|
1124
|
+
...definition,
|
|
1125
|
+
version: unlimitedLength ? String(Number(version) + 1) : version,
|
|
1126
|
+
inputSchema: {
|
|
1127
|
+
...definition.inputSchema,
|
|
1128
|
+
properties: {
|
|
1129
|
+
...properties,
|
|
1130
|
+
args: {
|
|
1131
|
+
type: 'array',
|
|
1132
|
+
maxItems: 128,
|
|
1133
|
+
items: unlimitedLength ? { type: 'string' } : { type: 'string', maxLength: 1024 },
|
|
1134
|
+
},
|
|
1135
|
+
},
|
|
1136
|
+
},
|
|
1137
|
+
},
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
function validateProcessArgs(args) {
|
|
1141
|
+
const index = args.findIndex((arg) => arg.includes('\0'));
|
|
1142
|
+
if (index !== -1)
|
|
1143
|
+
throw new RuntimeError('INVALID_ARGUMENTS', `args.${index} cannot contain a NUL character`);
|
|
1144
|
+
}
|
|
1145
|
+
function targetFor(context) {
|
|
1146
|
+
return { runId: context.runId, agentSessionId: context.agentSessionId };
|
|
1147
|
+
}
|
|
1148
|
+
function binding(name, description, properties, required, effects, resources, invoke, timeoutMs = 10000) {
|
|
1149
|
+
const handler = {
|
|
1150
|
+
resolveResources: (input, cwd, target) => resources(input, cwd, target),
|
|
1151
|
+
async invoke(input, context) {
|
|
1152
|
+
try {
|
|
1153
|
+
context.signal.throwIfAborted();
|
|
1154
|
+
const resolved = await resources(input, context.workingDirectory, targetFor(context));
|
|
1155
|
+
if (JSON.stringify(resolved) !== JSON.stringify(context.resources))
|
|
1156
|
+
return failure('APPROVAL_SCOPE_CHANGED', 'Resolved tool resources have changed');
|
|
1157
|
+
context.signal.throwIfAborted();
|
|
1158
|
+
return await invoke(input, context, resolved);
|
|
1159
|
+
}
|
|
1160
|
+
catch (error) {
|
|
1161
|
+
if (context.signal.aborted)
|
|
1162
|
+
throw error;
|
|
1163
|
+
return error instanceof RuntimeError
|
|
1164
|
+
? failure(error.code, error.message)
|
|
1165
|
+
: failure('LOCAL_IO_ERROR', 'Local operation failed');
|
|
1166
|
+
}
|
|
1167
|
+
},
|
|
1168
|
+
};
|
|
1169
|
+
return {
|
|
1170
|
+
definition: {
|
|
1171
|
+
name,
|
|
1172
|
+
version: '1',
|
|
1173
|
+
description,
|
|
1174
|
+
source: { kind: 'builtin' },
|
|
1175
|
+
effects,
|
|
1176
|
+
inputSchema: { type: 'object', properties, required, additionalProperties: false },
|
|
1177
|
+
supportsIdempotencyKey: false,
|
|
1178
|
+
supportsReconcile: false,
|
|
1179
|
+
concurrency: effects === 'read' ? 'parallel' : 'serial_per_run',
|
|
1180
|
+
timeoutMs,
|
|
1181
|
+
},
|
|
1182
|
+
handler,
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
function readonlyPathCandidates(command, args) {
|
|
1186
|
+
const candidates = [];
|
|
1187
|
+
for (const arg of args) {
|
|
1188
|
+
if (arg.includes('\0') || arg.includes('\r') || arg.includes('\n')) {
|
|
1189
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', 'Arguments contain disallowed control characters');
|
|
1190
|
+
}
|
|
1191
|
+
const lower = arg.toLowerCase();
|
|
1192
|
+
const flagName = lower.includes('=') ? lower.slice(0, lower.indexOf('=')) : lower;
|
|
1193
|
+
if (flagName === '--output' ||
|
|
1194
|
+
flagName === '--exec' ||
|
|
1195
|
+
flagName === '--exec-path' ||
|
|
1196
|
+
flagName === '--in-place' ||
|
|
1197
|
+
flagName === '--pre' ||
|
|
1198
|
+
flagName === '--pre-glob' ||
|
|
1199
|
+
flagName === '--hostname-bin' ||
|
|
1200
|
+
flagName === '--write' ||
|
|
1201
|
+
flagName === '--delete' ||
|
|
1202
|
+
flagName === '--remove' ||
|
|
1203
|
+
flagName === '--edit' ||
|
|
1204
|
+
flagName === '--force' ||
|
|
1205
|
+
flagName === '--interactive' ||
|
|
1206
|
+
flagName === '--open-files-in-pager' ||
|
|
1207
|
+
flagName === '--pager') {
|
|
1208
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Flag "${arg}" is not allowed in read-only mode`);
|
|
1209
|
+
}
|
|
1210
|
+
const skipShortFlagScan = command === 'objdump' && arg.startsWith('-M');
|
|
1211
|
+
if (!skipShortFlagScan) {
|
|
1212
|
+
if (/^-[a-zA-Z]+$/.test(arg)) {
|
|
1213
|
+
const letters = arg.slice(1);
|
|
1214
|
+
if (letters.includes('o')) {
|
|
1215
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Flag "${arg}" is not allowed in read-only mode`);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
else if (/^-o/i.test(arg)) {
|
|
1219
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Flag "${arg}" is not allowed in read-only mode`);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
if (command === 'tail' &&
|
|
1223
|
+
(flagName === '-f' || flagName === '-F' || flagName === '--follow' || flagName === '--pid')) {
|
|
1224
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Flag "${arg}" is not allowed for tail`);
|
|
1225
|
+
}
|
|
1226
|
+
const pathCandidate = arg.startsWith('--') && arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : arg;
|
|
1227
|
+
const isFlagToken = arg.startsWith('-') && !(arg.startsWith('--') && arg.includes('='));
|
|
1228
|
+
const isFindstrSwitch = command === 'findstr' && /^\/[A-Za-z](?::.*)?$/.test(arg);
|
|
1229
|
+
if (!isFlagToken && !isFindstrSwitch && pathCandidate)
|
|
1230
|
+
candidates.push(pathCandidate);
|
|
1231
|
+
}
|
|
1232
|
+
if (command === 'git')
|
|
1233
|
+
validateReadonlyGitArgs(args);
|
|
1234
|
+
return candidates;
|
|
1235
|
+
}
|
|
1236
|
+
function validateReadonlyGitArgs(args) {
|
|
1237
|
+
let subcommandIndex = -1;
|
|
1238
|
+
for (let i = 0; i < args.length; i++) {
|
|
1239
|
+
const arg = args[i];
|
|
1240
|
+
if (arg === '--')
|
|
1241
|
+
break;
|
|
1242
|
+
if (arg.startsWith('-')) {
|
|
1243
|
+
if (!gitSafePreFlags.has(arg)) {
|
|
1244
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `Git global option "${arg}" is not allowed in read-only mode`);
|
|
1245
|
+
}
|
|
1246
|
+
continue;
|
|
1247
|
+
}
|
|
1248
|
+
subcommandIndex = i;
|
|
1249
|
+
break;
|
|
1250
|
+
}
|
|
1251
|
+
if (subcommandIndex < 0) {
|
|
1252
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', 'git requires an explicit read-only subcommand (status, log, diff, show, branch, rev-parse, ls-files, ls-tree, describe, tag)');
|
|
1253
|
+
}
|
|
1254
|
+
const subcommand = args[subcommandIndex];
|
|
1255
|
+
if (!readonlyGitSubcommands.has(subcommand)) {
|
|
1256
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `git subcommand "${subcommand}" is not allowed in read-only mode`);
|
|
1257
|
+
}
|
|
1258
|
+
const subArgs = args.slice(subcommandIndex + 1);
|
|
1259
|
+
for (const arg of subArgs) {
|
|
1260
|
+
if (arg === '--')
|
|
1261
|
+
break;
|
|
1262
|
+
const lower = arg.toLowerCase();
|
|
1263
|
+
const flagName = lower.includes('=') ? lower.slice(0, lower.indexOf('=')) : lower;
|
|
1264
|
+
if (flagName === '-c' ||
|
|
1265
|
+
flagName === '--ext-diff' ||
|
|
1266
|
+
flagName === '--upload-pack' ||
|
|
1267
|
+
flagName === '--receive-pack' ||
|
|
1268
|
+
flagName === '--exec' ||
|
|
1269
|
+
flagName === '--output' ||
|
|
1270
|
+
flagName === '-o' ||
|
|
1271
|
+
flagName === '--git-dir' ||
|
|
1272
|
+
flagName === '--work-tree') {
|
|
1273
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `git ${subcommand} option "${arg}" is not allowed in read-only mode`);
|
|
1274
|
+
}
|
|
1275
|
+
if (subcommand === 'branch') {
|
|
1276
|
+
if ([
|
|
1277
|
+
'-d',
|
|
1278
|
+
'-D',
|
|
1279
|
+
'--delete',
|
|
1280
|
+
'-m',
|
|
1281
|
+
'-M',
|
|
1282
|
+
'--move',
|
|
1283
|
+
'-c',
|
|
1284
|
+
'-C',
|
|
1285
|
+
'--copy',
|
|
1286
|
+
'-u',
|
|
1287
|
+
'--set-upstream-to',
|
|
1288
|
+
'--unset-upstream',
|
|
1289
|
+
'--edit-description',
|
|
1290
|
+
'--create-reflog',
|
|
1291
|
+
'-f',
|
|
1292
|
+
'--force',
|
|
1293
|
+
].includes(flagName) ||
|
|
1294
|
+
(/^-[a-zA-Z]+$/.test(arg) && /[dDmMcCuf]/.test(arg.slice(1)))) {
|
|
1295
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `git branch mutating option "${arg}" is not allowed in read-only mode`);
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
if (subcommand === 'tag') {
|
|
1299
|
+
if ([
|
|
1300
|
+
'-a',
|
|
1301
|
+
'--annotate',
|
|
1302
|
+
'-s',
|
|
1303
|
+
'--sign',
|
|
1304
|
+
'-u',
|
|
1305
|
+
'--local-user',
|
|
1306
|
+
'-f',
|
|
1307
|
+
'--force',
|
|
1308
|
+
'-d',
|
|
1309
|
+
'--delete',
|
|
1310
|
+
'-m',
|
|
1311
|
+
'--message',
|
|
1312
|
+
'-F',
|
|
1313
|
+
'--file',
|
|
1314
|
+
'--edit',
|
|
1315
|
+
'--create-reflog',
|
|
1316
|
+
'--cleanup',
|
|
1317
|
+
].includes(flagName) ||
|
|
1318
|
+
(/^-[a-zA-Z]+$/.test(arg) && /[asufdmF]/.test(arg.slice(1)))) {
|
|
1319
|
+
throw new RuntimeError('READONLY_COMMAND_DENIED', `git tag mutating option "${arg}" is not allowed in read-only mode`);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async function ensureSafeDirectories(target, signal) {
|
|
1325
|
+
signal.throwIfAborted();
|
|
1326
|
+
const info = await lstat(target).catch((error) => {
|
|
1327
|
+
if (error.code !== 'ENOENT')
|
|
1328
|
+
throw error;
|
|
1329
|
+
});
|
|
1330
|
+
if (!info) {
|
|
1331
|
+
const parent = path.dirname(target);
|
|
1332
|
+
if (parent === target)
|
|
1333
|
+
throw invalidPath();
|
|
1334
|
+
await ensureSafeDirectories(parent, signal);
|
|
1335
|
+
signal.throwIfAborted();
|
|
1336
|
+
await mkdir(target).catch((error) => {
|
|
1337
|
+
if (error.code !== 'EEXIST')
|
|
1338
|
+
throw error;
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
if (!(await lstat(target)).isDirectory() || path.relative(target, await realpath(target)))
|
|
1342
|
+
throw invalidPath();
|
|
1343
|
+
}
|
|
1344
|
+
function safePathSyntax(value) {
|
|
1345
|
+
if (value.includes('\0'))
|
|
1346
|
+
return false;
|
|
1347
|
+
if (process.platform !== 'win32')
|
|
1348
|
+
return true;
|
|
1349
|
+
return value
|
|
1350
|
+
.replace(/^[a-z]:[\\/]/i, '')
|
|
1351
|
+
.split(/[\\/]/)
|
|
1352
|
+
.every((part) => !/[:<>"|?*]/.test(part) &&
|
|
1353
|
+
(!/[. ]$/.test(part) || part === '.' || part === '..') &&
|
|
1354
|
+
!/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part));
|
|
1355
|
+
}
|
|
1356
|
+
function unprotectedPath(target, git = false) {
|
|
1357
|
+
return target
|
|
1358
|
+
.split(/[\\/]/)
|
|
1359
|
+
.every((part) => !/^(\.saturn|\.env)$/i.test(part) && (git || !/^\.git$/i.test(part)));
|
|
1360
|
+
}
|
|
1361
|
+
function invalidPath() {
|
|
1362
|
+
return new RuntimeError('WORKSPACE_PATH_INVALID', 'Path is unavailable or outside the permitted workspace');
|
|
1363
|
+
}
|
|
1364
|
+
async function listDirectory(directory, signal) {
|
|
1365
|
+
const entries = [];
|
|
1366
|
+
let scanned = 0;
|
|
1367
|
+
let bytes = 0;
|
|
1368
|
+
let truncated = false;
|
|
1369
|
+
for await (const entry of await opendir(directory)) {
|
|
1370
|
+
signal.throwIfAborted();
|
|
1371
|
+
if (++scanned > maxEntries) {
|
|
1372
|
+
truncated = true;
|
|
1373
|
+
break;
|
|
1374
|
+
}
|
|
1375
|
+
if (!unprotectedPath(entry.name))
|
|
1376
|
+
continue;
|
|
1377
|
+
const type = entry.isDirectory()
|
|
1378
|
+
? 'directory'
|
|
1379
|
+
: entry.isFile()
|
|
1380
|
+
? 'file'
|
|
1381
|
+
: entry.isSymbolicLink()
|
|
1382
|
+
? 'symlink'
|
|
1383
|
+
: 'other';
|
|
1384
|
+
const item = { name: entry.name, type };
|
|
1385
|
+
bytes += Buffer.byteLength(JSON.stringify(item)) + 1;
|
|
1386
|
+
if (entries.length >= maxListedEntries || bytes > maxListBytes) {
|
|
1387
|
+
truncated = true;
|
|
1388
|
+
break;
|
|
1389
|
+
}
|
|
1390
|
+
entries.push(item);
|
|
1391
|
+
}
|
|
1392
|
+
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
1393
|
+
const lines = entries.map((entry) => JSON.stringify(entry));
|
|
1394
|
+
if (truncated)
|
|
1395
|
+
lines.push('Listing truncated');
|
|
1396
|
+
return success(lines.join('\n') || 'Directory is empty', 'none', { entries, truncated });
|
|
1397
|
+
}
|
|
1398
|
+
const snapshotKey = (file) => {
|
|
1399
|
+
const resolved = path.resolve(file);
|
|
1400
|
+
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
|
1401
|
+
};
|
|
1402
|
+
function sha256Hex(content) {
|
|
1403
|
+
return createHash('sha256').update(content).digest('hex');
|
|
1404
|
+
}
|
|
1405
|
+
function fileRevision(info) {
|
|
1406
|
+
return info && [info.dev, info.ino, info.size, info.mtimeMs, info.nlink].join(':');
|
|
1407
|
+
}
|
|
1408
|
+
function formatFileSnapshot(info, sha256) {
|
|
1409
|
+
const statRevision = fileRevision(info);
|
|
1410
|
+
return sha256 ? `${statRevision}:${sha256}` : statRevision;
|
|
1411
|
+
}
|
|
1412
|
+
function parseFileSnapshot(recorded) {
|
|
1413
|
+
const parts = recorded.split(':');
|
|
1414
|
+
if (parts.length === 6 && /^[0-9a-f]{64}$/.test(parts[5])) {
|
|
1415
|
+
return { stat: parts.slice(0, 5).join(':'), sha256: parts[5] };
|
|
1416
|
+
}
|
|
1417
|
+
return { stat: recorded };
|
|
1418
|
+
}
|
|
1419
|
+
async function existingFileInfo(file) {
|
|
1420
|
+
try {
|
|
1421
|
+
return await lstat(file);
|
|
1422
|
+
}
|
|
1423
|
+
catch (error) {
|
|
1424
|
+
if (error.code !== 'ENOENT')
|
|
1425
|
+
throw error;
|
|
1426
|
+
return undefined;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
function staleFile() {
|
|
1430
|
+
return new RuntimeError('FILE_VERSION_CONFLICT', 'File changed since it was last read or written. Call read_file again before editing or overwriting it.');
|
|
1431
|
+
}
|
|
1432
|
+
function requireFileSnapshot(context, file, current) {
|
|
1433
|
+
const recorded = context.fileSnapshots?.get(snapshotKey(file));
|
|
1434
|
+
if (recorded === undefined) {
|
|
1435
|
+
if (!current)
|
|
1436
|
+
throw invalidPath();
|
|
1437
|
+
throw new RuntimeError('FILE_READ_REQUIRED', 'Call read_file on this file before editing or overwriting it in this Run.');
|
|
1438
|
+
}
|
|
1439
|
+
const parsed = parseFileSnapshot(recorded);
|
|
1440
|
+
if (parsed.stat !== fileRevision(current))
|
|
1441
|
+
throw staleFile();
|
|
1442
|
+
return parsed;
|
|
1443
|
+
}
|
|
1444
|
+
async function recordReplacement(context, file, prepared, expectedSha256) {
|
|
1445
|
+
const snapshots = context.fileSnapshots;
|
|
1446
|
+
if (!snapshots)
|
|
1447
|
+
return;
|
|
1448
|
+
const canonical = await realpath(file).catch(() => file);
|
|
1449
|
+
const key = snapshotKey(canonical);
|
|
1450
|
+
// A rename or link can change ctime (and virtual/FUSE/DrvFs mounts may alter
|
|
1451
|
+
// inode or mtime slightly). Verify identity before refreshing the snapshot.
|
|
1452
|
+
const current = await lstat(canonical).catch(() => undefined);
|
|
1453
|
+
if (!current || !current.isFile() || current.nlink !== 1) {
|
|
1454
|
+
snapshots.delete(key);
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
if (current.dev === prepared.dev &&
|
|
1458
|
+
current.ino === prepared.ino &&
|
|
1459
|
+
current.size === prepared.size &&
|
|
1460
|
+
current.mtimeMs === prepared.mtimeMs) {
|
|
1461
|
+
snapshots.set(key, formatFileSnapshot(current, expectedSha256));
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
if (expectedSha256 !== undefined && current.size === prepared.size) {
|
|
1465
|
+
const verified = await readBytes(canonical, 0, maxFileBytes).catch(() => undefined);
|
|
1466
|
+
if (verified && !verified.more && sha256Hex(verified.bytes) === expectedSha256) {
|
|
1467
|
+
snapshots.set(key, formatFileSnapshot(verified.info, expectedSha256));
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
snapshots.delete(key);
|
|
1472
|
+
}
|
|
1473
|
+
async function readBytes(file, offset, limit, verifyRevision = false) {
|
|
1474
|
+
const handle = await open(file, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
|
|
1475
|
+
try {
|
|
1476
|
+
const info = await handle.stat();
|
|
1477
|
+
if (!info.isFile() || info.nlink !== 1)
|
|
1478
|
+
throw invalidPath();
|
|
1479
|
+
const buffer = await readFileWindow(handle, offset, limit + 1);
|
|
1480
|
+
if (verifyRevision && fileRevision(await handle.stat()) !== fileRevision(info))
|
|
1481
|
+
throw staleFile();
|
|
1482
|
+
return {
|
|
1483
|
+
bytes: buffer.subarray(0, limit),
|
|
1484
|
+
more: buffer.length > limit,
|
|
1485
|
+
mode: info.mode,
|
|
1486
|
+
info,
|
|
1487
|
+
next: buffer[limit],
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
finally {
|
|
1491
|
+
await handle.close();
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
async function readBytePage(file, offset, versioned, pageBytes = maxReadBytes, record) {
|
|
1495
|
+
const snapshot = versioned ? await readBytes(file, 0, maxFileBytes) : undefined;
|
|
1496
|
+
const revision = snapshot && !snapshot.more ? sha256Hex(snapshot.bytes) : undefined;
|
|
1497
|
+
const { bytes, more, next, info } = revision && snapshot
|
|
1498
|
+
? {
|
|
1499
|
+
bytes: snapshot.bytes.subarray(offset, offset + pageBytes),
|
|
1500
|
+
more: snapshot.bytes.length > offset + pageBytes,
|
|
1501
|
+
next: snapshot.bytes[offset + pageBytes],
|
|
1502
|
+
info: snapshot.info,
|
|
1503
|
+
}
|
|
1504
|
+
: await readBytes(file, offset, pageBytes, record !== undefined);
|
|
1505
|
+
let end = bytes.length;
|
|
1506
|
+
if (more && (next & 0xc0) === 0x80) {
|
|
1507
|
+
// The extra byte identifies whether the next page would start inside a character.
|
|
1508
|
+
do
|
|
1509
|
+
end--;
|
|
1510
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80);
|
|
1511
|
+
}
|
|
1512
|
+
if (bytes.includes(0))
|
|
1513
|
+
throw binaryFile();
|
|
1514
|
+
const body = decoder.decode(bytes.subarray(0, end));
|
|
1515
|
+
const snapshotSha256 = revision ??
|
|
1516
|
+
(record !== undefined && offset === 0 && !more && info.size <= maxFileBytes
|
|
1517
|
+
? sha256Hex(bytes)
|
|
1518
|
+
: undefined);
|
|
1519
|
+
record?.(info, snapshotSha256);
|
|
1520
|
+
return success(revision ? 'SHA-256: ' + revision + '\n' + body : body, 'none', {
|
|
1521
|
+
...(revision ? { sha256: revision } : {}),
|
|
1522
|
+
truncated: more,
|
|
1523
|
+
...(more ? { next_byte_offset: offset + end } : {}),
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
function binaryFile() {
|
|
1527
|
+
return new RuntimeError('BINARY_FILE', 'File contains binary data or invalid UTF-8');
|
|
1528
|
+
}
|
|
1529
|
+
async function readLinePage(file, offset, limit, versioned, signal, record) {
|
|
1530
|
+
const handle = await open(file, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
|
|
1531
|
+
try {
|
|
1532
|
+
const info = await handle.stat();
|
|
1533
|
+
if (!info.isFile() || info.nlink !== 1)
|
|
1534
|
+
throw invalidPath();
|
|
1535
|
+
const hash = (versioned || record !== undefined) && info.size <= maxFileBytes ? createHash('sha256') : undefined;
|
|
1536
|
+
const validator = new TextDecoder('utf-8', { fatal: true });
|
|
1537
|
+
const chunk = Buffer.alloc(64 * 1024);
|
|
1538
|
+
const line = Buffer.alloc(maxReadPageBytes + 1);
|
|
1539
|
+
const rows = [];
|
|
1540
|
+
let totalLines = 0;
|
|
1541
|
+
let pageBytes = 0;
|
|
1542
|
+
let lineBytes = 0;
|
|
1543
|
+
let lineStart = 0;
|
|
1544
|
+
let position = 0;
|
|
1545
|
+
let pageFull = false;
|
|
1546
|
+
let nextByteOffset;
|
|
1547
|
+
const validate = (bytes, stream) => {
|
|
1548
|
+
if (bytes.includes(0))
|
|
1549
|
+
throw binaryFile();
|
|
1550
|
+
try {
|
|
1551
|
+
validator.decode(bytes, { stream });
|
|
1552
|
+
}
|
|
1553
|
+
catch {
|
|
1554
|
+
throw binaryFile();
|
|
1555
|
+
}
|
|
1556
|
+
};
|
|
1557
|
+
const endLine = (terminated) => {
|
|
1558
|
+
const number = ++totalLines;
|
|
1559
|
+
if (number >= offset && rows.length < limit && !pageFull) {
|
|
1560
|
+
const prefix = number + ': ';
|
|
1561
|
+
const prefixBytes = prefix.length + (rows.length ? 1 : 0);
|
|
1562
|
+
const room = maxReadPageBytes - pageBytes - prefixBytes;
|
|
1563
|
+
const length = terminated && lineBytes <= line.length && line[lineBytes - 1] === 13 ? lineBytes - 1 : lineBytes;
|
|
1564
|
+
if (length <= room) {
|
|
1565
|
+
rows.push(prefix + decoder.decode(line.subarray(0, length)));
|
|
1566
|
+
pageBytes += prefixBytes + length;
|
|
1567
|
+
}
|
|
1568
|
+
else {
|
|
1569
|
+
pageFull = true;
|
|
1570
|
+
if (!rows.length) {
|
|
1571
|
+
// Keep a UTF-8 prefix and expose the byte position for continuing this same line.
|
|
1572
|
+
const partial = new TextDecoder('utf-8', { ignoreBOM: true }).decode(line.subarray(0, room), {
|
|
1573
|
+
stream: true,
|
|
1574
|
+
});
|
|
1575
|
+
rows.push(prefix + partial);
|
|
1576
|
+
nextByteOffset = lineStart + Buffer.byteLength(partial);
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
lineBytes = 0;
|
|
1581
|
+
};
|
|
1582
|
+
for (;;) {
|
|
1583
|
+
signal.throwIfAborted();
|
|
1584
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
|
|
1585
|
+
if (!bytesRead)
|
|
1586
|
+
break;
|
|
1587
|
+
const bytes = chunk.subarray(0, bytesRead);
|
|
1588
|
+
validate(bytes, true);
|
|
1589
|
+
if (position + bytesRead <= maxFileBytes)
|
|
1590
|
+
hash?.update(bytes);
|
|
1591
|
+
let start = 0;
|
|
1592
|
+
while (start < bytesRead) {
|
|
1593
|
+
const newline = bytes.indexOf(10, start);
|
|
1594
|
+
const end = newline === -1 ? bytesRead : newline;
|
|
1595
|
+
if (totalLines + 1 >= offset && rows.length < limit && !pageFull && lineBytes < line.length)
|
|
1596
|
+
bytes.copy(line, lineBytes, start, Math.min(end, start + line.length - lineBytes));
|
|
1597
|
+
lineBytes += end - start;
|
|
1598
|
+
if (newline === -1)
|
|
1599
|
+
break;
|
|
1600
|
+
endLine(true);
|
|
1601
|
+
start = end + 1;
|
|
1602
|
+
lineStart = position + start;
|
|
1603
|
+
}
|
|
1604
|
+
position += bytesRead;
|
|
1605
|
+
}
|
|
1606
|
+
validate(Buffer.alloc(0), false);
|
|
1607
|
+
if (lineBytes)
|
|
1608
|
+
endLine(false);
|
|
1609
|
+
const digest = position <= maxFileBytes ? hash?.digest('hex') : undefined;
|
|
1610
|
+
const revision = versioned ? digest : undefined;
|
|
1611
|
+
const last = rows.length ? offset + rows.length - 1 : null;
|
|
1612
|
+
const hasMore = nextByteOffset !== undefined || (last !== null && last < totalLines);
|
|
1613
|
+
if (record) {
|
|
1614
|
+
if (fileRevision(await handle.stat()) !== fileRevision(info))
|
|
1615
|
+
throw staleFile();
|
|
1616
|
+
signal.throwIfAborted();
|
|
1617
|
+
record(info, digest);
|
|
1618
|
+
}
|
|
1619
|
+
return success((revision ? 'SHA-256: ' + revision + '\n' : '') + rows.join('\n'), 'none', {
|
|
1620
|
+
...(revision ? { sha256: revision } : {}),
|
|
1621
|
+
totalLines,
|
|
1622
|
+
startLine: rows.length ? offset : null,
|
|
1623
|
+
endLine: last,
|
|
1624
|
+
truncated: hasMore,
|
|
1625
|
+
hasMore,
|
|
1626
|
+
...(nextByteOffset === undefined ? {} : { next_byte_offset: nextByteOffset }),
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
finally {
|
|
1630
|
+
await handle.close();
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
async function search(root, directory, query, signal, resolve) {
|
|
1634
|
+
const pending = [directory];
|
|
1635
|
+
const matches = [];
|
|
1636
|
+
let entries = 0;
|
|
1637
|
+
let scanned = 0;
|
|
1638
|
+
let outputBytes = 0;
|
|
1639
|
+
let skipped = 0;
|
|
1640
|
+
let truncated = false;
|
|
1641
|
+
scan: while (pending.length) {
|
|
1642
|
+
signal.throwIfAborted();
|
|
1643
|
+
for await (const entry of await opendir(pending.pop())) {
|
|
1644
|
+
signal.throwIfAborted();
|
|
1645
|
+
if (++entries > maxEntries) {
|
|
1646
|
+
truncated = true;
|
|
1647
|
+
break scan;
|
|
1648
|
+
}
|
|
1649
|
+
const candidate = path.join(entry.parentPath, entry.name);
|
|
1650
|
+
const relative = relativePathWithin(root, candidate);
|
|
1651
|
+
if (relative === undefined || !unprotectedPath(relative))
|
|
1652
|
+
continue;
|
|
1653
|
+
if (entry.isDirectory()) {
|
|
1654
|
+
const checked = await resolve(root, candidate, 'directory').catch(() => undefined);
|
|
1655
|
+
if (checked === candidate)
|
|
1656
|
+
pending.push(checked);
|
|
1657
|
+
}
|
|
1658
|
+
if (!entry.isFile())
|
|
1659
|
+
continue;
|
|
1660
|
+
let text;
|
|
1661
|
+
try {
|
|
1662
|
+
const file = await resolve(root, candidate, 'file');
|
|
1663
|
+
if (file !== candidate)
|
|
1664
|
+
continue;
|
|
1665
|
+
const { bytes, more } = await readBytes(file, 0, maxFileBytes);
|
|
1666
|
+
scanned += bytes.length;
|
|
1667
|
+
if (scanned > maxScannedBytes) {
|
|
1668
|
+
truncated = true;
|
|
1669
|
+
break scan;
|
|
1670
|
+
}
|
|
1671
|
+
if (more) {
|
|
1672
|
+
skipped++;
|
|
1673
|
+
continue;
|
|
1674
|
+
}
|
|
1675
|
+
text = decoder.decode(bytes);
|
|
1676
|
+
}
|
|
1677
|
+
catch {
|
|
1678
|
+
skipped++;
|
|
1679
|
+
continue;
|
|
1680
|
+
}
|
|
1681
|
+
for (const [line, value] of text.split(/\r?\n/).entries()) {
|
|
1682
|
+
const match = value.indexOf(query);
|
|
1683
|
+
if (match < 0)
|
|
1684
|
+
continue;
|
|
1685
|
+
const result = JSON.stringify({
|
|
1686
|
+
path: relative,
|
|
1687
|
+
line: line + 1,
|
|
1688
|
+
text: value.slice(Math.max(0, match - 40), match + 256),
|
|
1689
|
+
});
|
|
1690
|
+
outputBytes += Buffer.byteLength(result) + 1;
|
|
1691
|
+
if (matches.length >= maxMatches || outputBytes > maxSearchBytes) {
|
|
1692
|
+
truncated = true;
|
|
1693
|
+
break scan;
|
|
1694
|
+
}
|
|
1695
|
+
matches.push(result);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
return success(matches.join('\n') || 'No matching lines', 'none', {
|
|
1700
|
+
matches: matches.length,
|
|
1701
|
+
skipped,
|
|
1702
|
+
truncated,
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
async function readContainerBytePage(backend, containerPath, offset, pageBytes, signal, target) {
|
|
1706
|
+
if (!backend.readContainerFile) {
|
|
1707
|
+
throw new RuntimeError('SANDBOX_UNAVAILABLE', 'Container file reading is unavailable');
|
|
1708
|
+
}
|
|
1709
|
+
const { bytes, more } = await backend.readContainerFile(containerPath, offset, pageBytes, signal, target);
|
|
1710
|
+
let end = bytes.length;
|
|
1711
|
+
if (more && (bytes[end - 1] & 0xc0) === 0x80) {
|
|
1712
|
+
// Trim partial trailing UTF-8 sequence if sliced mid-character.
|
|
1713
|
+
do
|
|
1714
|
+
end--;
|
|
1715
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80);
|
|
1716
|
+
}
|
|
1717
|
+
if (bytes.includes(0))
|
|
1718
|
+
throw binaryFile();
|
|
1719
|
+
const body = decoder.decode(bytes.subarray(0, end));
|
|
1720
|
+
return success(body, 'none', {
|
|
1721
|
+
truncated: more,
|
|
1722
|
+
...(more ? { next_byte_offset: offset + end } : {}),
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
async function readContainerLinePage(backend, containerPath, offset, limit, signal, target) {
|
|
1726
|
+
if (!backend.readContainerFile) {
|
|
1727
|
+
throw new RuntimeError('SANDBOX_UNAVAILABLE', 'Container file reading is unavailable');
|
|
1728
|
+
}
|
|
1729
|
+
const { bytes, more } = await backend.readContainerFile(containerPath, 0, maxReadPageBytes * 8, signal, target);
|
|
1730
|
+
if (bytes.includes(0))
|
|
1731
|
+
throw binaryFile();
|
|
1732
|
+
const text = decoder.decode(bytes);
|
|
1733
|
+
const lines = text.split(/\r?\n/);
|
|
1734
|
+
if (lines.length > 0 && lines.at(-1) === '')
|
|
1735
|
+
lines.pop();
|
|
1736
|
+
const rows = [];
|
|
1737
|
+
let pageBytes = 0;
|
|
1738
|
+
let truncated = more;
|
|
1739
|
+
for (let i = offset - 1; i < lines.length && rows.length < limit; i++) {
|
|
1740
|
+
const row = `${i + 1}: ${lines[i]}`;
|
|
1741
|
+
const cost = Buffer.byteLength(row, 'utf8') + (rows.length ? 1 : 0);
|
|
1742
|
+
if (pageBytes + cost > maxReadPageBytes) {
|
|
1743
|
+
truncated = true;
|
|
1744
|
+
break;
|
|
1745
|
+
}
|
|
1746
|
+
rows.push(row);
|
|
1747
|
+
pageBytes += cost;
|
|
1748
|
+
}
|
|
1749
|
+
const last = rows.length ? offset + rows.length - 1 : null;
|
|
1750
|
+
const hasMore = truncated || (last !== null && last < lines.length);
|
|
1751
|
+
return success(rows.join('\n'), 'none', {
|
|
1752
|
+
totalLines: lines.length,
|
|
1753
|
+
startLine: rows.length ? offset : null,
|
|
1754
|
+
endLine: last,
|
|
1755
|
+
truncated: hasMore,
|
|
1756
|
+
hasMore,
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
function processScope(context) {
|
|
1760
|
+
return { workspaceId: context.workspaceId, runId: context.runId, agentId: context.agentId };
|
|
1761
|
+
}
|
|
1762
|
+
function processObservation(value, effect) {
|
|
1763
|
+
if (value.startError)
|
|
1764
|
+
return {
|
|
1765
|
+
outcome: {
|
|
1766
|
+
status: 'error',
|
|
1767
|
+
error: { code: 'PROCESS_START_FAILED', message: value.startError, retryable: false },
|
|
1768
|
+
data: processData(value),
|
|
1769
|
+
},
|
|
1770
|
+
effect,
|
|
1771
|
+
};
|
|
1772
|
+
return {
|
|
1773
|
+
outcome: {
|
|
1774
|
+
status: 'success',
|
|
1775
|
+
content: [
|
|
1776
|
+
{
|
|
1777
|
+
type: 'text',
|
|
1778
|
+
text: `Process ${value.processId}: ${value.status}\nstdout:\n${value.stdout}\nstderr:\n${value.stderr}`,
|
|
1779
|
+
},
|
|
1780
|
+
],
|
|
1781
|
+
data: processData(value),
|
|
1782
|
+
},
|
|
1783
|
+
effect,
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
function processData(value) {
|
|
1787
|
+
return {
|
|
1788
|
+
process_id: value.processId,
|
|
1789
|
+
scope: { ...value.scope },
|
|
1790
|
+
status: value.status,
|
|
1791
|
+
...(value.pid === undefined ? {} : { pid: value.pid }),
|
|
1792
|
+
exit_code: value.exitCode,
|
|
1793
|
+
signal: value.signal,
|
|
1794
|
+
termination_confirmed: value.terminationConfirmed,
|
|
1795
|
+
stdout: value.stdout,
|
|
1796
|
+
stderr: value.stderr,
|
|
1797
|
+
stdout_offset: value.stdoutOffset,
|
|
1798
|
+
stderr_offset: value.stderrOffset,
|
|
1799
|
+
next_stdout_offset: value.nextStdoutOffset,
|
|
1800
|
+
next_stderr_offset: value.nextStderrOffset,
|
|
1801
|
+
truncated: value.truncated,
|
|
1802
|
+
deadline_at: value.deadlineAt,
|
|
1803
|
+
...(value.stopReason ? { stop_reason: value.stopReason } : {}),
|
|
1804
|
+
...(value.startError ? { start_error: value.startError } : {}),
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
function success(text, effect, data) {
|
|
1808
|
+
return {
|
|
1809
|
+
outcome: {
|
|
1810
|
+
status: 'success',
|
|
1811
|
+
content: [{ type: 'text', text }],
|
|
1812
|
+
...(data === undefined ? {} : { data }),
|
|
1813
|
+
},
|
|
1814
|
+
effect,
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
function failure(code, message) {
|
|
1818
|
+
return { outcome: { status: 'error', error: { code, message, retryable: false } }, effect: 'none' };
|
|
1819
|
+
}
|