@clearideas/agent-runtime-sandbox 0.5.0 → 0.6.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/dist/policy.js ADDED
@@ -0,0 +1,649 @@
1
+ import { isSafeWorkspacePath } from "@clearideas/agent-runtime-core";
2
+ import { assertSandboxPath } from "./contracts.js";
3
+ /** Built-in operations served by the runtime-shipped helper. */
4
+ export const BUILTIN_WORKSPACE_TOOLS = [
5
+ "list_files",
6
+ "read_file",
7
+ "search_files",
8
+ "write_file",
9
+ "delete_file",
10
+ ];
11
+ export const BUILTIN_READ_TOOLS = [
12
+ "list_files",
13
+ "read_file",
14
+ "search_files",
15
+ ];
16
+ export const SHELL_TOOL_NAME = "shell";
17
+ export const SANDBOX_MOUNT_DIRECTORY = "/workspace/mounts";
18
+ export const SANDBOX_OUTPUT_DIRECTORY = "/workspace/output";
19
+ export const SANDBOX_STAGING_DIRECTORY = "/workspace/staging";
20
+ export const SANDBOX_STEPS_DIRECTORY = "/workspace/steps";
21
+ export const SANDBOX_HELPER_PATH = "/workspace/bin/agent-fs";
22
+ export const SANDBOX_WORKSPACES_FILE = "/workspace/workspaces.json";
23
+ export const DEFAULT_HELPER_COMMAND = ["python3", SANDBOX_HELPER_PATH];
24
+ const COMMAND_NAME = /^[a-z][a-z0-9_]*$/u;
25
+ const RESERVED_COMMAND_NAMES = new Set([
26
+ ...BUILTIN_WORKSPACE_TOOLS,
27
+ SHELL_TOOL_NAME,
28
+ ]);
29
+ const MAXIMUM_GLOB_LENGTH = 512;
30
+ const MAXIMUM_QUERY_LENGTH = 512;
31
+ const MAXIMUM_LINE_COUNT = 2_000;
32
+ const MAXIMUM_LIST_LIMIT = 5_000;
33
+ const MAXIMUM_SEARCH_LIMIT = 1_000;
34
+ const DEFAULT_LIST_LIMIT = 1_000;
35
+ export const DEFAULT_RUN_SANDBOX_LIMITS = {
36
+ memoryMb: 1_024,
37
+ cpuCount: 1,
38
+ processLimit: 128,
39
+ workspaceTmpfsMb: 1_024,
40
+ commandTimeoutMs: 60_000,
41
+ maxCommandTimeoutMs: 900_000,
42
+ maxCommandsPerRun: 200,
43
+ maxTotalSandboxSeconds: 900,
44
+ maxStdoutBytes: 1_048_576,
45
+ maxStderrBytes: 262_144,
46
+ maxArgs: 64,
47
+ maxArgBytes: 4_096,
48
+ maxTotalStagedBytes: 256 * 1_048_576,
49
+ maxOutputFiles: 50,
50
+ maxOutputBytes: 50 * 1_048_576,
51
+ };
52
+ export const resolveRunSandboxLimits = (partial = {}) => {
53
+ const limits = { ...DEFAULT_RUN_SANDBOX_LIMITS };
54
+ for (const [key, value] of Object.entries(partial)) {
55
+ if (value == null)
56
+ continue;
57
+ if (key === "cpuCount") {
58
+ if (!Number.isFinite(value) || value <= 0 || value > 1_024)
59
+ throw new Error("Sandbox cpuCount must be between 0 and 1024.");
60
+ }
61
+ else if (!Number.isSafeInteger(value) || value <= 0) {
62
+ throw new Error(`Sandbox limit ${key} must be a positive safe integer.`);
63
+ }
64
+ limits[key] = value;
65
+ }
66
+ if (limits.commandTimeoutMs > limits.maxCommandTimeoutMs) {
67
+ throw new Error("Sandbox commandTimeoutMs cannot exceed maxCommandTimeoutMs.");
68
+ }
69
+ return limits;
70
+ };
71
+ export const resolveRunSandboxPolicy = (input) => {
72
+ const policy = {
73
+ commands: { ...(input.commands ?? {}) },
74
+ shell: {
75
+ enabled: input.shell?.enabled ?? false,
76
+ program: input.shell?.program ?? ["/bin/sh", "-c"],
77
+ ...(input.shell?.timeoutMs ? { timeoutMs: input.shell.timeoutMs } : {}),
78
+ ...(input.shell?.modes ? { modes: input.shell.modes } : {}),
79
+ },
80
+ limits: resolveRunSandboxLimits(input.limits),
81
+ };
82
+ validateRunSandboxPolicy(policy);
83
+ return policy;
84
+ };
85
+ const compilePattern = (pattern, label) => {
86
+ if (pattern.length > 512)
87
+ throw new Error(`${label} pattern is too long: ${pattern}`);
88
+ try {
89
+ return new RegExp(pattern, "u");
90
+ }
91
+ catch {
92
+ throw new Error(`${label} pattern is not a valid regular expression: ${pattern}`);
93
+ }
94
+ };
95
+ export const validateRunSandboxPolicy = (policy) => {
96
+ for (const [name, entry] of Object.entries(policy.commands)) {
97
+ if (!COMMAND_NAME.test(name))
98
+ throw new Error(`Sandbox command name is invalid: ${name}`);
99
+ if (RESERVED_COMMAND_NAMES.has(name))
100
+ throw new Error(`Sandbox command name is reserved: ${name}`);
101
+ if ((entry.argv == null) === (entry.program == null)) {
102
+ throw new Error(`Sandbox command ${name} requires exactly one of argv or program.`);
103
+ }
104
+ if (entry.argv) {
105
+ if (entry.argv.length === 0)
106
+ throw new Error(`Sandbox command ${name} argv cannot be empty.`);
107
+ for (const element of entry.argv) {
108
+ for (const placeholder of element.matchAll(/\{([^}]*)\}/gu)) {
109
+ if (!["file", "mount", "output"].includes(placeholder[1] ?? "")) {
110
+ throw new Error(`Sandbox command ${name} uses an unknown placeholder: {${placeholder[1]}}`);
111
+ }
112
+ }
113
+ }
114
+ if (entry.args)
115
+ throw new Error(`Sandbox command ${name} cannot combine argv and args.`);
116
+ }
117
+ if (entry.program != null && entry.program.trim() === "")
118
+ throw new Error(`Sandbox command ${name} program cannot be empty.`);
119
+ for (const pattern of entry.args?.allowPatterns ?? [])
120
+ compilePattern(pattern, `Sandbox command ${name} allow`);
121
+ for (const pattern of entry.args?.denyPatterns ?? [])
122
+ compilePattern(pattern, `Sandbox command ${name} deny`);
123
+ if (entry.args?.maxCount != null &&
124
+ (!Number.isSafeInteger(entry.args.maxCount) || entry.args.maxCount < 0)) {
125
+ throw new Error(`Sandbox command ${name} args.maxCount must be a non-negative integer.`);
126
+ }
127
+ if (entry.timeoutMs != null &&
128
+ (!Number.isSafeInteger(entry.timeoutMs) || entry.timeoutMs <= 0)) {
129
+ throw new Error(`Sandbox command ${name} timeoutMs must be a positive integer.`);
130
+ }
131
+ }
132
+ if (policy.shell.enabled && (policy.shell.program?.length ?? 0) === 0) {
133
+ throw new Error("Sandbox shell requires a program.");
134
+ }
135
+ };
136
+ export class SandboxPolicyError extends Error {
137
+ code;
138
+ constructor(code, message) {
139
+ super(message);
140
+ this.name = "SandboxPolicyError";
141
+ this.code = code;
142
+ }
143
+ }
144
+ const notAllowed = (message) => new SandboxPolicyError("tool_not_allowed", message);
145
+ const invalidPath = (message) => new SandboxPolicyError("workspace_path_invalid", message);
146
+ const limitExceeded = (message) => new SandboxPolicyError("workspace_limit_exceeded", message);
147
+ const invalidArguments = (message) => new SandboxPolicyError("sandbox_command_failed", message);
148
+ const entryApplies = (entry, workspace) => (entry.workspaces == null ||
149
+ entry.workspaces.includes(workspace.binding.ref)) &&
150
+ (entry.modes == null || entry.modes.includes(workspace.mode));
151
+ const shellApplies = (shell, workspace) => shell.enabled &&
152
+ (shell.modes == null || shell.modes.includes(workspace.mode));
153
+ const pathSchema = {
154
+ type: "string",
155
+ minLength: 1,
156
+ maxLength: 1024,
157
+ description: "Relative POSIX path inside the workspace.",
158
+ };
159
+ const BUILTIN_SCHEMAS = {
160
+ list_files: {
161
+ description: "List files beneath a directory of the workspace. Supports an optional glob filter such as **/*.md and a result limit.",
162
+ readOnly: true,
163
+ inputSchema: {
164
+ type: "object",
165
+ additionalProperties: false,
166
+ properties: {
167
+ path: {
168
+ ...pathSchema,
169
+ description: "Directory to list; defaults to the root.",
170
+ },
171
+ glob: { type: "string", minLength: 1, maxLength: MAXIMUM_GLOB_LENGTH },
172
+ limit: { type: "integer", minimum: 1, maximum: MAXIMUM_LIST_LIMIT },
173
+ },
174
+ },
175
+ },
176
+ read_file: {
177
+ description: "Read one file. Text files return UTF-8 content with an optional line window; binary files return metadata and an artifact reference.",
178
+ readOnly: true,
179
+ inputSchema: {
180
+ type: "object",
181
+ additionalProperties: false,
182
+ required: ["path"],
183
+ properties: {
184
+ path: pathSchema,
185
+ startLine: { type: "integer", minimum: 1 },
186
+ lineCount: { type: "integer", minimum: 1, maximum: MAXIMUM_LINE_COUNT },
187
+ },
188
+ },
189
+ },
190
+ search_files: {
191
+ description: "Find lines containing a literal text query across text files. Returns file paths, line numbers, and matching lines.",
192
+ readOnly: true,
193
+ inputSchema: {
194
+ type: "object",
195
+ additionalProperties: false,
196
+ required: ["query"],
197
+ properties: {
198
+ query: {
199
+ type: "string",
200
+ minLength: 1,
201
+ maxLength: MAXIMUM_QUERY_LENGTH,
202
+ },
203
+ glob: { type: "string", minLength: 1, maxLength: MAXIMUM_GLOB_LENGTH },
204
+ caseSensitive: { type: "boolean" },
205
+ limit: { type: "integer", minimum: 1, maximum: MAXIMUM_SEARCH_LIMIT },
206
+ },
207
+ },
208
+ },
209
+ write_file: {
210
+ description: "Create or replace one file. Content is UTF-8 text unless encoding is base64.",
211
+ readOnly: false,
212
+ inputSchema: {
213
+ type: "object",
214
+ additionalProperties: false,
215
+ required: ["path", "content"],
216
+ properties: {
217
+ path: pathSchema,
218
+ content: { type: "string" },
219
+ encoding: { type: "string", enum: ["utf-8", "base64"] },
220
+ },
221
+ },
222
+ },
223
+ delete_file: {
224
+ description: "Delete one file from the workspace.",
225
+ readOnly: false,
226
+ inputSchema: {
227
+ type: "object",
228
+ additionalProperties: false,
229
+ required: ["path"],
230
+ properties: { path: pathSchema },
231
+ },
232
+ },
233
+ };
234
+ /** Describe the bare (un-prefixed) tools a binding exposes after host policy. */
235
+ export const describeWorkspaceTools = (workspace, policy) => {
236
+ const tools = [];
237
+ const permitted = new Set(workspace.mode === "read" ? BUILTIN_READ_TOOLS : BUILTIN_WORKSPACE_TOOLS);
238
+ const agentAllowlist = workspace.binding.tools
239
+ ? new Set(workspace.binding.tools)
240
+ : undefined;
241
+ const include = (name) => agentAllowlist == null || agentAllowlist.has(name);
242
+ for (const name of BUILTIN_WORKSPACE_TOOLS) {
243
+ if (!permitted.has(name) || !include(name))
244
+ continue;
245
+ const schema = BUILTIN_SCHEMAS[name];
246
+ tools.push({
247
+ name,
248
+ description: schema.description,
249
+ inputSchema: structuredClone(schema.inputSchema),
250
+ metadata: {
251
+ kind: "builtin",
252
+ readOnly: schema.readOnly,
253
+ destructive: !schema.readOnly,
254
+ },
255
+ });
256
+ }
257
+ for (const [name, entry] of Object.entries(policy.commands)) {
258
+ if (!entryApplies(entry, workspace) || !include(name))
259
+ continue;
260
+ const usesFile = entry.argv?.some((element) => element.includes("{file}"));
261
+ const inputSchema = entry.argv
262
+ ? {
263
+ type: "object",
264
+ additionalProperties: false,
265
+ ...(usesFile
266
+ ? {
267
+ required: ["file"],
268
+ properties: {
269
+ file: {
270
+ ...pathSchema,
271
+ description: `Workspace file to process${entry.inputs ? ` (matching ${entry.inputs.join(", ")})` : ""}.`,
272
+ },
273
+ },
274
+ }
275
+ : { properties: {} }),
276
+ }
277
+ : {
278
+ type: "object",
279
+ additionalProperties: false,
280
+ properties: {
281
+ args: {
282
+ type: "array",
283
+ items: { type: "string", maxLength: policy.limits.maxArgBytes },
284
+ maxItems: entry.args?.maxCount ?? policy.limits.maxArgs,
285
+ description: `Arguments passed to ${entry.program}.`,
286
+ },
287
+ },
288
+ };
289
+ tools.push({
290
+ name,
291
+ description: entry.description ??
292
+ (entry.argv
293
+ ? `Run ${entry.argv[0]} in the workspace.`
294
+ : `Run ${entry.program} with arguments in the workspace.`),
295
+ inputSchema,
296
+ metadata: { kind: "command", readOnly: false, destructive: true },
297
+ });
298
+ }
299
+ if (shellApplies(policy.shell, workspace) && include(SHELL_TOOL_NAME)) {
300
+ tools.push({
301
+ name: SHELL_TOOL_NAME,
302
+ description: "Run a shell command in the workspace directory. Output is bounded; the sandbox has no network.",
303
+ inputSchema: {
304
+ type: "object",
305
+ additionalProperties: false,
306
+ required: ["command"],
307
+ properties: {
308
+ command: {
309
+ type: "string",
310
+ minLength: 1,
311
+ maxLength: policy.limits.maxArgBytes,
312
+ },
313
+ },
314
+ },
315
+ metadata: { kind: "shell", readOnly: false, destructive: true },
316
+ });
317
+ }
318
+ return tools;
319
+ };
320
+ const requireString = (value, label, maximum, required) => {
321
+ if (value === undefined) {
322
+ if (required)
323
+ throw invalidArguments(`${label} is required.`);
324
+ return undefined;
325
+ }
326
+ if (typeof value !== "string")
327
+ throw invalidArguments(`${label} must be a string.`);
328
+ if (required && value.length === 0)
329
+ throw invalidArguments(`${label} cannot be empty.`);
330
+ if (value.length > maximum)
331
+ throw limitExceeded(`${label} exceeds ${maximum} characters.`);
332
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/u.test(value))
333
+ throw invalidArguments(`${label} contains control characters.`);
334
+ return value;
335
+ };
336
+ const requireInteger = (value, label, maximum) => {
337
+ if (value === undefined)
338
+ return undefined;
339
+ if (!Number.isSafeInteger(value) || Number(value) < 1)
340
+ throw invalidArguments(`${label} must be a positive integer.`);
341
+ if (Number(value) > maximum)
342
+ throw limitExceeded(`${label} exceeds ${maximum}.`);
343
+ return Number(value);
344
+ };
345
+ const requireBoolean = (value, label) => {
346
+ if (value === undefined)
347
+ return undefined;
348
+ if (typeof value !== "boolean")
349
+ throw invalidArguments(`${label} must be a boolean.`);
350
+ return value;
351
+ };
352
+ const requirePath = (value, label, required = true) => {
353
+ const text = requireString(value, label, 1024, required);
354
+ if (text === undefined)
355
+ return undefined;
356
+ if (!isSafeWorkspacePath(text))
357
+ throw invalidPath(`${label} must be a relative POSIX path with safe segments: ${text}`);
358
+ return text;
359
+ };
360
+ const rejectUnknownKeys = (input, allowed) => {
361
+ for (const key of Object.keys(input)) {
362
+ if (!allowed.includes(key))
363
+ throw invalidArguments(`Unexpected argument: ${key}`);
364
+ }
365
+ };
366
+ const globMatches = (pattern, value) => {
367
+ let source = "";
368
+ let index = 0;
369
+ while (index < pattern.length) {
370
+ const character = pattern[index];
371
+ if (character === "*") {
372
+ if (pattern[index + 1] === "*") {
373
+ const slash = pattern[index + 2] === "/";
374
+ source += slash ? "(?:.*/)?" : ".*";
375
+ index += slash ? 3 : 2;
376
+ continue;
377
+ }
378
+ source += "[^/]*";
379
+ index += 1;
380
+ continue;
381
+ }
382
+ if (character === "?") {
383
+ source += "[^/]";
384
+ index += 1;
385
+ continue;
386
+ }
387
+ source += character.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
388
+ index += 1;
389
+ }
390
+ return new RegExp(`^${source}$`, "u").test(value);
391
+ };
392
+ const mountDirectory = (alias) => assertSandboxPath(`${SANDBOX_MOUNT_DIRECTORY}/${alias}`);
393
+ const helperLimitFlags = (workspace, writable) => [
394
+ ...(writable ? ["--writable"] : []),
395
+ "--max-files",
396
+ String(workspace.store.limits?.maxFiles ?? 5_000),
397
+ "--max-bytes",
398
+ String(workspace.store.limits?.maxFileBytes ?? 1_048_576),
399
+ ];
400
+ const timeoutFor = (policy, requested) => Math.min(requested ?? policy.limits.commandTimeoutMs, policy.limits.maxCommandTimeoutMs);
401
+ /**
402
+ * Decide whether a request may execute and, if so, the exact argv. Every
403
+ * argument the model supplied is validated here before it reaches a process.
404
+ */
405
+ export const admitCommand = (request, context) => {
406
+ const { policy } = context;
407
+ const outputDirectory = assertSandboxPath(`${SANDBOX_OUTPUT_DIRECTORY}/${context.commandId}`);
408
+ const stagingDirectory = assertSandboxPath(`${SANDBOX_STAGING_DIRECTORY}/${context.commandId}`);
409
+ const input = request.arguments;
410
+ if (request.kind === "code") {
411
+ const language = requireString(input.language, "language", 64, true);
412
+ const code = typeof input.code === "string" ? input.code : undefined;
413
+ if (code === undefined)
414
+ throw invalidArguments("code is required.");
415
+ const profile = context.codeProfile?.(language);
416
+ if (!profile)
417
+ throw notAllowed(`No sandbox runtime profile for ${language}.`);
418
+ const stepDirectory = assertSandboxPath(`${SANDBOX_STEPS_DIRECTORY}/${context.commandId}`);
419
+ const sourcePath = `${stepDirectory}/main.${profile.extension}`;
420
+ const stagedFiles = [
421
+ { path: sourcePath, content: code, mode: 0o600 },
422
+ {
423
+ path: `${stepDirectory}/variables.json`,
424
+ content: JSON.stringify(input.variables ?? {}),
425
+ mode: 0o600,
426
+ },
427
+ ];
428
+ return {
429
+ kind: "code",
430
+ name: request.name,
431
+ argv: profile.argv(sourcePath),
432
+ cwd: stepDirectory,
433
+ timeoutMs: timeoutFor(policy, typeof input.timeoutMs === "number" ? input.timeoutMs : undefined),
434
+ stagedFiles,
435
+ outputDirectory,
436
+ expectsJson: false,
437
+ };
438
+ }
439
+ const workspace = context.workspace;
440
+ if (!workspace)
441
+ throw notAllowed("The command names no bound workspace.");
442
+ const mount = mountDirectory(workspace.alias);
443
+ const helper = [...context.helperCommand];
444
+ if (request.kind === "builtin") {
445
+ const name = request.name;
446
+ if (!BUILTIN_WORKSPACE_TOOLS.includes(name))
447
+ throw notAllowed(`Tool "${request.name}" is not available.`);
448
+ const readOnly = BUILTIN_SCHEMAS[name].readOnly;
449
+ if (!readOnly && workspace.mode !== "read_write")
450
+ throw notAllowed(`Tool "${request.name}" requires a read_write workspace.`);
451
+ if (workspace.binding.tools && !workspace.binding.tools.includes(name))
452
+ throw notAllowed(`Tool "${request.name}" is not available.`);
453
+ const flags = helperLimitFlags(workspace, workspace.mode === "read_write");
454
+ let argv;
455
+ const stagedFiles = [];
456
+ switch (name) {
457
+ case "list_files": {
458
+ rejectUnknownKeys(input, ["path", "glob", "limit"]);
459
+ const path = requirePath(input.path, "path", false);
460
+ const glob = requireString(input.glob, "glob", MAXIMUM_GLOB_LENGTH, false);
461
+ const limit = requireInteger(input.limit, "limit", MAXIMUM_LIST_LIMIT);
462
+ argv = [
463
+ ...helper,
464
+ "list",
465
+ "--mount",
466
+ mount,
467
+ ...flags,
468
+ ...(path ? ["--path", path] : []),
469
+ ...(glob ? ["--glob", glob] : []),
470
+ "--limit",
471
+ String(limit ?? DEFAULT_LIST_LIMIT),
472
+ ];
473
+ break;
474
+ }
475
+ case "read_file": {
476
+ rejectUnknownKeys(input, ["path", "startLine", "lineCount"]);
477
+ const path = requirePath(input.path, "path");
478
+ const startLine = requireInteger(input.startLine, "startLine", Number.MAX_SAFE_INTEGER);
479
+ const lineCount = requireInteger(input.lineCount, "lineCount", MAXIMUM_LINE_COUNT);
480
+ argv = [
481
+ ...helper,
482
+ "read",
483
+ "--mount",
484
+ mount,
485
+ ...flags,
486
+ "--path",
487
+ path,
488
+ ...(startLine ? ["--start-line", String(startLine)] : []),
489
+ ...(lineCount ? ["--line-count", String(lineCount)] : []),
490
+ "--artifact-dir",
491
+ outputDirectory,
492
+ ];
493
+ break;
494
+ }
495
+ case "search_files": {
496
+ rejectUnknownKeys(input, ["query", "glob", "caseSensitive", "limit"]);
497
+ const query = requireString(input.query, "query", MAXIMUM_QUERY_LENGTH, true);
498
+ const glob = requireString(input.glob, "glob", MAXIMUM_GLOB_LENGTH, false);
499
+ const caseSensitive = requireBoolean(input.caseSensitive, "caseSensitive");
500
+ const limit = requireInteger(input.limit, "limit", MAXIMUM_SEARCH_LIMIT);
501
+ argv = [
502
+ ...helper,
503
+ "search",
504
+ "--mount",
505
+ mount,
506
+ ...flags,
507
+ "--query",
508
+ query,
509
+ ...(glob ? ["--glob", glob] : []),
510
+ ...(caseSensitive ? ["--case-sensitive"] : []),
511
+ ...(limit ? ["--limit", String(limit)] : []),
512
+ ];
513
+ break;
514
+ }
515
+ case "write_file": {
516
+ rejectUnknownKeys(input, ["path", "content", "encoding"]);
517
+ const path = requirePath(input.path, "path");
518
+ if (typeof input.content !== "string")
519
+ throw invalidArguments("content must be a string.");
520
+ const encoding = requireString(input.encoding, "encoding", 16, false) ?? "utf-8";
521
+ if (encoding !== "utf-8" && encoding !== "base64")
522
+ throw invalidArguments("encoding must be utf-8 or base64.");
523
+ const maxBytes = workspace.store.limits?.maxFileBytes ?? 1_048_576;
524
+ if (Buffer.byteLength(input.content) >
525
+ maxBytes * (encoding === "base64" ? 2 : 1)) {
526
+ throw limitExceeded(`content exceeds the ${maxBytes}-byte limit.`);
527
+ }
528
+ const source = `${stagingDirectory}/content`;
529
+ stagedFiles.push({ path: source, content: input.content, mode: 0o400 });
530
+ argv = [
531
+ ...helper,
532
+ "write",
533
+ "--mount",
534
+ mount,
535
+ ...flags,
536
+ "--path",
537
+ path,
538
+ "--source",
539
+ source,
540
+ "--encoding",
541
+ encoding,
542
+ ];
543
+ break;
544
+ }
545
+ case "delete_file": {
546
+ rejectUnknownKeys(input, ["path"]);
547
+ const path = requirePath(input.path, "path");
548
+ argv = [
549
+ ...helper,
550
+ "delete",
551
+ "--mount",
552
+ mount,
553
+ ...flags,
554
+ "--path",
555
+ path,
556
+ ];
557
+ break;
558
+ }
559
+ }
560
+ return {
561
+ kind: "builtin",
562
+ name,
563
+ argv,
564
+ cwd: mount,
565
+ timeoutMs: timeoutFor(policy, undefined),
566
+ stagedFiles,
567
+ outputDirectory,
568
+ expectsJson: true,
569
+ };
570
+ }
571
+ if (request.kind === "shell") {
572
+ if (!shellApplies(policy.shell, workspace))
573
+ throw notAllowed("Shell commands are not enabled for this workspace.");
574
+ if (workspace.binding.tools &&
575
+ !workspace.binding.tools.includes(SHELL_TOOL_NAME))
576
+ throw notAllowed(`Tool "${SHELL_TOOL_NAME}" is not available.`);
577
+ rejectUnknownKeys(input, ["command"]);
578
+ const command = requireString(input.command, "command", policy.limits.maxArgBytes, true);
579
+ return {
580
+ kind: "shell",
581
+ name: SHELL_TOOL_NAME,
582
+ policyEntry: "shell",
583
+ argv: [...(policy.shell.program ?? ["/bin/sh", "-c"]), command],
584
+ cwd: mount,
585
+ timeoutMs: timeoutFor(policy, policy.shell.timeoutMs),
586
+ stagedFiles: [],
587
+ outputDirectory,
588
+ expectsJson: false,
589
+ };
590
+ }
591
+ const entry = policy.commands[request.name];
592
+ if (!entry || !entryApplies(entry, workspace))
593
+ throw notAllowed(`Tool "${request.name}" is not available.`);
594
+ if (workspace.binding.tools &&
595
+ !workspace.binding.tools.includes(request.name))
596
+ throw notAllowed(`Tool "${request.name}" is not available.`);
597
+ let argv;
598
+ if (entry.argv) {
599
+ const usesFile = entry.argv.some((element) => element.includes("{file}"));
600
+ rejectUnknownKeys(input, usesFile ? ["file"] : []);
601
+ let file;
602
+ if (usesFile) {
603
+ file = requirePath(input.file, "file");
604
+ if (entry.inputs &&
605
+ !entry.inputs.some((glob) => globMatches(glob, file))) {
606
+ throw invalidPath(`file does not match the inputs this command accepts: ${file}`);
607
+ }
608
+ }
609
+ argv = entry.argv.map((element) => element
610
+ .replaceAll("{mount}", mount)
611
+ .replaceAll("{output}", outputDirectory)
612
+ .replaceAll("{file}", file ? `${mount}/${file}` : ""));
613
+ }
614
+ else {
615
+ rejectUnknownKeys(input, ["args"]);
616
+ const rawArgs = input.args ?? [];
617
+ if (!Array.isArray(rawArgs))
618
+ throw invalidArguments("args must be an array.");
619
+ const maxCount = entry.args?.maxCount ?? policy.limits.maxArgs;
620
+ if (rawArgs.length > maxCount)
621
+ throw limitExceeded(`args exceeds ${maxCount} entries.`);
622
+ const args = rawArgs.map((value, index) => requireString(value, `args[${index}]`, policy.limits.maxArgBytes, false));
623
+ if (args.some((value) => value === undefined || value.length === 0))
624
+ throw invalidArguments("args entries must be non-empty strings.");
625
+ const deny = (entry.args?.denyPatterns ?? []).map((pattern) => compilePattern(pattern, "deny"));
626
+ for (const value of args) {
627
+ if (deny.some((pattern) => pattern.test(value)))
628
+ throw notAllowed(`Argument is not permitted: ${value}`);
629
+ }
630
+ const allow = (entry.args?.allowPatterns ?? []).map((pattern) => compilePattern(pattern, "allow"));
631
+ if (allow.length > 0) {
632
+ const first = args[0];
633
+ if (first === undefined || !allow.some((pattern) => pattern.test(first)))
634
+ throw notAllowed(`The first argument must match the host allowlist.`);
635
+ }
636
+ argv = [entry.program, ...args];
637
+ }
638
+ return {
639
+ kind: "command",
640
+ name: request.name,
641
+ policyEntry: request.name,
642
+ argv,
643
+ cwd: mount,
644
+ timeoutMs: timeoutFor(policy, entry.timeoutMs),
645
+ stagedFiles: [],
646
+ outputDirectory,
647
+ expectsJson: false,
648
+ };
649
+ };