@robota-sdk/agent-tools 3.0.0-beta.7 → 3.0.0-beta.71

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.
@@ -1,1443 +1,1409 @@
1
- // src/registry/tool-registry.ts
2
- import { ValidationError } from "@robota-sdk/agent-core";
3
- import { logger } from "@robota-sdk/agent-core";
1
+ import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute, join, posix, resolve, sep } from "node:path";
3
+ import { ToolExecutionError, ValidationError, logger } from "@robota-sdk/agent-core";
4
+ import { spawn } from "node:child_process";
5
+ import { z } from "zod";
6
+ import { randomBytes } from "node:crypto";
7
+ import fg from "fast-glob";
8
+ import pLimit from "p-limit";
9
+ //#region src/sandbox/e2b-sandbox-client.ts
10
+ var E2BSandboxClient = class {
11
+ sandbox;
12
+ connectSandbox;
13
+ createSandboxFromSnapshot;
14
+ constructor(options) {
15
+ this.sandbox = options.sandbox;
16
+ this.connectSandbox = options.connectSandbox;
17
+ this.createSandboxFromSnapshot = options.createSandboxFromSnapshot;
18
+ }
19
+ async run(command, options) {
20
+ const result = await this.sandbox.commands.run(command, {
21
+ background: false,
22
+ timeoutMs: options?.timeoutMs,
23
+ cwd: options?.workingDirectory
24
+ });
25
+ return {
26
+ stdout: result.stdout ?? "",
27
+ stderr: result.stderr ?? "",
28
+ exitCode: result.exitCode ?? result.exit_code ?? 0
29
+ };
30
+ }
31
+ async readFile(path) {
32
+ const content = await this.sandbox.files.read(path);
33
+ return typeof content === "string" ? content : Buffer.from(content).toString("utf8");
34
+ }
35
+ async writeFile(path, content) {
36
+ await this.sandbox.files.write(path, content);
37
+ }
38
+ async snapshot() {
39
+ if (this.sandbox.createSnapshot) {
40
+ const snapshot = await this.sandbox.createSnapshot();
41
+ const snapshotId = snapshot.snapshotId ?? snapshot.id;
42
+ if (!snapshotId) throw new Error("E2B createSnapshot() did not return a snapshot id.");
43
+ return snapshotId;
44
+ }
45
+ const sandboxId = this.sandbox.sandboxId;
46
+ if (!sandboxId) throw new Error("E2B sandboxId is required to create a resumable sandbox snapshot.");
47
+ if (!this.sandbox.pause) throw new Error("E2B sandbox adapter does not expose pause().");
48
+ await this.sandbox.pause();
49
+ return sandboxId;
50
+ }
51
+ async restore(snapshotId) {
52
+ if (this.createSandboxFromSnapshot) {
53
+ this.sandbox = await this.createSandboxFromSnapshot(snapshotId);
54
+ return;
55
+ }
56
+ if (this.connectSandbox) {
57
+ this.sandbox = await this.connectSandbox(snapshotId);
58
+ return;
59
+ }
60
+ if (this.sandbox.sandboxId === snapshotId && this.sandbox.connect) {
61
+ this.sandbox = await this.sandbox.connect();
62
+ return;
63
+ }
64
+ throw new Error("E2B sandbox restore requires connectSandbox(snapshotId) or sandbox.connect().");
65
+ }
66
+ };
67
+ //#endregion
68
+ //#region src/sandbox/in-memory-sandbox-client.ts
69
+ var InMemorySandboxClient = class {
70
+ files = /* @__PURE__ */ new Map();
71
+ snapshots = /* @__PURE__ */ new Map();
72
+ runHandler;
73
+ snapshotSequence = 0;
74
+ constructor(options = {}) {
75
+ for (const [path, content] of Object.entries(options.files ?? {})) this.files.set(path, content);
76
+ this.runHandler = options.runHandler;
77
+ }
78
+ async run(command, options) {
79
+ if (this.runHandler) return this.runHandler(command, options, this.files);
80
+ return {
81
+ stdout: "",
82
+ stderr: "",
83
+ exitCode: 0
84
+ };
85
+ }
86
+ async readFile(path) {
87
+ const content = this.files.get(path);
88
+ if (content === void 0) throw new Error(`Sandbox file not found: ${path}`);
89
+ return content;
90
+ }
91
+ async writeFile(path, content) {
92
+ this.files.set(path, content);
93
+ }
94
+ async snapshot() {
95
+ const snapshotId = `snapshot-${++this.snapshotSequence}`;
96
+ this.snapshots.set(snapshotId, new Map(this.files));
97
+ return snapshotId;
98
+ }
99
+ async restore(snapshotId) {
100
+ const snapshot = this.snapshots.get(snapshotId);
101
+ if (!snapshot) throw new Error(`Sandbox snapshot not found: ${snapshotId}`);
102
+ this.files.clear();
103
+ for (const [path, content] of snapshot.entries()) this.files.set(path, content);
104
+ }
105
+ getFile(path) {
106
+ return this.files.get(path);
107
+ }
108
+ };
109
+ //#endregion
110
+ //#region src/sandbox/workspace-manifest.ts
111
+ const DEFAULT_TARGET_ROOT = "/workspace";
112
+ const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
113
+ const SHELL_QUOTE_PATTERN = /'/g;
114
+ async function applyWorkspaceManifest(sandboxClient, manifest, options = {}) {
115
+ if (sandboxClient.applyManifest) return sandboxClient.applyManifest(manifest, options);
116
+ const targetRoot = normalizeSandboxRoot(options.targetRoot ?? DEFAULT_TARGET_ROOT);
117
+ const appliedEntries = [];
118
+ for (const [rawPath, entry] of Object.entries(manifest.entries)) {
119
+ const path = validateWorkspaceManifestPath(rawPath);
120
+ const targetPath = joinSandboxPath(targetRoot, path);
121
+ appliedEntries.push(await applyManifestEntry(sandboxClient, path, targetPath, targetRoot, entry, options));
122
+ }
123
+ return { entries: appliedEntries };
124
+ }
125
+ function validateWorkspaceManifestPath(path) {
126
+ if (path.length === 0) throw new Error("workspace manifest path must not be empty");
127
+ if (path.includes("\0")) throw new Error("workspace manifest path must not contain NUL bytes");
128
+ if (path.startsWith("/") || path.startsWith("\\") || WINDOWS_ABSOLUTE_PATH_PATTERN.test(path)) throw new Error("workspace manifest path must be workspace-relative");
129
+ const parts = path.replace(/\\/g, "/").split("/").filter(Boolean);
130
+ if (parts.length === 0) throw new Error("workspace manifest path must not resolve to the workspace root");
131
+ if (parts.some((part) => part === "..")) throw new Error("workspace manifest path cannot contain traversal segments");
132
+ const normalizedParts = parts.filter((part) => part !== ".");
133
+ if (normalizedParts.length === 0) throw new Error("workspace manifest path must not resolve to the workspace root");
134
+ return normalizedParts.join("/");
135
+ }
136
+ async function applyManifestEntry(sandboxClient, path, targetPath, targetRoot, entry, options) {
137
+ switch (entry.type) {
138
+ case "file":
139
+ await writeSandboxFile(sandboxClient, targetPath, targetRoot, entry.content);
140
+ return createAppliedEntry(path, entry.type);
141
+ case "dir":
142
+ await createSandboxDirectory(sandboxClient, targetPath);
143
+ return createAppliedEntry(path, entry.type);
144
+ case "localFile":
145
+ await copyLocalFile(sandboxClient, entry.src, targetPath, targetRoot, options);
146
+ return createAppliedEntry(path, entry.type);
147
+ case "localDir":
148
+ await copyLocalDirectory(sandboxClient, entry.src, targetPath, options);
149
+ return createAppliedEntry(path, entry.type);
150
+ case "gitRepo":
151
+ await cloneGitRepository(sandboxClient, entry, targetPath);
152
+ return createAppliedEntry(path, entry.type);
153
+ case "s3Mount":
154
+ case "gcsMount":
155
+ case "r2Mount":
156
+ case "azureBlobMount": return {
157
+ path,
158
+ type: entry.type,
159
+ status: "unsupported",
160
+ message: `${entry.type} requires a provider-specific sandbox adapter.`
161
+ };
162
+ default: return assertUnreachable(entry);
163
+ }
164
+ }
165
+ function createAppliedEntry(path, type) {
166
+ return {
167
+ path,
168
+ type,
169
+ status: "applied"
170
+ };
171
+ }
172
+ async function copyLocalFile(sandboxClient, source, targetPath, targetRoot, options) {
173
+ await writeSandboxFile(sandboxClient, targetPath, targetRoot, await readFile(resolveHostSourcePath(source, options.hostRoot), "utf8"));
174
+ }
175
+ async function copyLocalDirectory(sandboxClient, source, targetPath, options) {
176
+ await copyLocalDirectoryRecursive(sandboxClient, resolveHostSourcePath(source, options.hostRoot), targetPath);
177
+ }
178
+ async function copyLocalDirectoryRecursive(sandboxClient, sourcePath, targetPath) {
179
+ await createSandboxDirectory(sandboxClient, targetPath);
180
+ const entries = await readdir(sourcePath, { withFileTypes: true });
181
+ for (const entry of entries) {
182
+ const childSourcePath = join(sourcePath, entry.name);
183
+ const childTargetPath = joinSandboxPath(targetPath, entry.name);
184
+ if (entry.isDirectory()) {
185
+ await copyLocalDirectoryRecursive(sandboxClient, childSourcePath, childTargetPath);
186
+ continue;
187
+ }
188
+ if (entry.isFile()) {
189
+ const content = await readFile(childSourcePath, "utf8");
190
+ await sandboxClient.writeFile(childTargetPath, content);
191
+ }
192
+ }
193
+ }
194
+ async function cloneGitRepository(sandboxClient, entry, targetPath) {
195
+ await runSandboxCommand(sandboxClient, `git clone${entry.shallow === false ? "" : " --depth 1"}${entry.ref ? ` --branch ${quoteShellArg(entry.ref)}` : ""} ${quoteShellArg(entry.url)} ${quoteShellArg(targetPath)}`);
196
+ }
197
+ async function writeSandboxFile(sandboxClient, targetPath, targetRoot, content) {
198
+ const parentPath = posix.dirname(targetPath);
199
+ if (parentPath !== targetRoot) await createSandboxDirectory(sandboxClient, parentPath);
200
+ await sandboxClient.writeFile(targetPath, content);
201
+ }
202
+ async function createSandboxDirectory(sandboxClient, targetPath) {
203
+ await runSandboxCommand(sandboxClient, `mkdir -p ${quoteShellArg(targetPath)}`);
204
+ }
205
+ async function runSandboxCommand(sandboxClient, command) {
206
+ const result = await sandboxClient.run(command);
207
+ if (result.exitCode !== 0) throw new Error(`workspace manifest command failed: ${command}\n${result.stderr ?? result.stdout}`);
208
+ }
209
+ function resolveHostSourcePath(source, hostRoot) {
210
+ return isAbsolute(source) ? resolve(source) : resolve(hostRoot ?? process.cwd(), source);
211
+ }
212
+ function normalizeSandboxRoot(root) {
213
+ const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
214
+ if (!normalized.startsWith("/")) throw new Error("workspace manifest targetRoot must be an absolute sandbox path");
215
+ return normalized.length === 0 ? "/" : normalized;
216
+ }
217
+ function joinSandboxPath(root, path) {
218
+ const normalizedRoot = normalizeSandboxRoot(root);
219
+ if (normalizedRoot === "/") return `/${path}`;
220
+ return `${normalizedRoot}/${path}`;
221
+ }
222
+ function quoteShellArg(value) {
223
+ return `'${value.replace(SHELL_QUOTE_PATTERN, "'\\''")}'`;
224
+ }
225
+ function assertUnreachable(value) {
226
+ throw new Error(`unsupported workspace manifest entry: ${JSON.stringify(value)}`);
227
+ }
228
+ //#endregion
229
+ //#region src/registry/tool-registry.ts
230
+ /**
231
+ * Tool registry implementation
232
+ * Manages tool registration, validation, and retrieval
233
+ */
4
234
  var ToolRegistry = class {
5
- tools = /* @__PURE__ */ new Map();
6
- /**
7
- * Register a tool
8
- */
9
- register(tool) {
10
- if (!tool.schema?.name) {
11
- throw new ValidationError("Tool must have a valid schema with name");
12
- }
13
- const toolName = tool.schema.name;
14
- this.validateToolSchema(tool.schema);
15
- if (this.tools.has(toolName)) {
16
- logger.warn(`Tool "${toolName}" is already registered, overriding`, {
17
- toolName,
18
- existingTool: this.tools.get(toolName)?.constructor.name
19
- });
20
- }
21
- this.tools.set(toolName, tool);
22
- logger.debug(`Tool "${toolName}" registered successfully`, {
23
- toolName,
24
- toolType: tool.constructor.name,
25
- parameters: Object.keys(tool.schema.parameters?.properties || {})
26
- });
27
- }
28
- /**
29
- * Unregister a tool
30
- */
31
- unregister(name) {
32
- if (!this.tools.has(name)) {
33
- logger.warn(`Attempted to unregister non-existent tool "${name}"`);
34
- return;
35
- }
36
- this.tools.delete(name);
37
- logger.debug(`Tool "${name}" unregistered successfully`);
38
- }
39
- /**
40
- * Get tool by name
41
- */
42
- get(name) {
43
- return this.tools.get(name);
44
- }
45
- /**
46
- * Get all registered tools
47
- */
48
- getAll() {
49
- return Array.from(this.tools.values());
50
- }
51
- /**
52
- * Get tool schemas
53
- */
54
- getSchemas() {
55
- const tools = this.getAll();
56
- logger.debug("[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction", {
57
- count: tools.length,
58
- tools: tools.map((t) => ({
59
- name: t.schema?.name ?? "unnamed",
60
- hasSchema: !!t.schema,
61
- schemaType: typeof t.schema,
62
- toolType: t.constructor?.name || "unknown"
63
- }))
64
- });
65
- return this.getAll().map((tool) => tool.schema);
66
- }
67
- /**
68
- * Check if tool exists
69
- */
70
- has(name) {
71
- return this.tools.has(name);
72
- }
73
- /**
74
- * Clear all tools
75
- */
76
- clear() {
77
- const toolCount = this.tools.size;
78
- this.tools.clear();
79
- logger.debug(`Cleared ${toolCount} tools from registry`);
80
- }
81
- /**
82
- * Get tool names
83
- */
84
- getToolNames() {
85
- return Array.from(this.tools.keys());
86
- }
87
- /**
88
- * Get tools by pattern
89
- */
90
- getToolsByPattern(pattern) {
91
- const regex = typeof pattern === "string" ? new RegExp(pattern) : pattern;
92
- return this.getAll().filter((tool) => regex.test(tool.schema.name));
93
- }
94
- /**
95
- * Get tool count
96
- */
97
- size() {
98
- return this.tools.size;
99
- }
100
- /**
101
- * Validate tool schema
102
- */
103
- validateToolSchema(schema) {
104
- if (!schema.name || typeof schema.name !== "string") {
105
- throw new ValidationError("Tool schema must have a valid name");
106
- }
107
- if (!schema.description || typeof schema.description !== "string") {
108
- throw new ValidationError("Tool schema must have a description");
109
- }
110
- if (!schema.parameters || typeof schema.parameters !== "object" || schema.parameters === null || Array.isArray(schema.parameters)) {
111
- throw new ValidationError("Tool schema must have parameters object");
112
- }
113
- if (schema.parameters.type !== "object") {
114
- throw new ValidationError('Tool parameters type must be "object"');
115
- }
116
- if (schema.parameters.properties) {
117
- for (const propName of Object.keys(schema.parameters.properties)) {
118
- const propSchema = schema.parameters.properties[propName];
119
- if (!propSchema?.type) {
120
- throw new ValidationError(`Parameter "${propName}" must have a type`);
121
- }
122
- const validTypes = ["string", "number", "boolean", "array", "object"];
123
- if (!validTypes.includes(propSchema.type)) {
124
- throw new ValidationError(
125
- `Parameter "${propName}" has invalid type "${propSchema.type}"`
126
- );
127
- }
128
- }
129
- }
130
- if (schema.parameters.required) {
131
- const properties = schema.parameters.properties || {};
132
- for (const requiredField of schema.parameters.required) {
133
- if (!properties[requiredField]) {
134
- throw new ValidationError(
135
- `Required parameter "${requiredField}" is not defined in properties`
136
- );
137
- }
138
- }
139
- }
140
- }
235
+ tools = /* @__PURE__ */ new Map();
236
+ /**
237
+ * Register a tool
238
+ */
239
+ register(tool) {
240
+ if (!tool.schema?.name) throw new ValidationError("Tool must have a valid schema with name");
241
+ const toolName = tool.schema.name;
242
+ this.validateToolSchema(tool.schema);
243
+ if (this.tools.has(toolName)) logger.warn(`Tool "${toolName}" is already registered, overriding`, {
244
+ toolName,
245
+ existingTool: this.tools.get(toolName)?.constructor.name
246
+ });
247
+ this.tools.set(toolName, tool);
248
+ logger.debug(`Tool "${toolName}" registered successfully`, {
249
+ toolName,
250
+ toolType: tool.constructor.name,
251
+ parameters: Object.keys(tool.schema.parameters?.properties || {})
252
+ });
253
+ }
254
+ /**
255
+ * Unregister a tool
256
+ */
257
+ unregister(name) {
258
+ if (!this.tools.has(name)) {
259
+ logger.warn(`Attempted to unregister non-existent tool "${name}"`);
260
+ return;
261
+ }
262
+ this.tools.delete(name);
263
+ logger.debug(`Tool "${name}" unregistered successfully`);
264
+ }
265
+ /**
266
+ * Get tool by name
267
+ */
268
+ get(name) {
269
+ return this.tools.get(name);
270
+ }
271
+ /**
272
+ * Get all registered tools
273
+ */
274
+ getAll() {
275
+ return Array.from(this.tools.values());
276
+ }
277
+ /**
278
+ * Get tool schemas
279
+ */
280
+ getSchemas() {
281
+ const tools = this.getAll();
282
+ logger.debug("[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction", {
283
+ count: tools.length,
284
+ tools: tools.map((t) => ({
285
+ name: t.schema?.name ?? "unnamed",
286
+ hasSchema: !!t.schema,
287
+ schemaType: typeof t.schema,
288
+ toolType: t.constructor?.name || "unknown"
289
+ }))
290
+ });
291
+ return this.getAll().map((tool) => tool.schema);
292
+ }
293
+ /**
294
+ * Check if tool exists
295
+ */
296
+ has(name) {
297
+ return this.tools.has(name);
298
+ }
299
+ /**
300
+ * Clear all tools
301
+ */
302
+ clear() {
303
+ const toolCount = this.tools.size;
304
+ this.tools.clear();
305
+ logger.debug(`Cleared ${toolCount} tools from registry`);
306
+ }
307
+ /**
308
+ * Get tool names
309
+ */
310
+ getToolNames() {
311
+ return Array.from(this.tools.keys());
312
+ }
313
+ /**
314
+ * Get tools by pattern
315
+ */
316
+ getToolsByPattern(pattern) {
317
+ const regex = typeof pattern === "string" ? new RegExp(pattern) : pattern;
318
+ return this.getAll().filter((tool) => regex.test(tool.schema.name));
319
+ }
320
+ /**
321
+ * Get tool count
322
+ */
323
+ size() {
324
+ return this.tools.size;
325
+ }
326
+ /**
327
+ * Validate tool schema
328
+ */
329
+ validateToolSchema(schema) {
330
+ if (!schema.name || typeof schema.name !== "string") throw new ValidationError("Tool schema must have a valid name");
331
+ if (!schema.description || typeof schema.description !== "string") throw new ValidationError("Tool schema must have a description");
332
+ if (!schema.parameters || typeof schema.parameters !== "object" || schema.parameters === null || Array.isArray(schema.parameters)) throw new ValidationError("Tool schema must have parameters object");
333
+ if (schema.parameters.type !== "object") throw new ValidationError("Tool parameters type must be \"object\"");
334
+ if (schema.parameters.properties) for (const propName of Object.keys(schema.parameters.properties)) {
335
+ const propSchema = schema.parameters.properties[propName];
336
+ if (!propSchema?.type) throw new ValidationError(`Parameter "${propName}" must have a type`);
337
+ if (![
338
+ "string",
339
+ "number",
340
+ "boolean",
341
+ "array",
342
+ "object"
343
+ ].includes(propSchema.type)) throw new ValidationError(`Parameter "${propName}" has invalid type "${propSchema.type}"`);
344
+ }
345
+ if (schema.parameters.required) {
346
+ const properties = schema.parameters.properties || {};
347
+ for (const requiredField of schema.parameters.required) if (!properties[requiredField]) throw new ValidationError(`Required parameter "${requiredField}" is not defined in properties`);
348
+ }
349
+ }
141
350
  };
142
-
143
- // src/implementations/function-tool.ts
144
- import { ToolExecutionError, ValidationError as ValidationError2 } from "@robota-sdk/agent-core";
145
-
146
- // src/implementations/function-tool/schema-converter.ts
351
+ //#endregion
352
+ //#region src/implementations/function-tool/parameter-validator.ts
353
+ /**
354
+ * Validate individual parameter type against its schema.
355
+ * Returns an error string if invalid, undefined if valid.
356
+ */
357
+ function validateParameterType(key, value, schema) {
358
+ switch (schema["type"]) {
359
+ case "string":
360
+ if (typeof value !== "string") return `Parameter "${key}" must be a string, got ${typeof value}`;
361
+ break;
362
+ case "number":
363
+ if (typeof value !== "number" || isNaN(value)) return `Parameter "${key}" must be a number, got ${typeof value}`;
364
+ break;
365
+ case "boolean":
366
+ if (typeof value !== "boolean") return `Parameter "${key}" must be a boolean, got ${typeof value}`;
367
+ break;
368
+ case "array":
369
+ if (!Array.isArray(value)) return `Parameter "${key}" must be an array, got ${typeof value}`;
370
+ if (schema.items) for (let i = 0; i < value.length; i++) {
371
+ const itemError = validateParameterType(`${key}[${i}]`, value[i], schema.items);
372
+ if (itemError) return itemError;
373
+ }
374
+ break;
375
+ case "object":
376
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return `Parameter "${key}" must be an object, got ${typeof value}`;
377
+ break;
378
+ }
379
+ if (schema.enum && schema.enum.length > 0) {
380
+ const enumValues = schema.enum;
381
+ let isValidEnum = false;
382
+ for (const enumValue of enumValues) if (value === enumValue) {
383
+ isValidEnum = true;
384
+ break;
385
+ }
386
+ if (!isValidEnum) return `Parameter "${key}" must be one of: ${enumValues.join(", ")}, got ${value}`;
387
+ }
388
+ }
389
+ /**
390
+ * Collect all validation errors for the given parameters against a schema.
391
+ */
392
+ function getValidationErrors(parameters, schemaRequired, schemaProperties, additionalProperties) {
393
+ const errors = [];
394
+ for (const field of schemaRequired) if (!(field in parameters)) errors.push(`Missing required parameter: ${field}`);
395
+ for (const [key, value] of Object.entries(parameters)) {
396
+ const paramSchema = schemaProperties[key];
397
+ if (!paramSchema) {
398
+ if (additionalProperties === true) continue;
399
+ if (additionalProperties && typeof additionalProperties === "object") {
400
+ const additionalTypeError = validateParameterType(key, value, additionalProperties);
401
+ if (additionalTypeError) errors.push(additionalTypeError);
402
+ continue;
403
+ }
404
+ errors.push(`Unknown parameter: ${key}`);
405
+ continue;
406
+ }
407
+ const typeError = validateParameterType(key, value, paramSchema);
408
+ if (typeError) errors.push(typeError);
409
+ }
410
+ return errors;
411
+ }
412
+ /**
413
+ * Validate parameters and return a structured result.
414
+ */
415
+ function validateToolParameters(parameters, schemaRequired, schemaProperties, additionalProperties) {
416
+ const errors = getValidationErrors(parameters, schemaRequired, schemaProperties, additionalProperties);
417
+ return {
418
+ isValid: errors.length === 0,
419
+ errors
420
+ };
421
+ }
422
+ //#endregion
423
+ //#region src/implementations/function-tool/schema-converter.ts
424
+ /**
425
+ * Convert Zod schema to JSON Schema format with safe undefined handling
426
+ */
147
427
  function zodToJsonSchema(schema, options = {}) {
148
- const properties = {};
149
- const required = [];
150
- const schemaDef = schema._def;
151
- if (!schemaDef) {
152
- throw new Error("Zod schema is missing _def; cannot convert to JSON schema.");
153
- }
154
- if (schemaDef.typeName === "ZodObject" && schemaDef.shape) {
155
- const shape = typeof schemaDef.shape === "function" ? schemaDef.shape() : schemaDef.shape;
156
- for (const [key, typeObj] of Object.entries(shape)) {
157
- const property = convertZodTypeToProperty(typeObj);
158
- properties[key] = property;
159
- if (isRequiredField(typeObj)) {
160
- required.push(key);
161
- }
162
- }
163
- }
164
- return {
165
- type: "object",
166
- properties,
167
- required,
168
- ...options.allowAdditionalProperties && { additionalProperties: true }
169
- };
428
+ const properties = {};
429
+ const required = [];
430
+ const schemaDef = schema._def;
431
+ if (!schemaDef) throw new Error("Zod schema is missing _def; cannot convert to JSON schema.");
432
+ if (schemaDef.typeName === "ZodObject" && schemaDef.shape) {
433
+ const shape = typeof schemaDef.shape === "function" ? schemaDef.shape() : schemaDef.shape;
434
+ for (const [key, typeObj] of Object.entries(shape)) {
435
+ properties[key] = convertZodTypeToProperty(typeObj);
436
+ if (isRequiredField(typeObj)) required.push(key);
437
+ }
438
+ }
439
+ return {
440
+ type: "object",
441
+ properties,
442
+ required,
443
+ ...(options.allowAdditionalProperties || schemaDef.unknownKeys === "passthrough") && { additionalProperties: true }
444
+ };
170
445
  }
446
+ /**
447
+ * Convert individual Zod type to parameter schema with safe undefined handling
448
+ */
171
449
  function convertZodTypeToProperty(typeObj) {
172
- const typeDef = typeObj._def;
173
- if (!typeDef) {
174
- throw new Error("Zod type is missing _def; cannot convert to JSON schema.");
175
- }
176
- const base = {};
177
- if (typeDef.description) {
178
- base.description = typeDef.description;
179
- }
180
- switch (typeDef.typeName) {
181
- case "ZodString":
182
- return { type: "string", ...base };
183
- case "ZodNumber":
184
- return { type: "number", ...base };
185
- case "ZodBoolean":
186
- return { type: "boolean", ...base };
187
- case "ZodArray": {
188
- if (!typeDef.type) {
189
- throw new Error("ZodArray is missing item type; cannot convert to JSON schema.");
190
- }
191
- const arrayItems = convertZodTypeToProperty(typeDef.type);
192
- return {
193
- type: "array",
194
- items: arrayItems,
195
- ...base
196
- };
197
- }
198
- case "ZodObject":
199
- return { type: "object", ...base };
200
- case "ZodEnum": {
201
- const enumValues = typeDef.values;
202
- if (!enumValues || !Array.isArray(enumValues)) {
203
- throw new Error("ZodEnum is missing enum values; cannot convert to JSON schema.");
204
- }
205
- return {
206
- type: "string",
207
- enum: enumValues,
208
- ...base
209
- };
210
- }
211
- case "ZodOptional":
212
- if (typeDef.innerType) {
213
- const innerProperty = convertZodTypeToProperty(typeDef.innerType);
214
- return { ...innerProperty, ...base };
215
- }
216
- throw new Error("ZodOptional is missing innerType; cannot convert to JSON schema.");
217
- case "ZodNullable":
218
- if (typeDef.innerType) {
219
- const innerProperty = convertZodTypeToProperty(typeDef.innerType);
220
- return { ...innerProperty, ...base };
221
- }
222
- throw new Error("ZodNullable is missing innerType; cannot convert to JSON schema.");
223
- case "ZodDefault":
224
- if (typeDef.innerType) {
225
- const innerProperty = convertZodTypeToProperty(typeDef.innerType);
226
- return { ...innerProperty, ...base };
227
- }
228
- throw new Error("ZodDefault is missing innerType; cannot convert to JSON schema.");
229
- case "ZodRecord":
230
- if (typeDef.valueType) {
231
- const valueProperty = convertZodTypeToProperty(typeDef.valueType);
232
- return { type: "object", additionalProperties: valueProperty, ...base };
233
- }
234
- return { type: "object", additionalProperties: { type: "string" }, ...base };
235
- default:
236
- throw new Error(`Unsupported Zod type: ${String(typeDef.typeName)}`);
237
- }
450
+ const typeDef = typeObj._def;
451
+ if (!typeDef) throw new Error("Zod type is missing _def; cannot convert to JSON schema.");
452
+ const base = {};
453
+ if (typeDef.description) base.description = typeDef.description;
454
+ switch (typeDef.typeName) {
455
+ case "ZodString": return {
456
+ type: "string",
457
+ ...base
458
+ };
459
+ case "ZodNumber": return {
460
+ type: "number",
461
+ ...base
462
+ };
463
+ case "ZodBoolean": return {
464
+ type: "boolean",
465
+ ...base
466
+ };
467
+ case "ZodArray":
468
+ if (!typeDef.type) throw new Error("ZodArray is missing item type; cannot convert to JSON schema.");
469
+ return {
470
+ type: "array",
471
+ items: convertZodTypeToProperty(typeDef.type),
472
+ ...base
473
+ };
474
+ case "ZodObject": return {
475
+ type: "object",
476
+ ...base
477
+ };
478
+ case "ZodEnum": {
479
+ const enumValues = typeDef.values;
480
+ if (!enumValues || !Array.isArray(enumValues)) throw new Error("ZodEnum is missing enum values; cannot convert to JSON schema.");
481
+ return {
482
+ type: "string",
483
+ enum: enumValues,
484
+ ...base
485
+ };
486
+ }
487
+ case "ZodOptional":
488
+ if (typeDef.innerType) return {
489
+ ...convertZodTypeToProperty(typeDef.innerType),
490
+ ...base
491
+ };
492
+ throw new Error("ZodOptional is missing innerType; cannot convert to JSON schema.");
493
+ case "ZodNullable":
494
+ if (typeDef.innerType) return {
495
+ ...convertZodTypeToProperty(typeDef.innerType),
496
+ ...base
497
+ };
498
+ throw new Error("ZodNullable is missing innerType; cannot convert to JSON schema.");
499
+ case "ZodDefault":
500
+ if (typeDef.innerType) return {
501
+ ...convertZodTypeToProperty(typeDef.innerType),
502
+ ...base
503
+ };
504
+ throw new Error("ZodDefault is missing innerType; cannot convert to JSON schema.");
505
+ case "ZodRecord":
506
+ if (typeDef.valueType) return {
507
+ type: "object",
508
+ additionalProperties: convertZodTypeToProperty(typeDef.valueType),
509
+ ...base
510
+ };
511
+ return {
512
+ type: "object",
513
+ additionalProperties: { type: "string" },
514
+ ...base
515
+ };
516
+ default: throw new Error(`Unsupported Zod type: ${String(typeDef.typeName)}`);
517
+ }
238
518
  }
519
+ /**
520
+ * Check if a Zod field is required (not optional or nullable)
521
+ */
239
522
  function isRequiredField(typeObj) {
240
- const typeDef = typeObj._def;
241
- if (!typeDef) {
242
- throw new Error("Zod schema is missing _def; cannot determine required fields.");
243
- }
244
- return typeDef.typeName !== "ZodOptional" && typeDef.typeName !== "ZodNullable" && typeDef.typeName !== "ZodDefault";
523
+ const typeDef = typeObj._def;
524
+ if (!typeDef) throw new Error("Zod schema is missing _def; cannot determine required fields.");
525
+ return typeDef.typeName !== "ZodOptional" && typeDef.typeName !== "ZodNullable" && typeDef.typeName !== "ZodDefault";
245
526
  }
246
-
247
- // src/implementations/function-tool.ts
527
+ //#endregion
528
+ //#region src/implementations/function-tool.ts
529
+ /**
530
+ * Function tool implementation
531
+ * Wraps a JavaScript function as a tool with schema validation
532
+ *
533
+ * Implements IFunctionTool without extending AbstractTool to avoid
534
+ * circular runtime dependency (tools → agents → tools).
535
+ */
248
536
  var FunctionTool = class {
249
- schema;
250
- fn;
251
- eventService;
252
- constructor(schema, fn) {
253
- this.schema = schema;
254
- this.fn = fn;
255
- this.validateConstructorInputs();
256
- }
257
- /**
258
- * Get tool name
259
- */
260
- getName() {
261
- return this.schema.name;
262
- }
263
- /**
264
- * Set EventService for post-construction injection.
265
- * Accepts EventService as-is without transformation.
266
- * Caller is responsible for providing properly configured EventService.
267
- */
268
- setEventService(eventService) {
269
- this.eventService = eventService;
270
- }
271
- /**
272
- * Execute the function tool
273
- */
274
- async execute(parameters, context) {
275
- const toolName = this.schema.name;
276
- if (!this.validate(parameters)) {
277
- const errors = this.getValidationErrors(parameters);
278
- throw new ValidationError2(`Invalid parameters for tool "${toolName}": ${errors.join(", ")}`);
279
- }
280
- const startTime = Date.now();
281
- let result;
282
- try {
283
- result = await this.fn(parameters, context);
284
- } catch (error) {
285
- if (error instanceof ToolExecutionError || error instanceof ValidationError2) {
286
- throw error;
287
- }
288
- throw new ToolExecutionError(
289
- `Function tool execution failed: ${error instanceof Error ? error.message : String(error)}`,
290
- toolName,
291
- error instanceof Error ? error : new Error(String(error)),
292
- {
293
- parameterCount: Object.keys(parameters || {}).length,
294
- hasContext: !!context
295
- }
296
- );
297
- }
298
- const executionTime = Date.now() - startTime;
299
- return {
300
- success: true,
301
- data: result,
302
- metadata: {
303
- executionTime,
304
- toolName,
305
- parameters
306
- }
307
- };
308
- }
309
- /**
310
- * Validate parameters (simple boolean result)
311
- */
312
- validate(parameters) {
313
- return this.getValidationErrors(parameters).length === 0;
314
- }
315
- /**
316
- * Validate tool parameters with detailed result
317
- */
318
- validateParameters(parameters) {
319
- const errors = this.getValidationErrors(parameters);
320
- return {
321
- isValid: errors.length === 0,
322
- errors
323
- };
324
- }
325
- /**
326
- * Get tool description
327
- */
328
- getDescription() {
329
- return this.schema.description;
330
- }
331
- /**
332
- * Get detailed validation errors
333
- */
334
- getValidationErrors(parameters) {
335
- const errors = [];
336
- const required = this.schema.parameters.required || [];
337
- const properties = this.schema.parameters.properties || {};
338
- for (const field of required) {
339
- if (!(field in parameters)) {
340
- errors.push(`Missing required parameter: ${field}`);
341
- }
342
- }
343
- for (const [key, value] of Object.entries(parameters)) {
344
- const paramSchema = properties[key];
345
- if (!paramSchema) {
346
- errors.push(`Unknown parameter: ${key}`);
347
- continue;
348
- }
349
- const typeError = this.validateParameterType(key, value, paramSchema);
350
- if (typeError) {
351
- errors.push(typeError);
352
- }
353
- }
354
- return errors;
355
- }
356
- /**
357
- * Validate individual parameter type
358
- */
359
- validateParameterType(key, value, schema) {
360
- const expectedType = schema["type"];
361
- switch (expectedType) {
362
- case "string":
363
- if (typeof value !== "string") {
364
- return `Parameter "${key}" must be a string, got ${typeof value}`;
365
- }
366
- break;
367
- case "number":
368
- if (typeof value !== "number" || isNaN(value)) {
369
- return `Parameter "${key}" must be a number, got ${typeof value}`;
370
- }
371
- break;
372
- case "boolean":
373
- if (typeof value !== "boolean") {
374
- return `Parameter "${key}" must be a boolean, got ${typeof value}`;
375
- }
376
- break;
377
- case "array":
378
- if (!Array.isArray(value)) {
379
- return `Parameter "${key}" must be an array, got ${typeof value}`;
380
- }
381
- if (schema.items) {
382
- for (let i = 0; i < value.length; i++) {
383
- const itemError = this.validateParameterType(`${key}[${i}]`, value[i], schema.items);
384
- if (itemError) {
385
- return itemError;
386
- }
387
- }
388
- }
389
- break;
390
- case "object":
391
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
392
- return `Parameter "${key}" must be an object, got ${typeof value}`;
393
- }
394
- break;
395
- }
396
- if (schema.enum && schema.enum.length > 0) {
397
- const enumValues = schema.enum;
398
- let isValidEnum = false;
399
- for (const enumValue of enumValues) {
400
- if (value === enumValue) {
401
- isValidEnum = true;
402
- break;
403
- }
404
- }
405
- if (!isValidEnum) {
406
- return `Parameter "${key}" must be one of: ${enumValues.join(", ")}, got ${value}`;
407
- }
408
- }
409
- return void 0;
410
- }
411
- /**
412
- * Validate constructor inputs
413
- */
414
- validateConstructorInputs() {
415
- if (!this.schema) {
416
- throw new ValidationError2("Tool schema is required");
417
- }
418
- if (!this.fn || typeof this.fn !== "function") {
419
- throw new ValidationError2("Tool function is required and must be a function");
420
- }
421
- if (!this.schema.name) {
422
- throw new ValidationError2("Tool schema must have a name");
423
- }
424
- }
537
+ schema;
538
+ fn;
539
+ eventService;
540
+ constructor(schema, fn) {
541
+ this.schema = schema;
542
+ this.fn = fn;
543
+ this.validateConstructorInputs();
544
+ }
545
+ /**
546
+ * Get tool name
547
+ */
548
+ getName() {
549
+ return this.schema.name;
550
+ }
551
+ /**
552
+ * Set EventService for post-construction injection.
553
+ * Accepts EventService as-is without transformation.
554
+ * Caller is responsible for providing properly configured EventService.
555
+ */
556
+ setEventService(eventService) {
557
+ this.eventService = eventService;
558
+ }
559
+ /**
560
+ * Execute the function tool
561
+ */
562
+ async execute(parameters, context) {
563
+ const toolName = this.schema.name;
564
+ if (!this.validate(parameters)) throw new ValidationError(`Invalid parameters for tool "${toolName}": ${getValidationErrors(parameters, this.schema.parameters.required || [], this.schema.parameters.properties || {}, this.schema.parameters.additionalProperties).join(", ")}`);
565
+ const startTime = Date.now();
566
+ let result;
567
+ try {
568
+ result = await this.fn(parameters, context);
569
+ } catch (error) {
570
+ if (error instanceof ToolExecutionError || error instanceof ValidationError) throw error;
571
+ throw new ToolExecutionError(`Function tool execution failed: ${error instanceof Error ? error.message : String(error)}`, toolName, error instanceof Error ? error : new Error(String(error)), {
572
+ parameterCount: Object.keys(parameters || {}).length,
573
+ hasContext: !!context
574
+ });
575
+ }
576
+ const executionTime = Date.now() - startTime;
577
+ return {
578
+ success: true,
579
+ data: result,
580
+ metadata: {
581
+ executionTime,
582
+ toolName,
583
+ parameters
584
+ }
585
+ };
586
+ }
587
+ /**
588
+ * Validate parameters (simple boolean result)
589
+ */
590
+ validate(parameters) {
591
+ return getValidationErrors(parameters, this.schema.parameters.required || [], this.schema.parameters.properties || {}, this.schema.parameters.additionalProperties).length === 0;
592
+ }
593
+ /**
594
+ * Validate tool parameters with detailed result
595
+ */
596
+ validateParameters(parameters) {
597
+ return validateToolParameters(parameters, this.schema.parameters.required || [], this.schema.parameters.properties || {}, this.schema.parameters.additionalProperties);
598
+ }
599
+ /**
600
+ * Get tool description
601
+ */
602
+ getDescription() {
603
+ return this.schema.description;
604
+ }
605
+ /**
606
+ * Validate constructor inputs
607
+ */
608
+ validateConstructorInputs() {
609
+ if (!this.schema) throw new ValidationError("Tool schema is required");
610
+ if (!this.fn || typeof this.fn !== "function") throw new ValidationError("Tool function is required and must be a function");
611
+ if (!this.schema.name) throw new ValidationError("Tool schema must have a name");
612
+ }
425
613
  };
614
+ /**
615
+ * Helper function to create a function tool from a simple function
616
+ */
426
617
  function createFunctionTool(name, description, parameters, fn) {
427
- const schema = {
428
- name,
429
- description,
430
- parameters
431
- };
432
- return new FunctionTool(schema, fn);
618
+ return new FunctionTool({
619
+ name,
620
+ description,
621
+ parameters
622
+ }, fn);
433
623
  }
624
+ /**
625
+ * Helper function to create a function tool from Zod schema
626
+ */
434
627
  function createZodFunctionTool(name, description, zodSchema, fn) {
435
- const parameters = zodToJsonSchema(zodSchema);
436
- const schema = {
437
- name,
438
- description,
439
- parameters
440
- };
441
- const wrappedFn = async (parameters2, context) => {
442
- const parseResult = zodSchema.safeParse(parameters2);
443
- if (!parseResult.success) {
444
- throw new ValidationError2(`Zod validation failed: ${parseResult.error}`);
445
- }
446
- const result = await fn(parseResult.data || parameters2, context);
447
- return typeof result === "string" ? result : JSON.stringify(result);
448
- };
449
- return new FunctionTool(schema, wrappedFn);
628
+ const schema = {
629
+ name,
630
+ description,
631
+ parameters: zodToJsonSchema(zodSchema)
632
+ };
633
+ const wrappedFn = async (parameters, context) => {
634
+ const parseResult = zodSchema.safeParse(parameters);
635
+ if (!parseResult.success) throw new ValidationError(`Zod validation failed: ${parseResult.error}`);
636
+ const result = await fn(parseResult.data || parameters, context);
637
+ return typeof result === "string" ? result : JSON.stringify(result);
638
+ };
639
+ return new FunctionTool(schema, wrappedFn);
450
640
  }
451
-
452
- // src/implementations/openapi-tool.ts
453
- import { ToolExecutionError as ToolExecutionError2, ValidationError as ValidationError3 } from "@robota-sdk/agent-core";
454
- var OpenAPITool = class {
455
- schema;
456
- apiSpec;
457
- operationId;
458
- baseURL;
459
- config;
460
- eventService;
461
- constructor(config) {
462
- this.config = config;
463
- if (typeof config.spec !== "object" || config.spec === null || typeof config.spec.openapi !== "string" || typeof config.spec.paths !== "object") {
464
- throw new Error(
465
- 'Invalid OpenAPI spec: must contain "openapi" (string) and "paths" (object) fields'
466
- );
467
- }
468
- this.apiSpec = config.spec;
469
- this.operationId = config.operationId;
470
- this.baseURL = config.baseURL;
471
- this.schema = this.createSchemaFromOpenAPI();
472
- }
473
- /**
474
- * Execute the OpenAPI tool
475
- */
476
- async execute(parameters, context) {
477
- const toolName = this.schema.name;
478
- const validation = this.validateParameters(parameters);
479
- if (!validation.isValid) {
480
- throw new ValidationError3(
481
- `Invalid parameters for OpenAPI tool "${toolName}": ${validation.errors.join(", ")}`
482
- );
483
- }
484
- try {
485
- const startTime = Date.now();
486
- const result = await this.executeAPICall(parameters, context);
487
- const executionTime = Date.now() - startTime;
488
- return {
489
- success: true,
490
- data: result,
491
- metadata: {
492
- executionTime,
493
- toolName,
494
- operationId: this.operationId,
495
- baseURL: this.baseURL
496
- }
497
- };
498
- } catch (error) {
499
- if (error instanceof ToolExecutionError2 || error instanceof ValidationError3) {
500
- throw error;
501
- }
502
- const safeError = error instanceof Error ? error : new Error(String(error));
503
- throw new ToolExecutionError2(
504
- `OpenAPI tool execution failed: ${safeError.message}`,
505
- toolName,
506
- safeError,
507
- {
508
- operationId: this.operationId,
509
- baseURL: this.baseURL,
510
- parametersCount: Object.keys(parameters).length
511
- }
512
- );
513
- }
514
- }
515
- /**
516
- * Validate tool parameters
517
- */
518
- validate(parameters) {
519
- return this.validateParameters(parameters).isValid;
520
- }
521
- /**
522
- * Validate tool parameters with detailed result
523
- */
524
- validateParameters(parameters) {
525
- const required = this.schema.parameters.required || [];
526
- const errors = [];
527
- for (const field of required) {
528
- if (!(field in parameters)) {
529
- errors.push(`Missing required parameter: ${field}`);
530
- }
531
- }
532
- return {
533
- isValid: errors.length === 0,
534
- errors
535
- };
536
- }
537
- /**
538
- * Get tool name
539
- */
540
- getName() {
541
- return this.schema.name;
542
- }
543
- /**
544
- * Set EventService for post-construction injection.
545
- */
546
- setEventService(eventService) {
547
- this.eventService = eventService;
548
- }
549
- /**
550
- * Get tool description
551
- */
552
- getDescription() {
553
- return this.schema.description;
554
- }
555
- /**
556
- * Execute the actual API call
557
- * @private
558
- */
559
- async executeAPICall(parameters, _context) {
560
- const operation = this.findOperation();
561
- if (!operation) {
562
- throw new Error(`Operation ${this.operationId} not found in OpenAPI spec`);
563
- }
564
- const requestConfig = this.buildRequestConfig(operation, parameters);
565
- throw new Error("Not implemented: actual API execution is not yet available");
566
- }
567
- /**
568
- * Find the operation in the OpenAPI specification
569
- */
570
- findOperation() {
571
- for (const [path, pathItem] of Object.entries(this.apiSpec.paths || {})) {
572
- if (!pathItem) continue;
573
- for (const method of [
574
- "get",
575
- "post",
576
- "put",
577
- "delete",
578
- "patch",
579
- "head",
580
- "options"
581
- ]) {
582
- const operation = pathItem[method];
583
- if (operation?.operationId === this.operationId) {
584
- return { method, path, operation };
585
- }
586
- }
587
- }
588
- return void 0;
589
- }
590
- /**
591
- * Build HTTP request configuration from OpenAPI operation and parameters
592
- */
593
- buildRequestConfig(opInfo, parameters) {
594
- const { method, path, operation } = opInfo;
595
- let url = this.baseURL + path;
596
- const headers = {};
597
- let body;
598
- const params = operation.parameters || [];
599
- for (const param of params) {
600
- const value = parameters[param.name];
601
- if (value === void 0 && param.required) {
602
- throw new Error(`Required parameter ${param.name} is missing`);
603
- }
604
- if (value !== void 0) {
605
- switch (param.in) {
606
- case "path":
607
- url = url.replace(`{${param.name}}`, encodeURIComponent(String(value)));
608
- break;
609
- case "query": {
610
- const separator = url.includes("?") ? "&" : "?";
611
- url += `${separator}${param.name}=${encodeURIComponent(String(value))}`;
612
- break;
613
- }
614
- case "header":
615
- headers[param.name] = String(value);
616
- break;
617
- }
618
- }
619
- }
620
- if (["post", "put", "patch"].includes(method) && operation.requestBody) {
621
- const requestBody = operation.requestBody;
622
- const jsonContent = requestBody.content?.["application/json"];
623
- if (jsonContent) {
624
- headers["Content-Type"] = "application/json";
625
- const bodyParams = {};
626
- for (const [key, value] of Object.entries(parameters)) {
627
- const isParamUsed = params.some((p) => p.name === key);
628
- if (!isParamUsed) {
629
- bodyParams[key] = value;
630
- }
631
- }
632
- body = JSON.stringify(bodyParams);
633
- }
634
- }
635
- if (this.config.auth) {
636
- switch (this.config.auth.type) {
637
- case "bearer":
638
- headers["Authorization"] = `Bearer ${this.config.auth.token}`;
639
- break;
640
- case "apiKey": {
641
- const headerName = this.config.auth.header || "X-API-Key";
642
- headers[headerName] = this.config.auth.apiKey || "";
643
- break;
644
- }
645
- }
646
- }
647
- const result = {
648
- method,
649
- url,
650
- headers
651
- };
652
- if (body !== void 0) {
653
- result.body = body;
654
- }
655
- return result;
656
- }
657
- /**
658
- * Create tool schema from OpenAPI operation specification
659
- */
660
- createSchemaFromOpenAPI() {
661
- const operation = this.findOperation();
662
- if (!operation) {
663
- throw new Error(
664
- `[STRICT-POLICY][EMITTER-CONTRACT] OpenAPI operation not found: ${this.operationId}. Emitter contract must provide a valid operationId present in the OpenAPI document.`
665
- );
666
- }
667
- const { operation: opSpec } = operation;
668
- const properties = {};
669
- const required = [];
670
- const params = opSpec.parameters || [];
671
- for (const param of params) {
672
- properties[param.name] = this.convertOpenAPIParamToSchema(param);
673
- if (param.required) {
674
- required.push(param.name);
675
- }
676
- }
677
- if (opSpec.requestBody) {
678
- const requestBody = opSpec.requestBody;
679
- const jsonContent = requestBody.content?.["application/json"];
680
- if (jsonContent?.schema) {
681
- const bodySchema = this.convertOpenAPISchemaToParameterSchema(jsonContent.schema);
682
- if (bodySchema.type === "object" && bodySchema.properties) {
683
- Object.assign(properties, bodySchema.properties);
684
- const schemaWithRequired = bodySchema;
685
- if (schemaWithRequired.required) {
686
- required.push(...schemaWithRequired.required);
687
- }
688
- }
689
- }
690
- }
691
- const schemaParams = {
692
- type: "object",
693
- properties
694
- };
695
- if (required.length > 0) {
696
- schemaParams.required = required;
697
- }
698
- return {
699
- name: this.operationId,
700
- description: opSpec.summary || opSpec.description || `OpenAPI operation: ${this.operationId}`,
701
- parameters: schemaParams
702
- };
703
- }
704
- /**
705
- * Convert OpenAPI parameter to tool parameter schema
706
- */
707
- convertOpenAPIParamToSchema(param) {
708
- const schema = param.schema;
709
- return this.convertOpenAPISchemaToParameterSchema(schema);
710
- }
711
- /**
712
- * Convert OpenAPI schema to parameter schema
713
- */
714
- convertOpenAPISchemaToParameterSchema(schema) {
715
- if ("$ref" in schema) {
716
- return { type: "object" };
717
- }
718
- const result = {
719
- type: this.mapOpenAPIType(schema.type)
720
- };
721
- if (schema.description) {
722
- result.description = schema.description;
723
- }
724
- if (schema.enum) {
725
- result.enum = schema.enum;
726
- }
727
- if (schema.minimum !== void 0) {
728
- result.minimum = schema.minimum;
729
- }
730
- if (schema.maximum !== void 0) {
731
- result.maximum = schema.maximum;
732
- }
733
- if (schema.pattern) {
734
- result.pattern = schema.pattern;
735
- }
736
- if (schema.format) {
737
- result.format = schema.format;
738
- }
739
- if (schema.default !== void 0) {
740
- result.default = schema.default;
741
- }
742
- if (schema.type === "array" && schema.items) {
743
- result.items = this.convertOpenAPISchemaToParameterSchema(schema.items);
744
- }
745
- if (schema.type === "object" && schema.properties) {
746
- result.properties = {};
747
- for (const [propName, propSchema] of Object.entries(schema.properties)) {
748
- result.properties[propName] = this.convertOpenAPISchemaToParameterSchema(propSchema);
749
- }
750
- if (schema.required && schema.required.length > 0) {
751
- result.required = schema.required;
752
- }
753
- }
754
- return result;
755
- }
756
- /**
757
- * Map OpenAPI type to JSON schema type
758
- */
759
- mapOpenAPIType(type) {
760
- switch (type) {
761
- case "string":
762
- return "string";
763
- case "number":
764
- return "number";
765
- case "integer":
766
- return "integer";
767
- case "boolean":
768
- return "boolean";
769
- case "array":
770
- return "array";
771
- case "object":
772
- return "object";
773
- default:
774
- return "string";
775
- }
776
- }
777
- };
778
- function createOpenAPITool(config) {
779
- return new OpenAPITool(config);
780
- }
781
-
782
- // src/builtins/bash-tool.ts
783
- import { spawn } from "child_process";
784
- import { z } from "zod";
785
- var DEFAULT_TIMEOUT_MS = 12e4;
786
- var BashSchema = z.object({
787
- command: z.string().describe("The bash command to execute"),
788
- timeout: z.number().optional().describe("Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)"),
789
- workingDirectory: z.string().optional().describe("Working directory for the command. Defaults to the current working directory")
641
+ //#endregion
642
+ //#region src/builtins/bash-tool.ts
643
+ /**
644
+ * BashTool — execute shell commands via child_process.spawn
645
+ *
646
+ * Returns TToolResult JSON string. Non-zero exit is returned as success:true
647
+ * with exitCode set, matching Claude Code behaviour (the command ran, it just
648
+ * exited non-zero — the LLM can decide what to do with that information).
649
+ */
650
+ const DEFAULT_TIMEOUT_MS$2 = 12e4;
651
+ const BashSchema = z.object({
652
+ command: z.string().describe("The bash command to execute"),
653
+ timeout: z.number().optional().describe("Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)"),
654
+ workingDirectory: z.string().optional().describe("Working directory for the command. Defaults to the current working directory")
790
655
  });
791
- async function runBash(args) {
792
- const { command, timeout = DEFAULT_TIMEOUT_MS, workingDirectory } = args;
793
- return new Promise((resolve3) => {
794
- const stdoutChunks = [];
795
- const stderrChunks = [];
796
- let timedOut = false;
797
- let settled = false;
798
- const child = spawn("sh", ["-c", command], {
799
- cwd: workingDirectory ?? process.cwd(),
800
- env: process.env,
801
- stdio: ["pipe", "pipe", "pipe"]
802
- });
803
- child.stdout.on("data", (chunk) => {
804
- stdoutChunks.push(chunk);
805
- });
806
- child.stderr.on("data", (chunk) => {
807
- stderrChunks.push(chunk);
808
- });
809
- const timer = setTimeout(() => {
810
- timedOut = true;
811
- child.kill("SIGTERM");
812
- }, timeout);
813
- function settle(result) {
814
- if (settled) return;
815
- settled = true;
816
- clearTimeout(timer);
817
- resolve3(JSON.stringify(result));
818
- }
819
- child.on("error", (err) => {
820
- settle({
821
- success: false,
822
- output: "",
823
- error: err.message
824
- });
825
- });
826
- child.on("close", (code) => {
827
- if (timedOut) {
828
- settle({
829
- success: false,
830
- output: Buffer.concat(stdoutChunks).toString("utf8"),
831
- error: `Command timed out after ${timeout}ms`,
832
- exitCode: code ?? void 0
833
- });
834
- return;
835
- }
836
- const stdout = Buffer.concat(stdoutChunks).toString("utf8");
837
- const stderr = Buffer.concat(stderrChunks).toString("utf8");
838
- const exitCode = code ?? 0;
839
- const output = stderr ? `${stdout}
840
- stderr:
841
- ${stderr}` : stdout;
842
- settle({
843
- success: true,
844
- output,
845
- exitCode
846
- });
847
- });
848
- });
656
+ /**
657
+ * Run a shell command and return stdout + stderr.
658
+ * Resolves with the TToolResult JSON string.
659
+ */
660
+ async function runBash(args, options = {}) {
661
+ const { command, timeout: rawTimeout = DEFAULT_TIMEOUT_MS$2, workingDirectory } = args;
662
+ const timeout = Math.min(rawTimeout, 6e5);
663
+ if (options.sandboxClient) try {
664
+ const sandboxResult = await options.sandboxClient.run(command, {
665
+ timeoutMs: timeout,
666
+ workingDirectory
667
+ });
668
+ const result = {
669
+ success: true,
670
+ output: sandboxResult.stderr ? `${sandboxResult.stdout}\nstderr:\n${sandboxResult.stderr}` : sandboxResult.stdout,
671
+ exitCode: sandboxResult.exitCode
672
+ };
673
+ return JSON.stringify(result);
674
+ } catch (err) {
675
+ const result = {
676
+ success: false,
677
+ output: "",
678
+ error: err instanceof Error ? err.message : String(err)
679
+ };
680
+ return JSON.stringify(result);
681
+ }
682
+ return new Promise((resolve) => {
683
+ const stdoutChunks = [];
684
+ const stderrChunks = [];
685
+ let timedOut = false;
686
+ let settled = false;
687
+ const child = spawn("sh", ["-c", command], {
688
+ cwd: workingDirectory ?? process.cwd(),
689
+ env: process.env,
690
+ stdio: [
691
+ "pipe",
692
+ "pipe",
693
+ "pipe"
694
+ ]
695
+ });
696
+ child.stdout.on("data", (chunk) => {
697
+ stdoutChunks.push(chunk);
698
+ });
699
+ child.stderr.on("data", (chunk) => {
700
+ stderrChunks.push(chunk);
701
+ });
702
+ const timer = setTimeout(() => {
703
+ timedOut = true;
704
+ child.kill("SIGTERM");
705
+ settle({
706
+ success: false,
707
+ output: Buffer.concat(stdoutChunks).toString("utf8"),
708
+ error: `Command timed out after ${timeout}ms`
709
+ });
710
+ }, timeout);
711
+ function settle(result) {
712
+ if (settled) return;
713
+ settled = true;
714
+ clearTimeout(timer);
715
+ resolve(JSON.stringify(result));
716
+ }
717
+ child.on("error", (err) => {
718
+ settle({
719
+ success: false,
720
+ output: "",
721
+ error: err.message
722
+ });
723
+ });
724
+ child.on("close", (code) => {
725
+ if (timedOut) {
726
+ settle({
727
+ success: false,
728
+ output: Buffer.concat(stdoutChunks).toString("utf8"),
729
+ error: `Command timed out after ${timeout}ms`,
730
+ exitCode: code ?? void 0
731
+ });
732
+ return;
733
+ }
734
+ const stdout = Buffer.concat(stdoutChunks).toString("utf8");
735
+ const stderr = Buffer.concat(stderrChunks).toString("utf8");
736
+ const exitCode = code ?? 0;
737
+ settle({
738
+ success: true,
739
+ output: stderr ? `${stdout}\nstderr:\n${stderr}` : stdout,
740
+ exitCode
741
+ });
742
+ });
743
+ });
849
744
  }
850
- var bashTool = createZodFunctionTool(
851
- "Bash",
852
- "Executes a given bash command and returns its output.\n\nThe working directory persists between commands, but shell state does not.\n\nIMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands. Instead, use the appropriate dedicated tool:\n - File search: Use Glob (NOT find or ls)\n - Content search: Use Grep (NOT grep or rg)\n - Read files: Use Read (NOT cat/head/tail)\n - Edit files: Use Edit (NOT sed/awk)\n\nFor simple commands, keep the description brief (5-10 words). For complex commands, include enough context to clarify what the command does.\n\nOutput is limited to 30,000 characters. Longer output will be middle-truncated.",
853
- BashSchema,
854
- async (params) => {
855
- return runBash(params);
856
- }
857
- );
858
-
859
- // src/builtins/read-tool.ts
860
- import { readFile, stat } from "fs/promises";
861
- import { z as z2 } from "zod";
862
- var DEFAULT_LIMIT = 2e3;
863
- var ReadSchema = z2.object({
864
- filePath: z2.string().describe("The absolute path to the file to read"),
865
- offset: z2.number().optional().describe(
866
- "The line number to start reading from (1-based). Only provide if the file is too large to read at once"
867
- ),
868
- limit: z2.number().optional().describe(
869
- `The number of lines to read (default: ${DEFAULT_LIMIT}). Only provide if the file is too large to read at once`
870
- )
745
+ /**
746
+ * Create a BashTool instance — register with Robota agent tools registry.
747
+ */
748
+ function createBashTool(options = {}) {
749
+ return createZodFunctionTool("Bash", "Executes a given bash command and returns its output.\n\nThe working directory persists between commands, but shell state does not.\n\nIMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands. Instead, use the appropriate dedicated tool:\n - File search: Use Glob (NOT find or ls)\n - Content search: Use Grep (NOT grep or rg)\n - Read files: Use Read (NOT cat/head/tail)\n - Edit files: Use Edit (NOT sed/awk)\n\nFor simple commands, keep the description brief (5-10 words). For complex commands, include enough context to clarify what the command does.\n\nOutput is limited to 30,000 characters. Longer output will be middle-truncated.", BashSchema, async (params) => {
750
+ return runBash(params, options);
751
+ });
752
+ }
753
+ /**
754
+ * BashTool instance — register with Robota agent tools registry.
755
+ */
756
+ const bashTool = createBashTool();
757
+ //#endregion
758
+ //#region src/builtins/path-guard.ts
759
+ /**
760
+ * Returns a JSON-serialized TToolResult error when filePath is outside cwd.
761
+ * Returns undefined when the path is within cwd or cwd is not set.
762
+ */
763
+ function checkPathWithinCwd(filePath, cwd) {
764
+ if (cwd === void 0) return void 0;
765
+ const resolved = resolve(filePath);
766
+ const cwdResolved = resolve(cwd);
767
+ if (resolved !== cwdResolved && !resolved.startsWith(cwdResolved + sep)) {
768
+ const result = {
769
+ success: false,
770
+ output: "",
771
+ error: `Access denied: "${filePath}" is outside the working directory`
772
+ };
773
+ return JSON.stringify(result);
774
+ }
775
+ }
776
+ //#endregion
777
+ //#region src/builtins/read-tool.ts
778
+ /**
779
+ * ReadTool — read a file and return its contents with line numbers (cat -n style).
780
+ *
781
+ * Supports offset/limit for partial reads. Detects binary files and refuses to
782
+ * return their raw bytes. Default limit is 2000 lines.
783
+ */
784
+ const DEFAULT_LIMIT$1 = 2e3;
785
+ const ReadSchema = z.object({
786
+ filePath: z.string().describe("The absolute path to the file to read"),
787
+ offset: z.number().optional().describe("The line number to start reading from (1-based). Only provide if the file is too large to read at once"),
788
+ limit: z.number().optional().describe(`The number of lines to read (default: ${DEFAULT_LIMIT$1}). Only provide if the file is too large to read at once`)
871
789
  });
790
+ /**
791
+ * Heuristic binary detection: scan the first 8 KB for null bytes.
792
+ */
872
793
  function isBinary(buffer) {
873
- const checkLength = Math.min(buffer.length, 8192);
874
- for (let i = 0; i < checkLength; i++) {
875
- if (buffer[i] === 0) return true;
876
- }
877
- return false;
794
+ const checkLength = Math.min(buffer.length, 8192);
795
+ for (let i = 0; i < checkLength; i++) if (buffer[i] === 0) return true;
796
+ return false;
878
797
  }
798
+ /**
799
+ * Format lines with 1-based line numbers in cat -n style.
800
+ * Pads line number to the width of the highest line number.
801
+ */
879
802
  function formatWithLineNumbers(lines, startLine) {
880
- const lastLineNum = startLine + lines.length - 1;
881
- const width = String(lastLineNum).length;
882
- return lines.map((line, idx) => {
883
- const lineNum = String(startLine + idx).padStart(width, " ");
884
- return `${lineNum} ${line}`;
885
- }).join("\n");
803
+ const lastLineNum = startLine + lines.length - 1;
804
+ const width = String(lastLineNum).length;
805
+ return lines.map((line, idx) => {
806
+ return `${String(startLine + idx).padStart(width, " ")}\t${line}`;
807
+ }).join("\n");
886
808
  }
887
- async function readFileTool(args) {
888
- const { filePath, offset, limit = DEFAULT_LIMIT } = args;
889
- const startLine = offset !== void 0 && offset > 0 ? offset : 1;
890
- let fileStats;
891
- try {
892
- fileStats = await stat(filePath);
893
- } catch (err) {
894
- const result2 = {
895
- success: false,
896
- output: "",
897
- error: `File not found: ${filePath}`
898
- };
899
- return JSON.stringify(result2);
900
- }
901
- if (!fileStats.isFile()) {
902
- const result2 = {
903
- success: false,
904
- output: "",
905
- error: `Path is not a file: ${filePath}`
906
- };
907
- return JSON.stringify(result2);
908
- }
909
- let buffer;
910
- try {
911
- buffer = await readFile(filePath);
912
- } catch (err) {
913
- const result2 = {
914
- success: false,
915
- output: "",
916
- error: err instanceof Error ? err.message : String(err)
917
- };
918
- return JSON.stringify(result2);
919
- }
920
- if (isBinary(buffer)) {
921
- const result2 = {
922
- success: false,
923
- output: "",
924
- error: `Binary file not supported: ${filePath}`
925
- };
926
- return JSON.stringify(result2);
927
- }
928
- const content = buffer.toString("utf8");
929
- const allLines = content.split("\n");
930
- if (allLines[allLines.length - 1] === "") {
931
- allLines.pop();
932
- }
933
- const zeroBasedStart = startLine - 1;
934
- const selectedLines = allLines.slice(zeroBasedStart, zeroBasedStart + limit);
935
- const output = formatWithLineNumbers(selectedLines, startLine);
936
- const totalLines = allLines.length;
937
- const returnedLines = selectedLines.length;
938
- const header = returnedLines < totalLines ? `[File: ${filePath} (lines ${startLine}-${startLine + returnedLines - 1} of ${totalLines})]
939
- ` : `[File: ${filePath} (${totalLines} lines)]
940
- `;
941
- const result = {
942
- success: true,
943
- output: header + output
944
- };
945
- return JSON.stringify(result);
809
+ function formatReadResult(filePath, content, startLine, limit) {
810
+ const allLines = content.split("\n");
811
+ if (allLines[allLines.length - 1] === "") allLines.pop();
812
+ const zeroBasedStart = startLine - 1;
813
+ const selectedLines = allLines.slice(zeroBasedStart, zeroBasedStart + limit);
814
+ const output = formatWithLineNumbers(selectedLines, startLine);
815
+ const totalLines = allLines.length;
816
+ const returnedLines = selectedLines.length;
817
+ const result = {
818
+ success: true,
819
+ output: (returnedLines < totalLines ? `[File: ${filePath} (lines ${startLine}-${startLine + returnedLines - 1} of ${totalLines})]\n` : `[File: ${filePath} (${totalLines} lines)]\n`) + output
820
+ };
821
+ return JSON.stringify(result);
946
822
  }
947
- var readTool = createZodFunctionTool(
948
- "Read",
949
- "Reads a file from the local filesystem.\n\nBy default, reads up to 2000 lines from the beginning of the file. You can optionally specify offset and limit for partial reads.\n\nResults are returned using cat -n format, with line numbers starting at 1.\n\nThe file_path parameter must be an absolute path, not a relative path.",
950
- ReadSchema,
951
- async (params) => {
952
- return readFileTool(params);
953
- }
954
- );
955
-
956
- // src/builtins/write-tool.ts
957
- import { writeFile, mkdir } from "fs/promises";
958
- import { dirname } from "path";
959
- import { z as z3 } from "zod";
960
- var WriteSchema = z3.object({
961
- filePath: z3.string().describe("The absolute path to the file to write"),
962
- content: z3.string().describe("The content to write to the file")
823
+ async function readFileTool(args, options = {}) {
824
+ const { filePath, offset, limit = DEFAULT_LIMIT$1 } = args;
825
+ const startLine = offset !== void 0 && offset > 0 ? offset : 1;
826
+ if (options.sandboxClient) try {
827
+ return formatReadResult(filePath, await options.sandboxClient.readFile(filePath), startLine, limit);
828
+ } catch (err) {
829
+ const result = {
830
+ success: false,
831
+ output: "",
832
+ error: err instanceof Error ? err.message : String(err)
833
+ };
834
+ return JSON.stringify(result);
835
+ }
836
+ const pathError = checkPathWithinCwd(filePath, options.cwd);
837
+ if (pathError !== void 0) return pathError;
838
+ let fileStats;
839
+ try {
840
+ fileStats = await stat(filePath);
841
+ } catch (err) {
842
+ const result = {
843
+ success: false,
844
+ output: "",
845
+ error: `File not found: ${filePath}`
846
+ };
847
+ return JSON.stringify(result);
848
+ }
849
+ if (!fileStats.isFile()) {
850
+ const result = {
851
+ success: false,
852
+ output: "",
853
+ error: `Path is not a file: ${filePath}`
854
+ };
855
+ return JSON.stringify(result);
856
+ }
857
+ let buffer;
858
+ try {
859
+ buffer = await readFile(filePath);
860
+ } catch (err) {
861
+ const result = {
862
+ success: false,
863
+ output: "",
864
+ error: err instanceof Error ? err.message : String(err)
865
+ };
866
+ return JSON.stringify(result);
867
+ }
868
+ if (isBinary(buffer)) {
869
+ const result = {
870
+ success: false,
871
+ output: "",
872
+ error: `Binary file not supported: ${filePath}`
873
+ };
874
+ return JSON.stringify(result);
875
+ }
876
+ return formatReadResult(filePath, buffer.toString("utf8"), startLine, limit);
877
+ }
878
+ /**
879
+ * Create a ReadTool instance — register with Robota agent tools registry.
880
+ */
881
+ function createReadTool(options = {}) {
882
+ return createZodFunctionTool("Read", "Reads a file from the local filesystem.\n\nBy default, reads up to 2000 lines from the beginning of the file. You can optionally specify offset and limit for partial reads.\n\nResults are returned using cat -n format, with line numbers starting at 1.\n\nThe file_path parameter must be an absolute path, not a relative path.", ReadSchema, async (params) => {
883
+ return readFileTool(params, options);
884
+ });
885
+ }
886
+ /**
887
+ * ReadTool instance — register with Robota agent tools registry.
888
+ */
889
+ const readTool = createReadTool();
890
+ //#endregion
891
+ //#region src/builtins/atomic-file-write.ts
892
+ const TEMP_RANDOM_BYTES = 6;
893
+ const PRESERVED_MODE_BITS = 4095;
894
+ const MISSING_FILE_ERROR_CODE = "ENOENT";
895
+ function createTempFilePath(filePath) {
896
+ const dir = dirname(filePath);
897
+ const name = basename(filePath);
898
+ const suffix = randomBytes(TEMP_RANDOM_BYTES).toString("hex");
899
+ return join(dir, `.${name}.robota-tmp-${process.pid}-${Date.now()}-${suffix}`);
900
+ }
901
+ async function readExistingMode(filePath) {
902
+ try {
903
+ return (await stat(filePath)).mode & PRESERVED_MODE_BITS;
904
+ } catch (error) {
905
+ if (error instanceof Error && hasErrorCode(error, MISSING_FILE_ERROR_CODE)) return void 0;
906
+ throw error;
907
+ }
908
+ }
909
+ function hasErrorCode(error, code) {
910
+ return "code" in error && error.code === code;
911
+ }
912
+ async function atomicWriteUtf8File(filePath, content) {
913
+ await mkdir(dirname(filePath), { recursive: true });
914
+ const existingMode = await readExistingMode(filePath);
915
+ const tempFilePath = createTempFilePath(filePath);
916
+ try {
917
+ await writeFile(tempFilePath, content, "utf8");
918
+ if (existingMode !== void 0) await chmod(tempFilePath, existingMode);
919
+ await rename(tempFilePath, filePath);
920
+ } catch (error) {
921
+ await rm(tempFilePath, { force: true }).catch(() => void 0);
922
+ throw error;
923
+ }
924
+ }
925
+ //#endregion
926
+ //#region src/builtins/write-tool.ts
927
+ /**
928
+ * WriteTool — write content to a file, auto-creating parent directories.
929
+ */
930
+ const WriteSchema = z.object({
931
+ filePath: z.string().describe("The absolute path to the file to write"),
932
+ content: z.string().describe("The content to write to the file")
963
933
  });
964
- async function writeFileTool(args) {
965
- const { filePath, content } = args;
966
- try {
967
- await mkdir(dirname(filePath), { recursive: true });
968
- await writeFile(filePath, content, "utf8");
969
- const result = {
970
- success: true,
971
- output: `Written ${Buffer.byteLength(content, "utf8")} bytes to ${filePath}`
972
- };
973
- return JSON.stringify(result);
974
- } catch (err) {
975
- const result = {
976
- success: false,
977
- output: "",
978
- error: err instanceof Error ? err.message : String(err)
979
- };
980
- return JSON.stringify(result);
981
- }
934
+ async function writeFileTool(args, options = {}) {
935
+ const { filePath, content } = args;
936
+ if (!options.sandboxClient) {
937
+ const pathError = checkPathWithinCwd(filePath, options.cwd);
938
+ if (pathError !== void 0) return pathError;
939
+ }
940
+ try {
941
+ if (options.sandboxClient) await options.sandboxClient.writeFile(filePath, content);
942
+ else await atomicWriteUtf8File(filePath, content);
943
+ const result = {
944
+ success: true,
945
+ output: `Written ${Buffer.byteLength(content, "utf8")} bytes to ${filePath}`
946
+ };
947
+ return JSON.stringify(result);
948
+ } catch (err) {
949
+ const result = {
950
+ success: false,
951
+ output: "",
952
+ error: err instanceof Error ? err.message : String(err)
953
+ };
954
+ return JSON.stringify(result);
955
+ }
982
956
  }
983
- var writeTool = createZodFunctionTool(
984
- "Write",
985
- "Writes a file to the local filesystem. This will overwrite an existing file if one exists.\n\nALWAYS prefer the Edit tool for modifying existing files \u2014 it only sends the diff. Only use this tool to create new files or for complete rewrites.\n\nNEVER create documentation files (*.md) or README files unless explicitly requested by the user.",
986
- WriteSchema,
987
- async (params) => {
988
- return writeFileTool(params);
989
- }
990
- );
991
-
992
- // src/builtins/edit-tool.ts
993
- import { readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
994
- import { z as z4 } from "zod";
995
- var EditSchema = z4.object({
996
- filePath: z4.string().describe("The absolute path to the file to modify"),
997
- oldString: z4.string().describe("The text to replace (must be an exact match of existing content)"),
998
- newString: z4.string().describe("The text to replace it with (must be different from old_string)"),
999
- replaceAll: z4.boolean().optional().describe(
1000
- "Replace all occurrences of old_string (default: false). Useful for renaming variables"
1001
- )
957
+ /**
958
+ * Create a WriteTool instance — register with Robota agent tools registry.
959
+ */
960
+ function createWriteTool(options = {}) {
961
+ return createZodFunctionTool("Write", "Writes a file to the local filesystem. This will overwrite an existing file if one exists.\n\nALWAYS prefer the Edit tool for modifying existing files — it only sends the diff. Only use this tool to create new files or for complete rewrites.\n\nNEVER create documentation files (*.md) or README files unless explicitly requested by the user.", WriteSchema, async (params) => {
962
+ return writeFileTool(params, options);
963
+ });
964
+ }
965
+ /**
966
+ * WriteTool instance — register with Robota agent tools registry.
967
+ */
968
+ const writeTool = createWriteTool();
969
+ //#endregion
970
+ //#region src/builtins/edit-tool.ts
971
+ /**
972
+ * EditTool — perform string-replace edits on a file.
973
+ *
974
+ * By default, requires the oldString to appear exactly once in the file
975
+ * (ensuring surgical edits). Pass replaceAll:true to replace all occurrences.
976
+ */
977
+ const EditSchema = z.object({
978
+ filePath: z.string().describe("The absolute path to the file to modify"),
979
+ oldString: z.string().describe("The text to replace (must be an exact match of existing content)"),
980
+ newString: z.string().describe("The text to replace it with (must be different from old_string)"),
981
+ replaceAll: z.boolean().optional().describe("Replace all occurrences of old_string (default: false). Useful for renaming variables")
1002
982
  });
1003
- async function editFileTool(args) {
1004
- const { filePath, oldString, newString, replaceAll = false } = args;
1005
- let content;
1006
- try {
1007
- content = await readFile2(filePath, "utf8");
1008
- } catch (err) {
1009
- const result2 = {
1010
- success: false,
1011
- output: "",
1012
- error: `File not found: ${filePath}`
1013
- };
1014
- return JSON.stringify(result2);
1015
- }
1016
- if (!content.includes(oldString)) {
1017
- const result2 = {
1018
- success: false,
1019
- output: "",
1020
- error: `oldString not found in file: ${filePath}`
1021
- };
1022
- return JSON.stringify(result2);
1023
- }
1024
- if (!replaceAll) {
1025
- const firstIdx = content.indexOf(oldString);
1026
- const lastIdx = content.lastIndexOf(oldString);
1027
- if (firstIdx !== lastIdx) {
1028
- const occurrences = content.split(oldString).length - 1;
1029
- const result2 = {
1030
- success: false,
1031
- output: "",
1032
- error: `oldString is not unique in file (found ${occurrences} occurrences). Provide more context to make it unique, or use replaceAll:true.`
1033
- };
1034
- return JSON.stringify(result2);
1035
- }
1036
- }
1037
- const updated = replaceAll ? content.split(oldString).join(newString) : content.slice(0, content.indexOf(oldString)) + newString + content.slice(content.indexOf(oldString) + oldString.length);
1038
- try {
1039
- await writeFile2(filePath, updated, "utf8");
1040
- } catch (err) {
1041
- const result2 = {
1042
- success: false,
1043
- output: "",
1044
- error: err instanceof Error ? err.message : String(err)
1045
- };
1046
- return JSON.stringify(result2);
1047
- }
1048
- const count = replaceAll ? content.split(oldString).length - 1 : 1;
1049
- const result = {
1050
- success: true,
1051
- output: `Replaced ${count} occurrence(s) in ${filePath}`
1052
- };
1053
- return JSON.stringify(result);
983
+ async function editFileTool(args, options = {}) {
984
+ const { filePath, oldString, newString, replaceAll = false } = args;
985
+ if (!options.sandboxClient) {
986
+ const pathError = checkPathWithinCwd(filePath, options.cwd);
987
+ if (pathError !== void 0) return pathError;
988
+ }
989
+ let content;
990
+ try {
991
+ content = options.sandboxClient ? await options.sandboxClient.readFile(filePath) : await readFile(filePath, "utf8");
992
+ } catch (err) {
993
+ const result = {
994
+ success: false,
995
+ output: "",
996
+ error: `File not found: ${filePath}`
997
+ };
998
+ return JSON.stringify(result);
999
+ }
1000
+ if (!content.includes(oldString)) {
1001
+ const result = {
1002
+ success: false,
1003
+ output: "",
1004
+ error: `oldString not found in file: ${filePath}`
1005
+ };
1006
+ return JSON.stringify(result);
1007
+ }
1008
+ if (!replaceAll) {
1009
+ if (content.indexOf(oldString) !== content.lastIndexOf(oldString)) {
1010
+ const result = {
1011
+ success: false,
1012
+ output: "",
1013
+ error: `oldString is not unique in file (found ${content.split(oldString).length - 1} occurrences). Provide more context to make it unique, or use replaceAll:true.`
1014
+ };
1015
+ return JSON.stringify(result);
1016
+ }
1017
+ }
1018
+ const updated = replaceAll ? content.split(oldString).join(newString) : content.slice(0, content.indexOf(oldString)) + newString + content.slice(content.indexOf(oldString) + oldString.length);
1019
+ try {
1020
+ if (options.sandboxClient) await options.sandboxClient.writeFile(filePath, updated);
1021
+ else await atomicWriteUtf8File(filePath, updated);
1022
+ } catch (err) {
1023
+ const result = {
1024
+ success: false,
1025
+ output: "",
1026
+ error: err instanceof Error ? err.message : String(err)
1027
+ };
1028
+ return JSON.stringify(result);
1029
+ }
1030
+ const count = replaceAll ? content.split(oldString).length - 1 : 1;
1031
+ const matchIdx = content.indexOf(oldString);
1032
+ const startLine = matchIdx >= 0 ? content.substring(0, matchIdx).split("\n").length : 1;
1033
+ const result = {
1034
+ success: true,
1035
+ output: `Replaced ${count} occurrence(s) in ${filePath}`,
1036
+ startLine
1037
+ };
1038
+ return JSON.stringify(result);
1054
1039
  }
1055
- var editTool = createZodFunctionTool(
1056
- "Edit",
1057
- "Performs exact string replacements in files.\n\nYou must use the Read tool at least once before editing. When editing text from Read output, preserve the exact indentation.\n\nThe edit will FAIL if old_string is not unique in the file. Either provide more surrounding context to make it unique, or use replace_all to change every instance.\n\nALWAYS prefer editing existing files over creating new ones.",
1058
- EditSchema,
1059
- async (params) => {
1060
- return editFileTool(params);
1061
- }
1062
- );
1063
-
1064
- // src/builtins/glob-tool.ts
1065
- import { stat as stat2 } from "fs/promises";
1066
- import { resolve } from "path";
1067
- import fg from "fast-glob";
1068
- import { z as z5 } from "zod";
1069
- var DEFAULT_MAX_RESULTS = 1e3;
1070
- var GlobSchema = z5.object({
1071
- pattern: z5.string().describe('The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")'),
1072
- path: z5.string().optional().describe(
1073
- "The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided"
1074
- ),
1075
- limit: z5.number().optional().describe(
1076
- "Maximum number of results to return (default: 1000). Use a smaller limit to save context space"
1077
- )
1040
+ /**
1041
+ * Create an EditTool instance — register with Robota agent tools registry.
1042
+ */
1043
+ function createEditTool(options = {}) {
1044
+ return createZodFunctionTool("Edit", "Performs exact string replacements in files.\n\nYou must use the Read tool at least once before editing. When editing text from Read output, preserve the exact indentation.\n\nThe edit will FAIL if old_string is not unique in the file. Either provide more surrounding context to make it unique, or use replace_all to change every instance.\n\nALWAYS prefer editing existing files over creating new ones.", EditSchema, async (params) => {
1045
+ return editFileTool(params, options);
1046
+ });
1047
+ }
1048
+ /**
1049
+ * EditTool instance — register with Robota agent tools registry.
1050
+ */
1051
+ const editTool = createEditTool();
1052
+ //#endregion
1053
+ //#region src/builtins/glob-tool.ts
1054
+ /**
1055
+ * GlobTool — fast file pattern search using fast-glob.
1056
+ *
1057
+ * Excludes node_modules and .git by default.
1058
+ * Results are sorted by modification time (most recently modified first).
1059
+ */
1060
+ const DEFAULT_MAX_RESULTS = 1e3;
1061
+ const GlobSchema = z.object({
1062
+ pattern: z.string().describe("The glob pattern to match files against (e.g. \"**/*.ts\", \"src/**/*.tsx\")"),
1063
+ path: z.string().optional().describe("The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided"),
1064
+ limit: z.number().optional().describe("Maximum number of results to return (default: 1000). Use a smaller limit to save context space")
1078
1065
  });
1079
1066
  async function globFileTool(args) {
1080
- const { pattern, path: basePath } = args;
1081
- const cwd = basePath ? resolve(basePath) : process.cwd();
1082
- let matches;
1083
- try {
1084
- matches = await fg(pattern, {
1085
- cwd,
1086
- ignore: ["**/node_modules/**", "**/.git/**"],
1087
- dot: true,
1088
- absolute: false
1089
- });
1090
- } catch (err) {
1091
- const result2 = {
1092
- success: false,
1093
- output: "",
1094
- error: err instanceof Error ? err.message : String(err)
1095
- };
1096
- return JSON.stringify(result2);
1097
- }
1098
- const withMtime = await Promise.all(
1099
- matches.map(async (p) => {
1100
- const absPath = resolve(cwd, p);
1101
- try {
1102
- const s = await stat2(absPath);
1103
- return { path: p, mtime: s.mtimeMs };
1104
- } catch {
1105
- return { path: p, mtime: 0 };
1106
- }
1107
- })
1108
- );
1109
- withMtime.sort((a, b) => b.mtime - a.mtime);
1110
- const maxResults = args.limit ?? DEFAULT_MAX_RESULTS;
1111
- const totalMatches = withMtime.length;
1112
- const truncated = totalMatches > maxResults;
1113
- const limited = truncated ? withMtime.slice(0, maxResults) : withMtime;
1114
- const sorted = limited.map((f) => f.path);
1115
- let output = sorted.length > 0 ? sorted.join("\n") : "(no matches)";
1116
- if (truncated) {
1117
- output += `
1118
-
1119
- [Showing ${maxResults} of ${totalMatches} matches. Use limit parameter to see more.]`;
1120
- }
1121
- const result = {
1122
- success: true,
1123
- output
1124
- };
1125
- return JSON.stringify(result);
1067
+ const { pattern, path: basePath } = args;
1068
+ const cwd = basePath ? resolve(basePath) : process.cwd();
1069
+ let matches;
1070
+ try {
1071
+ matches = await fg(pattern, {
1072
+ cwd,
1073
+ ignore: ["**/node_modules/**", "**/.git/**"],
1074
+ dot: true,
1075
+ absolute: false
1076
+ });
1077
+ } catch (err) {
1078
+ const result = {
1079
+ success: false,
1080
+ output: "",
1081
+ error: err instanceof Error ? err.message : String(err)
1082
+ };
1083
+ return JSON.stringify(result);
1084
+ }
1085
+ const limit = pLimit(100);
1086
+ const withMtime = await Promise.all(matches.map((p) => limit(async () => {
1087
+ const absPath = resolve(cwd, p);
1088
+ try {
1089
+ return {
1090
+ path: p,
1091
+ mtime: (await stat(absPath)).mtimeMs
1092
+ };
1093
+ } catch {
1094
+ return {
1095
+ path: p,
1096
+ mtime: 0
1097
+ };
1098
+ }
1099
+ })));
1100
+ withMtime.sort((a, b) => b.mtime - a.mtime);
1101
+ const maxResults = args.limit ?? DEFAULT_MAX_RESULTS;
1102
+ const totalMatches = withMtime.length;
1103
+ const truncated = totalMatches > maxResults;
1104
+ const sorted = (truncated ? withMtime.slice(0, maxResults) : withMtime).map((f) => f.path);
1105
+ let output = sorted.length > 0 ? sorted.join("\n") : "(no matches)";
1106
+ if (truncated) output += `\n\n[Showing ${maxResults} of ${totalMatches} matches. Use limit parameter to see more.]`;
1107
+ return JSON.stringify({
1108
+ success: true,
1109
+ output
1110
+ });
1126
1111
  }
1127
- var globTool = createZodFunctionTool(
1128
- "Glob",
1129
- "Fast file pattern matching tool that works with any codebase size.\n\nSupports glob patterns like '**/*.js' or 'src/**/*.ts'. Returns matching file paths sorted by modification time.\n\nUse this tool when you need to find files by name patterns. When doing an open-ended search that may require multiple rounds, use the Agent tool instead.\n\nDefault limit is 1000 results. Use the limit parameter if you need fewer results to save context space.",
1130
- GlobSchema,
1131
- async (params) => {
1132
- return globFileTool(params);
1133
- }
1134
- );
1135
-
1136
- // src/builtins/grep-tool.ts
1137
- import { readFile as readFile3, readdir, stat as stat3 } from "fs/promises";
1138
- import { join, resolve as resolve2 } from "path";
1139
- import { z as z6 } from "zod";
1140
- var GrepSchema = z6.object({
1141
- pattern: z6.string().describe("The regular expression pattern to search for in file contents"),
1142
- path: z6.string().optional().describe("File or directory to search in. Defaults to the current working directory"),
1143
- glob: z6.string().optional().describe(
1144
- 'Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched'
1145
- ),
1146
- contextLines: z6.number().optional().describe(
1147
- 'Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0'
1148
- ),
1149
- outputMode: z6.enum(["files_with_matches", "content"]).optional().describe(
1150
- 'Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines with context'
1151
- )
1112
+ /**
1113
+ * GlobTool instance — register with Robota agent tools registry.
1114
+ */
1115
+ const globTool = createZodFunctionTool("Glob", "Fast file pattern matching tool that works with any codebase size.\n\nSupports glob patterns like '**/*.js' or 'src/**/*.ts'. Returns matching file paths sorted by modification time.\n\nUse this tool when you need to find files by name patterns. When doing an open-ended search that may require multiple rounds, use the Agent tool instead.\n\nDefault limit is 1000 results. Use the limit parameter if you need fewer results to save context space.", GlobSchema, async (params) => {
1116
+ return globFileTool(params);
1117
+ });
1118
+ //#endregion
1119
+ //#region src/builtins/grep-tool.ts
1120
+ /**
1121
+ * GrepTool — recursive regex content search.
1122
+ *
1123
+ * Supports two output modes:
1124
+ * - files_with_matches (default): return only file paths that contain a match
1125
+ * - content: return matching lines with optional context lines
1126
+ */
1127
+ const GrepSchema = z.object({
1128
+ pattern: z.string().describe("The regular expression pattern to search for in file contents"),
1129
+ path: z.string().optional().describe("File or directory to search in. Defaults to the current working directory"),
1130
+ glob: z.string().optional().describe("Glob pattern to filter files (e.g. \"*.ts\", \"*.{ts,tsx}\"). Only files matching this pattern will be searched"),
1131
+ contextLines: z.number().optional().describe("Number of context lines to show before and after each match. Only applies when outputMode is \"content\". Default: 0"),
1132
+ outputMode: z.enum(["files_with_matches", "content"]).optional().describe("Output mode: \"files_with_matches\" shows only file paths (default), \"content\" shows matching lines with context")
1152
1133
  });
1134
+ /** Convert a simple glob to a RegExp for file name filtering. */
1153
1135
  function globToRegex(glob) {
1154
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".+").replace(/\*/g, "[^/]*");
1155
- return new RegExp(`^${escaped}$`);
1136
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".+").replace(/\*/g, "[^/]*");
1137
+ return new RegExp(`^${escaped}$`);
1156
1138
  }
1139
+ /** Check if a file name matches an optional glob filter. */
1157
1140
  function matchesGlob(filename, glob) {
1158
- if (glob === void 0) return true;
1159
- return globToRegex(glob).test(filename);
1141
+ if (glob === void 0) return true;
1142
+ return globToRegex(glob).test(filename);
1160
1143
  }
1144
+ /** Gather all files under a directory recursively, excluding node_modules/.git. */
1161
1145
  async function collectFiles(dirPath, glob) {
1162
- const results = [];
1163
- async function walk(current) {
1164
- let entryNames;
1165
- try {
1166
- entryNames = await readdir(current);
1167
- } catch {
1168
- return;
1169
- }
1170
- for (const name of entryNames) {
1171
- if (name === "node_modules" || name === ".git") continue;
1172
- const fullPath = join(current, name);
1173
- let fileStat;
1174
- try {
1175
- fileStat = await stat3(fullPath);
1176
- } catch {
1177
- continue;
1178
- }
1179
- if (fileStat.isDirectory()) {
1180
- await walk(fullPath);
1181
- } else if (fileStat.isFile()) {
1182
- if (matchesGlob(name, glob)) {
1183
- results.push(fullPath);
1184
- }
1185
- }
1186
- }
1187
- }
1188
- await walk(dirPath);
1189
- return results;
1146
+ const results = [];
1147
+ async function walk(current) {
1148
+ let entryNames;
1149
+ try {
1150
+ entryNames = await readdir(current);
1151
+ } catch {
1152
+ return;
1153
+ }
1154
+ for (const name of entryNames) {
1155
+ if (name === "node_modules" || name === ".git") continue;
1156
+ const fullPath = join(current, name);
1157
+ let fileStat;
1158
+ try {
1159
+ fileStat = await stat(fullPath);
1160
+ } catch {
1161
+ continue;
1162
+ }
1163
+ if (fileStat.isDirectory()) await walk(fullPath);
1164
+ else if (fileStat.isFile()) {
1165
+ if (matchesGlob(name, glob)) results.push(fullPath);
1166
+ }
1167
+ }
1168
+ }
1169
+ await walk(dirPath);
1170
+ return results;
1190
1171
  }
1172
+ /** Search a single file for lines matching the regex. */
1191
1173
  function searchFile(content, filePath, regex, contextLines, outputMode) {
1192
- const lines = content.split("\n");
1193
- const matchingIndices = [];
1194
- for (let i = 0; i < lines.length; i++) {
1195
- if (regex.test(lines[i])) {
1196
- matchingIndices.push(i);
1197
- }
1198
- }
1199
- if (matchingIndices.length === 0) return [];
1200
- if (outputMode === "files_with_matches") {
1201
- return [filePath];
1202
- }
1203
- const includedIndices = /* @__PURE__ */ new Set();
1204
- for (const idx of matchingIndices) {
1205
- for (let c = Math.max(0, idx - contextLines); c <= Math.min(lines.length - 1, idx + contextLines); c++) {
1206
- includedIndices.add(c);
1207
- }
1208
- }
1209
- const outputLines = [];
1210
- const sortedIndices = Array.from(includedIndices).sort((a, b) => a - b);
1211
- let prevIdx;
1212
- for (const idx of sortedIndices) {
1213
- if (prevIdx !== void 0 && idx > prevIdx + 1) {
1214
- outputLines.push("--");
1215
- }
1216
- const lineNum = idx + 1;
1217
- const marker = matchingIndices.includes(idx) ? ":" : "-";
1218
- outputLines.push(`${filePath}:${lineNum}${marker}${lines[idx]}`);
1219
- prevIdx = idx;
1220
- }
1221
- return outputLines;
1174
+ const lines = content.split("\n");
1175
+ const matchingIndices = [];
1176
+ for (let i = 0; i < lines.length; i++) if (regex.test(lines[i])) matchingIndices.push(i);
1177
+ if (matchingIndices.length === 0) return [];
1178
+ if (outputMode === "files_with_matches") return [filePath];
1179
+ const includedIndices = /* @__PURE__ */ new Set();
1180
+ for (const idx of matchingIndices) for (let c = Math.max(0, idx - contextLines); c <= Math.min(lines.length - 1, idx + contextLines); c++) includedIndices.add(c);
1181
+ const outputLines = [];
1182
+ const sortedIndices = Array.from(includedIndices).sort((a, b) => a - b);
1183
+ let prevIdx;
1184
+ for (const idx of sortedIndices) {
1185
+ if (prevIdx !== void 0 && idx > prevIdx + 1) outputLines.push("--");
1186
+ const lineNum = idx + 1;
1187
+ const marker = matchingIndices.includes(idx) ? ":" : "-";
1188
+ outputLines.push(`${filePath}:${lineNum}${marker}${lines[idx]}`);
1189
+ prevIdx = idx;
1190
+ }
1191
+ return outputLines;
1222
1192
  }
1223
1193
  async function grepFileTool(args) {
1224
- const {
1225
- pattern,
1226
- path: searchPath,
1227
- glob,
1228
- contextLines = 0,
1229
- outputMode = "files_with_matches"
1230
- } = args;
1231
- const targetPath = searchPath ? resolve2(searchPath) : process.cwd();
1232
- let regex;
1233
- try {
1234
- regex = new RegExp(pattern);
1235
- } catch (err) {
1236
- const result2 = {
1237
- success: false,
1238
- output: "",
1239
- error: `Invalid regex pattern: ${pattern}`
1240
- };
1241
- return JSON.stringify(result2);
1242
- }
1243
- let targetStat;
1244
- try {
1245
- targetStat = await stat3(targetPath);
1246
- } catch {
1247
- const result2 = {
1248
- success: false,
1249
- output: "",
1250
- error: `Path not found: ${targetPath}`
1251
- };
1252
- return JSON.stringify(result2);
1253
- }
1254
- let files;
1255
- if (targetStat.isFile()) {
1256
- files = [targetPath];
1257
- } else {
1258
- files = await collectFiles(targetPath, glob);
1259
- }
1260
- const allOutputLines = [];
1261
- for (const filePath of files) {
1262
- let content;
1263
- try {
1264
- const buffer = await readFile3(filePath);
1265
- const checkLen = Math.min(buffer.length, 8192);
1266
- let hasBinary = false;
1267
- for (let i = 0; i < checkLen; i++) {
1268
- if (buffer[i] === 0) {
1269
- hasBinary = true;
1270
- break;
1271
- }
1272
- }
1273
- if (hasBinary) continue;
1274
- content = buffer.toString("utf8");
1275
- } catch {
1276
- continue;
1277
- }
1278
- const fileMatches = searchFile(content, filePath, regex, contextLines, outputMode);
1279
- allOutputLines.push(...fileMatches);
1280
- }
1281
- const result = {
1282
- success: true,
1283
- output: allOutputLines.length > 0 ? allOutputLines.join("\n") : "(no matches)"
1284
- };
1285
- return JSON.stringify(result);
1194
+ const { pattern, path: searchPath, glob, contextLines = 0, outputMode = "files_with_matches" } = args;
1195
+ const targetPath = searchPath ? resolve(searchPath) : process.cwd();
1196
+ let regex;
1197
+ try {
1198
+ regex = new RegExp(pattern);
1199
+ } catch (err) {
1200
+ const result = {
1201
+ success: false,
1202
+ output: "",
1203
+ error: `Invalid regex pattern: ${pattern}`
1204
+ };
1205
+ return JSON.stringify(result);
1206
+ }
1207
+ let targetStat;
1208
+ try {
1209
+ targetStat = await stat(targetPath);
1210
+ } catch {
1211
+ const result = {
1212
+ success: false,
1213
+ output: "",
1214
+ error: `Path not found: ${targetPath}`
1215
+ };
1216
+ return JSON.stringify(result);
1217
+ }
1218
+ let files;
1219
+ if (targetStat.isFile()) files = [targetPath];
1220
+ else files = await collectFiles(targetPath, glob);
1221
+ const allOutputLines = [];
1222
+ for (const filePath of files) {
1223
+ let content;
1224
+ try {
1225
+ const buffer = await readFile(filePath);
1226
+ const checkLen = Math.min(buffer.length, 8192);
1227
+ let hasBinary = false;
1228
+ for (let i = 0; i < checkLen; i++) if (buffer[i] === 0) {
1229
+ hasBinary = true;
1230
+ break;
1231
+ }
1232
+ if (hasBinary) continue;
1233
+ content = buffer.toString("utf8");
1234
+ } catch {
1235
+ continue;
1236
+ }
1237
+ const fileMatches = searchFile(content, filePath, regex, contextLines, outputMode);
1238
+ allOutputLines.push(...fileMatches);
1239
+ }
1240
+ const result = {
1241
+ success: true,
1242
+ output: allOutputLines.length > 0 ? allOutputLines.join("\n") : "(no matches)"
1243
+ };
1244
+ return JSON.stringify(result);
1286
1245
  }
1287
- var grepTool = createZodFunctionTool(
1288
- "Grep",
1289
- "A powerful search tool built on regex matching.\n\nSupports full regex syntax (e.g., 'log.*Error', 'function\\\\s+\\\\w+'). Filter files with glob parameter (e.g., '*.js', '**/*.tsx').\n\nOutput modes: 'content' shows matching lines with context, 'files_with_matches' shows only file paths (default), 'count' shows match counts.\n\nUse this tool for ALL search tasks. NEVER invoke grep or rg as a Bash command.\n\nUse head_limit to control result size and save context space.",
1290
- GrepSchema,
1291
- async (params) => {
1292
- return grepFileTool(params);
1293
- }
1294
- );
1295
-
1296
- // src/builtins/web-fetch-tool.ts
1297
- import { z as z7 } from "zod";
1298
- var DEFAULT_TIMEOUT_MS2 = 3e4;
1299
- var MAX_RESPONSE_BYTES = 5e6;
1300
- var WebFetchSchema = z7.object({
1301
- url: z7.string().describe("The URL to fetch"),
1302
- headers: z7.record(z7.string()).optional().describe("Optional HTTP headers as key-value pairs")
1246
+ /**
1247
+ * GrepTool instance — register with Robota agent tools registry.
1248
+ */
1249
+ const grepTool = createZodFunctionTool("Grep", "A powerful search tool built on regex matching.\n\nSupports full regex syntax (e.g., 'log.*Error', 'function\\\\s+\\\\w+'). Filter files with glob parameter (e.g., '*.js', '**/*.tsx').\n\nOutput modes: 'content' shows matching lines with context, 'files_with_matches' shows only file paths (default), 'count' shows match counts.\n\nUse this tool for ALL search tasks. NEVER invoke grep or rg as a Bash command.\n\nUse head_limit to control result size and save context space.", GrepSchema, async (params) => {
1250
+ return grepFileTool(params);
1251
+ });
1252
+ //#endregion
1253
+ //#region src/builtins/web-fetch-tool.ts
1254
+ /**
1255
+ * WebFetchTool — fetch a URL and return its content as text.
1256
+ *
1257
+ * HTML is stripped to plain text for readability. Uses Node.js native fetch.
1258
+ * Output is capped at 30K chars (same as other tools).
1259
+ */
1260
+ const DEFAULT_TIMEOUT_MS$1 = 3e4;
1261
+ const MAX_RESPONSE_BYTES = 5e6;
1262
+ const WebFetchSchema = z.object({
1263
+ url: z.string().describe("The URL to fetch"),
1264
+ headers: z.record(z.string()).optional().describe("Optional HTTP headers as key-value pairs")
1303
1265
  });
1266
+ /** Strip HTML tags and decode common entities to produce readable text. */
1304
1267
  function htmlToText(html) {
1305
- return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
1268
+ return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
1269
+ }
1270
+ function classifyFetchError(err) {
1271
+ if (!(err instanceof Error)) return String(err);
1272
+ if (err.name === "AbortError") return `Request timed out after ${DEFAULT_TIMEOUT_MS$1 / 1e3}s. The server did not respond in time.`;
1273
+ const code = err.code;
1274
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return `Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`;
1275
+ if (code === "ECONNREFUSED") return `Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`;
1276
+ if (code === "ECONNRESET") return `Network error: Connection was reset by the server. The server may be temporarily unavailable.`;
1277
+ if (code === "ETIMEDOUT") return `Network error: Connection timed out. The server is not reachable within the expected time.`;
1278
+ if (code === "CERT_HAS_EXPIRED" || code === "UNABLE_TO_VERIFY_LEAF_SIGNATURE") return `Network error: SSL certificate error (${code}). The server's certificate is invalid. Do not retry with the same URL.`;
1279
+ return `Network error: ${err.message} Check that the URL is correct and the server is reachable.`;
1306
1280
  }
1307
1281
  async function runWebFetch(args) {
1308
- const { url, headers } = args;
1309
- try {
1310
- new URL(url);
1311
- } catch {
1312
- const result = { success: false, output: "", error: `Invalid URL: ${url}` };
1313
- return JSON.stringify(result);
1314
- }
1315
- try {
1316
- const controller = new AbortController();
1317
- const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS2);
1318
- const response = await fetch(url, {
1319
- headers: {
1320
- "User-Agent": "Robota-CLI/3.0",
1321
- ...headers ?? {}
1322
- },
1323
- signal: controller.signal,
1324
- redirect: "follow"
1325
- });
1326
- clearTimeout(timeout);
1327
- if (!response.ok) {
1328
- const result2 = {
1329
- success: false,
1330
- output: "",
1331
- error: `HTTP ${response.status} ${response.statusText}`
1332
- };
1333
- return JSON.stringify(result2);
1334
- }
1335
- const contentType = response.headers.get("content-type") ?? "";
1336
- const buffer = await response.arrayBuffer();
1337
- if (buffer.byteLength > MAX_RESPONSE_BYTES) {
1338
- const result2 = {
1339
- success: false,
1340
- output: "",
1341
- error: `Response too large: ${buffer.byteLength} bytes (max ${MAX_RESPONSE_BYTES})`
1342
- };
1343
- return JSON.stringify(result2);
1344
- }
1345
- let text = new TextDecoder().decode(buffer);
1346
- if (contentType.includes("html")) {
1347
- text = htmlToText(text);
1348
- }
1349
- const result = { success: true, output: text };
1350
- return JSON.stringify(result);
1351
- } catch (err) {
1352
- const message = err instanceof Error ? err.message : String(err);
1353
- const result = { success: false, output: "", error: message };
1354
- return JSON.stringify(result);
1355
- }
1282
+ const { url, headers } = args;
1283
+ try {
1284
+ new URL(url);
1285
+ } catch {
1286
+ const result = {
1287
+ success: false,
1288
+ output: "",
1289
+ error: `Invalid URL: "${url}". Fix the URL format before retrying.`
1290
+ };
1291
+ return JSON.stringify(result);
1292
+ }
1293
+ try {
1294
+ const controller = new AbortController();
1295
+ const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS$1);
1296
+ const response = await fetch(url, {
1297
+ headers: {
1298
+ "User-Agent": "Robota-CLI/3.0",
1299
+ ...headers ?? {}
1300
+ },
1301
+ signal: controller.signal,
1302
+ redirect: "follow"
1303
+ });
1304
+ clearTimeout(timeout);
1305
+ if (!response.ok) {
1306
+ const retryHint = response.status >= 500 ? " The server is temporarily unavailable — retrying may help." : " Do not retry with the same URL.";
1307
+ const result = {
1308
+ success: false,
1309
+ output: "",
1310
+ error: `HTTP ${response.status} ${response.statusText}.${retryHint}`
1311
+ };
1312
+ return JSON.stringify(result);
1313
+ }
1314
+ const contentType = response.headers.get("content-type") ?? "";
1315
+ const buffer = await response.arrayBuffer();
1316
+ if (buffer.byteLength > MAX_RESPONSE_BYTES) {
1317
+ const result = {
1318
+ success: false,
1319
+ output: "",
1320
+ error: `Response too large: ${buffer.byteLength} bytes (max ${MAX_RESPONSE_BYTES}). Consider fetching a more specific URL or a paginated endpoint.`
1321
+ };
1322
+ return JSON.stringify(result);
1323
+ }
1324
+ let text = new TextDecoder().decode(buffer);
1325
+ if (contentType.includes("html")) text = htmlToText(text);
1326
+ return JSON.stringify({
1327
+ success: true,
1328
+ output: text
1329
+ });
1330
+ } catch (err) {
1331
+ const result = {
1332
+ success: false,
1333
+ output: "",
1334
+ error: classifyFetchError(err)
1335
+ };
1336
+ return JSON.stringify(result);
1337
+ }
1356
1338
  }
1357
- var webFetchTool = createZodFunctionTool(
1358
- "WebFetch",
1359
- "Fetch a URL and return its content as text. HTML pages are converted to plain text.",
1360
- WebFetchSchema,
1361
- async (params) => runWebFetch(params)
1362
- );
1363
-
1364
- // src/builtins/web-search-tool.ts
1365
- import { z as z8 } from "zod";
1366
- var DEFAULT_LIMIT2 = 10;
1367
- var DEFAULT_TIMEOUT_MS3 = 15e3;
1368
- var WebSearchSchema = z8.object({
1369
- query: z8.string().describe("The search query"),
1370
- limit: z8.number().optional().describe(`Maximum number of results to return (default: ${DEFAULT_LIMIT2})`)
1339
+ const webFetchTool = createZodFunctionTool("WebFetch", "Fetch a URL and return its content as text. HTML pages are converted to plain text.", WebFetchSchema, async (params) => runWebFetch(params));
1340
+ //#endregion
1341
+ //#region src/builtins/web-search-tool.ts
1342
+ /**
1343
+ * WebSearchTool — search the web and return results.
1344
+ *
1345
+ * Uses Brave Search API when BRAVE_API_KEY is set.
1346
+ * Returns an error with setup instructions otherwise.
1347
+ */
1348
+ const DEFAULT_LIMIT = 10;
1349
+ const DEFAULT_TIMEOUT_MS = 15e3;
1350
+ const WebSearchSchema = z.object({
1351
+ query: z.string().describe("The search query"),
1352
+ limit: z.number().optional().describe(`Maximum number of results to return (default: ${DEFAULT_LIMIT})`)
1371
1353
  });
1372
1354
  async function runWebSearch(args) {
1373
- const { query, limit = DEFAULT_LIMIT2 } = args;
1374
- const apiKey = process.env["BRAVE_API_KEY"];
1375
- if (!apiKey) {
1376
- const result = {
1377
- success: false,
1378
- output: "",
1379
- error: "Web search requires BRAVE_API_KEY environment variable. Get a free API key at https://brave.com/search/api/ (2,000 queries/month free)."
1380
- };
1381
- return JSON.stringify(result);
1382
- }
1383
- try {
1384
- const controller = new AbortController();
1385
- const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS3);
1386
- const params = new URLSearchParams({
1387
- q: query,
1388
- count: String(Math.min(limit, 20))
1389
- });
1390
- const response = await fetch(`https://api.search.brave.com/res/v1/web/search?${params}`, {
1391
- headers: {
1392
- Accept: "application/json",
1393
- "Accept-Encoding": "gzip",
1394
- "X-Subscription-Token": apiKey
1395
- },
1396
- signal: controller.signal
1397
- });
1398
- clearTimeout(timeout);
1399
- if (!response.ok) {
1400
- const result2 = {
1401
- success: false,
1402
- output: "",
1403
- error: `Brave Search API error: HTTP ${response.status} ${response.statusText}`
1404
- };
1405
- return JSON.stringify(result2);
1406
- }
1407
- const data = await response.json();
1408
- const results = (data.web?.results ?? []).map((r) => ({
1409
- title: r.title,
1410
- url: r.url,
1411
- snippet: r.description
1412
- }));
1413
- const result = { success: true, output: JSON.stringify(results, null, 2) };
1414
- return JSON.stringify(result);
1415
- } catch (err) {
1416
- const message = err instanceof Error ? err.message : String(err);
1417
- const result = { success: false, output: "", error: message };
1418
- return JSON.stringify(result);
1419
- }
1355
+ const { query, limit = DEFAULT_LIMIT } = args;
1356
+ const apiKey = process.env["BRAVE_API_KEY"];
1357
+ if (!apiKey) return JSON.stringify({
1358
+ success: false,
1359
+ output: "",
1360
+ error: "Web search requires BRAVE_API_KEY environment variable. Get a free API key at https://brave.com/search/api/ (2,000 queries/month free)."
1361
+ });
1362
+ try {
1363
+ const controller = new AbortController();
1364
+ const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
1365
+ const params = new URLSearchParams({
1366
+ q: query,
1367
+ count: String(Math.min(limit, 20))
1368
+ });
1369
+ const response = await fetch(`https://api.search.brave.com/res/v1/web/search?${params}`, {
1370
+ headers: {
1371
+ Accept: "application/json",
1372
+ "Accept-Encoding": "gzip",
1373
+ "X-Subscription-Token": apiKey
1374
+ },
1375
+ signal: controller.signal
1376
+ });
1377
+ clearTimeout(timeout);
1378
+ if (!response.ok) {
1379
+ const result = {
1380
+ success: false,
1381
+ output: "",
1382
+ error: `Brave Search API error: HTTP ${response.status} ${response.statusText}`
1383
+ };
1384
+ return JSON.stringify(result);
1385
+ }
1386
+ const results = ((await response.json()).web?.results ?? []).map((r) => ({
1387
+ title: r.title,
1388
+ url: r.url,
1389
+ snippet: r.description
1390
+ }));
1391
+ const result = {
1392
+ success: true,
1393
+ output: JSON.stringify(results, null, 2)
1394
+ };
1395
+ return JSON.stringify(result);
1396
+ } catch (err) {
1397
+ const result = {
1398
+ success: false,
1399
+ output: "",
1400
+ error: err instanceof Error ? err.message : String(err)
1401
+ };
1402
+ return JSON.stringify(result);
1403
+ }
1420
1404
  }
1421
- var webSearchTool = createZodFunctionTool(
1422
- "WebSearch",
1423
- "Search the web and return results with title, URL, and snippet.",
1424
- WebSearchSchema,
1425
- async (params) => runWebSearch(params)
1426
- );
1427
- export {
1428
- FunctionTool,
1429
- OpenAPITool,
1430
- ToolRegistry,
1431
- bashTool,
1432
- createFunctionTool,
1433
- createOpenAPITool,
1434
- createZodFunctionTool,
1435
- editTool,
1436
- globTool,
1437
- grepTool,
1438
- readTool,
1439
- webFetchTool,
1440
- webSearchTool,
1441
- writeTool,
1442
- zodToJsonSchema
1443
- };
1405
+ const webSearchTool = createZodFunctionTool("WebSearch", "Search the web and return results with title, URL, and snippet.", WebSearchSchema, async (params) => runWebSearch(params));
1406
+ //#endregion
1407
+ export { E2BSandboxClient, FunctionTool, InMemorySandboxClient, ToolRegistry, applyWorkspaceManifest, bashTool, createBashTool, createEditTool, createFunctionTool, createReadTool, createWriteTool, createZodFunctionTool, editTool, globTool, grepTool, readTool, validateWorkspaceManifestPath, webFetchTool, webSearchTool, writeTool, zodToJsonSchema };
1408
+
1409
+ //# sourceMappingURL=index.js.map