@mastra/core
Version:
12,288 lines • 457 kB
JavaScript
const require_rolldown_runtime = require("./rolldown-runtime-BrhgMLW6.cjs");
const require_request_context = require("./request-context-D9RXYCy8.cjs");
const require_errors = require("./errors-D5kMB1FQ.cjs");
const require_workspace_skills = require("./workspace-skills-CKBkzxPb.cjs");
const require_base = require("./base-BIzR1D3_.cjs");
const require_logger = require("./logger-CvzZYuJd.cjs");
const require_tool = require("./tool-BMl4Lb5_.cjs");
require("./utils-D-eNsgDM.cjs");
let stream = require("stream");
let zod_v4 = require("zod/v4");
let crypto = require("crypto");
let fs = require("fs");
let module$1 = require("module");
let os = require("os");
os = require_rolldown_runtime.__toESM(os, 1);
let path = require("path");
path = require_rolldown_runtime.__toESM(path, 1);
let path_posix = require("path/posix");
path_posix = require_rolldown_runtime.__toESM(path_posix, 1);
let fs_promises = require("fs/promises");
fs_promises = require_rolldown_runtime.__toESM(fs_promises, 1);
let child_process = require("child_process");
let url = require("url");
let ignore = require("ignore");
ignore = require_rolldown_runtime.__toESM(ignore, 1);
let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
// src/workspace/sandbox/utils.ts
/**
* Shell-quote an argument for safe interpolation into a shell command string.
* Safe characters (alphanumeric, `.`, `_`, `-`, `/`, `=`, `:`, `@`) pass through.
* Everything else is wrapped in single quotes with embedded quotes escaped.
*/
function shellQuote(arg) {
if (/^[a-zA-Z0-9._\-\/=:@]+$/.test(arg)) return arg;
return `'${arg.replace(/'/g, "'\\''")}'`;
}
/**
* Split a shell command string on operators (&&, ||, ;) while respecting quotes.
*
* This is a quote-aware splitter that won't split inside single or double quoted strings.
* Handles escaped quotes within quoted strings.
*
* @example
* ```typescript
* splitShellCommand('echo "hello && world" && ls')
* // => { parts: ['echo "hello && world"', 'ls'], operators: ['&&'] }
*
* splitShellCommand("bash -c 'cd /tmp && pwd' || echo fail")
* // => { parts: ["bash -c 'cd /tmp && pwd'", 'echo fail'], operators: ['||'] }
* ```
*/
function splitShellCommand(command) {
const parts = [];
const operators = [];
let current = "";
let i = 0;
let inSingleQuote = false;
let inDoubleQuote = false;
while (i < command.length) {
const char = command[i];
const next = command[i + 1];
if (char === "\\" && i + 1 < command.length) {
current += char + next;
i += 2;
continue;
}
if (char === "'" && !inDoubleQuote) {
inSingleQuote = !inSingleQuote;
current += char;
i++;
continue;
}
if (char === "\"" && !inSingleQuote) {
inDoubleQuote = !inDoubleQuote;
current += char;
i++;
continue;
}
if (!inSingleQuote && !inDoubleQuote) {
if (char === "&" && next === "&" || char === "|" && next === "|") {
parts.push(current.trim());
operators.push(char + next);
current = "";
i += 2;
while (i < command.length && /\s/.test(command[i])) i++;
continue;
}
if (char === ";") {
parts.push(current.trim());
operators.push(";");
current = "";
i++;
while (i < command.length && /\s/.test(command[i])) i++;
continue;
}
}
current += char;
i++;
}
if (current.trim()) parts.push(current.trim());
return {
parts,
operators
};
}
/**
* Reassemble command parts with their operators.
*
* @example
* ```typescript
* reassembleShellCommand(['echo hello', 'ls'], ['&&'])
* // => 'echo hello && ls'
* ```
*/
function reassembleShellCommand(parts, operators) {
let result = parts[0] ?? "";
for (let i = 0; i < operators.length; i++) result += ` ${operators[i]} ${parts[i + 1] ?? ""}`;
return result.trim();
}
// src/workspace/constants/index.ts
const WORKSPACE_TOOLS_PREFIX = "mastra_workspace";
/**
* Workspace tool name constants.
* Use these to reference workspace tools by name.
*
* @example
* ```typescript
* import { WORKSPACE_TOOLS } from '@mastra/core/workspace';
*
* if (toolName === WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND) {
* // Handle sandbox execution
* }
* ```
*/
const WORKSPACE_TOOLS = {
FILESYSTEM: {
READ_FILE: `${WORKSPACE_TOOLS_PREFIX}_read_file`,
WRITE_FILE: `${WORKSPACE_TOOLS_PREFIX}_write_file`,
EDIT_FILE: `${WORKSPACE_TOOLS_PREFIX}_edit_file`,
LIST_FILES: `${WORKSPACE_TOOLS_PREFIX}_list_files`,
DELETE: `${WORKSPACE_TOOLS_PREFIX}_delete`,
FILE_STAT: `${WORKSPACE_TOOLS_PREFIX}_file_stat`,
MKDIR: `${WORKSPACE_TOOLS_PREFIX}_mkdir`,
GREP: `${WORKSPACE_TOOLS_PREFIX}_grep`,
AST_EDIT: `${WORKSPACE_TOOLS_PREFIX}_ast_edit`,
APPLY_PATCH: `${WORKSPACE_TOOLS_PREFIX}_apply_patch`
},
SANDBOX: {
EXECUTE_COMMAND: `${WORKSPACE_TOOLS_PREFIX}_execute_command`,
GET_PROCESS_OUTPUT: `${WORKSPACE_TOOLS_PREFIX}_get_process_output`,
KILL_PROCESS: `${WORKSPACE_TOOLS_PREFIX}_kill_process`
},
COMPUTER: {
SCREENSHOT: `${WORKSPACE_TOOLS_PREFIX}_computer_screenshot`,
CLICK: `${WORKSPACE_TOOLS_PREFIX}_computer_click`,
DOUBLE_CLICK: `${WORKSPACE_TOOLS_PREFIX}_computer_double_click`,
RIGHT_CLICK: `${WORKSPACE_TOOLS_PREFIX}_computer_right_click`,
MOVE_MOUSE: `${WORKSPACE_TOOLS_PREFIX}_computer_move_mouse`,
DRAG: `${WORKSPACE_TOOLS_PREFIX}_computer_drag`,
TYPE: `${WORKSPACE_TOOLS_PREFIX}_computer_type`,
PRESS_KEY: `${WORKSPACE_TOOLS_PREFIX}_computer_press_key`,
SCROLL: `${WORKSPACE_TOOLS_PREFIX}_computer_scroll`,
GET_SCREEN_INFO: `${WORKSPACE_TOOLS_PREFIX}_computer_get_screen_info`,
WAIT: `${WORKSPACE_TOOLS_PREFIX}_computer_wait`
},
SEARCH: {
SEARCH: `${WORKSPACE_TOOLS_PREFIX}_search`,
INDEX: `${WORKSPACE_TOOLS_PREFIX}_index`
},
LSP: { LSP_INSPECT: `${WORKSPACE_TOOLS_PREFIX}_lsp_inspect` }
};
// src/workspace/lifecycle.ts
/**
* Call a lifecycle method on a provider, preferring the `_`-prefixed wrapper
* (which adds status tracking & race-condition safety) when available,
* falling back to the plain method for interface-only implementations.
*
* @example
* ```typescript
* await callLifecycle(sandbox, 'start'); // calls sandbox._start() ?? sandbox.start()
* await callLifecycle(filesystem, 'init'); // calls filesystem._init() ?? filesystem.init()
* ```
*/
async function callLifecycle(provider, method) {
const wrappedFn = provider[`_${method}`];
if (typeof wrappedFn === "function") await wrappedFn.call(provider);
else {
const plainFn = provider[method];
if (typeof plainFn === "function") await plainFn.call(provider);
}
}
// src/workspace/filesystem/composite-filesystem.ts
/**
* CompositeFilesystem - Routes operations to mounted filesystems based on path.
*
* Creates a unified filesystem view by combining multiple filesystems at different
* mount points. Useful for composing local storage, S3, and other backends.
*
* @example
* ```typescript
* const cfs = new CompositeFilesystem({
* mounts: {
* '/local': new LocalFilesystem({ basePath: './data' }),
* '/s3': new S3Filesystem({ bucket: 'my-bucket', ... }),
* }
* });
*
* // readdir('/') returns ['local', 's3']
* // readFile('/local/file.txt') reads from LocalFilesystem
* // readFile('/s3/data.json') reads from S3Filesystem
* ```
*/
/**
* CompositeFilesystem implementation.
*
* Routes file operations to the appropriate underlying filesystem based on path.
* Supports cross-mount operations (copy/move between different filesystems).
*
* The generic parameter preserves the concrete types of mounted filesystems,
* enabling typed access via `mounts.get()`.
*
* @example
* ```typescript
* const cfs = new CompositeFilesystem({
* mounts: {
* '/local': new LocalFilesystem({ basePath: './data' }),
* '/s3': new S3Filesystem({ bucket: 'my-bucket' }),
* },
* });
*
* cfs.mounts.get('/local') // LocalFilesystem
* cfs.mounts.get('/s3') // S3Filesystem
* ```
*/
var CompositeFilesystem = class {
id;
name = "CompositeFilesystem";
provider = "composite";
readOnly;
status = "ready";
_mounts;
constructor(config) {
this.id = `cfs-${Date.now().toString(36)}`;
this._mounts = /* @__PURE__ */ new Map();
for (const [path, fs] of Object.entries(config.mounts)) {
const normalized = this.normalizePath(path);
this._mounts.set(normalized, fs);
}
if (this._mounts.size === 0) throw new Error("CompositeFilesystem requires at least one mount");
this.readOnly = [...this._mounts.values()].every((fs) => fs.readOnly) || void 0;
const mountPaths = [...this._mounts.keys()];
for (const a of mountPaths) for (const b of mountPaths) if (a !== b && b.startsWith(a + "/")) throw new Error(`Nested mount paths are not supported: "${b}" is nested under "${a}"`);
}
/**
* Get all mount paths.
*/
get mountPaths() {
return Array.from(this._mounts.keys());
}
/**
* Get the mounts map.
* Returns a typed map where `get()` preserves the concrete filesystem type per mount path.
*/
get mounts() {
return this._mounts;
}
/**
* Get status and metadata for this composite filesystem.
* Includes info from each mounted filesystem in `metadata.mounts`.
*/
async getInfo() {
const mounts = {};
for (const [mountPath, fs] of this._mounts) mounts[mountPath] = await fs.getInfo?.() ?? null;
return {
id: this.id,
name: this.name,
provider: this.provider,
status: this.status,
readOnly: this.readOnly,
metadata: { mounts }
};
}
/**
* Get the underlying filesystem for a given path.
* Returns undefined if the path doesn't resolve to any mount.
*/
getFilesystemForPath(path) {
return this.resolveMount(path)?.fs;
}
/**
* Get the mount path for a given path.
* Returns undefined if the path doesn't resolve to any mount.
*/
getMountPathForPath(path) {
return this.resolveMount(path)?.mountPath;
}
/**
* Resolve a workspace-relative path to an absolute disk path.
* Strips the mount prefix and delegates to the underlying filesystem.
*/
resolveAbsolutePath(path) {
const r = this.resolveMount(path);
if (!r) return void 0;
return r.fs.resolveAbsolutePath?.(r.fsPath);
}
normalizePath(path) {
if (!path || path === "/" || path === ".") return "/";
let n = path_posix.default.normalize(path);
if (n === ".") return "/";
if (!n.startsWith("/")) n = `/${n}`;
if (n.length > 1 && n.endsWith("/")) n = n.slice(0, -1);
return n;
}
resolveMount(path) {
const normalized = this.normalizePath(path);
let best = null;
for (const [mountPath, fs] of this._mounts) if (normalized === mountPath || normalized.startsWith(mountPath + "/")) {
if (!best || mountPath.length > best.mountPath.length) best = {
mountPath,
fs
};
}
if (!best) return null;
let fsPath = normalized.slice(best.mountPath.length);
if (fsPath === "/") fsPath = "";
else if (fsPath.startsWith("/")) fsPath = fsPath.slice(1);
return {
fs: best.fs,
fsPath,
mountPath: best.mountPath
};
}
getVirtualEntries(path) {
const normalized = this.normalizePath(path);
if (this.resolveMount(normalized)) return null;
const entriesMap = /* @__PURE__ */ new Map();
for (const [mountPath, fs] of this._mounts.entries()) if (normalized === "/" ? mountPath.startsWith("/") : mountPath.startsWith(normalized + "/")) {
const remaining = normalized === "/" ? mountPath.slice(1) : mountPath.slice(normalized.length + 1);
const next = remaining.split("/")[0];
if (next && !entriesMap.has(next)) {
const isDirectMount = remaining === next;
const entry = {
name: next,
type: "directory"
};
if (isDirectMount) entry.mount = {
provider: fs.provider,
icon: fs.icon,
displayName: fs.displayName,
description: fs.description,
status: fs.status,
error: fs.error
};
entriesMap.set(next, entry);
}
}
return entriesMap.size > 0 ? Array.from(entriesMap.values()) : null;
}
isVirtualPath(path) {
const normalized = this.normalizePath(path);
if (normalized === "/" && !this._mounts.has("/")) return true;
for (const mountPath of this._mounts.keys()) if (mountPath.startsWith(normalized + "/")) return true;
return false;
}
/**
* Assert that a filesystem is writable (not read-only).
* @throws {PermissionError} if the filesystem is read-only
*/
assertWritable(fs, path, operation) {
if (fs.readOnly) throw new require_errors.PermissionError(path, `${operation} (filesystem is read-only)`);
}
async init() {
this.status = "initializing";
for (const [mountPath, fs] of this._mounts.entries()) try {
await callLifecycle(fs, "init");
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
console.warn(`[CompositeFilesystem] Mount "${mountPath}" failed to initialize: ${message}`);
}
this.status = "ready";
}
async destroy() {
this.status = "destroying";
const errors = [];
for (const fs of this._mounts.values()) try {
await callLifecycle(fs, "destroy");
} catch (e) {
errors.push(e instanceof Error ? e : new Error(String(e)));
}
if (errors.length > 0) {
this.status = "error";
throw new AggregateError(errors, "Some filesystems failed to destroy");
}
this.status = "destroyed";
}
async readFile(path, options) {
const r = this.resolveMount(path);
if (!r) throw new require_errors.FilesystemError(`No mount for path: ${path}`, "ENOENT", path);
return r.fs.readFile(r.fsPath, options);
}
async writeFile(path, content, options) {
const r = this.resolveMount(path);
if (!r) throw new Error(`No mount for path: ${path}`);
this.assertWritable(r.fs, path, "writeFile");
return r.fs.writeFile(r.fsPath, content, options);
}
async appendFile(path, content) {
const r = this.resolveMount(path);
if (!r) throw new Error(`No mount for path: ${path}`);
this.assertWritable(r.fs, path, "appendFile");
return r.fs.appendFile(r.fsPath, content);
}
async deleteFile(path, options) {
const r = this.resolveMount(path);
if (!r) throw new Error(`No mount for path: ${path}`);
this.assertWritable(r.fs, path, "deleteFile");
return r.fs.deleteFile(r.fsPath, options);
}
async copyFile(src, dest, options) {
const srcR = this.resolveMount(src);
const destR = this.resolveMount(dest);
if (!srcR) throw new Error(`No mount for source: ${src}`);
if (!destR) throw new Error(`No mount for dest: ${dest}`);
this.assertWritable(destR.fs, dest, "copyFile");
if (srcR.mountPath === destR.mountPath) return srcR.fs.copyFile(srcR.fsPath, destR.fsPath, options);
const content = await srcR.fs.readFile(srcR.fsPath);
await destR.fs.writeFile(destR.fsPath, content, { overwrite: options?.overwrite });
}
async moveFile(src, dest, options) {
const srcR = this.resolveMount(src);
const destR = this.resolveMount(dest);
if (!srcR) throw new Error(`No mount for source: ${src}`);
if (!destR) throw new Error(`No mount for dest: ${dest}`);
this.assertWritable(destR.fs, dest, "moveFile");
this.assertWritable(srcR.fs, src, "moveFile");
if (srcR.mountPath === destR.mountPath) return srcR.fs.moveFile(srcR.fsPath, destR.fsPath, options);
await this.copyFile(src, dest, options);
await srcR.fs.deleteFile(srcR.fsPath);
}
async readdir(path, options) {
const virtual = this.getVirtualEntries(path);
if (virtual) return virtual;
const r = this.resolveMount(path);
if (!r) throw new require_errors.FilesystemError(`No mount for path: ${path}`, "ENOENT", path);
return r.fs.readdir(r.fsPath, options);
}
async mkdir(path, options) {
const r = this.resolveMount(path);
if (!r) throw new Error(`No mount for path: ${path}`);
this.assertWritable(r.fs, path, "mkdir");
return r.fs.mkdir(r.fsPath, options);
}
async rmdir(path, options) {
const r = this.resolveMount(path);
if (!r) throw new Error(`No mount for path: ${path}`);
this.assertWritable(r.fs, path, "rmdir");
return r.fs.rmdir(r.fsPath, options);
}
async exists(path) {
if (this.isVirtualPath(path)) return true;
const r = this.resolveMount(path);
if (!r) return false;
if (r.fsPath === "") return true;
return r.fs.exists(r.fsPath);
}
async stat(path) {
const normalized = this.normalizePath(path);
if (this.isVirtualPath(path)) {
const parts = normalized.split("/").filter(Boolean);
const now = /* @__PURE__ */ new Date();
return {
name: parts[parts.length - 1] || "",
path: normalized,
type: "directory",
size: 0,
createdAt: now,
modifiedAt: now
};
}
const r = this.resolveMount(path);
if (!r) throw new require_errors.FilesystemError(`No mount for path: ${path}`, "ENOENT", path);
if (r.fsPath === "") {
const parts = normalized.split("/").filter(Boolean);
const now = /* @__PURE__ */ new Date();
return {
name: parts[parts.length - 1] || "",
path: normalized,
type: "directory",
size: 0,
createdAt: now,
modifiedAt: now
};
}
return r.fs.stat(r.fsPath);
}
async isFile(path) {
if (this.isVirtualPath(path)) return false;
const r = this.resolveMount(path);
if (!r) return false;
try {
return (await r.fs.stat(r.fsPath)).type === "file";
} catch {
return false;
}
}
async isDirectory(path) {
if (this.isVirtualPath(path)) return true;
const r = this.resolveMount(path);
if (!r) return false;
if (r.fsPath === "") return true;
try {
return (await r.fs.stat(r.fsPath)).type === "directory";
} catch {
return false;
}
}
/**
* Get instructions describing the mounted filesystems.
* Used by agents to understand available storage locations.
*/
getInstructions(_opts) {
return `Filesystem mount points:\n${Array.from(this._mounts.entries()).map(([mountPath, fs]) => {
return `- ${mountPath}: ${fs.displayName || fs.provider} ${fs.readOnly ? "(read-only)" : "(read-write)"}`;
}).join("\n")}`;
}
};
// src/workspace/filesystem/mastra-filesystem.ts
/**
* MastraFilesystem Base Class
*
* Abstract base class for filesystem providers that want automatic logger integration
* and lifecycle management.
*
* Extends MastraBase to receive the Mastra logger when registered with a Mastra instance.
*
* ## Lifecycle Management
*
* The base class provides race-condition-safe lifecycle wrappers:
* - `_init()` - Handles concurrent calls, status management
* - `_destroy()` - Handles concurrent calls and status management
*
* Subclasses override the plain `init()` and `destroy()` methods to provide
* their implementation. Callers use the `_`-prefixed wrappers (or `callLifecycle()`)
* which add status tracking and race-condition safety.
*
* External providers can extend this class to get logger support, or implement
* the WorkspaceFilesystem interface directly if they don't need logging.
*/
/**
* Abstract base class for filesystem providers with logger support and lifecycle management.
*
* Providers that extend this class automatically receive the Mastra logger
* when the filesystem is used with a Mastra instance.
*
* @example
* ```typescript
* class MyCustomFilesystem extends MastraFilesystem {
* readonly id = 'my-fs';
* readonly name = 'MyCustomFilesystem';
* readonly provider = 'custom';
* status: ProviderStatus = 'pending';
*
* constructor() {
* super({ name: 'MyCustomFilesystem' });
* }
*
* // Override init() to provide initialization logic
* async init(): Promise<void> {
* // Your initialization logic here
* }
*
* async readFile(path: string): Promise<string | Buffer> {
* await this.ensureReady();
* this.logger.debug('Reading file', { path });
* // Implementation...
* }
* // ... implement other WorkspaceFilesystem methods
* }
* ```
*/
var MastraFilesystem = class extends require_base.MastraBase {
/** Error message when status is 'error' */
error;
/** Promise for _init() to prevent race conditions from concurrent calls */
_initPromise;
/** Promise for _destroy() to prevent race conditions from concurrent calls */
_destroyPromise;
/** Lifecycle callbacks */
_onInit;
_onDestroy;
/** Additional (normalized) text extensions configured for this filesystem */
_textExtensions;
constructor(options) {
super({
name: options.name,
component: require_logger.RegisteredLogger.WORKSPACE
});
this._onInit = options.onInit;
this._onDestroy = options.onDestroy;
this._textExtensions = new Set((options.textExtensions ?? []).map(require_workspace_skills.normalizeTextExtension));
}
/**
* Check if a file should be treated as text, honoring any `textExtensions`
* configured on this filesystem in addition to the built-in set.
*/
isTextFile(filename) {
return require_workspace_skills.isTextFile(filename, this._textExtensions);
}
/**
* Initialize the filesystem (wrapper with status management and race-condition safety).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management automatically.
*
* Subclasses override `init()` to provide their initialization logic.
*/
async _init() {
if (this.status === "ready") return;
if (this._destroyPromise) try {
await this._destroyPromise;
} catch {}
if (this._initPromise) return this._initPromise;
this._initPromise = this._executeInit();
try {
await this._initPromise;
} finally {
this._initPromise = void 0;
}
}
/**
* Internal init execution - handles status.
*/
async _executeInit() {
this.status = "initializing";
this.error = void 0;
try {
await this.init();
this.status = "ready";
try {
await this._onInit?.({ filesystem: this });
} catch (error) {
this.logger.warn("onInit callback failed", { error });
}
} catch (error) {
this.status = "error";
this.error = error instanceof Error ? error.message : String(error);
this.logger.error("Failed to initialize filesystem", {
error,
id: this.id
});
throw error;
}
}
/**
* Override this method to implement filesystem initialization logic.
*
* Called by `_init()` after status is set to 'initializing'.
* Status will be set to 'ready' on success, 'error' on failure.
*
* @example
* ```typescript
* async init(): Promise<void> {
* this._client = new StorageClient({ ... });
* await this._client.connect();
* }
* ```
*/
async init() {}
/**
* Ensure the filesystem is ready.
*
* Calls `_init()` if status is not 'ready'. Useful for lazy initialization
* where operations should automatically initialize the filesystem if needed.
*
* @throws {FilesystemNotReadyError} if the filesystem fails to reach 'ready' status
*
* @example
* ```typescript
* async readFile(path: string): Promise<string | Buffer> {
* await this.ensureReady();
* // Now safe to use the filesystem
* }
* ```
*/
async ensureReady() {
if (this.status !== "ready") await this._init();
if (this.status !== "ready") throw new require_errors.FilesystemNotReadyError(this.id);
}
/**
* Destroy the filesystem and clean up all resources (wrapper with status management).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management.
*
* Subclasses override `destroy()` to provide their destroy logic.
*/
async _destroy() {
if (this.status === "destroyed") return;
if (this.status === "pending") {
this.status = "destroyed";
return;
}
if (this._destroyPromise) return this._destroyPromise;
this._destroyPromise = this._executeDestroy();
try {
await this._destroyPromise;
} finally {
this._destroyPromise = void 0;
}
}
/**
* Internal destroy execution - handles status.
*/
async _executeDestroy() {
if (this._initPromise) try {
await this._initPromise;
} catch {}
this.status = "destroying";
try {
await this._onDestroy?.({ filesystem: this });
await this.destroy();
this.status = "destroyed";
} catch (error) {
this.status = "error";
this.logger.error("Failed to destroy filesystem", {
error,
id: this.id
});
throw error;
}
}
/**
* Override this method to implement filesystem destroy logic.
*
* Called by `_destroy()` after status is set to 'destroying'.
* Status will be set to 'destroyed' on success, 'error' on failure.
*/
async destroy() {}
};
// src/workspace/utils.ts
/**
* Resolve an instructions override against default instructions.
*
* - `undefined` → return default
* - `string` → return the string as-is
* - `function` → call with { defaultInstructions, requestContext }
*/
function resolveInstructions(override, getDefault, requestContext) {
if (typeof override === "string") return override;
const defaultInstructions = getDefault();
if (override === void 0) return defaultInstructions;
return override({
defaultInstructions,
requestContext
});
}
// src/workspace/filesystem/local-filesystem.ts
/**
* Local Filesystem Provider
*
* A filesystem implementation backed by a folder on the local disk.
* This is the default filesystem for development and local agents.
*/
/**
* Stores workspace files in a folder on the host machine for development
* and persistent local storage.
*
* @example
* ```typescript
* import { Workspace, LocalFilesystem } from '@mastra/core/workspace';
*
* const workspace = new Workspace({
* filesystem: new LocalFilesystem({ basePath: './my-workspace' }),
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Local filesystem documentation](https://mastra.ai/reference/workspace/local-filesystem)
* if packaged docs are unavailable.
*/
var LocalFilesystem = class extends MastraFilesystem {
id;
name = "LocalFilesystem";
provider = "local";
readOnly;
status = "pending";
_basePath;
_contained;
_allowedPaths;
_instructionsOverride;
/**
* The absolute base path on disk where files are stored.
* Useful for understanding how workspace paths map to disk paths.
*/
get basePath() {
return this._basePath;
}
/**
* Whether file operations are restricted to stay within basePath.
*
* When `true` (default), relative paths resolve against basePath and
* absolute paths are kept as-is. Any resolved path that falls outside
* basePath (and allowedPaths) throws a PermissionError. When `false`,
* no containment check is applied.
*
* **Note:** When used as a CompositeFilesystem mount with `contained: false`,
* the agent can access any path on the host filesystem through this mount.
*/
get contained() {
return this._contained;
}
/**
* Current set of resolved allowed paths.
* These paths are permitted beyond basePath when containment is enabled.
*/
get allowedPaths() {
return this._allowedPaths;
}
/**
* Update allowed paths. Accepts a direct array or an updater callback
* receiving the current paths (React setState pattern).
*
* @example
* ```typescript
* // Set directly
* fs.setAllowedPaths(['../shared-data']);
*
* // Update with callback
* fs.setAllowedPaths(prev => [...prev, '~/.claude/skills']);
* ```
*/
setAllowedPaths(pathsOrUpdater) {
const newPaths = typeof pathsOrUpdater === "function" ? pathsOrUpdater(this._allowedPaths) : pathsOrUpdater;
this._allowedPaths = newPaths.map((p) => require_workspace_skills.resolveToBasePath(this._basePath, p));
}
constructor(options) {
super({
...options,
name: "LocalFilesystem"
});
this.id = options.id ?? this.generateId();
this._basePath = path.resolve(require_workspace_skills.expandTilde(options.basePath));
this._contained = options.contained ?? true;
this.readOnly = options.readOnly;
this._allowedPaths = (options.allowedPaths ?? []).map((p) => require_workspace_skills.resolveToBasePath(this._basePath, p));
this._instructionsOverride = options.instructions;
}
/**
* Return mount config for sandbox integration.
* LocalSandbox uses this to create a symlink from the mount path to basePath.
*/
getMountConfig() {
return {
type: "local",
basePath: this._basePath
};
}
generateId() {
return `local-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
/**
* Check if an absolute path falls within basePath or any allowed path.
*/
_isWithinRoot(absolutePath, root) {
const relative = path.relative(root, absolutePath);
return !relative.startsWith("..") && !path.isAbsolute(relative);
}
_resolvePathForContainment(absolutePath) {
try {
return fs.realpathSync.native(absolutePath);
} catch (error) {
if (!require_workspace_skills.isEnoentError(error)) throw error;
}
let currentPath = path.parse(absolutePath).root;
const pending = absolutePath.slice(currentPath.length).split(path.sep);
let symlinkDepth = 0;
let currentIsDirectory = true;
while (pending.length > 0) {
const component = pending.shift();
if (!component) continue;
if (currentIsDirectory === false) fs.realpathSync.native(`${currentPath}${path.sep}${component}`);
if (component === ".") continue;
if (component === "..") {
currentPath = path.dirname(currentPath);
currentIsDirectory = void 0;
continue;
}
const candidate = path.join(currentPath, component);
try {
const stat = (0, fs.lstatSync)(candidate);
if (stat.isSymbolicLink()) {
if (++symlinkDepth > 40) return void 0;
const target = (0, fs.readlinkSync)(candidate);
const root = path.parse(target).root;
if (root) currentPath = root;
pending.unshift(...target.slice(root.length).split(path.sep));
currentIsDirectory = void 0;
continue;
}
currentIsDirectory = stat.isDirectory();
currentPath = fs.realpathSync.native(candidate);
continue;
} catch (error) {
if (!require_workspace_skills.isEnoentError(error)) throw error;
currentIsDirectory = void 0;
}
currentPath = candidate;
}
return currentPath;
}
_isWithinAnyRoot(absolutePath) {
const roots = [this._basePath, ...this._allowedPaths];
const resolvedPath = this._resolvePathForContainment(absolutePath);
if (!resolvedPath) return false;
return roots.some((root) => {
const resolvedRoot = this._resolvePathForContainment(root);
return resolvedRoot ? this._isWithinRoot(resolvedPath, resolvedRoot) : false;
});
}
toBuffer(content) {
if (Buffer.isBuffer(content)) return content;
if (content instanceof Uint8Array) return Buffer.from(content);
return Buffer.from(content, "utf-8");
}
resolvePath(inputPath) {
const absolutePath = require_workspace_skills.resolveToBasePath(this._basePath, inputPath);
if (this._contained) {
if (!this._isWithinAnyRoot(absolutePath)) throw new require_errors.PermissionError(inputPath, this._accessOperationHint(inputPath));
}
return absolutePath;
}
/**
* Build the operation string for a containment-violation `PermissionError`.
*
* When the caller passed an absolute path, suggest a concrete relative form
* only when that suffix names an existing entry under the workspace (e.g.
* `/src/app.ts` → `src/app.ts` if `<basePath>/src` exists). Otherwise emit a
* soft hint that doesn't lie about specific paths — agents that mistake `/`
* for the workspace root learn the workspace is sandboxed without us
* inventing a fictitious in-workspace location for `/etc/passwd`.
*/
_accessOperationHint(inputPath) {
if (!path.isAbsolute(inputPath)) return "access";
const stripped = inputPath.replace(/^[/\\]+/, "");
if (!stripped) return "access";
const firstSegment = stripped.split(/[/\\]/, 1)[0];
if (firstSegment && firstSegment !== "." && firstSegment !== "..") try {
if ((0, fs.realpathSync)(path.join(this._basePath, firstSegment))) return `access (path is outside the workspace; use a relative path like "${stripped}")`;
} catch {}
return "access (path is outside the workspace; use a path relative to the workspace root, without a leading \"/\")";
}
/**
* Resolve a workspace-relative path to an absolute disk path.
* Uses the same resolution logic as internal file operations.
* Returns `undefined` if the path violates containment.
*/
resolveAbsolutePath(inputPath) {
try {
return this.resolvePath(inputPath);
} catch {
return;
}
}
toRelativePath(absolutePath) {
return path.relative(this._basePath, absolutePath).replace(/\\/g, "/");
}
assertWritable(operation) {
if (this.readOnly) throw new require_errors.WorkspaceReadOnlyError(operation);
}
/**
* Check canonical roots even when the target does not exist yet: the nearest
* existing ancestor may be a symlink outside the workspace.
*/
async assertPathContained(absolutePath) {
if (this._contained && !this._isWithinAnyRoot(absolutePath)) throw new require_errors.PermissionError(absolutePath, "access");
}
async containedRoots() {
const roots = [];
for (const root of [this._basePath, ...this._allowedPaths]) try {
roots.push(await fs_promises.realpath(root));
} catch (error) {
if (!require_workspace_skills.isEnoentError(error)) throw error;
}
return roots;
}
assertCanonicalPathContained(canonicalPath, absolutePath, roots) {
if (!roots.some((root) => this._isWithinRoot(canonicalPath, root))) throw new require_errors.PermissionError(absolutePath, "access");
}
async openContainedPath(absolutePath, metadataOnly = false) {
const roots = await this.containedRoots();
const checkedPath = await fs_promises.realpath(absolutePath);
this.assertCanonicalPathContained(checkedPath, absolutePath, roots);
const flags = metadataOnly ? process.platform === "linux" ? 2097152 : fs.constants.O_RDONLY | fs.constants.O_NONBLOCK : "r";
const handle = await fs_promises.open(absolutePath, flags);
try {
const opened = await handle.stat({ bigint: true });
const canonicalPath = await fs_promises.realpath(absolutePath);
this.assertCanonicalPathContained(canonicalPath, absolutePath, roots);
const current = await fs_promises.stat(canonicalPath, { bigint: true });
if (opened.dev === 0n || opened.ino === 0n || current.dev === 0n || current.ino === 0n || opened.dev !== current.dev || opened.ino !== current.ino) throw new require_errors.PermissionError(absolutePath, "access");
return {
handle,
canonicalPath
};
} catch (error) {
await handle.close();
throw error;
}
}
async readFile(inputPath, options) {
this.logger.debug("Reading file", {
path: inputPath,
encoding: options?.encoding
});
await this.ensureReady();
const absolutePath = this.resolvePath(inputPath);
try {
if (this._contained) {
const { handle } = await this.openContainedPath(absolutePath);
try {
if ((await handle.stat()).isDirectory()) throw new require_errors.IsDirectoryError(inputPath);
return options?.encoding ? await handle.readFile({ encoding: options.encoding }) : await handle.readFile();
} finally {
await handle.close();
}
}
if ((await fs_promises.stat(absolutePath)).isDirectory()) throw new require_errors.IsDirectoryError(inputPath);
return options?.encoding ? await fs_promises.readFile(absolutePath, { encoding: options.encoding }) : await fs_promises.readFile(absolutePath);
} catch (error) {
if (error instanceof require_errors.IsDirectoryError) throw error;
if (require_workspace_skills.isEnoentError(error)) throw new require_errors.FileNotFoundError(inputPath);
throw error;
}
}
async writeFile(inputPath, content, options) {
const contentSize = Buffer.isBuffer(content) ? content.length : content.length;
this.logger.debug("Writing file", {
path: inputPath,
size: contentSize,
recursive: options?.recursive
});
await this.ensureReady();
this.assertWritable("writeFile");
const absolutePath = this.resolvePath(inputPath);
await this.assertPathContained(absolutePath);
if (options?.recursive === false) {
const dir = path.dirname(absolutePath);
const parentPath = path.dirname(inputPath);
try {
if (!(await fs_promises.stat(dir)).isDirectory()) throw new require_errors.NotDirectoryError(parentPath);
} catch (error) {
if (error instanceof require_errors.NotDirectoryError) throw error;
if (require_workspace_skills.isEnoentError(error)) throw new require_errors.DirectoryNotFoundError(parentPath);
throw error;
}
}
if (options?.recursive !== false) {
const dir = path.dirname(absolutePath);
await fs_promises.mkdir(dir, { recursive: true });
}
if (options?.expectedMtime) try {
const currentStat = await fs_promises.stat(absolutePath);
if (currentStat.mtime.getTime() !== options.expectedMtime.getTime()) throw new require_errors.StaleFileError(inputPath, options.expectedMtime, currentStat.mtime);
} catch (error) {
if (error instanceof require_errors.StaleFileError) throw error;
if (!require_workspace_skills.isEnoentError(error)) throw error;
}
const writeFlag = options?.overwrite === false ? "wx" : "w";
try {
await fs_promises.writeFile(absolutePath, this.toBuffer(content), { flag: writeFlag });
} catch (error) {
if (options?.overwrite === false && require_workspace_skills.isEexistError(error)) throw new require_errors.FileExistsError(inputPath);
throw error;
}
}
async appendFile(inputPath, content) {
const contentSize = Buffer.isBuffer(content) ? content.length : content.length;
this.logger.debug("Appending to file", {
path: inputPath,
size: contentSize
});
await this.ensureReady();
this.assertWritable("appendFile");
const absolutePath = this.resolvePath(inputPath);
await this.assertPathContained(absolutePath);
const dir = path.dirname(absolutePath);
await fs_promises.mkdir(dir, { recursive: true });
await fs_promises.appendFile(absolutePath, this.toBuffer(content));
}
async deleteFile(inputPath, options) {
this.logger.debug("Deleting file", {
path: inputPath,
force: options?.force
});
await this.ensureReady();
this.assertWritable("deleteFile");
const absolutePath = this.resolvePath(inputPath);
await this.assertPathContained(absolutePath);
try {
if ((await fs_promises.stat(absolutePath)).isDirectory()) throw new require_errors.IsDirectoryError(inputPath);
await fs_promises.unlink(absolutePath);
} catch (error) {
if (error instanceof require_errors.IsDirectoryError) throw error;
if (require_workspace_skills.isEnoentError(error)) {
if (!options?.force) throw new require_errors.FileNotFoundError(inputPath);
} else throw error;
}
}
async copyFile(src, dest, options) {
this.logger.debug("Copying file", {
src,
dest,
recursive: options?.recursive
});
await this.ensureReady();
this.assertWritable("copyFile");
const srcPath = this.resolvePath(src);
const destPath = this.resolvePath(dest);
await this.assertPathContained(srcPath);
await this.assertPathContained(destPath);
try {
if ((await fs_promises.stat(srcPath)).isDirectory()) {
if (!options?.recursive) throw new require_errors.IsDirectoryError(src);
await this.copyDirectory(srcPath, destPath, options);
} else {
await fs_promises.mkdir(path.dirname(destPath), { recursive: true });
const copyFlags = options?.overwrite === false ? fs.constants.COPYFILE_EXCL : 0;
try {
await fs_promises.copyFile(srcPath, destPath, copyFlags);
} catch (error) {
if (options?.overwrite === false && require_workspace_skills.isEexistError(error)) throw new require_errors.FileExistsError(dest);
throw error;
}
}
} catch (error) {
if (error instanceof require_errors.IsDirectoryError || error instanceof require_errors.FileExistsError) throw error;
if (require_workspace_skills.isEnoentError(error)) throw new require_errors.FileNotFoundError(src);
throw error;
}
}
async copyDirectory(src, dest, options) {
await this.ensureReady();
await fs_promises.mkdir(dest, { recursive: true });
const entries = await fs_promises.readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcEntry = path.join(src, entry.name);
const destEntry = path.join(dest, entry.name);
await this.assertPathContained(srcEntry);
await this.assertPathContained(destEntry);
if (entry.isDirectory()) await this.copyDirectory(srcEntry, destEntry, options);
else {
const copyFlags = options?.overwrite === false ? fs.constants.COPYFILE_EXCL : 0;
try {
await fs_promises.copyFile(srcEntry, destEntry, copyFlags);
} catch (error) {
if (options?.overwrite === false && require_workspace_skills.isEexistError(error)) continue;
throw error;
}
}
}
}
async moveFile(src, dest, options) {
this.logger.debug("Moving file", {
src,
dest,
overwrite: options?.overwrite
});
await this.ensureReady();
this.assertWritable("moveFile");
const srcPath = this.resolvePath(src);
const destPath = this.resolvePath(dest);
await this.assertPathContained(srcPath);
await this.assertPathContained(destPath);
try {
await fs_promises.mkdir(path.dirname(destPath), { recursive: true });
if (options?.overwrite === false) {
await this.copyFile(src, dest, {
...options,
overwrite: false
});
await fs_promises.rm(srcPath, {
recursive: true,
force: true
});
return;
}
try {
await fs_promises.rename(srcPath, destPath);
} catch (error) {
if (error.code !== "EXDEV") throw error;
await this.copyFile(src, dest, options);
await fs_promises.rm(srcPath, {
recursive: true,
force: true
});
}
} catch (error) {
if (error instanceof require_errors.FileExistsError) throw error;
if (require_workspace_skills.isEnoentError(error)) throw new require_errors.FileNotFoundError(src);
throw error;
}
}
async mkdir(inputPath, options) {
this.logger.debug("Creating directory", {
path: inputPath,
recursive: options?.recursive
});
await this.ensureReady();
this.assertWritable("mkdir");
const absolutePath = this.resolvePath(inputPath);
await this.assertPathContained(absolutePath);
try {
await fs_promises.mkdir(absolutePath, { recursive: options?.recursive ?? true });
} catch (error) {
if (require_workspace_skills.isEexistError(error)) {
if (!(await fs_promises.stat(absolutePath)).isDirectory()) throw new require_errors.FileExistsError(inputPath);
} else if (require_workspace_skills.isEnoentError(error)) {
const parentPath = path.dirname(inputPath);
throw new require_errors.DirectoryNotFoundError(parentPath);
} else throw error;
}
}
async rmdir(inputPath, options) {
this.logger.debug("Removing directory", {
path: inputPath,
recursive: options?.recursive,
force: options?.force
});
await this.ensureReady();
this.assertWritable("rmdir");
const absolutePath = this.resolvePath(inputPath);
await this.assertPathContained(absolutePath);
try {
if (!(await fs_promises.stat(absolutePath)).isDirectory()) throw new require_errors.NotDirectoryError(inputPath);
if (options?.recursive) await fs_promises.rm(absolutePath, {
recursive: true,
force: options?.force ?? false
});
else {
if ((await fs_promises.readdir(absolutePath)).length > 0) throw new require_errors.DirectoryNotEmptyError(inputPath);
await fs_promises.rmdir(absolutePath);
}
} catch (error) {
if (error instanceof require_errors.NotDirectoryError || error instanceof require_errors.DirectoryNotEmptyError) throw error;
if (require_workspace_skills.isEnoentError(error)) {
if (!options?.force) throw new require_errors.DirectoryNotFoundError(inputPath);
} else throw error;
}
}
async readdir(inputPath, options) {
this.logger.debug("Reading directory", {
path: inputPath,
recursive: options?.recursive
});
await this.ensureReady();
const absolutePath = this.resolvePath(inputPath);
let directoryHandle;
try {
if (this._contained) directoryHandle = (await this.openContainedPath(absolutePath)).handle;
const stats = directoryHandle ? await directoryHandle.stat({ bigint: true }) : await fs_promises.stat(absolutePath, { bigint: true });
if (!stats.isDirectory()) throw new require_errors.NotDirectoryError(inputPath);
const directoryPath = directoryHandle && process.platform === "linux" ? `/proc/self/fd/${directoryHandle.fd}` : absolutePath;
const entries = await fs_promises.readdir(directoryPath, { withFileTypes: true });
const result = [];
for (const entry of entries) {
const entryPath = path.join(absolutePath, entry.name);
const entryDiskPath = path.join(directoryPath, entry.name);
if (options?.extension) {
const extensions = Array.isArray(options.extension) ? options.extension : [options.extension];
if (entry.isFile()) {
const ext = path.extname(entry.name);
if (!extensions.some((e) => e === ext || e === ext.slice(1))) continue;
}
}
const isSymlink = entry.isSymbolicLink();
let symlinkTarget;
let resolvedType = "file";
if (isSymlink) try {
symlinkTarget = await fs_promises.readlink(entryDiskPath);
resolvedType = (await fs_promises.stat(entryDiskPath)).isDirectory() ? "directory" : "file";
} catch {
resolvedType = "file";
}
else resolvedType = entry.isDirectory() ? "directory" : "file";
const fileEntry = {
name: entry.name,
type: resolvedType,
isSymlink: isSymlink || void 0,
symlinkTarget
};
if (resolvedType === "file" && !isSymlink) try {
fileEntry.size = (await fs_promises.stat(entryDiskPath)).size;
} catch {}
result.push(fileEntry);
if (options?.recursive && resolvedType === "directory") {
const depth = options.maxDepth ?? 100;
if (depth > 0) {
const subEntries = await this.readdir(this.toRelativePath(entryPath), {
...options,
maxDepth: depth - 1
});
result.push(...subEntries.map((e) => ({
...e,
name: `${entry.name}/${e.name}`
})));
}
}
}
if (directoryHandle && directoryPath === absolutePath) {
const current = await this.openContainedPath(absolutePath);
try {
const currentStat = await current.handle.stat({ bigint: true });
if (stats.dev === 0n || stats.ino === 0n || currentStat.dev === 0n || currentStat.ino === 0n || stats.dev !== currentStat.dev || stats.ino !== currentStat.ino) throw new require_errors.PermissionError(absolutePath, "access");
} finally {
await current.handle.close();
}
}
return result;
} catch (error) {
if (error instanceof require_errors.NotDirectoryError) throw error;
if (require_workspace_skills.isEnoentError(error)) throw new require_errors.DirectoryNotFoundError(inputPath);
throw error;
} finally {
await directoryHandle?.close();
}
}
async containedMetadata(absolutePath) {
if (process.platform === "linux") {
const { handle } = await this.openContainedPath(absolutePath, true);
try {
return await handle.stat();
} finally {
await handle.close();
}
}
try {
const { handle } = await this.openContainedPath(absolutePath, true);
try {
return await handle.stat();
} finally {
await handle.close();
}
} catch (error) {
if (!(error instanceof Error) || !("code" in error) || error.code !== "EACCES") throw error;
const roots = await this.containedRoots();
const before = await fs_promises.realpath(absolutePath);
this.assertCanonicalPathContained(before, absolutePath, roots);
const stats = await fs_promises.stat(absolutePath);
const after = await fs_promises.realpath(absolutePath);
this.assertCanonicalPathContained(after, absolutePath, roots);
const current = await fs_promises.stat(after, { bigint: true });
if (before !== after || !Number.isSafeInteger(stats.dev) || !Number.isSafeInteger(stats.ino) || current.dev === 0n || current.ino === 0n || BigInt(stats.dev) !== current.dev || BigInt(stats.ino) !== current.ino) throw new require_errors.PermissionError(absolutePath, "access");
return stats;
}
}
async exists(inputPath) {
await this.ensureReady();
const absolutePath = this.resolvePath(inputPath);
if (!this._contained) return require_workspace_skills.fsExists(absolutePath);
try {
await this.containedMetadata(absolutePath);
return true;
} catch (error) {
if (require_workspace_skills.isEnoentError(error)) return false;
throw error;
}
}
async stat(inputPath) {
await this.ensureReady();
const absolutePath = this.resolvePath(inputPath);
if (!this._contained) return {
...await require_workspace_skills.fsStat(absolutePath, inputPath),
path: this.toRelativePath(absolutePath)
};
try {
const stats = await this.containedMetadata(absolutePath);
return {
name: path.basename(absolutePath),
path: this.toRelativePath(absolutePath),
type: stats.isDirectory() ? "directory" : "file",
size: stats.size,
createdAt: stats.birthtime,
modifiedAt: stats.mtime,
mimeType: stats.isFile() ? require_workspace_skills.getMimeType(absolutePath) : void 0
};
} catch (error) {
if (require_workspace_skills.isEnoentError(error)) throw new require_errors.FileNotFoundError(inputPath);
throw error;
}
}
async realpath(inputPath) {
await this.ensureReady();
const absolutePath = this.resolvePath(inputPath);
if (!this._contained) return this.toRelativePath(await fs_promises.realpath(absolutePath));
const { handle, canonicalPath } = await this.openContainedPath(absolutePath, true);
await handle.close();
return this.toRelativePath(canonicalPath);
}
/**
* Initialize the local filesystem by creating the base directory.
* Status management is handled by the base class.
*/
async init() {
this.logger.debug("Initializing filesystem", { basePath: this._basePath });
await fs_promises.mkdir(this._basePath, { recursive: true });
this.logger.debug("Filesystem initialized", { basePath: this._basePath });
}
/**
* Clean up the local filesystem.
* LocalFilesystem doesn't delete files on destroy by default.
* Status management is handled by the base class.
*/
async destroy() {}
getInfo() {
return {
id: this.id,
name: this.name,
provider: this.provider,
readOnly: this.readOnly,
status: this.status,
error: this.error,
metadata: {
basePath: this.basePath,
contained: this._contained,
...this._allowedPaths.length > 0 && { allowedPaths: [...this._allowedPaths] }
}
};
}
getInstructions(opts) {
return resolveInstructions(this._instructionsOverride, () => this._getDefaultInstructions(), opts?.requestContext);
}
_getDefaultInstructions() {
const parts = [`Local filesystem at "${this.basePath}". Relative paths resolve from this directory.`];
if (this._contained) {
if (this._allowedPaths.length > 0) parts.push(`File access is restricted to this directory and the following allowed paths: ${this._allowedPaths.join(", ")}.`);
else parts.push("File access is restricted to this directory.");
} else parts.push("Containment is disabled, so any path on the host filesystem is accessible.");
return parts.join(" ");
}
};
// src/workspace/filesystem/file-read-tracker.ts
/**
* Derive a stable read-record scope for a filesystem from its configuration.
*
* The scope identifies the *backing file store*, not the object instance:
* two `LocalFilesystem` instances with the same `basePath` point at the same
* files and must share read records (suspend/resume creates fresh instances),
* while different base paths are different files and must not. Instance ids
* (`filesystem.id`, `workspace.id`) are auto-generated per construction and
* would break record persistence across resume for dynamically resolved
* workspaces — so the scope is derived from `provider` + `basePath` instead.
*
* Filesystems without a `basePath` (e.g. in-memory or composite filesystems)
* fall back to the bare provider string. That is deliberately coarse:
* same-provider filesystems share records, which matches the pre-scoping
* behavior and is still guarded by the mtime staleness check. Per-mount scope
* routing for CompositeFilesystem is a possible follow-up.
*/
function deriveReadScope(fs) {
return fs.basePath ? `${fs.provider}:${fs.basePath}` : fs.provider;
}
/**
* Normalize a path for read-record keying: unify separators, resolve dot
* segments, remove trailing slash. Shared by all FileReadTracker
* implementations so records key identically regardless of backing store.
*/
function normalizeReadTrackerPath(pathStr) {
return path.posix.normalize(pathStr.replace(/\\/g, "/")).replace(/\/$/, "") || "/";
}
/**
* Evaluate whether a file needs re-reading given its read record (if any) and
* its current modification time. Shared by all FileReadTracker implementations
* so the policy semantics and error messages stay identical.
*/
function evaluateReadRecord(path, record, currentModifiedAt, scope) {
if (!record) return {
needsReRead: true,
reason: `File "${path}" has not been read. You must read a file before writing to it.`
};
if (record.scope !== scope) return {
needsReRead: true,
reason: `File "${path}" was read in a different filesystem. You must read a file before writing to it.`
};
if (currentModifiedAt.getTime() > record.modifiedAtRead.getTime()) return {
needsReRead: true,
reason: `File "${path}" was modified since last read (read at: ${record.modifiedAtRead.toISOString()}, current: ${currentModifiedAt.toISOString()}). Please re-read the file to get the latest contents.`
};
return { needsReRead: false };
}
/**
* In-memory implementation of FileReadTracker.
*/
var InMemoryFileReadTracker = class {
records = /* @__PURE__ */ new Map();
recordRead(path, modifiedAt, scope) {
const normalizedPath = normalizeReadTrackerPath(path);
this.records.set(normalizedPath, {
path: normalizedPath,
readAt: /* @__PURE__ */ new Date(),
modifiedAtRead: modifiedAt,
scope
});
}
getReadRecord(path) {
return this.records.get(normalizeReadTrackerPath(path));
}
needsReRead(path, currentModifiedAt, scope) {
return evaluateReadRecord(path, this.getReadRecord(path), currentModifiedAt, scope);
}
clearReadRecord(path) {
this.records.delete(normalizeReadTrackerPath(path));
}
clear() {
this.records.clear();
}
};
// src/workspace/filesystem/file-write-lock.ts
/**
* In-memory implementation of FileWriteLock using per-path promise queues.
*
* Adapted from mastracode's `withWriteLock` pattern.
*/
var InMemoryFileWriteLock = class {
queues = /* @__PURE__ */ new Map();
timeoutMs;
constructor(opts) {
this.timeoutMs = opts?.timeoutMs ?? 3e4;
}
get size() {
return this.queues.size;
}
withLock(filePath, fn) {
const key = this.normalizePath(filePath);
const currentQueue = this.queues.get(key) ?? Promise.resolve();
let resolve;
let reject;
const resultPromise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const queuePromise = currentQueue.catch(() => {}).then(async () => {
let timeoutId;
try {
const result = await Promise.race([fn(), new Promise((_, rej) => {
timeoutId = setTimeout(() => rej(/* @__PURE__ */ new Error(`write-lock timeout on "${key}" after ${this.timeoutMs}ms`)), this.timeoutMs);
})]);
clearTimeout(timeoutId);
resolve(result);
} catch (error) {
clearTimeout(timeoutId);
reject(error);
}
});
this.queues.set(key, queuePromise);
queuePromise.finally(() => {
if (this.queues.get(key) === queuePromise) this.queues.delete(key);
});
return resultPromise;
}
normalizePath(pathStr) {
return path.posix.normalize(pathStr.replace(/\\/g, "/").replace(/^\/\/+/, "/")).replace(/\/+$/, "") || "/";
}
};
// src/workspace/sandbox/errors.ts
var SandboxError = class extends Error {
code;
details;
constructor(message, code, details) {
super(message);
this.code = code;
this.details = details;
this.name = "SandboxError";
}
};
var SandboxExecutionError = class extends SandboxError {
exitCode;
stdout;
stderr;
constructor(message, exitCode, stdout, stderr) {
super(message, "EXECUTION_FAILED", {
exitCode,
stdout,
stderr
});
this.exitCode = exitCode;
this.stdout = stdout;
this.stderr = stderr;
this.name = "SandboxExecutionError";
}
};
var SandboxTimeoutError = class extends SandboxError {
timeoutMs;
operation;
constructor(timeoutMs, operation) {
super(`Execution timed out after ${timeoutMs}ms`, "TIMEOUT", {
timeoutMs,
operation
});
this.timeoutMs = timeoutMs;
this.operation = operation;
this.name = "SandboxTimeoutError";
}
};
var SandboxNotReadyError = class extends SandboxError {
constructor(idOrStatus) {
super(`Sandbox is not ready: ${idOrStatus}`, "NOT_READY", { id: idOrStatus });
this.name = "SandboxNotReadyError";
}
};
/**
* Thrown when a caller requests a sandbox feature that the active provider
* cannot honor (e.g. an explicit per-file permission mode on a provider whose
* upload mechanism does not support one).
*/
var SandboxUnsupportedFeatureError = class extends SandboxError {
constructor(message, details) {
super(message, "UNSUPPORTED_FEATURE", details);
this.name = "SandboxUnsupportedFeatureError";
}
};
/**
* Thrown when a sandbox operation is cancelled via an {@link AbortSignal}.
* Carries a stable `code` of `ABORTED` so callers can reliably detect cancellation.
*/
var SandboxAbortError = class extends SandboxError {
constructor(operation = "operation", reason) {
super(`Sandbox operation aborted: ${operation}`, "ABORTED", {
operation,
reason
});
this.name = "SandboxAbortError";
this.cause = reason;
}
};
var IsolationUnavailableError = class extends SandboxError {
backend;
reason;
constructor(backend, reason) {
super(`Isolation backend '${backend}' is not available: ${reason}`, "ISOLATION_UNAVAILABLE", {
backend,
reason
});
this.backend = backend;
this.reason = reason;
this.name = "IsolationUnavailableError";
}
};
/**
* Base error for mount operations.
*/
var MountError = class extends SandboxError {
mountPath;
constructor(message, mountPath, details) {
super(message, "MOUNT_ERROR", {
...details,
mountPath
});
this.mountPath = mountPath;
this.name = "MountError";
}
};
/**
* Error thrown when sandbox doesn't support mounting.
*/
var MountNotSupportedError = class extends SandboxError {
constructor(sandboxProvider) {
super(`Sandbox provider '${sandboxProvider}' does not support mounting`, "MOUNT_NOT_SUPPORTED", { sandboxProvider });
this.name = "MountNotSupportedError";
}
};
/**
* Error thrown when a filesystem cannot be mounted.
*/
var FilesystemNotMountableError = class extends SandboxError {
constructor(filesystemProvider, reason) {
const message = reason ? `Filesystem '${filesystemProvider}' cannot be mounted: ${reason}` : `Filesystem '${filesystemProvider}' does not support mounting`;
super(message, "FILESYSTEM_NOT_MOUNTABLE", {
filesystemProvider,
reason
});
this.name = "FilesystemNotMountableError";
}
};
// src/workspace/sandbox/mounts/types.ts
/**
* Error thrown when a required FUSE tool (s3fs, gcsfuse, macFUSE) is not installed.
*
* Distinguished from general mount errors so `LocalSandbox.mount()` can mark the
* mount as `unavailable` (warning) rather than `error`. The workspace still works
* via SDK filesystem methods — only sandbox process access to the mount path is affected.
*/
var MountToolNotFoundError = class extends Error {
constructor(message) {
super(message);
this.name = "MountToolNotFoundError";
}
};
// src/workspace/sandbox/mount-manager.ts
/**
* Mount Manager
*
* Encapsulates all mount-related state and operations for sandboxes.
* Used by BaseSandbox to manage filesystem mounts.
*/
/**
* Manages filesystem mounts for a sandbox.
*
* Provides methods for tracking mount state, updating entries,
* and processing pending mounts.
*/
var MountManager = class {
_entries = /* @__PURE__ */ new Map();
_mountFn;
_onMount;
_sandbox;
_workspace;
logger;
constructor(config) {
this._mountFn = config.mount;
this.logger = config.logger;
}
/**
* Set the sandbox and workspace references for onMount hook args.
* Called by Workspace during construction.
*/
setContext(context) {
this._sandbox = context.sandbox;
this._workspace = context.workspace;
}
/**
* Set the onMount hook for custom mount handling.
* Called before each mount - can skip, handle, or defer to default.
*/
setOnMount(hook) {
this._onMount = hook;
}
/**
* Update the logger instance.
* Called when the sandbox receives a logger from Mastra.
* @internal
*/
__setLogger(logger) {
this.logger = logger;
}
/**
* Get all mount entries.
*/
get entries() {
return this._entries;
}
/**
* Get a mount entry by path.
*/
get(path) {
return this._entries.get(path);
}
/**
* Check if a mount exists at the given path.
*/
has(path) {
return this._entries.has(path);
}
/**
* Add pending mounts from workspace config.
* These will be processed when `processPending()` is called.
*/
add(mounts) {
const paths = Object.keys(mounts);
this.logger.debug("Adding pending mounts", {
count: paths.length,
paths
});
for (const [path, filesystem] of Object.entries(mounts)) this._entries.set(path, {
filesystem,
state: "pending"
});
}
/**
* Update a mount entry's state.
* Creates the entry if it doesn't exist.
*/
set(path, updates) {
const existing = this._entries.get(path);
if (existing) {
existing.state = updates.state;
if (updates.config) {
existing.config = updates.config;
existing.configHash = this.hashConfig(updates.config);
}
if ("error" in updates) existing.error = updates.error;
} else if (updates.filesystem) this._entries.set(path, {
filesystem: updates.filesystem,
state: updates.state,
config: updates.config,
configHash: updates.config ? this.hashConfig(updates.config) : void 0,
error: updates.error
});
else this.logger.debug("set() called for unknown path without filesystem", { path });
}
/**
* Delete a mount entry.
*/
delete(path) {
return this._entries.delete(path);
}
/**
* Clear all mount entries.
*/
clear() {
this._entries.clear();
}
/**
* Process all pending mounts.
* Call this after sandbox is ready (in start()).
*/
async processPending() {
const pendingCount = [...this._entries.values()].filter((e) => e.state === "pending").length;
if (pendingCount === 0) return;
this.logger.debug("Processing pending mounts", { count: pendingCount });
for (const [path, entry] of this._entries) {
if (entry.state !== "pending") continue;
const fsProvider = entry.filesystem.provider;
const config = entry.filesystem.getMountConfig?.();
if (this._onMount) try {
const hookResult = await this._onMount({
filesystem: entry.filesystem,
mountPath: path,
config,
sandbox: this._sandbox,
workspace: this._workspace
});
if (hookResult === false) {
entry.state = "unsupported";
entry.error = "Skipped by onMount hook";
this.logger.debug("Mount skipped by onMount hook", {
path,
provider: fsProvider
});
continue;
}
if (hookResult && typeof hookResult === "object") {
if (hookResult.success) {
entry.state = "mounted";
entry.config = config;
entry.configHash = config ? this.hashConfig(config) : void 0;
this.logger.info("Mount handled by onMount hook", {
path,
provider: fsProvider
});
} else {
entry.state = "error";
entry.error = hookResult.error ?? "Mount hook failed";
this.logger.error("Mount hook failed", {
path,
provider: fsProvider,
error: entry.error
});
}
continue;
}
} catch (err) {
entry.state = "error";
entry.error = `Mount hook error: ${String(err)}`;
this.logger.error("Mount hook threw error", {
path,
provider: fsProvider,
error: entry.error
});
continue;
}
if (!config) {
entry.state = "unsupported";
entry.error = "Filesystem does not support mounting";
this.logger.debug("Filesystem does not support mounting", {
path,
provider: fsProvider
});
continue;
}
entry.config = config;
entry.configHash = this.hashConfig(config);
entry.state = "mounting";
this.logger.debug("Mounting filesystem", {
path,
provider: fsProvider,
type: config.type
});
try {
const result = await this._mountFn(entry.filesystem, path);
if (result.success) {
entry.state = "mounted";
this.logger.info("Mount successful", {
path,
provider: fsProvider
});
} else if (result.unavailable) {
entry.state = "unavailable";
entry.error = result.error ?? "FUSE tool not installed";
this.logger.warn("FUSE mount unavailable", {
path,
provider: fsProvider,
error: entry.error
});
} else {
entry.state = "error";
entry.error = result.error ?? "Mount failed";
this.logger.error("Mount failed", {
path,
provider: fsProvider,
error: entry.error
});
}
} catch (err) {
if (err instanceof MountToolNotFoundError) {
entry.state = "unavailable";
entry.error = String(err);
this.logger.warn("FUSE mount unavailable", {
path,
provider: fsProvider,
error: entry.error
});
} else {
entry.state = "error";
entry.error = String(err);
this.logger.error("Mount threw error", {
path,
provider: fsProvider,
error: entry.error
});
}
}
}
}
/**
* Generate a marker filename for a mount path.
* Used by sandboxes to store mount metadata for reconnection detection.
*
* @param mountPath - The mount path to generate a filename for
* @returns A safe filename like "mount-abc123"
*/
markerFilename(mountPath) {
let hash = 0;
for (let i = 0; i < mountPath.length; i++) {
const char = mountPath.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash |= 0;
}
return `mount-${Math.abs(hash).toString(36)}`;
}
/**
* Generate marker file content for a mount path.
* Format: "path|configHash" - used for detecting config changes on reconnect.
*
* @param mountPath - The mount path
* @returns Marker content string, or null if no config hash available
*/
getMarkerContent(mountPath) {
const entry = this._entries.get(mountPath);
if (!entry?.configHash) return null;
return `${mountPath}|${entry.configHash}`;
}
/**
* Parse marker file content.
*
* @param content - The marker file content (format: "path|configHash")
* @returns Parsed path and configHash, or null if invalid format
*/
parseMarkerContent(content) {
const separatorIndex = content.lastIndexOf("|");
if (separatorIndex <= 0) return null;
const path = content.slice(0, separatorIndex);
const configHash = content.slice(separatorIndex + 1);
if (!path || !configHash) return null;
return {
path,
configHash
};
}
/**
* Check if a config hash matches the expected hash for a mount path.
*
* @param mountPath - The mount path to check
* @param storedHash - The hash from the marker file
* @returns true if the hashes match
*/
isConfigMatching(mountPath, storedHash) {
return this._entries.get(mountPath)?.configHash === storedHash;
}
/**
* Compute a hash for a mount config. Used for comparing configs across mounts.
*
* @param config - The config to hash
* @returns A hash string suitable for comparison
*/
computeConfigHash(config) {
return this.hashConfig(config);
}
/**
* Hash a mount config for comparison.
*/
hashConfig(config) {
const normalized = JSON.stringify(this.sortKeysDeep(config));
return (0, crypto.createHash)("sha256").update(normalized).digest("hex").slice(0, 16);
}
sortKeysDeep(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map((item) => this.sortKeysDeep(item));
return Object.keys(obj).sort().reduce((acc, key) => {
acc[key] = this.sortKeysDeep(obj[key]);
return acc;
}, {});
}
};
/** Maximum permitted {@link SandboxFileInput.mode} value (permission bits only). */
const MAX_SANDBOX_FILE_MODE = 511;
/**
* Validate an explicit {@link SandboxFileInput.mode} value.
*
* @throws {SandboxError} with code `INVALID_ARGUMENT` if the mode is not an
* integer in the range `0o001`–`0o777`.
*/
function validateSandboxFileMode(mode) {
if (!Number.isInteger(mode) || mode < 1 || mode > 511) throw new SandboxError(`Invalid file mode ${mode}: must be an integer between 0o001 (1) and 0o777 (511).`, "INVALID_ARGUMENT", { mode });
}
/**
* Assert that no file in the list requests an explicit permission mode.
*
* Used by providers whose upload mechanism cannot honor a mode, so that an
* explicit mode is rejected rather than silently discarded.
*
* @throws {SandboxUnsupportedFeatureError} if any file specifies a `mode`.
*/
function assertModesUnsupported(files, provider) {
if (files.some((f) => f.mode !== void 0)) throw new SandboxUnsupportedFeatureError(`The ${provider} sandbox does not support per-file permission modes in writeFiles(). Omit 'mode' to use the provider default.`, { provider });
}
/**
* Type guard: does this sandbox support the networking capability?
*
* @example
* ```typescript
* if (supportsNetworking(sandbox)) {
* const url = await sandbox.networking.getPortUrl(4111);
* }
* ```
*/
function supportsNetworking(sandbox) {
return typeof sandbox.networking?.getPortUrl === "function";
}
/**
* Type guard: does this sandbox support the computer-use (desktop) capability?
*
* @example
* ```typescript
* if (supportsComputer(sandbox)) {
* const { data } = await sandbox.computer.screenshot();
* }
* ```
*/
function supportsComputer(sandbox) {
const computer = sandbox.computer;
return typeof computer?.screenshot === "function" && typeof computer.leftClick === "function" && typeof computer.rightClick === "function" && typeof computer.doubleClick === "function" && typeof computer.moveMouse === "function" && typeof computer.drag === "function" && typeof computer.scroll === "function" && typeof computer.type === "function" && typeof computer.press === "function" && typeof computer.getScreenSize === "function" && typeof computer.getCursorPosition === "function";
}
// src/workspace/sandbox/process-manager/process-handle.ts
/**
* Process Handle (Base Class)
*
* Abstract base class for process handles.
* Manages stdout/stderr callback dispatch and provides lazy
* reader/writer stream getters — subclasses only implement
* the platform-specific primitives.
*/
const DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES = 1048576;
/**
* Most output one stream can retain, even with `maxRetainedBytes: Infinity`.
* Retained chunks are joined into one string, and V8 throws `RangeError: Invalid string length`
* past ~512 Mi UTF-16 code units. A string never has more code units than UTF-8 bytes, so
* 256 MiB keeps the join well inside that limit.
*/
const MAX_RETAINED_PROCESS_OUTPUT_BYTES = 268435456;
/**
* A process asked to keep all of its output (`maxRetainedBytes` above
* {@link MAX_RETAINED_PROCESS_OUTPUT_BYTES}, e.g. Infinity) produced more than can be held.
* The process is killed and `wait()` rejects with this error rather than returning partial output.
*/
var ProcessOutputLimitError = class extends Error {
stream;
limitBytes;
name = "ProcessOutputLimitError";
constructor(stream, limitBytes) {
super(`Process ${stream} exceeded ${limitBytes} bytes, the most output that can be retained in full; the process was killed. Redirect large output to a file or set a finite maxRetainedBytes to keep only the newest output.`);
this.stream = stream;
this.limitBytes = limitBytes;
}
};
const RETAINED_OUTPUT_COMPACT_CHUNK_THRESHOLD = 128;
/** @internal */
function validateMaxRetainedProcessOutputBytes(maxRetainedBytes) {
if (maxRetainedBytes === Infinity) return maxRetainedBytes;
if (!Number.isFinite(maxRetainedBytes) || maxRetainedBytes < 0 || !Number.isInteger(maxRetainedBytes)) throw new RangeError("maxRetainedBytes must be a non-negative integer or Infinity");
return maxRetainedBytes;
}
function advanceStartByUtf8Bytes(value, start, minimumBytesToDrop) {
let nextStart = start;
let droppedBytes = 0;
while (nextStart < value.length && droppedBytes < minimumBytesToDrop) {
const codePoint = value.codePointAt(nextStart);
if (codePoint < 128) droppedBytes += 1;
else if (codePoint < 2048) droppedBytes += 2;
else if (codePoint < 65536) droppedBytes += 3;
else droppedBytes += 4;
nextStart += codePoint > 65535 ? 2 : 1;
}
return {
start: nextStart,
droppedBytes
};
}
var RetainedOutputBuffer = class {
maxBytes;
hardLimitBytes;
chunks = [];
bytes = 0;
droppedBytes = 0;
cachedValue;
overflowedLimit = false;
/**
* @param maxBytes keep the newest `maxBytes`; above `hardLimitBytes` (e.g. Infinity) means keep everything
* @param hardLimitBytes overridable only so tests can reach the limit without allocating 256 MiB
*/
constructor(maxBytes, hardLimitBytes = MAX_RETAINED_PROCESS_OUTPUT_BYTES) {
this.maxBytes = maxBytes;
this.hardLimitBytes = hardLimitBytes;
}
/**
* True once a keep-everything buffer received more than `hardLimitBytes`.
* It then stops retaining: what it holds is incomplete and further data is only counted as dropped.
*/
get overflowed() {
return this.overflowedLimit;
}
append(data) {
const dataBytes = Buffer.byteLength(data);
if (dataBytes === 0) return;
if (this.overflowedLimit) {
this.droppedBytes += dataBytes;
return;
}
if (this.maxBytes > this.hardLimitBytes && this.bytes + dataBytes > this.hardLimitBytes) {
this.overflowedLimit = true;
this.droppedBytes += dataBytes;
return;
}
if (this.maxBytes === 0) {
this.droppedBytes += dataBytes;
return;
}
this.chunks.push({
data,
start: 0,
bytes: dataBytes,
dataBytes
});
this.bytes += dataBytes;
this.cachedValue = void 0;
this.trim();
this.compactIfNeeded();
}
toString() {
this.cachedValue ??= this.chunks.map((chunk) => chunk.data.slice(chunk.start)).join("");
return this.cachedValue;
}
get truncated() {
return this.droppedBytes > 0;
}
get dropped() {
return this.droppedBytes;
}
trim() {
if (this.maxBytes === Infinity) return;
while (this.bytes > this.maxBytes && this.chunks.length > 0) {
const overflowBytes = this.bytes - this.maxBytes;
const firstChunk = this.chunks[0];
if (firstChunk.bytes <= overflowBytes) {
this.chunks.shift();
this.bytes -= firstChunk.bytes;
this.droppedBytes += firstChunk.bytes;
continue;
}
const { start, droppedBytes } = advanceStartByUtf8Bytes(firstChunk.data, firstChunk.start, overflowBytes);
firstChunk.start = start;
firstChunk.bytes -= droppedBytes;
this.bytes -= droppedBytes;
this.droppedBytes += droppedBytes;
if (firstChunk.bytes === 0) {
this.chunks.shift();
continue;
}
if (firstChunk.dataBytes > this.maxBytes) {
firstChunk.data = Buffer.from(firstChunk.data.slice(firstChunk.start), "utf8").toString("utf8");
firstChunk.start = 0;
firstChunk.dataBytes = firstChunk.bytes;
}
}
}
compactIfNeeded() {
if (this.chunks.length <= RETAINED_OUTPUT_COMPACT_CHUNK_THRESHOLD) return;
const data = this.toString();
this.bytes = Buffer.byteLength(data);
this.chunks = this.bytes === 0 ? [] : [{
data,
start: 0,
bytes: this.bytes,
dataBytes: this.bytes
}];
this.cachedValue = data;
}
};
/**
* Thrown by {@link ProcessHandle.closeStdin} when the sandbox provider has no
* way to close a running process's stdin.
*
* `handle.writer.end()` treats this error as a successful finish, so piping to
* a process stays safe on providers without stdin close support.
*/
var UnsupportedStdinCloseError = class extends Error {
name = "UnsupportedStdinCloseError";
};
/**
* Handle to a spawned process.
*
* Subclasses implement the platform-specific primitives (kill, sendStdin,
* wait). The base class handles bounded stdout/stderr accumulation, callback
* dispatch via `emitStdout`/`emitStderr`, lazy `reader`/`writer` stream
* getters, and optional streaming callbacks on `wait()`.
*
* **For consumers:**
* - `handle.stdout` — poll retained output
* - `handle.wait()` — wait for exit, optionally with streaming callbacks
* - `handle.reader` / `handle.writer` — Node.js stream interop (LSP, JSON-RPC, pipes)
* - `onStdout`/`onStderr` callbacks in {@link SpawnProcessOptions} — stream at spawn time
*
* **For implementors:** Call `emitStdout(data)` / `emitStderr(data)` from
* your transport callback (ChildProcess events, WebSocket messages, etc.)
* to dispatch data. Pass `options` through to `super(options)` to wire
* user callbacks automatically.
*
* @example
* ```typescript
* // Poll model
* const handle = await sandbox.processes.spawn('node server.js');
* console.log(handle.stdout);
*
* // Stream model — callbacks at spawn time
* const handle = await sandbox.processes.spawn('npm run dev', {
* onStdout: (data) => console.log(data),
* });
*
* // Stream model — callbacks during wait
* const result = await handle.wait({
* onStdout: (data) => process.stdout.write(data),
* onStderr: (data) => process.stderr.write(data),
* });
*
* // Stream model — pipe to LSP, JSON-RPC, etc.
* const handle = await sandbox.processes.spawn('typescript-language-server --stdio');
* const connection = createMessageConnection(
* new StreamMessageReader(handle.reader),
* new StreamMessageWriter(handle.writer),
* );
* ```
*/
var ProcessHandle = class {
/** The command that was spawned (set by the process manager) */
command;
/**
* Close the process's stdin, signaling EOF.
*
* Providers that cannot close stdin throw {@link UnsupportedStdinCloseError}.
* The default implementation is the unsupported case, so providers only
* override this when their transport exposes a stdin close primitive.
*/
async closeStdin() {
throw new UnsupportedStdinCloseError(`${this.constructor.name} does not support closing stdin`);
}
/**
* Wait for the process to finish and return the result.
*
* Optionally pass `onStdout`/`onStderr` callbacks to stream output chunks
* while waiting. The callbacks are automatically removed when `wait()`
* resolves, so there's no cleanup needed by the caller.
*
* Optionally pass an `abortSignal` to couple the blocking wait to a caller
* lifetime: on abort the process is killed (mirroring the spawn-time
* `abortSignal` convention in {@link CommandOptions}), which lets the wait
* settle with the killed process's result instead of blocking forever.
*
* Subclasses implement `wait()` with platform-specific logic; the base
* constructor wraps it to handle the optional streaming callbacks.
*/
async wait(_options) {
throw new Error(`${this.constructor.name} must implement wait()`);
}
_stdout;
_stderr;
_outputLimitError;
_killedByAbort = false;
_abortKill;
_stdoutListeners = /* @__PURE__ */ new Set();
_stderrListeners = /* @__PURE__ */ new Set();
_reader;
_writer;
constructor(options) {
const maxRetainedBytes = validateMaxRetainedProcessOutputBytes(options?.maxRetainedBytes ?? 1048576);
this._stdout = new RetainedOutputBuffer(maxRetainedBytes, options?.retainedOutputHardLimitBytes);
this._stderr = new RetainedOutputBuffer(maxRetainedBytes, options?.retainedOutputHardLimitBytes);
if (options?.onStdout) this._stdoutListeners.add(options.onStdout);
if (options?.onStderr) this._stderrListeners.add(options.onStderr);
const implWait = this.wait.bind(this);
this.wait = async (waitOptions) => {
if (waitOptions?.onStdout) this._stdoutListeners.add(waitOptions.onStdout);
if (waitOptions?.onStderr) this._stderrListeners.add(waitOptions.onStderr);
const abortSignal = waitOptions?.abortSignal;
const onAbort = () => {
this.killForAbort().catch(() => {});
};
if (abortSignal?.aborted) onAbort();
else abortSignal?.addEventListener("abort", onAbort, { once: true });
try {
let result;
try {
result = await implWait();
} catch (error) {
throw this._outputLimitError ?? error;
}
if (this._outputLimitError) throw this._outputLimitError;
return {
...result,
stdoutTruncated: this.stdoutTruncated,
stderrTruncated: this.stderrTruncated,
stdoutDroppedBytes: this.stdoutDroppedBytes,
stderrDroppedBytes: this.stderrDroppedBytes
};
} finally {
abortSignal?.removeEventListener("abort", onAbort);
if (waitOptions?.onStdout) this._stdoutListeners.delete(waitOptions.onStdout);
if (waitOptions?.onStderr) this._stderrListeners.delete(waitOptions.onStderr);
}
};
}
/**
* @internal Whether the process was killed because an `abortSignal` passed to spawn or
* `wait()` fired while it was still running. A direct `kill()` does not set it.
*/
get killedByAbort() {
return this._killedByAbort;
}
/** @internal Kill the process for a fired abort signal and record it in {@link killedByAbort}. */
async killForAbort() {
if (this.exitCode !== void 0) return;
return this._abortKill ??= this.runAbortKill();
}
async runAbortKill() {
this._killedByAbort = true;
try {
if (!await this.kill()) {
this._killedByAbort = false;
this._abortKill = void 0;
}
} catch (error) {
this._killedByAbort = false;
this._abortKill = void 0;
throw error;
}
}
/** Retained stdout so far */
get stdout() {
return this._stdout.toString();
}
/** Retained stderr so far */
get stderr() {
return this._stderr.toString();
}
/** Whether stdout has dropped older output due to the retention limit */
get stdoutTruncated() {
return this._stdout.truncated;
}
/** Whether stderr has dropped older output due to the retention limit */
get stderrTruncated() {
return this._stderr.truncated;
}
/** Number of stdout bytes dropped due to the retention limit */
get stdoutDroppedBytes() {
return this._stdout.dropped;
}
/** Number of stderr bytes dropped due to the retention limit */
get stderrDroppedBytes() {
return this._stderr.dropped;
}
/**
* Emit stdout data — accumulates, dispatches to user callback, and pushes to reader stream.
* @internal Called by subclasses and process managers to dispatch transport data.
*/
emitStdout(data) {
this._stdout.append(data);
if (this._stdout.overflowed) this.failForOutputLimit("stdout", this._stdout.hardLimitBytes);
for (const listener of this._stdoutListeners) listener(data);
this._reader?.push(data);
}
/**
* Emit stderr data — accumulates and dispatches to user callback.
* @internal Called by subclasses and process managers to dispatch transport data.
*/
emitStderr(data) {
this._stderr.append(data);
if (this._stderr.overflowed) this.failForOutputLimit("stderr", this._stderr.hardLimitBytes);
for (const listener of this._stderrListeners) listener(data);
}
failForOutputLimit(stream, limitBytes) {
if (this._outputLimitError) return;
this._outputLimitError = new ProcessOutputLimitError(stream, limitBytes);
this.kill().catch(() => {});
}
/** Readable stream of stdout (for use with StreamMessageReader, pipes, etc.) */
get reader() {
if (!this._reader) {
this._reader = new stream.Readable({ read() {} });
this.wait().then(() => this._reader.push(null), () => this._reader.push(null));
}
return this._reader;
}
/** Writable stream to stdin (for use with StreamMessageWriter, pipes, etc.) */
get writer() {
if (!this._writer) this._writer = new stream.Writable({
write: (chunk, _encoding, cb) => {
this.sendStdin(chunk.toString()).then(() => cb(), cb);
},
final: (cb) => {
this.closeStdin().then(() => cb(), (err) => cb(err instanceof UnsupportedStdinCloseError ? null : err));
}
});
return this._writer;
}
};
// src/workspace/sandbox/mastra-sandbox.ts
/**
* MastraSandbox Base Class
*
* Abstract base class for sandbox providers that want automatic logger integration.
* Extends MastraBase to receive the Mastra logger when registered with a Mastra instance.
*
* MountManager is automatically created if the subclass implements `mount()`.
* Use `declare readonly mounts: MountManager` to get non-optional typing.
*
* ## Lifecycle Management
*
* The base class provides race-condition-safe lifecycle wrappers:
* - `_start()` - Handles concurrent calls, status management, and mount processing
* - `_stop()` - Handles concurrent calls and status management
* - `_destroy()` - Handles concurrent calls and status management
*
* Subclasses override the plain `start()`, `stop()`, and `destroy()` methods
* to provide their implementation. Callers use the `_`-prefixed wrappers
* (or `callLifecycle()`) which add status tracking and race-condition safety.
*
* External providers can extend this class to get logger support, or implement
* the WorkspaceSandbox interface directly if they don't need logging.
*/
/**
* Abstract base class for sandbox providers with logger support.
*
* Providers that extend this class automatically receive the Mastra logger
* when the sandbox is used with a Mastra instance. MountManager is also
* automatically created if the subclass implements `mount()`.
*
* @example
* ```typescript
* class MyCustomSandbox extends MastraSandbox {
* declare readonly mounts: MountManager; // Non-optional type
* readonly id = 'my-sandbox';
* readonly name = 'MyCustomSandbox';
* readonly provider = 'custom';
* status: ProviderStatus = 'pending';
*
* constructor() {
* super({
* name: 'MyCustomSandbox',
* processes: new MyProcessManager({ env: myEnv }),
* });
* }
*
* async start(): Promise<void> { /* startup logic *\/ }
* async mount(filesystem, mountPath) { ... }
* async unmount(mountPath) { ... }
* }
* ```
*/
var MastraSandbox = class MastraSandbox extends require_base.MastraBase {
/** Default timeout for foreground commands; background spawns are unaffected. */
defaultCommandTimeout;
/** Optional networking capability - implement to expose public port URLs */
networking;
/** Optional computer-use (desktop) capability - implement to enable workspace computer tools */
computer;
/** Process manager */
processes;
/** Mount manager - automatically created if subclass implements mount() */
mounts;
/**
* Persist the sandbox's current state when supported.
*
* The default implementation is a no-op for providers without snapshot support.
*/
async snapshot() {}
/**
* Whether `snapshot()` persists real checkpoints. Providers overriding
* `snapshot()` with a real implementation should also override this to true.
*/
supportsCheckpoints = false;
/** Promise for _start() to prevent race conditions from concurrent calls */
_startPromise;
/** The subclass's `start()`, captured before the constructor shadows it. */
_implStart;
/** Whether acquisition runs through {@link find}/{@link connect}/{@link create}. */
_useAcquisitionPrimitives;
/** Promise for _stop() to prevent race conditions from concurrent calls */
_stopPromise;
/** Promise for _destroy() to prevent race conditions from concurrent calls */
_destroyPromise;
/** Lifecycle callbacks */
_onStart;
_onStop;
_onDestroy;
/**
* Runtime environment overlay, merged into every process spawn.
*
* JS-private (`#`) rather than TS `private` so subclasses that declare
* their own `env` member (several providers do) can never collide with it.
*/
#env;
/**
* Effective default working directory, exposed via the
* {@link workingDirectory} getter. Protected so providers that compute or
* probe their effective value (e.g. a default like `/workspace`, or a
* runtime probe) can write it back with {@link setWorkingDirectory} and
* keep the getter truthful.
*/
_workingDirectory;
constructor(options) {
super({
name: options.name,
component: require_logger.RegisteredLogger.WORKSPACE
});
this._onStart = options.onStart;
this._onStop = options.onStop;
this._onDestroy = options.onDestroy;
this.#env = { ...options.env };
this._workingDirectory = options.workingDirectory;
const hasStartOverride = this.start !== MastraSandbox.prototype.start;
this._implStart = this.start.bind(this);
this.start = (options) => this._start(options);
this._useAcquisitionPrimitives = !hasStartOverride && typeof this.create === "function";
if (this._useAcquisitionPrimitives && typeof this.find === "function" && typeof this.connect !== "function") throw new Error(`${this.constructor.name}: find() requires connect() to adopt the handle it returns.`);
if (this.mount) this.mounts = new MountManager({
mount: this.mount.bind(this),
logger: this.logger
});
if (options.processes) {
const pm = options.processes;
pm.sandbox = this;
this.processes = pm;
if (!this.executeCommand) this.executeCommand = async (command, args, opts) => {
const fullCommand = args?.length ? `${command} ${args.map((a) => shellQuote(a)).join(" ")}` : command;
this.logger.debug("Executing command", {
sandbox: this.name,
command: fullCommand,
cwd: opts?.cwd
});
const handle = await pm.spawn(fullCommand, {
...opts,
timeout: opts?.timeout ?? this.defaultCommandTimeout,
...args?.length ? { originalInvocation: {
command,
args: [...args]
} } : {},
maxRetainedBytes: opts?.maxRetainedBytes ?? 1048576,
stdinMode: "ignore"
});
try {
const result = await handle.wait();
if (handle.exitCode === void 0) await handle.kill();
this.logger.debug("Command completed", {
sandbox: this.name,
exitCode: result.exitCode,
duration: result.executionTimeMs
});
return {
...result,
command: fullCommand
};
} finally {
pm.release(handle.pid);
}
};
}
}
/**
* Update the sandbox's runtime environment overlay.
*
* The updater receives a copy of the current overlay and returns the new
* one, so a single call can set, unset, or batch-update variables:
*
* ```typescript
* sandbox.setEnv(env => ({ ...env, GH_TOKEN: token }));
* ```
*
* Changes apply immediately to subsequent commands and processes routed
* through the sandbox's process manager (including the built-in
* `executeCommand`), survive provider pause/resume and VM replacement,
* and are never written into the VM — the overlay is merged per spawn,
* not persisted. Removing a key removes it from the overlay only;
* env values a provider supplies on its own still apply.
*/
setEnv(update) {
this.#env = { ...update({ ...this.#env }) };
}
/**
* Snapshot of the current runtime environment overlay.
*
* Returns a fresh copy — mutating it never affects the stored overlay; use
* {@link setEnv} to change it. The process manager reads this per spawn to
* merge the overlay into command environments.
*/
getEnv() {
return { ...this.#env };
}
/**
* The sandbox's default working directory, when one is configured.
*
* Commands and process spawns without a per-command `cwd` run here;
* per-command `cwd` always wins. `undefined` means the provider's own
* default applies (typically the home directory).
*/
get workingDirectory() {
return this._workingDirectory;
}
/**
* Set the effective working directory after construction. For providers
* that resolve the value themselves — a computed default, or a runtime
* probe that needs a running VM — so the {@link workingDirectory} getter
* stays truthful.
*/
setWorkingDirectory(dir) {
this._workingDirectory = dir;
}
/**
* Attach or replace the start hook after construction. The updater receives
* the installed hook and returns its replacement, so callers compose instead
* of clobbering a hook they didn't know about; ignoring `prev` replaces it.
*
* ```typescript
* sandbox.setOnStart(prev => async args => {
* await prev?.(args); // whatever prepared the sandbox runs first
* await mySetup(args);
* });
* ```
*
* Errors stay FATAL, so a throw stops the hooks after it. Each call wraps
* the current hook, so attach once per sandbox or the work stacks.
*/
setOnStart(update) {
this._onStart = update(this._onStart);
}
/**
* Start the sandbox (wrapper with status management and race-condition safety).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management and automatically processes pending mounts after startup.
*
* Subclasses override `start()` to provide their startup logic.
*/
async _start(options) {
if (this.status === "running") return { outcome: "connected" };
if (this._stopPromise) await this._stopPromise;
if (this._destroyPromise) await this._destroyPromise;
if (this.status === "destroyed") throw new Error("Cannot start a destroyed sandbox");
if (this._startPromise) return this._startPromise;
this._startPromise = this._executeStart(options);
try {
return await this._startPromise;
} finally {
this._startPromise = void 0;
}
}
/**
* Internal start execution - handles status, the onStart hook, and mount
* processing.
*/
async _executeStart(options) {
this.status = "starting";
let result;
try {
result = this._useAcquisitionPrimitives ? await this._acquire(options) : await this._implStart(options);
this.status = "running";
} catch (error) {
this.status = "error";
throw error;
}
const outcome = result?.outcome;
try {
await this._onStart?.({
sandbox: this,
outcome
});
} catch (error) {
this.status = "error";
throw new Error(`Sandbox '${this.id}' onStart hook failed: ${error instanceof Error ? error.message : error}`, { cause: error });
}
try {
await this.mounts?.processPending();
} catch (error) {
this.logger.warn("Unexpected error processing pending mounts", { error });
}
return result;
}
/** Base-orchestrated acquisition (rung 1 — see {@link start}). */
async _acquire(options) {
const handle = this.find ? await this.find(options) : void 0;
if (handle != null) {
if (!this.connect) throw new Error(`${this.constructor.name}: find() requires connect() to adopt the handle it returns.`);
await this.connect(handle, options);
return { outcome: "connected" };
}
await this.create(options);
return { outcome: "created" };
}
/**
* Sandbox startup. Providers plug in at one of three rungs (best available
* wins); either way the base owns coalescing, status management, the
* onStart setup hook, and mount processing:
*
* 1. Implement the {@link find}/{@link connect}/{@link create} primitives
* (and do NOT override `start()`) — the base orchestrates acquisition
* and derives the outcome structurally. For providers whose API
* decomposes into lookup/wake/provision.
* 2. Override `start()` returning {@link SandboxStartResult} — for
* providers with a fused getOrCreate-style API where decomposition
* would add round-trips.
* 3. Override `start()` returning void — the outcome is unknown.
*
* The base constructor wraps `start()` so direct calls are routed through
* `_start()`. Use METHOD syntax when overriding — a class-field `start`
* initializer would overwrite the wrapper. Implementing neither rung throws:
* a sandbox with nothing to start says so with an empty `async start() {}`.
*
* Id-keyed getOrCreate contract: a sandbox constructed with a known `id`
* resolves that id on start — reconnect/resume when the provider finds an
* existing VM for it, create otherwise.
*/
async start(_options) {
throw new Error(`${this.constructor.name} implements neither start() nor the create() acquisition primitive, so starting it would do nothing. Implement one using method syntax.`);
}
/**
* Ensure the sandbox is running.
*
* Calls `_start()` if status is not 'running'. Useful for lazy initialization
* where operations should automatically start the sandbox if needed.
*
* This is the lazy entry point into the id-keyed getOrCreate contract
* described on {@link start}.
*
* @throws {SandboxNotReadyError} if the sandbox fails to reach 'running' status
*
* @example
* ```typescript
* async executeCommand(command: string): Promise<CommandResult> {
* await this.ensureRunning();
* // Now safe to use the sandbox
* }
* ```
*/
async ensureRunning() {
if (this.status === "destroyed") throw new SandboxNotReadyError(this.id);
if (this.status === "destroying" || this.status === "stopping") return;
if (this.status !== "running") await this._start();
if (this.status !== "running") throw new SandboxNotReadyError(this.id);
}
/**
* Stop the sandbox (wrapper with status management and race-condition safety).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management.
*
* Subclasses override `stop()` to provide their stop logic.
*/
async _stop() {
if (this.status === "stopped") return;
if (this._startPromise) await this._startPromise.catch(() => {});
if (this._stopPromise) return this._stopPromise;
this._stopPromise = this._executeStop();
try {
await this._stopPromise;
} finally {
this._stopPromise = void 0;
}
}
/**
* Internal stop execution - handles status.
*/
async _executeStop() {
this.status = "stopping";
try {
await this._onStop?.({ sandbox: this });
await this.stop();
this.status = "stopped";
} catch (error) {
this.status = "error";
throw error;
}
}
/**
* Override this method to implement sandbox stop logic.
*
* Called by `_stop()` after status is set to 'stopping'.
* Status will be set to 'stopped' on success, 'error' on failure.
*/
async stop() {}
/**
* Destroy the sandbox and clean up all resources (wrapper with status management).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management.
*
* Subclasses override `destroy()` to provide their destroy logic.
*/
async _destroy() {
if (this.status === "destroyed") return;
if (this.status === "pending") {
this.status = "destroyed";
return;
}
if (this._startPromise) await this._startPromise.catch(() => {});
if (this._stopPromise) await this._stopPromise.catch(() => {});
if (this._destroyPromise) return this._destroyPromise;
this._destroyPromise = this._executeDestroy();
try {
await this._destroyPromise;
} finally {
this._destroyPromise = void 0;
}
}
/**
* Internal destroy execution - handles status.
*/
async _executeDestroy() {
this.status = "destroying";
try {
await this._onDestroy?.({ sandbox: this });
await this.destroy();
this.status = "destroyed";
} catch (error) {
this.status = "error";
throw error;
}
}
/**
* Override this method to implement sandbox destroy logic.
*
* Called by `_destroy()` after status is set to 'destroying'.
* Status will be set to 'destroyed' on success, 'error' on failure.
*/
async destroy() {}
/**
* Override to propagate logger to MountManager.
* @internal
*/
__setLogger(logger) {
super.__setLogger(logger);
this.mounts?.__setLogger(logger);
}
};
// src/workspace/sandbox/execa.ts
let cached;
let loading;
const importModule$1 = (moduleName) => import(
/* @vite-ignore */
/* webpackIgnore: true */
moduleName
);
/**
* Lazily imports execa using a runtime-constructed module specifier.
* This prevents bundlers (Vite/Rollup/esbuild) from resolving execa at build time,
* which is necessary for Cloudflare Workers where execa's transitive deps
* (npm-run-path → unicorn-magic) use Node-only conditional exports.
*/
async function getExeca() {
if (cached) return cached;
if (!loading) loading = (async () => {
try {
const execa = (await importModule$1("execa")).execa;
cached = execa;
return execa;
} catch (err) {
throw new Error("execa is required for local process execution but is not available in this environment. LocalProcessManager is not supported in Cloudflare Workers or other non-Node runtimes.", { cause: err });
}
})();
return loading;
}
// src/workspace/sandbox/process-manager/process-manager.ts
var SandboxProcessManager = class {
/**
* The sandbox this process manager belongs to.
* Set automatically by MastraSandbox when processes are passed into the constructor.
* @internal
*/
sandbox;
env;
/** Tracked process handles keyed by PID. Populated by spawn(), used by get()/kill(). */
_tracked = /* @__PURE__ */ new Map();
/** PIDs that have been read after exit and should not be re-discovered by subclass fallbacks. */
_dismissed = /* @__PURE__ */ new Set();
constructor({ env = {} } = {}) {
this.env = env;
const impl = {
spawn: this.spawn.bind(this),
list: this.list.bind(this),
get: this.get.bind(this)
};
this.spawn = async (...args) => {
if (args[1]?.maxRetainedBytes !== void 0) validateMaxRetainedProcessOutputBytes(args[1].maxRetainedBytes);
await this.sandbox.ensureRunning();
const sandboxEnv = this.sandbox.getEnv?.();
if (sandboxEnv && Object.keys(sandboxEnv).length > 0) args[1] = {
...args[1],
env: {
...sandboxEnv,
...args[1]?.env
}
};
const handle = await impl.spawn(...args);
this._dismissed.delete(handle.pid);
handle.command = args[0];
const abortSignal = args[1]?.abortSignal;
if (abortSignal) {
const onAbort = () => {
handle.killForAbort().catch(() => {});
};
if (abortSignal.aborted) onAbort();
else {
abortSignal.addEventListener("abort", onAbort, { once: true });
handle.wait().then(() => abortSignal.removeEventListener("abort", onAbort), () => abortSignal.removeEventListener("abort", onAbort));
}
}
return handle;
};
this.list = async () => {
await this.sandbox.ensureRunning();
return impl.list();
};
this.get = async (...args) => {
await this.sandbox.ensureRunning();
if (this._dismissed.has(args[0])) return void 0;
const handle = await impl.get(...args);
if (handle?.exitCode !== void 0 && args[1]?.release !== false) {
this._tracked.delete(handle.pid);
this._dismissed.add(handle.pid);
}
return handle;
};
}
/** Spawn a process. */
async spawn(command, options = {}) {
throw new Error(`${this.constructor.name} must implement spawn()`);
}
/** List all tracked processes. */
async list() {
throw new Error(`${this.constructor.name} must implement list()`);
}
/**
* Get a handle to a process by PID. Subclasses can override for fallback behavior.
*
* Reading an exited process releases it by default: later calls return
* `undefined`. Pass `{ release: false }` to read it and leave it available,
* for example to show its output without taking it from the agent.
*/
async get(pid, options) {
return this._tracked.get(pid);
}
/** Release a completed process handle and its retained output. */
release(pid) {
this._tracked.delete(pid);
this._dismissed.add(pid);
}
/** Kill a process by PID. Returns true if killed, false if not found. */
async kill(pid) {
const handle = await this.get(pid);
if (!handle) return false;
const killed = await handle.kill();
if (killed) await handle.wait().catch(() => {});
this.release(handle.pid);
return killed;
}
};
// src/workspace/sandbox/local-process-manager.ts
/**
* Local Process Manager
*
* Local implementation of SandboxProcessManager using execa.
* Tracks processes in-memory since there's no server to query.
*/
const isWindows = process.platform === "win32";
/** How long a timed-out process tree gets to exit after SIGTERM before it is sent SIGKILL. */
const TIMEOUT_KILL_GRACE_MS = 2e3;
/** How long output may keep draining after the process exits before wait() settles without it. */
const EXIT_OUTPUT_GRACE_MS = 2e3;
const OOM_SCORE_ADJ_PATH = "/proc/self/oom_score_adj";
/** `oom_score_adj` given to spawned commands unless `MASTRA_COMMAND_OOM_SCORE_ADJ` overrides it. */
const DEFAULT_COMMAND_OOM_SCORE_ADJ = 500;
/**
* The `oom_score_adj` to give spawned commands: `MASTRA_COMMAND_OOM_SCORE_ADJ` (1-1000), or the
* default when it is unset or not a number. `0`, `off` or `false` turns the adjustment off.
*/
function commandOomScoreAdj() {
const configured = process.env.MASTRA_COMMAND_OOM_SCORE_ADJ?.trim();
if (configured && /^(0+|off|false)$/i.test(configured)) return void 0;
if (configured && /^\d+$/.test(configured)) return Math.min(Number(configured), 1e3);
return DEFAULT_COMMAND_OOM_SCORE_ADJ;
}
/**
* Prefix a shell command so that its shell raises its own `oom_score_adj` first (Linux only).
*
* The agent and the commands it runs share one memory limit in a container. When a command's
* processes use it all up, the kernel OOM killer kills the process with the highest score, and a
* Node agent holding a few hundred MB often outscores each of many smaller workers. Everything the
* shell starts inherits the raised score (also across `exec`), so the kernel kills the workload
* instead, and the agent sees `Killed` / exit 137 in the command result.
*
* Raising your own score needs no privilege. A failed write (no `/proc`, read-only `/proc`) is
* silent, and the prefix changes neither the command's output nor its exit status. It stays on
* the command's first line, so shell error line numbers are unchanged. It is skipped when the
* agent's own score is already at or above the target, since lowering a score needs privilege.
*/
function withRaisedOomScore(command) {
if (process.platform !== "linux") return command;
const target = commandOomScoreAdj();
if (target === void 0) return command;
let current;
try {
current = Number.parseInt((0, fs.readFileSync)(OOM_SCORE_ADJ_PATH, "utf8"), 10);
} catch {
return command;
}
if (!(current < target)) return command;
return `{ echo ${target} >${OOM_SCORE_ADJ_PATH}; } 2>/dev/null; ${command}`;
}
/**
* Find a POSIX shell on Windows for commands built with POSIX quoting.
* Checks `MASTRA_WINDOWS_SHELL`, then Git Bash next to a `git.exe` on the command's PATH
* (Git for Windows puts `Git\cmd` on PATH, not `Git\bin`), then the default
* Git for Windows install location. Bare `bash` on PATH is skipped on purpose:
* it is often WSL's launcher, which can't see Windows paths.
*/
function findWindowsPosixShell(searchPath) {
const candidates = [];
const configured = process.env.MASTRA_WINDOWS_SHELL?.trim();
if (configured && /^cmd(\.exe)?$/i.test(configured)) return configured;
if (configured) candidates.push(configured);
for (const dir of (searchPath ?? "").split(path.win32.delimiter)) if (dir && (0, fs.existsSync)(path.win32.join(dir, "git.exe"))) candidates.push(path.win32.join(dir, "..", "bin", "bash.exe"), path.win32.join(dir, "..", "..", "bin", "bash.exe"));
candidates.push(path.win32.join(process.env.ProgramFiles ?? "C:\\Program Files", "Git", "bin", "bash.exe"));
return candidates.find((candidate) => (0, fs.existsSync)(candidate));
}
/**
* Local implementation of ProcessHandle wrapping an execa subprocess.
* Not exported — internal to this module.
*/
var LocalProcessHandle = class extends ProcessHandle {
pid;
exitCode;
_numericPid;
subprocess;
waitPromise;
startTime;
constructor(subprocess, pid, startTime, options, outputEncoding = "utf-8") {
super(options);
this.pid = String(pid);
this._numericPid = pid;
this.subprocess = subprocess;
this.startTime = startTime;
let timedOut = false;
let killTimeoutId;
let releaseTimeoutId;
let exitGraceId;
const timeoutId = options?.timeout ? setTimeout(() => {
timedOut = true;
killProcessTree(this._numericPid, subprocess, "SIGTERM");
killTimeoutId = setTimeout(() => {
killProcessTree(this._numericPid, subprocess, "SIGKILL");
releaseTimeoutId = setTimeout(() => {
subprocess.stdout?.destroy();
subprocess.stderr?.destroy();
}, TIMEOUT_KILL_GRACE_MS);
}, TIMEOUT_KILL_GRACE_MS);
}, options.timeout) : void 0;
const clearTimers = () => {
clearTimeout(timeoutId);
clearTimeout(killTimeoutId);
clearTimeout(releaseTimeoutId);
clearTimeout(exitGraceId);
};
const toExitCode = (code, signal) => signal && code === null ? 128 : code ?? 0;
const stdoutDecoder = new TextDecoder(outputEncoding);
const stderrDecoder = new TextDecoder(outputEncoding);
let stdoutDecoderEnded = false;
let stderrDecoderEnded = false;
const flushStdoutDecoder = () => {
if (stdoutDecoderEnded) return;
stdoutDecoderEnded = true;
const data = stdoutDecoder.decode();
if (data) this.emitStdout(data);
};
const flushStderrDecoder = () => {
if (stderrDecoderEnded) return;
stderrDecoderEnded = true;
const data = stderrDecoder.decode();
if (data) this.emitStderr(data);
};
this.waitPromise = new Promise((resolve) => {
let settled = false;
const settle = (exitCode, signal) => {
if (settled) return;
settled = true;
resolve({
success: exitCode === 0,
exitCode,
stdout: this.stdout,
stderr: this.stderr,
executionTimeMs: Date.now() - this.startTime,
killed: signal !== null,
timedOut
});
};
subprocess.on("close", (code, signal) => {
clearTimers();
flushStdoutDecoder();
flushStderrDecoder();
if (timedOut) {
const timeoutMsg = `\nProcess timed out after ${options.timeout}ms`;
this.emitStderr(timeoutMsg);
this.exitCode = 124;
} else this.exitCode = toExitCode(code, signal);
settle(this.exitCode, signal);
});
subprocess.on("exit", (code, signal) => {
exitGraceId = setTimeout(() => {
if (!timedOut) settle(toExitCode(code, signal), signal);
}, EXIT_OUTPUT_GRACE_MS);
});
subprocess.on("error", (err) => {
settled = true;
clearTimers();
flushStdoutDecoder();
flushStderrDecoder();
this.emitStderr(err.message);
this.exitCode = 1;
resolve({
success: false,
exitCode: 1,
stdout: this.stdout,
stderr: this.stderr,
executionTimeMs: Date.now() - this.startTime
});
});
});
subprocess.stdout?.on("data", (data) => {
const decoded = stdoutDecoder.decode(data, { stream: true });
if (decoded) this.emitStdout(decoded);
});
subprocess.stdout?.on("end", flushStdoutDecoder);
subprocess.stderr?.on("data", (data) => {
const decoded = stderrDecoder.decode(data, { stream: true });
if (decoded) this.emitStderr(decoded);
});
subprocess.stderr?.on("end", flushStderrDecoder);
}
async wait() {
return this.waitPromise;
}
async kill() {
if (this.exitCode !== void 0) return false;
await killProcessTree(this._numericPid, this.subprocess, "SIGKILL");
return true;
}
async sendStdin(data) {
if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
if (!this.subprocess.stdin) throw new Error(`Process ${this.pid} does not have stdin available`);
return new Promise((resolve, reject) => {
this.subprocess.stdin.write(data, (err) => err ? reject(err) : resolve());
});
}
async closeStdin() {
if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
if (!this.subprocess.stdin) throw new Error(`Process ${this.pid} does not have stdin available`);
if (this.subprocess.stdin.writableEnded) return;
return new Promise((resolve, reject) => {
this.subprocess.stdin.end((err) => err ? reject(err) : resolve());
});
}
};
/**
* Kill a process and all its children.
*
* On Unix, we use process groups (negative PID) since processes are spawned
* with `detached: true` which creates a new process group.
*
* On Windows, `process.kill(-pid)` doesn't work (no process groups), and
* `detached: true` opens a new console window. Instead we use `taskkill /T`
* which recursively kills the process tree by PID.
*/
async function killProcessTree(pid, subprocess, signal) {
if (isWindows) try {
await (await getExeca())("taskkill", [
"/T",
"/F",
"/PID",
String(pid)
], {
reject: false,
stdio: "ignore"
});
} catch {
subprocess.kill(signal);
}
else try {
process.kill(-pid, signal);
} catch {
subprocess.kill(signal);
}
}
var LocalProcessManager = class extends SandboxProcessManager {
outputEncoding;
constructor({ outputEncoding = "utf-8", ...options } = {}) {
super(options);
new TextDecoder(outputEncoding);
this.outputEncoding = outputEncoding;
}
async spawn(command, options = {}) {
let cwd = this.sandbox.workingDirectory;
if (options.cwd) {
if (path.isAbsolute(options.cwd)) cwd = options.cwd;
else {
const normalizedWorkingDir = path.resolve(this.sandbox.workingDirectory);
const normalizedOptionsCwd = path.resolve(options.cwd);
cwd = normalizedOptionsCwd === normalizedWorkingDir || normalizedOptionsCwd.startsWith(`${normalizedWorkingDir}${path.sep}`) ? normalizedOptionsCwd : path.resolve(this.sandbox.workingDirectory, options.cwd);
}
}
let env = this.sandbox.buildEnv(options.env);
const invocation = options.originalInvocation;
const posixShell = isWindows && this.sandbox.isolation === "none" && invocation !== void 0 && !/^(cmd|powershell|pwsh)(\.exe)?$/i.test(path.win32.basename(invocation.command)) ? findWindowsPosixShell(env.PATH) : void 0;
const usesBash = posixShell !== void 0 && !/^cmd(\.exe)?$/i.test(path.win32.basename(posixShell));
if (usesBash) env = {
MSYS_NO_PATHCONV: "1",
MSYS2_ARG_CONV_EXCL: "*",
...env
};
const directShell = isWindows && this.sandbox.isolation === "none" && invocation !== void 0 && /^(sh|sh\.exe)$/i.test(path.win32.basename(invocation.command)) && invocation.args[0] === "-c" && invocation.args.length >= 2;
const wrapped = directShell ? {
command: usesBash && /^sh(\.exe)?$/i.test(invocation.command) ? posixShell : invocation.command,
args: invocation.args
} : usesBash && invocation ? {
command: [invocation.command, ...invocation.args].map(shellQuote).join(" "),
args: []
} : this.sandbox.wrapCommandForIsolation(withRaisedOomScore(command));
const stdio = options.stdinMode === "ignore" ? [
"ignore",
"pipe",
"pipe"
] : "pipe";
const baseOptions = {
cwd,
env,
stdio,
reject: false,
buffer: false,
stripFinalNewline: false,
extendEnv: false
};
let execaOptions;
if (isWindows) execaOptions = {
...baseOptions,
shell: !directShell && this.sandbox.isolation === "none" && (posixShell ?? true),
windowsHide: true
};
else execaOptions = {
...baseOptions,
detached: true,
shell: this.sandbox.isolation === "none"
};
const subprocess = (await getExeca())(wrapped.command, wrapped.args, execaOptions);
if (!subprocess.pid) {
const result = await subprocess;
throw new Error(result.message || "Process failed to spawn");
}
const handle = new LocalProcessHandle(subprocess, subprocess.pid, Date.now(), options, this.outputEncoding);
this._tracked.set(handle.pid, handle);
return handle;
}
async list() {
return Array.from(this._tracked.values()).map((handle) => ({
pid: handle.pid,
running: handle.exitCode === void 0,
exitCode: handle.exitCode
}));
}
};
// src/workspace/sandbox/native-sandbox/detect.ts
/**
* Platform Detection
*
* Detects available sandboxing backends for the current platform.
*/
/**
* Check if a command exists on the system.
*/
function commandExists(command) {
try {
(0, child_process.execFileSync)("which", [command], { stdio: "ignore" });
return true;
} catch {
return false;
}
}
/**
* Check if seatbelt (sandbox-exec) is available.
* This is built-in on macOS.
*/
function isSeatbeltAvailable() {
if (os.default.platform() !== "darwin") return false;
return commandExists("sandbox-exec");
}
/**
* Check if bubblewrap (bwrap) is available.
* This must be installed on Linux systems.
*/
function isBwrapAvailable() {
if (os.default.platform() !== "linux") return false;
return commandExists("bwrap");
}
/**
* Detect the best available isolation backend for the current platform.
*
* @returns The recommended isolation backend and availability info
*
* @example
* ```typescript
* const result = detectIsolation();
* if (result.available) {
* console.log(`Using ${result.backend} for sandboxing`);
* } else {
* console.warn(result.message);
* }
* ```
*/
function detectIsolation() {
const platform = os.default.platform();
if (platform === "darwin") {
const available = isSeatbeltAvailable();
return {
backend: "seatbelt",
available,
message: available ? "macOS seatbelt (sandbox-exec) is available" : "macOS seatbelt (sandbox-exec) not found - this is unexpected on macOS"
};
}
if (platform === "linux") {
const available = isBwrapAvailable();
return {
backend: "bwrap",
available,
message: available ? "Linux bubblewrap (bwrap) is available" : "Linux bubblewrap (bwrap) not found. Install with: apt install bubblewrap (Debian/Ubuntu) or dnf install bubblewrap (Fedora)"
};
}
return {
backend: "none",
available: false,
message: `Native sandboxing is not supported on ${platform}. Commands will run without isolation.`
};
}
/**
* Check if a specific isolation backend is available.
*
* @param backend - The isolation backend to check
* @returns Whether the backend is available on this system
*/
function isIsolationAvailable(backend) {
switch (backend) {
case "seatbelt": return isSeatbeltAvailable();
case "bwrap": return isBwrapAvailable();
case "none": return true;
default: return false;
}
}
/**
* Get the recommended isolation backend for this platform.
* Returns 'none' if no sandboxing is available.
*/
function getRecommendedIsolation() {
const result = detectIsolation();
return result.available ? result.backend : "none";
}
// src/workspace/sandbox/native-sandbox/seatbelt.ts
/**
* Seatbelt (macOS sandbox-exec)
*
* macOS built-in sandboxing using sandbox-exec with SBPL profiles.
*
* Important: Uses `-p` (inline profile) instead of `-f` (file) because
* `-f` doesn't work reliably with path filters on modern macOS.
*
* Note on macOS sandbox limitations:
* - `(allow file-read* (subpath ...))` only works WITH a preceding `(allow file-read*)`
* - So for reads: allow all, then deny specific paths
* - For writes: allow specific paths with subpath filters
*
* Based on the approach used by Claude Code's sandbox-runtime:
* https://github.com/anthropic-experimental/sandbox-runtime
*/
/**
* Mach services needed for basic operation
*/
const MACH_SERVICES = [
"com.apple.distributed_notifications@Uv3",
"com.apple.logd",
"com.apple.system.logger",
"com.apple.system.notification_center",
"com.apple.system.opendirectoryd.libinfo",
"com.apple.system.opendirectoryd.membership",
"com.apple.bsd.dirhelper",
"com.apple.securityd.xpc",
"com.apple.SecurityServer",
"com.apple.trustd.agent"
];
/**
* SBPL comment that marks a profile as generated by Mastra.
*
* Written into every generated profile. A profile file that carries this marker is ours,
* even when it sits at a path the user configured, so Mastra regenerates it instead of
* treating it as user-authored SBPL.
*/
const GENERATED_PROFILE_MARKER = "; mastra-generated-profile (regenerated on every start)";
/**
* Check whether a profile file was generated by Mastra.
*
* @param profile - The SBPL profile content read from disk
* @returns True when the content carries the generated-profile marker
*/
function isGeneratedSeatbeltProfile(profile) {
return profile.includes(GENERATED_PROFILE_MARKER);
}
/**
* Escape a path for use in SBPL profile.
* Uses JSON.stringify for proper escaping.
*/
function escapePath(pathStr) {
return JSON.stringify(pathStr);
}
function canonicalizePath(pathStr) {
try {
return (0, fs.realpathSync)(pathStr);
} catch {
return pathStr;
}
}
/**
* Generate a seatbelt profile for the given configuration.
*
* The profile:
* - Allows all file reads (can't restrict with subpath on macOS)
* - Restricts file writes to temp directories, configured writable paths, and the workspace unless read-only
* - Blocks network unless explicitly allowed
*
* @param workspacePath - The workspace directory to sandbox
* @param config - Additional sandbox configuration
* @returns The generated SBPL profile content
*/
function generateSeatbeltProfile(workspacePath, config) {
if (config.allowSystemBinaries === false) throw new Error("allowSystemBinaries: false is not supported by seatbelt (macOS). Use bubblewrap on Linux or remove this restriction.");
const lines = [];
lines.push("(version 1)");
lines.push(GENERATED_PROFILE_MARKER);
lines.push("(deny default (with message \"mastra-sandbox\"))");
lines.push("");
lines.push("; Process permissions");
lines.push("(allow process-exec)");
lines.push("(allow process-fork)");
lines.push("(allow process-info* (target same-sandbox))");
lines.push("(allow signal (target same-sandbox))");
lines.push("");
lines.push("; Mach IPC");
lines.push("(allow mach-lookup");
for (const service of MACH_SERVICES) lines.push(` (global-name "${service}")`);
lines.push(")");
lines.push("");
lines.push("; IPC");
lines.push("(allow ipc-posix-shm)");
lines.push("(allow ipc-posix-sem)");
lines.push("");
lines.push("; User preferences");
lines.push("(allow user-preference-read)");
lines.push("");
lines.push("; sysctl");
lines.push("(allow sysctl-read)");
lines.push("");
lines.push("; Device files");
for (const device of [
"/dev/null",
"/dev/zero",
"/dev/random",
"/dev/urandom",
"/dev/tty"
]) {
lines.push(`(allow file-ioctl (literal "${device}"))`);
lines.push(`(allow file-write-data (literal "${device}"))`);
}
lines.push("");
lines.push("; File read access (allow all - macOS sandbox limitation)");
lines.push("(allow file-read*)");
for (const p of config.readOnlyPaths ?? []) lines.push(`(allow file-read* (subpath ${escapePath(p)}))`);
lines.push("");
lines.push("; File write access (restricted to workspace and temp)");
const canonicalWorkspacePath = canonicalizePath(workspacePath);
if (!config.readOnly) lines.push(`(allow file-write* (subpath ${escapePath(canonicalWorkspacePath)}))`);
for (const tempPath of [
"/private/tmp",
"/var/folders",
"/private/var/folders"
]) if (config.readOnly) lines.push(`(allow file-write* (require-all (subpath ${escapePath(tempPath)}) (require-not (subpath ${escapePath(canonicalWorkspacePath)}))))`);
else lines.push(`(allow file-write* (subpath ${escapePath(tempPath)}))`);
for (const p of config.readWritePaths ?? []) lines.push(`(allow file-write* (subpath ${escapePath(canonicalizePath(p))}))`);
lines.push("");
lines.push("; Network");
if (config.allowNetwork) lines.push("(allow network*)");
else lines.push("(deny network* (with message \"mastra-sandbox-network\"))");
return lines.join("\n");
}
/**
* Build the command arguments for sandbox-exec.
*
* Uses `-p` (inline profile) instead of `-f` (file) because
* `-f` doesn't work reliably with path filters on modern macOS.
*
* @param command - The full shell command string to run
* @param profile - The SBPL profile content (not a file path)
* @returns Wrapped command and arguments for sandbox-exec
*/
function buildSeatbeltCommand(command, profile) {
return {
command: "sandbox-exec",
args: [
"-p",
profile,
"sh",
"-c",
command
]
};
}
// src/workspace/sandbox/native-sandbox/bubblewrap.ts
/**
* Bubblewrap (Linux bwrap)
*
* Linux sandboxing using user namespaces and bind mounts.
* https://github.com/containers/bubblewrap
*/
/**
* System paths to mount read-only by default.
* These are needed for basic command execution.
*/
const DEFAULT_READONLY_BINDS = [
"/usr",
"/lib",
"/lib64",
"/bin",
"/sbin",
"/etc/alternatives",
"/etc/ssl",
"/etc/ca-certificates",
"/etc/resolv.conf",
"/etc/hosts",
"/etc/passwd",
"/etc/group",
"/etc/nsswitch.conf",
"/etc/ld.so.cache",
"/etc/localtime"
];
/**
* Build the bwrap command arguments for the given configuration.
*
* @param command - The full shell command string to run inside the sandbox
* @param workspacePath - The workspace directory (mounted read-write)
* @param config - Additional sandbox configuration
* @returns Wrapped command and arguments for bwrap
*/
function buildBwrapCommand(command, workspacePath, config) {
if (config.bwrapArgs && config.bwrapArgs.length > 0) return {
command: "bwrap",
args: [
...config.bwrapArgs,
"--",
"sh",
"-c",
command
]
};
const bwrapArgs = [];
bwrapArgs.push("--unshare-pid");
bwrapArgs.push("--unshare-ipc");
bwrapArgs.push("--unshare-uts");
if (!config.allowNetwork) bwrapArgs.push("--unshare-net");
bwrapArgs.push("--proc", "/proc");
bwrapArgs.push("--tmpfs", "/tmp");
for (const path of DEFAULT_READONLY_BINDS) bwrapArgs.push("--ro-bind-try", path, path);
for (const path of config.readOnlyPaths ?? []) bwrapArgs.push("--ro-bind", path, path);
if (config.allowSystemBinaries !== false) {
const nodePath = process.execPath;
const nodeDir = path.dirname(nodePath);
if (!DEFAULT_READONLY_BINDS.some((p) => nodeDir.startsWith(p))) bwrapArgs.push("--ro-bind", nodeDir, nodeDir);
bwrapArgs.push("--ro-bind-try", "/opt", "/opt");
bwrapArgs.push("--ro-bind-try", "/snap", "/snap");
}
if (config.readOnly) bwrapArgs.push("--ro-bind", workspacePath, workspacePath);
else bwrapArgs.push("--bind", workspacePath, workspacePath);
for (const path of config.readWritePaths ?? []) bwrapArgs.push("--bind", path, path);
bwrapArgs.push("--dev", "/dev");
bwrapArgs.push("--chdir", workspacePath);
bwrapArgs.push("--die-with-parent");
bwrapArgs.push("--", "sh", "-c", command);
return {
command: "bwrap",
args: bwrapArgs
};
}
// src/workspace/sandbox/native-sandbox/wrapper.ts
/**
* Command Wrapper
*
* Wraps commands with the appropriate sandbox backend.
*/
/**
* Wrap a command with the appropriate sandbox backend.
*
* @param command - The full shell command string to run
* @param options - Wrapping options
* @returns The wrapped command and arguments
*
* @example
* ```typescript
* const wrapped = wrapCommand('node script.js', {
* backend: 'seatbelt',
* workspacePath: '/workspace',
* config: { allowNetwork: false },
* });
* // wrapped.command = 'sandbox-exec'
* // wrapped.args = ['-p', '<profile>', 'sh', '-c', 'node script.js']
* ```
*/
function wrapCommand(command, options) {
switch (options.backend) {
case "seatbelt": return buildSeatbeltCommand(command, options.seatbeltProfile ?? generateSeatbeltProfile(options.workspacePath, options.config));
case "bwrap": return buildBwrapCommand(command, options.workspacePath, options.config);
default: return {
command,
args: []
};
}
}
// src/workspace/sandbox/local-sandbox.ts
/**
* Local Sandbox Provider
*
* A sandbox implementation that executes commands on the local machine.
* This is the default sandbox for development and local agents.
*
* Supports optional native OS sandboxing:
* - macOS: Uses seatbelt (sandbox-exec) for filesystem and network isolation
* - Linux: Uses bubblewrap (bwrap) for namespace isolation
*/
/**
* Directory for mount marker files used to detect config changes across restarts.
*
* Resolved lazily so `os.tmpdir()` is never invoked at module-load time. The
* Agent/evals runtime (which transitively imports this module) is bundled into
* the Studio client, where `node:os` is shimmed to an empty object and
* `os.tmpdir` is `undefined`. Evaluating it at import time crashes Studio boot.
* See https://github.com/mastra-ai/mastra/issues/18519.
*/
function getMarkerDir() {
return path.join(os.tmpdir(), ".mastra-mounts");
}
/** Allowlist pattern for mount paths — absolute path with safe characters only. */
const SAFE_MOUNT_PATH = /^\/[a-zA-Z0-9_.\-/]+$/;
function validateMountPath(mountPath) {
if (!SAFE_MOUNT_PATH.test(mountPath)) throw new Error(`Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`);
const segments = mountPath.split("/").filter(Boolean);
if (segments.length === 0) throw new Error(`Invalid mount path: ${mountPath}. Root path "/" is not allowed.`);
if (segments.some((seg) => seg === "." || seg === "..")) throw new Error(`Invalid mount path: ${mountPath}. Path segments cannot be "." or "..".`);
}
/** Canonicalize mount path so `/data`, `/data/`, `//data` all resolve to `/data`. */
function normalizeMountPath(mountPath) {
return `/${mountPath.split("/").filter(Boolean).join("/")}`;
}
/**
* Executes workspace commands on the host machine for development and trusted
* local execution. Isolation requires explicit configuration.
*
* @example
* ```typescript
* import { Workspace, LocalSandbox } from '@mastra/core/workspace';
*
* const workspace = new Workspace({
* sandbox: new LocalSandbox({ workingDirectory: './my-workspace' }),
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Local sandbox documentation](https://mastra.ai/reference/workspace/local-sandbox)
* if packaged docs are unavailable.
*/
var LocalSandbox = class LocalSandbox extends MastraSandbox {
id;
name = "LocalSandbox";
provider = "local";
status = "pending";
isolation;
env;
_outputEncoding;
timeout;
_nativeSandboxConfig;
/**
* SBPL the user wrote, read from `seatbeltProfilePath` at start. Set only when that file
* already existed and does not carry our generated-profile marker. While it is undefined,
* `wrapCommand()` generates the profile from the live `_nativeSandboxConfig` on every call,
* so the profile always tracks the allowlist.
*/
_customSeatbeltProfile;
/** Where the profile file lives on disk: the configured path, or one we generated. */
_seatbeltProfilePath;
_sandboxFolderPath;
_createdAt;
_instructionsOverride;
_activeMountPaths = /* @__PURE__ */ new Set();
/** Snapshot of `readWritePaths` from ctor; entries here are never removed on unmount. */
_initialReadWritePaths;
/** Refcount for isolation paths added by mounts (not present in `_initialReadWritePaths`). */
_mountIsolationRefCount = /* @__PURE__ */ new Map();
/** Normalized mount path → canonical isolation path recorded for that mount. */
_mountPathToIsolationPath = /* @__PURE__ */ new Map();
/** Named checkpoint to seed from on start and persist to on snapshot. */
_checkpointName;
/** Boot-only fallback checkpoint used when `_checkpointName` has no state. */
_seedCheckpointName;
/** Directory where named checkpoints live. */
_checkpointsDirectory;
/** Chains snapshot() calls so concurrent captures never interleave. */
_snapshotChain = Promise.resolve();
/**
* The effective working directory. Narrowed to `string`: the constructor
* always computes a value (the option, expanded, or `<cwd>/.sandbox`), so
* unlike the base getter this never returns `undefined`.
*/
get workingDirectory() {
return this._workingDirectory;
}
constructor(options = {}) {
const requestedIsolation = options.isolation ?? "none";
if (requestedIsolation === "seatbelt" && process.platform === "win32") throw new IsolationUnavailableError("seatbelt", "Seatbelt isolation is only supported on macOS, not Windows.");
if (requestedIsolation !== "none" && !isIsolationAvailable(requestedIsolation)) throw new IsolationUnavailableError(requestedIsolation, detectIsolation().message);
super({
...options,
name: "LocalSandbox",
processes: new LocalProcessManager({
env: options.env ?? {},
outputEncoding: options.outputEncoding
})
});
this.timeout = options.timeout ?? 3e4;
this.defaultCommandTimeout = this.timeout;
this.id = options.id ?? this.generateId();
this._createdAt = /* @__PURE__ */ new Date();
this.setWorkingDirectory(require_workspace_skills.expandTilde(options.workingDirectory ?? path.join(process.cwd(), ".sandbox")));
this.env = options.env ?? {};
this._outputEncoding = options.outputEncoding;
this._nativeSandboxConfig = {
...options.nativeSandbox,
readWritePaths: [...options.nativeSandbox?.readWritePaths ?? []],
readOnlyPaths: [...options.nativeSandbox?.readOnlyPaths ?? []]
};
this._initialReadWritePaths = new Set(this._nativeSandboxConfig.readWritePaths ?? []);
this.isolation = requestedIsolation;
this._instructionsOverride = options.instructions;
this._checkpointName = options.checkpointName;
this._seedCheckpointName = options.seedCheckpointName;
this._checkpointsDirectory = options.checkpointsDirectory ? require_workspace_skills.expandTilde(options.checkpointsDirectory) : path.join(path.dirname(this.workingDirectory), ".checkpoints");
}
/**
* Construct a sibling `LocalSandbox` that inherits this sandbox's
* configuration (isolation, native sandbox config, instructions) with
* per-instance overrides.
*
* Performs no I/O — the sandbox clone creates its working directory on its
* own `start()`. `sandboxId` and `idleTimeoutMinutes` have no local
* equivalent and are ignored: local sandboxes reattach by logical `id` and
* have no provider-managed idle teardown.
*/
clone(options = {}) {
return new LocalSandbox({
...options.id !== void 0 && { id: options.id },
workingDirectory: options.workingDirectory ?? this.workingDirectory,
env: options.env ?? this.env,
timeout: this.timeout,
isolation: this.isolation,
outputEncoding: this._outputEncoding,
nativeSandbox: {
...this._nativeSandboxConfig,
readWritePaths: [...this._initialReadWritePaths],
readOnlyPaths: [...this._nativeSandboxConfig.readOnlyPaths ?? []]
},
...this._instructionsOverride !== void 0 && { instructions: this._instructionsOverride },
...(options.checkpointName ?? this._checkpointName) !== void 0 && { checkpointName: options.checkpointName ?? this._checkpointName },
...(options.seedCheckpointName ?? this._seedCheckpointName) !== void 0 && { seedCheckpointName: options.seedCheckpointName ?? this._seedCheckpointName },
checkpointsDirectory: this._checkpointsDirectory
});
}
/**
* Acquisition primitives (base-orchestrated start): an existing working
* directory is the "found sandbox" — reattaching reports `outcome: 'connected'`,
* a missing directory means a fresh sandbox (`outcome: 'created'`).
*
* This stat and the `mkdir` in `create()` are not atomic, so `'created'` is
* best-effort: two processes starting on the same working directory can both
* report it. Keep onStart setup idempotent.
*/
async find() {
try {
await fs_promises.stat(this.workingDirectory);
return this.workingDirectory;
} catch (err) {
if (err?.code !== "ENOENT") throw err;
return;
}
}
async connect(_handle) {
await this._prepareWorkspace();
}
async create() {
await this._prepareWorkspace();
}
/**
* Shared start body for both branches: ensure the working directory
* exists, seed it from a checkpoint when empty, and set up the seatbelt
* profile on macOS. Everything here is idempotent.
*/
async _prepareWorkspace() {
this.logger.debug("Starting sandbox", {
workingDirectory: this.workingDirectory,
isolation: this.isolation
});
await fs_promises.mkdir(this.workingDirectory, { recursive: true });
await this._seedFromCheckpoint();
if (this.isolation === "seatbelt") {
const userProvidedPath = this._nativeSandboxConfig.seatbeltProfilePath;
if (userProvidedPath) {
this._seatbeltProfilePath = userProvidedPath;
let existingProfile;
try {
existingProfile = await fs_promises.readFile(userProvidedPath, "utf-8");
} catch (err) {
if (err instanceof Error && "code" in err && err.code !== "ENOENT") throw err;
}
if (existingProfile !== void 0 && !isGeneratedSeatbeltProfile(existingProfile)) this._customSeatbeltProfile = existingProfile;
else {
this._customSeatbeltProfile = void 0;
const generatedProfile = generateSeatbeltProfile(this.workingDirectory, this._nativeSandboxConfig);
await fs_promises.mkdir(path.dirname(userProvidedPath), { recursive: true });
await fs_promises.writeFile(userProvidedPath, generatedProfile, "utf-8");
}
} else {
const generatedProfile = generateSeatbeltProfile(this.workingDirectory, this._nativeSandboxConfig);
const configHash = Buffer.from(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(this.workingDirectory + JSON.stringify(this._nativeSandboxConfig)))).toString("hex").slice(0, 8);
this._sandboxFolderPath = path.join(process.cwd(), ".sandbox-profiles");
await fs_promises.mkdir(this._sandboxFolderPath, { recursive: true });
this._seatbeltProfilePath = path.join(this._sandboxFolderPath, `seatbelt-${configHash}.sb`);
await fs_promises.writeFile(this._seatbeltProfilePath, generatedProfile, "utf-8");
}
}
this.logger.debug("Sandbox started", { workingDirectory: this.workingDirectory });
}
/** LocalSandbox persists real filesystem-backed checkpoints. */
supportsCheckpoints = true;
/** Resolve the on-disk directory for a named checkpoint, rejecting unsafe names. */
_checkpointPath(name) {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.includes("..")) throw new Error(`Invalid checkpoint name: ${name}`);
return path.join(this._checkpointsDirectory, name);
}
/**
* Seed an empty/missing working directory from the configured checkpoint.
* Missing checkpoint or already-populated workdir → no-op (normal start).
*/
async _seedFromCheckpoint() {
if (!this._checkpointName && !this._seedCheckpointName) return;
if ((await fs_promises.readdir(this.workingDirectory).catch(() => [])).length > 0) return;
const candidates = [this._checkpointName, this._seedCheckpointName].filter((name) => name !== void 0);
candidates: for (const name of candidates) {
const checkpointDir = this._checkpointPath(name);
if (!await this._checkpointIdentity(checkpointDir)) continue;
this.logger.debug("Seeding working directory from checkpoint", {
checkpointName: name,
checkpointDir
});
for (let attempt = 0; attempt < 5; attempt++) {
const before = await this._checkpointIdentity(checkpointDir);
if (!before) continue candidates;
try {
await fs_promises.cp(checkpointDir, this.workingDirectory, { recursive: true });
if (await this._checkpointIdentity(checkpointDir) === before) return;
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
await fs_promises.rm(this.workingDirectory, {
recursive: true,
force: true
});
await fs_promises.mkdir(this.workingDirectory, { recursive: true });
}
throw new Error(`Checkpoint "${name}" kept changing while seeding the working directory`);
}
}
/**
* Identity of the directory currently at `checkpointDir`, or undefined if no
* directory is there. Retries briefly to cover the instant in
* `_captureCheckpoint` where the old checkpoint has been renamed away but the
* replacement has not yet been renamed into place. The window is two atomic
* renames, so a couple of short retries close it.
*/
async _checkpointIdentity(checkpointDir) {
for (let attempt = 0; attempt < 3; attempt++) {
if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, 25));
try {
const stat = await fs_promises.stat(checkpointDir, { bigint: true });
return stat.isDirectory() ? `${stat.dev}:${stat.ino}:${stat.ctimeNs}` : void 0;
} catch {}
}
}
/**
* Persist the working directory as the configured named checkpoint.
* Copies to a temp sibling, then swaps it into place with rename so a
* concurrent boot always observes a complete checkpoint. No-op when no
* checkpoint name is set.
*/
async snapshot() {
if (!this._checkpointName) return;
const run = this._snapshotChain.then(() => this._captureCheckpoint(this._checkpointName));
this._snapshotChain = run.catch(() => {});
return run;
}
async _captureCheckpoint(name) {
const target = this._checkpointPath(name);
await fs_promises.mkdir(this._checkpointsDirectory, { recursive: true });
const tmp = path.join(this._checkpointsDirectory, `.tmp-${name}-${Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6))).toString("hex")}`);
const backup = path.join(this._checkpointsDirectory, `.bak-${name}-${Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6))).toString("hex")}`);
let targetMoved = false;
try {
await fs_promises.cp(this.workingDirectory, tmp, { recursive: true });
try {
await fs_promises.rename(target, backup);
targetMoved = true;
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
await fs_promises.rename(tmp, target);
} catch (error) {
await fs_promises.rm(tmp, {
recursive: true,
force: true
}).catch(() => {});
if (targetMoved) await fs_promises.rename(backup, target).catch(() => {});
throw error;
}
if (targetMoved) await fs_promises.rm(backup, {
recursive: true,
force: true
}).catch(() => {});
this.logger.debug("Captured checkpoint", {
checkpointName: name,
target
});
}
/**
* Stop the local sandbox.
* Kills background processes and unmounts all active mounts. Unlike remote
* providers, a local sandbox has no suspend/resume — its background
* processes ARE the runtime state, so a stopped sandbox must not leave them
* running. Files in the working directory are untouched and `start()` works
* again afterwards.
* Status management is handled by the base class.
*/
async stop() {
this.logger.debug("Stopping sandbox", { workingDirectory: this.workingDirectory });
const procs = await this.processes.list();
await Promise.all(procs.map((p) => this.processes.kill(p.pid)));
for (const mountPath of [...this._activeMountPaths]) try {
await this.unmount(mountPath);
} catch {}
}
/**
* Destroy the local sandbox and clean up resources.
* Unmounts all filesystems, clears mount state, and cleans up seatbelt profile.
* Status management is handled by the base class.
*/
async destroy() {
this.logger.debug("Destroying sandbox", { workingDirectory: this.workingDirectory });
const procs = await this.processes.list();
await Promise.all(procs.map((p) => this.processes.kill(p.pid)));
for (const mountPath of [...this._activeMountPaths]) try {
await this.unmount(mountPath);
} catch {}
this._activeMountPaths.clear();
this.mounts.clear();
if (this._seatbeltProfilePath && !this._nativeSandboxConfig.seatbeltProfilePath) try {
await fs_promises.unlink(this._seatbeltProfilePath);
} catch {}
this._seatbeltProfilePath = void 0;
this._customSeatbeltProfile = void 0;
if (this._sandboxFolderPath) {
try {
await fs_promises.rmdir(this._sandboxFolderPath);
} catch {}
this._sandboxFolderPath = void 0;
}
}
/** @deprecated Use `status === 'running'` instead. */
async isReady() {
return this.status === "running";
}
async getInfo() {
return {
id: this.id,
name: this.name,
provider: this.provider,
status: this.status,
createdAt: this._createdAt,
resources: {
memoryMB: Math.round(os.totalmem() / 1024 / 1024),
cpuCores: os.cpus().length
},
metadata: {
workingDirectory: this.workingDirectory,
platform: os.platform(),
nodeVersion: process.version,
isolation: this.isolation,
isolationConfig: this.isolation !== "none" ? {
allowNetwork: this._nativeSandboxConfig.allowNetwork ?? false,
readOnlyPaths: this._nativeSandboxConfig.readOnlyPaths,
readWritePaths: this._nativeSandboxConfig.readWritePaths
} : void 0
}
};
}
getInstructions(opts) {
return resolveInstructions(this._instructionsOverride, () => this._getDefaultInstructions(), opts?.requestContext);
}
_getDefaultInstructions() {
return `Local command execution. Working directory: "${this.workingDirectory}".`;
}
generateId() {
return `local-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
/**
* Build the environment object for execution.
* Always includes PATH by default (needed for finding executables).
* Merges the sandbox's configured env with any additional env from the command.
* @internal Used by LocalProcessManager.
*/
buildEnv(additionalEnv) {
return {
PATH: process.env.PATH,
...this.env,
...additionalEnv
};
}
/**
* Mount a filesystem at a path on the local host.
*
* - **local** — Creates a symlink from `<workingDir>/<mount>` to the basePath.
*
* Virtual mount paths (e.g. `/s3`) are resolved under the sandbox's workingDirectory.
* Other mount types can be handled via the `onMount` hook.
*/
async mount(filesystem, mountPath) {
validateMountPath(mountPath);
mountPath = normalizeMountPath(mountPath);
const hostPath = this.resolveHostPath(mountPath);
this.logger.debug("Mounting", {
mountPath,
hostPath
});
const config = filesystem.getMountConfig?.();
if (!config) {
const error = `Filesystem "${filesystem.id}" does not provide a mount config`;
this.logger.error("Filesystem does not provide a mount config", { filesystemId: filesystem.id });
this.mounts.set(mountPath, {
filesystem,
state: "error",
error
});
return {
success: false,
mountPath,
error
};
}
const existingMount = await this.checkExistingMount(hostPath, config);
if (existingMount === "matching") {
this.logger.debug("Detected existing mount with correct config, skipping", {
provider: filesystem.provider,
filesystemId: filesystem.id,
hostPath
});
this.mounts.set(mountPath, {
filesystem,
state: "mounted",
config
});
this._activeMountPaths.add(mountPath);
this.addMountPathToIsolation(mountPath, hostPath);
return {
success: true,
mountPath
};
} else if (existingMount === "foreign") {
const error = `Cannot mount at ${hostPath}: path is already occupied by an existing mount or symlink that was not created by Mastra. Unmount it manually or use a different mount path.`;
this.logger.error("Mount path occupied by foreign mount or symlink", { hostPath });
this.mounts.set(mountPath, {
filesystem,
state: "error",
config,
error
});
return {
success: false,
mountPath,
error
};
} else if (existingMount === "mismatched") {
this.logger.debug("Config mismatch on our mount, unmounting to re-mount with new config");
await this.unmount(mountPath);
}
this.logger.debug("Mount config type", { type: config.type });
if (config.type !== "local") {
const error = `Unsupported mount type: ${config.type}`;
this.mounts.set(mountPath, {
filesystem,
state: "unsupported",
config,
error
});
return {
success: false,
mountPath,
error
};
}
this.mounts.set(mountPath, {
filesystem,
state: "mounting",
config
});
try {
if ((await fs_promises.readdir(hostPath)).length > 0) {
const error = `Cannot mount at ${hostPath}: directory exists and is not empty. Mounting would hide existing files. Use a different path or empty the directory first.`;
this.logger.error("Cannot mount at non-empty directory", { hostPath });
this.mounts.set(mountPath, {
filesystem,
state: "error",
config,
error
});
return {
success: false,
mountPath,
error
};
}
await fs_promises.rmdir(hostPath);
} catch (err) {
if ((err instanceof Error && "code" in err ? err.code : void 0) === "ENOTDIR") {
const error = `Cannot mount at ${hostPath}: path is a regular file. Use a different mount path or remove the file first.`;
this.logger.error("Cannot mount at path that is a regular file", { hostPath });
this.mounts.set(mountPath, {
filesystem,
state: "error",
config,
error
});
return {
success: false,
mountPath,
error
};
}
}
const localConfig = config;
try {
await fs_promises.mkdir(path.dirname(hostPath), { recursive: true });
await fs_promises.symlink(localConfig.basePath, hostPath);
this.logger.debug("Symlinked local mount", {
hostPath,
basePath: localConfig.basePath
});
} catch (error) {
this.logger.error("Error mounting filesystem", {
provider: filesystem.provider,
filesystemId: filesystem.id,
hostPath,
error
});
this.mounts.set(mountPath, {
filesystem,
state: "error",
config,
error: String(error)
});
return {
success: false,
mountPath,
error: String(error)
};
}
this.mounts.set(mountPath, {
filesystem,
state: "mounted",
config
});
this._activeMountPaths.add(mountPath);
await this.writeMarkerFile(mountPath, hostPath);
this.addMountPathToIsolation(mountPath, hostPath);
this.logger.debug("Mounted", {
mountPath,
hostPath
});
return {
success: true,
mountPath
};
}
/**
* Unmount a filesystem from a path.
*/
async unmount(mountPath) {
validateMountPath(mountPath);
mountPath = normalizeMountPath(mountPath);
const hostPath = this.resolveHostPath(mountPath);
this.logger.debug("Unmounting", {
mountPath,
hostPath
});
this.removeMountIsolationForPath(mountPath);
let isSymlink = false;
try {
isSymlink = (await fs_promises.lstat(hostPath)).isSymbolicLink();
} catch {}
this.mounts.delete(mountPath);
this._activeMountPaths.delete(mountPath);
const filename = this.mounts.markerFilename(hostPath);
const markerPath = path.join(getMarkerDir(), filename);
try {
await fs_promises.unlink(markerPath);
} catch {}
if (isSymlink) try {
await fs_promises.unlink(hostPath);
this.logger.debug("Unmounted and removed symlink", { hostPath });
} catch {
this.logger.debug("Could not remove symlink", { hostPath });
}
}
/**
* Write a marker file for detecting config changes.
* Uses hostPath (resolved OS path) for the marker filename and content,
* and mountPath (virtual path) for looking up the entry.
*/
async writeMarkerFile(mountPath, hostPath) {
const entry = this.mounts.get(mountPath);
if (!entry?.configHash) return;
const filename = this.mounts.markerFilename(hostPath);
const markerContent = `${hostPath}|${entry.configHash}`;
const markerFilePath = path.join(getMarkerDir(), filename);
try {
await fs_promises.mkdir(getMarkerDir(), { recursive: true });
await fs_promises.writeFile(markerFilePath, markerContent, "utf-8");
} catch {
this.logger.debug("Could not write marker file", { markerFilePath });
}
}
/**
* Check if a path is already mounted and if the config matches.
* Uses hostPath (resolved OS path) for checking the actual mount point.
*/
async checkExistingMount(hostPath, newConfig) {
try {
const stats = await fs_promises.lstat(hostPath);
if (stats.isSymbolicLink() && newConfig.type === "local") {
const linkTarget = await fs_promises.readlink(hostPath).catch(() => null);
const resolvedTarget = linkTarget ? path.resolve(path.dirname(hostPath), linkTarget) : null;
const expectedTarget = path.resolve(newConfig.basePath);
if (!resolvedTarget || resolvedTarget !== expectedTarget) return await this.hasMarkerFile(hostPath) ? "mismatched" : "foreign";
return this.checkMarkerFile(hostPath, newConfig);
} else if (stats.isSymbolicLink()) return await this.hasMarkerFile(hostPath) ? "mismatched" : "foreign";
} catch {}
return "not_mounted";
}
/**
* Check if a marker file exists for a given host path (regardless of content).
* Returns true if we previously created a mount here.
*/
async hasMarkerFile(hostPath) {
const filename = this.mounts.markerFilename(hostPath);
const markerPath = path.join(getMarkerDir(), filename);
try {
await fs_promises.access(markerPath);
return true;
} catch {
return false;
}
}
/**
* Check if a marker file matches the given config.
* Returns 'matching' if hash matches, 'mismatched' if hash differs,
* or 'foreign' if no marker exists (we didn't create this mount).
*/
async checkMarkerFile(hostPath, newConfig) {
const filename = this.mounts.markerFilename(hostPath);
const markerPath = path.join(getMarkerDir(), filename);
try {
const content = await fs_promises.readFile(markerPath, "utf-8");
const parsed = this.mounts.parseMarkerContent(content.trim());
if (!parsed) return "mismatched";
const newConfigHash = this.mounts.computeConfigHash(newConfig);
this.logger.debug("Marker check", {
storedHash: parsed.configHash,
newConfigHash
});
if (parsed.path === hostPath && parsed.configHash === newConfigHash) return "matching";
return "mismatched";
} catch {
return "foreign";
}
}
/**
* Dynamically add a mount path to the sandbox isolation allowlist.
*
* - Seatbelt: pushes to readWritePaths (wrapCommand reads config each call)
* - Bwrap: pushes to readWritePaths (buildBwrapCommand reads config each call)
*
* Local mounts are symlinks under `workingDirectory`. Bubblewrap cannot
* `--bind` a symlink (it fails with "Unable to mount source on destination"),
* so we store the canonical path (`realpath`) of the mount point — the same
* directory the symlink refers to.
*/
addMountPathToIsolation(mountPath, hostPath) {
if (this.isolation === "none") return;
const normMount = normalizeMountPath(mountPath);
if (this._mountPathToIsolationPath.has(normMount)) return;
let isolationPath = hostPath;
try {
isolationPath = (0, fs.realpathSync)(hostPath);
} catch {}
if (!this._nativeSandboxConfig.readWritePaths) this._nativeSandboxConfig = {
...this._nativeSandboxConfig,
readWritePaths: []
};
const paths = this._nativeSandboxConfig.readWritePaths;
if (!paths.includes(isolationPath)) paths.push(isolationPath);
if (!this._initialReadWritePaths.has(isolationPath)) this._mountIsolationRefCount.set(isolationPath, (this._mountIsolationRefCount.get(isolationPath) ?? 0) + 1);
this._mountPathToIsolationPath.set(normMount, isolationPath);
}
/**
* Reverse {@link addMountPathToIsolation}: drop refcounted paths from the allowlist on unmount
* while preserving user-provided `readWritePaths` from construction.
*/
removeMountIsolationForPath(mountPath) {
if (this.isolation === "none") return;
const normMount = normalizeMountPath(mountPath);
const isolationPath = this._mountPathToIsolationPath.get(normMount);
if (isolationPath === void 0) return;
this._mountPathToIsolationPath.delete(normMount);
if (this._initialReadWritePaths.has(isolationPath)) return;
const next = (this._mountIsolationRefCount.get(isolationPath) ?? 0) - 1;
if (next <= 0) {
this._mountIsolationRefCount.delete(isolationPath);
const paths = this._nativeSandboxConfig.readWritePaths;
if (paths) {
const idx = paths.indexOf(isolationPath);
if (idx !== -1) paths.splice(idx, 1);
}
} else this._mountIsolationRefCount.set(isolationPath, next);
}
/**
* Resolve a virtual mount path to a host filesystem path.
*
* Virtual paths like "/s3" become `<workingDir>/s3`. This differs from E2B
* where root-level paths like `/s3` are used directly (E2B runs in a VM with sudo).
* LocalSandbox runs on the host, so mounts are scoped under workingDirectory.
*/
resolveHostPath(mountPath) {
return path.join(this.workingDirectory, mountPath.replace(/^\/+/, ""));
}
/**
* Wrap a command with the configured isolation backend.
* @internal Used by LocalProcessManager for background process isolation.
*/
wrapCommandForIsolation(command) {
if (this.isolation === "none") return {
command,
args: []
};
return wrapCommand(command, {
backend: this.isolation,
workspacePath: this.workingDirectory,
seatbeltProfile: this._customSeatbeltProfile,
config: this._nativeSandboxConfig
});
}
/**
* Detect the best available isolation backend for this platform.
* Returns detection result with backend recommendation and availability.
*
* @example
* ```typescript
* const result = LocalSandbox.detectIsolation();
* const sandbox = new LocalSandbox({
* isolation: result.available ? result.backend : 'none',
* });
* ```
*/
static detectIsolation() {
return detectIsolation();
}
};
// src/workspace/tools/apply-patch-parser.ts
/**
* Parser and in-memory applier for the apply_patch format used by OpenAI Codex
* and OpenCode:
*
* ```
* *** Begin Patch
* *** Add File: path/to/new.ts
* +line one
* *** Update File: path/to/existing.ts
* *** Move to: path/to/renamed.ts
* @@ optional context line
* unchanged line
* -removed line
* +added line
* *** Delete File: path/to/old.ts
* *** End Patch
* ```
*
* Parsing and applying are pure: nothing here touches a filesystem.
*/
var ApplyPatchError = class extends Error {
constructor(message) {
super(message);
this.name = "ApplyPatchError";
}
};
const BEGIN_PATCH = "*** Begin Patch";
const END_PATCH = "*** End Patch";
const ADD_FILE = "*** Add File: ";
const DELETE_FILE = "*** Delete File: ";
const UPDATE_FILE = "*** Update File: ";
const MOVE_TO = "*** Move to: ";
const END_OF_FILE = "*** End of File";
function isFileHeader(line) {
return line.startsWith(ADD_FILE) || line.startsWith(DELETE_FILE) || line.startsWith(UPDATE_FILE) || line === END_PATCH;
}
function headerPath(line, prefix, lineNumber) {
const path$6 = line.slice(prefix.length).trim();
if (!path$6) throw new ApplyPatchError(`Line ${lineNumber}: missing file path after "${prefix.trim()}"`);
return path.posix.normalize(path$6);
}
/**
* Parse a patch into its file operations. Throws {@link ApplyPatchError} on
* malformed input or when the same path is touched more than once.
*/
function parsePatch(patch) {
const lines = patch.replace(/\r\n/g, "\n").split("\n");
while (lines.length > 0 && lines[0].trim() === "") lines.shift();
while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop();
if (lines[0]?.trim() !== BEGIN_PATCH) throw new ApplyPatchError(`The first line of the patch must be "${BEGIN_PATCH}"`);
if (lines.length < 2 || lines[lines.length - 1].trim() !== END_PATCH) throw new ApplyPatchError(`The last line of the patch must be "${END_PATCH}"`);
const operations = [];
let i = 1;
const last = lines.length - 1;
while (i < last) {
const line = lines[i];
const lineNumber = i + 1;
if (line.startsWith(ADD_FILE)) {
const path = headerPath(line, ADD_FILE, lineNumber);
i++;
const contentLines = [];
while (i < last && !isFileHeader(lines[i])) {
const bodyLine = lines[i];
if (!bodyLine.startsWith("+")) throw new ApplyPatchError(`Line ${i + 1}: every line of an added file must start with "+"`);
contentLines.push(bodyLine.slice(1));
i++;
}
operations.push({
type: "add",
path,
content: contentLines.length ? contentLines.join("\n") + "\n" : ""
});
continue;
}
if (line.startsWith(DELETE_FILE)) {
operations.push({
type: "delete",
path: headerPath(line, DELETE_FILE, lineNumber)
});
i++;
continue;
}
if (line.startsWith(UPDATE_FILE)) {
const path = headerPath(line, UPDATE_FILE, lineNumber);
i++;
let moveTo;
if (i < last && lines[i].startsWith(MOVE_TO)) {
moveTo = headerPath(lines[i], MOVE_TO, i + 1);
i++;
}
const chunks = [];
let current;
while (i < last && !isFileHeader(lines[i])) {
const bodyLine = lines[i];
if (bodyLine === "@@" || bodyLine.startsWith("@@ ")) {
current = {
context: bodyLine.slice(2).trim() || void 0,
oldLines: [],
newLines: [],
contextSource: [],
isEndOfFile: false
};
chunks.push(current);
} else if (bodyLine.trim() === END_OF_FILE) {
if (!current) throw new ApplyPatchError(`Line ${i + 1}: "${END_OF_FILE}" must follow a hunk`);
current.isEndOfFile = true;
current = void 0;
} else {
if (!current) {
if (chunks.length > 0) throw new ApplyPatchError(`Line ${i + 1}: expected "@@" to start a new hunk`);
current = {
oldLines: [],
newLines: [],
contextSource: [],
isEndOfFile: false
};
chunks.push(current);
}
const marker = bodyLine[0];
const text = bodyLine.slice(1);
if (bodyLine === "" || marker === " ") {
current.contextSource.push(current.oldLines.length);
current.oldLines.push(text);
current.newLines.push(text);
} else if (marker === "-") current.oldLines.push(text);
else if (marker === "+") {
current.contextSource.push(void 0);
current.newLines.push(text);
} else throw new ApplyPatchError(`Line ${i + 1}: hunk lines must start with " " (context), "-" (remove) or "+" (add)`);
}
i++;
}
if (chunks.length === 0 && !moveTo) throw new ApplyPatchError(`Line ${lineNumber}: "${UPDATE_FILE.trim()}" for ${path} has no hunks`);
const isEmpty = (chunk) => chunk.oldLines.length === 0 && chunk.newLines.length === 0;
if (chunks.some((chunk, k) => isEmpty(chunk) && (chunk.context === void 0 || k === chunks.length - 1))) throw new ApplyPatchError(`Line ${lineNumber}: "${UPDATE_FILE.trim()}" for ${path} has an empty hunk`);
operations.push({
type: "update",
path,
moveTo,
chunks
});
continue;
}
throw new ApplyPatchError(`Line ${lineNumber}: expected "${ADD_FILE.trim()}", "${UPDATE_FILE.trim()}" or "${DELETE_FILE.trim()}", got "${line}"`);
}
if (operations.length === 0) throw new ApplyPatchError("The patch contains no file operations");
const seen = /* @__PURE__ */ new Set();
for (const path of patchPaths(operations)) {
if (seen.has(path)) throw new ApplyPatchError(`The patch touches ${path} more than once; combine those changes into one operation`);
seen.add(path);
}
return operations;
}
/** Every path a set of operations reads or writes, including move destinations. */
function patchPaths(operations) {
return operations.flatMap((op) => op.type === "update" && op.moveTo ? [op.path, op.moveTo] : [op.path]);
}
/**
* Find `pattern` in `lines` at or after `start`. Tries an exact match first,
* then ignores trailing whitespace, then ignores surrounding whitespace.
*/
function seekSequence(lines, pattern, start, endOfFile) {
if (pattern.length === 0) return start;
if (pattern.length > lines.length) return -1;
const lastStart = lines.length - pattern.length;
const from = endOfFile ? lastStart : start;
const normalizers = [
(s) => s,
(s) => s.trimEnd(),
(s) => s.trim()
];
for (const normalize of normalizers) for (let i = from; i <= lastStart; i++) {
let matched = true;
for (let j = 0; j < pattern.length; j++) if (normalize(lines[i + j]) !== normalize(pattern[j])) {
matched = false;
break;
}
if (matched) return i;
}
return -1;
}
/**
* Apply update hunks to file content in memory. Throws {@link ApplyPatchError}
* when a hunk cannot be located. Preserves the file's line endings and whether
* it ends with a newline.
*/
function applyChunks(content, chunks, path) {
const eol = content.includes("\r\n") ? "\r\n" : "\n";
const hadTrailingNewline = content.length === 0 || content.endsWith("\n");
const lines = content.split(/\r?\n/);
if (hadTrailingNewline) lines.pop();
const replacements = [];
let cursor = 0;
for (const chunk of chunks) {
if (chunk.context !== void 0) {
const contextIndex = seekSequence(lines, [chunk.context], cursor, false);
if (contextIndex === -1) throw new ApplyPatchError(`Could not find context line "${chunk.context}" in ${path}`);
cursor = contextIndex + 1;
}
if (chunk.oldLines.length === 0 && chunk.newLines.length === 0) continue;
if (chunk.oldLines.length === 0) {
const at = chunk.context !== void 0 ? cursor : lines.length;
replacements.push({
start: at,
deleteCount: 0,
newLines: chunk.newLines
});
cursor = at;
continue;
}
let oldLines = chunk.oldLines;
let newLines = chunk.newLines;
let index = seekSequence(lines, oldLines, cursor, chunk.isEndOfFile);
if (index === -1 && oldLines[oldLines.length - 1] === "") {
oldLines = oldLines.slice(0, -1);
if (newLines[newLines.length - 1] === "") newLines = newLines.slice(0, -1);
index = seekSequence(lines, oldLines, cursor, chunk.isEndOfFile);
}
if (index === -1) throw new ApplyPatchError(`Could not find the lines to replace in ${path}:\n${chunk.oldLines.join("\n")}\nRead the file again and make sure context and "-" lines match its current content.`);
replacements.push({
start: index,
deleteCount: oldLines.length,
newLines: newLines.map((line, k) => {
const source = chunk.contextSource[k];
return source !== void 0 && source < oldLines.length ? lines[index + source] : line;
})
});
cursor = index + oldLines.length;
}
for (const { start, deleteCount, newLines } of [...replacements].reverse()) lines.splice(start, deleteCount, ...newLines);
if (lines.length === 0) return "";
return lines.join(eol) + (hadTrailingNewline ? eol : "");
}
// src/workspace/tools/helpers.ts
/**
* Workspace Tool Helpers
*
* Runtime assertions for extracting workspace resources from tool execution context.
*/
const NUMERIC_STRING_REGEX = /^-?\d+(?:\.\d+)?$/;
/**
* Preprocessor for numeric tool params: models sometimes send numbers as
* strings (e.g. `"10"` instead of `10`), and a strict `z.number()` rejects
* the call outright. Coerce unambiguous numeric strings; anything else
* passes through unchanged so schema validation still reports it.
*/
function coerceNumericString(value) {
if (typeof value !== "string") return value;
const trimmed = value.trim();
return NUMERIC_STRING_REGEX.test(trimmed) ? Number(trimmed) : value;
}
/**
* Extract workspace from tool execution context.
* Throws if workspace is not available.
*/
function requireWorkspace(context) {
if (!context?.workspace) throw new require_errors.WorkspaceNotAvailableError();
return context.workspace;
}
/**
* Extract filesystem from workspace in tool execution context.
* Throws if workspace or filesystem is not available.
*/
function requireFilesystem(context) {
const workspace = requireWorkspace(context);
if (!workspace.filesystem) throw new require_errors.FilesystemNotAvailableError();
return {
workspace,
filesystem: workspace.filesystem
};
}
/**
* Extract sandbox from workspace in tool execution context.
* Throws if workspace or sandbox is not available.
*/
function requireSandbox(context) {
const workspace = requireWorkspace(context);
if (!workspace.sandbox) throw new require_errors.SandboxNotAvailableError();
return {
workspace,
sandbox: workspace.sandbox
};
}
function getDynamicSandboxCacheKeyHint(workspace) {
const hasResolver = workspace.hasSandboxResolver();
const hasCacheKey = workspace.hasSandboxCacheKey();
if (!hasResolver || hasCacheKey) return "";
return " If this process was started from a dynamic sandbox resolver, configure sandboxCacheKey or have the resolver return the same sandbox for follow-up calls.";
}
/**
* Emit workspace metadata as a data chunk so the UI can render workspace info immediately.
* Should be called at the start of every workspace tool's execute function.
*/
async function emitWorkspaceMetadata(context, toolName) {
const info = await requireWorkspace(context).getInfo({
requestContext: context?.requestContext,
resolveDynamicProviders: false
});
const toolCallId = context?.agent?.toolCallId;
await context?.writer?.custom({
type: "data-workspace-metadata",
data: {
toolName,
toolCallId,
...info
}
});
}
/**
* Get LSP diagnostics text to append to edit tool results.
* Non-blocking — returns empty string on any failure.
*
* LSP is a Workspace-level feature. This helper checks if the workspace
* has an LSP manager and uses it to get diagnostics for the edited file.
*
* @param workspace - The workspace (must have an LSP manager for diagnostics)
* @param filePath - Relative path within the filesystem (as used by the tool)
* @param content - The file content after the edit
* @returns Formatted diagnostics text, or empty string if unavailable
*/
async function getEditDiagnosticsText(workspace, filePath, content) {
try {
const lspManager = workspace.lsp;
if (!lspManager) return "";
const isWindowsRoot = /^[A-Za-z]:[\\/]/.test(lspManager.root) || /^(?:\\\\|\/\/)[^\\]+[\\][^\\/]+/.test(lspManager.root);
const absolutePath = workspace.filesystem?.resolveAbsolutePath?.(filePath) ?? (isWindowsRoot ? path.default.win32.resolve(lspManager.root, filePath.replace(/^\/+/, "")) : path.default.posix.resolve(lspManager.root, filePath.replace(/^\/+/, "")));
const DIAG_TIMEOUT_MS = 1e4;
let diagTimer;
const diagnostics = await Promise.race([lspManager.getDiagnostics(absolutePath, content), new Promise((_, reject) => {
diagTimer = setTimeout(() => reject(/* @__PURE__ */ new Error("LSP diagnostics timeout")), DIAG_TIMEOUT_MS);
})]).finally(() => clearTimeout(diagTimer));
if (diagnostics === null) return "";
if (diagnostics.length === 0) return "";
const seen = /* @__PURE__ */ new Set();
const deduped = diagnostics.filter((d) => {
const key = `${d.severity}:${d.line}:${d.character}:${d.message}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
const groups = {
error: [],
warning: [],
info: [],
hint: []
};
for (const d of deduped) groups[d.severity].push(d);
const lines = ["\n\nLSP Diagnostics:"];
for (const [severity, label] of [
["error", "Errors"],
["warning", "Warnings"],
["info", "Info"],
["hint", "Hints"]
]) {
const items = groups[severity];
if (items.length === 0) continue;
lines.push(`${label}:`);
for (const d of items) {
const source = d.source ? ` [${d.source}]` : "";
lines.push(` ${d.line}:${d.character} - ${d.message}${source}`);
}
}
let result = lines.join("\n");
const maxChars = 2e3;
if (result.length > maxChars) {
const cutoff = result.lastIndexOf("\n", maxChars);
result = result.slice(0, cutoff > 0 ? cutoff : maxChars) + "\n ... (truncated)";
}
return result;
} catch {
return "";
}
}
// src/workspace/tools/tracing.ts
const ENV_FIELD_NAMES = /* @__PURE__ */ new Set([
"env",
"environment",
"process_env"
]);
const SECRET_FIELD_PATTERN = /(^|[_-])(api[_-]?key|key|token|secret|password|passwd|pwd|credential|credentials|auth|authorization|cookie|session)([_-]|$)/i;
function normalizeFieldName(key) {
return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
}
function isPlainObject(value) {
return Object.prototype.toString.call(value) === "[object Object]";
}
function redactEnv(value) {
return {
redacted: true,
keys: isPlainObject(value) || Array.isArray(value) ? Object.keys(value).sort() : void 0
};
}
function sanitizeWorkspaceTraceData(value, seen = /* @__PURE__ */ new WeakSet()) {
if (Array.isArray(value)) {
if (seen.has(value)) return "[redacted:circular]";
seen.add(value);
try {
return value.map((item) => sanitizeWorkspaceTraceData(item, seen));
} finally {
seen.delete(value);
}
}
if (!isPlainObject(value)) return value;
if (seen.has(value)) return "[redacted:circular]";
seen.add(value);
try {
return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
const normalized = normalizeFieldName(key);
if (ENV_FIELD_NAMES.has(normalized)) return [key, redactEnv(entry)];
if (SECRET_FIELD_PATTERN.test(normalized)) return [key, "[redacted]"];
return [key, sanitizeWorkspaceTraceData(entry, seen)];
}));
} finally {
seen.delete(value);
}
}
/**
* Start a WORKSPACE_ACTION child span from the tool execution context.
*
* Returns a handle with `end()` and `error()` methods. If no tracing context
* is available (no parent span), all operations are safe no-ops.
*
* @example
* ```typescript
* const span = startWorkspaceSpan(context, workspace, {
* category: 'filesystem',
* operation: 'readFile',
* input: { path },
* attributes: { filesystemProvider: filesystem.provider },
* });
* try {
* const result = await filesystem.readFile(path);
* span.end({ success: true }, { bytesTransferred: result.length });
* return result;
* } catch (err) {
* span.error(err);
* throw err;
* }
* ```
*/
function startWorkspaceSpan(context, workspace, options) {
const currentSpan = context?.tracing?.currentSpan ?? context?.tracingContext?.currentSpan;
if (!currentSpan) return noOpHandle;
const { category, operation, input, attributes } = options;
const span = currentSpan.createChildSpan({
type: "workspace_action",
name: `workspace:${category}:${operation}`,
input: sanitizeWorkspaceTraceData(input),
attributes: {
category,
workspaceId: workspace?.id,
workspaceName: workspace?.name,
...attributes
}
});
return {
span,
end(attrs, output) {
span?.end({
output: sanitizeWorkspaceTraceData(output),
attributes: { ...attrs }
});
},
error(err, attrs) {
const error = err instanceof Error ? err : new Error(String(err));
span?.error({
error,
attributes: {
success: false,
...attrs
}
});
}
};
}
/** No-op handle when tracing is not available */
const noOpHandle = {
span: void 0,
end() {},
error() {}
};
/** No-op handle when tracing is not available */
const noOpSkillHandle = {
span: void 0,
end() {},
error() {}
};
/**
* Start a SKILL_ACTION child span from the tool execution context.
*
* Skill operations were previously traced as `WORKSPACE_ACTION` with
* `category: 'skill'`, which only held while skills lived on a workspace.
* Agent-level skills have no workspace, so skills get their own span type and
* all five operations (resolve, inject, activate, search, read) share it.
*
* Returns a handle with `end()` and `error()`. With no parent span every
* operation is a safe no-op.
*/
function startSkillSpan(context, options) {
const currentSpan = context?.tracing?.currentSpan ?? context?.tracingContext?.currentSpan;
if (!currentSpan) return noOpSkillHandle;
const { operation, input, attributes } = options;
const span = currentSpan.createChildSpan({
type: "skill_action",
name: `skill:${operation}`,
input: sanitizeWorkspaceTraceData(input),
attributes: {
operation,
...attributes
}
});
return {
span,
end(attrs, output) {
span?.end({
output: sanitizeWorkspaceTraceData(output),
attributes: { ...attrs }
});
},
error(err, attrs) {
const error = err instanceof Error ? err : new Error(String(err));
span?.error({
error,
attributes: {
success: false,
...attrs
}
});
}
};
}
// src/workspace/tools/apply-patch.ts
/**
* Paths a patch writes, used to take write locks and run read-before-write
* checks before the tool executes. Returns `[]` for a malformed patch so the
* tool itself can report the parse error.
*/
function getApplyPatchWritePaths(input) {
if (typeof input?.patch !== "string") return [];
try {
return patchPaths(parsePatch(input.patch));
} catch {
return [];
}
}
const PATCH_NOT_APPLIED = "Patch not applied, no files were changed:";
/** False when the tool returned a validation failure and touched no file. */
function applyPatchDidWrite(result) {
return !(typeof result === "string" && result.startsWith(PATCH_NOT_APPLIED));
}
async function statOrUndefined(filesystem, path) {
try {
return await filesystem.stat(path);
} catch (error) {
if (error instanceof require_errors.FileNotFoundError) return void 0;
throw error;
}
}
function checkNotStale(path, stat, expectedMtimes) {
const expected = expectedMtimes?.[path];
if (expected && stat.modifiedAt.getTime() !== expected.getTime()) throw new require_errors.StaleFileError(path, expected, stat.modifiedAt);
}
async function requireExistingFile(filesystem, path, expectedMtimes) {
const stat = await statOrUndefined(filesystem, path);
if (!stat) throw new ApplyPatchError(`${path} does not exist`);
if (stat.type !== "file") throw new ApplyPatchError(`${path} is a directory, not a file`);
checkNotStale(path, stat, expectedMtimes);
return stat.modifiedAt;
}
async function requireMissing(filesystem, path) {
if (await statOrUndefined(filesystem, path)) throw new ApplyPatchError(`${path} already exists`);
}
const applyPatchTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.APPLY_PATCH,
description: `Create, update, move and delete files in one call by applying a patch. Every change applies, or none do.
Format:
*** Begin Patch
*** Add File: path/to/new-file.ts
+first line of the new file
+second line
*** Update File: path/to/existing.ts
*** Move to: path/to/renamed.ts
@@ optional line near the change, e.g. a function signature
unchanged context line
-line to remove
+line to add
*** Delete File: path/to/obsolete.ts
*** End Patch
Rules:
- Paths are relative to the workspace root. Each path may appear only once per patch.
- "*** Move to:" is optional and must directly follow "*** Update File:".
- In an update, each line starts with " " (context), "-" (remove) or "+" (add). Include about 3 lines of context around each change so it can be located. Start each further hunk with "@@".
- "*** End of File" after a hunk anchors it to the end of the file.
- Added files must not already exist; updated and deleted files must exist.`,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({ patch: zod_v4.z.string().describe("The full patch text, from \"*** Begin Patch\" to \"*** End Patch\"") }),
execute: async ({ patch }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.APPLY_PATCH);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "applyPatch",
input: { patchLength: patch.length },
attributes: { filesystemProvider: filesystem.provider }
});
try {
if (filesystem.readOnly) throw new require_errors.WorkspaceReadOnlyError("apply_patch");
const expectedMtimes = context?.__expectedMtimes;
const summary = [];
const changes = [];
try {
const operations = parsePatch(patch);
for (const op of operations) if (op.type === "add") {
await requireMissing(filesystem, op.path);
changes.push({
kind: "write",
path: op.path,
content: op.content
});
summary.push(`A ${op.path}`);
} else if (op.type === "delete") {
const mtime = await requireExistingFile(filesystem, op.path, expectedMtimes);
changes.push({
kind: "delete",
path: op.path,
original: await filesystem.readFile(op.path),
mtime
});
summary.push(`D ${op.path}`);
} else {
const mtime = await requireExistingFile(filesystem, op.path, expectedMtimes);
if (op.chunks.length === 0 && op.moveTo) {
await requireMissing(filesystem, op.moveTo);
const raw = await filesystem.readFile(op.path);
changes.push({
kind: "write",
path: op.moveTo,
content: raw
});
changes.push({
kind: "delete",
path: op.path,
original: raw,
mtime
});
summary.push(`R ${op.path} -> ${op.moveTo}`);
continue;
}
const original = await filesystem.readFile(op.path, { encoding: "utf-8" });
if (typeof original !== "string") throw new ApplyPatchError(`${op.path} is a binary file and cannot be patched`);
const updated = applyChunks(original, op.chunks, op.path);
if (op.moveTo && op.moveTo !== op.path) {
await requireMissing(filesystem, op.moveTo);
changes.push({
kind: "write",
path: op.moveTo,
content: updated
});
changes.push({
kind: "delete",
path: op.path,
original,
mtime
});
summary.push(`R ${op.path} -> ${op.moveTo}`);
} else {
changes.push({
kind: "write",
path: op.path,
content: updated,
original,
mtime
});
summary.push(`M ${op.path}`);
}
}
} catch (error) {
if (error instanceof ApplyPatchError) {
span.end({ success: false });
return `${PATCH_NOT_APPLIED} ${error.message}`;
}
throw error;
}
const ordered = [...changes.filter((c) => c.kind === "write"), ...changes.filter((c) => c.kind === "delete")];
const done = [];
try {
for (const change of ordered) {
if (change.kind === "write") await filesystem.writeFile(change.path, change.content, {
overwrite: change.original !== void 0,
expectedMtime: change.mtime
});
else {
const current = await filesystem.stat(change.path);
if (current.modifiedAt.getTime() !== change.mtime.getTime()) throw new require_errors.StaleFileError(change.path, change.mtime, current.modifiedAt);
await filesystem.deleteFile(change.path);
}
done.push(change);
}
} catch (error) {
const rollbackFailures = await rollback(filesystem, done);
if (rollbackFailures.length > 0) throw new Error(`apply_patch failed while writing (${error.message}) and could not restore: ${rollbackFailures.join(", ")}`, { cause: error });
throw error;
}
span.end({ success: true });
return `Applied patch:\n${summary.join("\n")}`;
} catch (err) {
span.error(err);
throw err;
}
}
});
/** Revert committed changes in reverse order. Returns the paths that could not be restored. */
async function rollback(filesystem, done) {
const failures = [];
for (const change of [...done].reverse()) try {
if (change.kind === "delete") await filesystem.writeFile(change.path, change.original);
else if (change.original !== void 0) await filesystem.writeFile(change.path, change.original);
else await filesystem.deleteFile(change.path);
} catch {
failures.push(change.path);
}
return failures;
}
// src/workspace/tools/ast-edit.ts
/**
* AST Edit Tool
*
* Provides AST-aware code transformations for workspace files.
* Uses @ast-grep/napi for syntax-aware pattern matching and transforms.
*
* Requires @ast-grep/napi as an optional peer dependency.
*/
let astGrepModule;
let loadingPromise;
const importModule = (moduleName) => import(
/* @vite-ignore */
/* webpackIgnore: true */
moduleName
);
/**
* Try to load @ast-grep/napi. Returns null if not available.
* Uses dynamic import to avoid compile-time dependency.
* Concurrent callers share the same in-flight promise.
*/
async function loadAstGrep() {
if (astGrepModule !== void 0) return astGrepModule;
if (!loadingPromise) loadingPromise = (async () => {
try {
const mod = await importModule("@ast-grep/napi");
astGrepModule = {
parse: mod.parse,
Lang: mod.Lang
};
return astGrepModule;
} catch {
astGrepModule = null;
return null;
}
})();
return loadingPromise;
}
/**
* Check if @ast-grep/napi is available without importing it.
* Useful for deciding whether to create the tool at registration time.
*/
function isAstGrepAvailable() {
if (astGrepModule !== void 0) return astGrepModule !== null;
try {
(0, module$1.createRequire)(require("url").pathToFileURL(__filename).href).resolve("@ast-grep/napi");
return true;
} catch {
return false;
}
}
/**
* Map file extension to ast-grep Lang enum.
*
* Only languages with built-in tree-sitter grammars in @ast-grep/napi are
* supported. Python, Go, Rust, etc. require separate @ast-grep/lang-* packages
* which are not currently integrated.
*/
function getLanguageFromPath(filePath, Lang) {
switch (filePath.split(".").pop()?.toLowerCase()) {
case "ts": return Lang.TypeScript;
case "tsx":
case "jsx": return Lang.Tsx;
case "js": return Lang.JavaScript;
case "html": return Lang.Html;
case "css": return Lang.Css;
default: return null;
}
}
/** Escape regex metacharacters in a string. */
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Rename all identifier occurrences matching `oldName` to `newName`.
* Not scope-aware: renames all occurrences regardless of scope.
*/
function renameIdentifiers(content, root, oldName, newName) {
let modifiedContent = content;
let count = 0;
const identifiers = root.findAll({ rule: {
kind: "identifier",
regex: `^${escapeRegex(oldName)}$`
} });
const replacements = [];
const seen = /* @__PURE__ */ new Set();
for (const id of identifiers) {
const range = id.range();
if (seen.has(range.start.index)) continue;
seen.add(range.start.index);
replacements.push({
start: range.start.index,
end: range.end.index,
text: newName
});
count++;
}
replacements.sort((a, b) => b.start - a.start);
for (const { start, end, text } of replacements) modifiedContent = modifiedContent.slice(0, start) + text + modifiedContent.slice(end);
return {
content: modifiedContent,
count
};
}
/**
* Build an import statement string from its parts.
*/
function buildImportStatement(defaultName, namedImports, moduleStr) {
if (defaultName && namedImports.length > 0) return `import ${defaultName}, { ${namedImports.join(", ")} } from ${moduleStr};`;
else if (defaultName) return `import ${defaultName} from ${moduleStr};`;
return `import { ${namedImports.join(", ")} } from ${moduleStr};`;
}
/**
* Merge new names into an existing import statement.
* Returns null if nothing needs to change.
*/
function mergeIntoExistingImport(content, existingImport, names, isDefault) {
const text = existingImport.text();
if (/^import\s+\*\s+as\s+/.test(text)) return null;
const defaultMatch = text.match(/^import\s+(?!type\s)(?!\{)(\w+)/);
const namedMatch = text.match(/\{([^}]*)\}/);
const moduleMatch = text.match(/(["'][^"']+["'])\s*;?\s*$/);
if (!moduleMatch) return null;
const moduleStr = moduleMatch[1] ?? "";
let existingDefault = defaultMatch ? defaultMatch[1] ?? null : null;
const existingNamed = namedMatch ? (namedMatch[1] ?? "").split(",").map((s) => s.trim()).filter(Boolean) : [];
let newDefault = existingDefault;
const newNamed = [...existingNamed];
if (isDefault && names.length > 0) {
if (!existingDefault) newDefault = names[0] ?? null;
for (const name of names.slice(1)) if (!newNamed.includes(name)) newNamed.push(name);
} else for (const name of names) if (!newNamed.includes(name)) newNamed.push(name);
const defaultChanged = newDefault !== existingDefault;
const namedChanged = newNamed.length !== existingNamed.length;
if (!defaultChanged && !namedChanged) return null;
const importStatement = buildImportStatement(newDefault, newNamed, moduleStr);
const range = existingImport.range();
return content.slice(0, range.start.index) + importStatement + content.slice(range.end.index);
}
/**
* Add an import statement to the file.
* Inserts after the last existing import, or at the beginning if none exist.
* If the module is already imported, merges new names into it.
*/
function addImport(content, root, importSpec) {
const { module, names, isDefault } = importSpec;
const imports = root.findAll({ rule: { kind: "import_statement" } });
const existingImport = imports.find((imp) => {
const text = imp.text();
if (/^import\s+type\s/.test(text)) return false;
if (/^import\s+\*\s+as\s+/.test(text)) return false;
return text.includes(`'${module}'`) || text.includes(`"${module}"`);
});
if (existingImport) return mergeIntoExistingImport(content, existingImport, names, isDefault) ?? content;
const moduleStr = `'${module}'`;
const importStatement = buildImportStatement(isDefault ? names[0] : null, isDefault ? names.slice(1) : names, moduleStr);
const lastImport = imports.at(-1);
if (lastImport) {
const pos = lastImport.range().end.index;
return content.slice(0, pos) + "\n" + importStatement + content.slice(pos);
}
return importStatement + "\n\n" + content;
}
/**
* Remove an import by module name.
* Matches against the import source string.
*/
function removeImport(content, root, targetName) {
const imports = root.findAll({ rule: { kind: "import_statement" } });
for (const imp of imports) {
const moduleMatch = imp.text().match(/from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]/);
const moduleName = moduleMatch?.[1] ?? moduleMatch?.[2];
if (moduleName === targetName || moduleName?.startsWith(`${targetName}/`)) {
const range = imp.range();
const start = range.start.index;
let end = range.end.index;
if (content[end] === "\n") end++;
return content.slice(0, start) + content.slice(end);
}
}
return content;
}
/**
* Pattern-based replacement using AST metavariables.
* Pattern uses $VARNAME placeholders that match any AST node.
* Replacement substitutes matched text back in.
*/
function patternReplace(content, root, pattern, replacement) {
let modifiedContent = content;
let count = 0;
try {
const matches = root.findAll({ rule: { pattern } });
const replacements = [];
const metaVars = [...pattern.matchAll(/\$(\w+)/g)].map((m) => m[1]).filter((v) => v !== void 0);
for (const match of matches) {
const range = match.range();
let replacementText = replacement;
for (const varName of metaVars) {
const matchedNode = match.getMatch(varName);
if (matchedNode) replacementText = replacementText.replace(new RegExp(`\\$${varName}`, "g"), matchedNode.text());
}
replacements.push({
start: range.start.index,
end: range.end.index,
text: replacementText
});
count++;
}
replacements.sort((a, b) => b.start - a.start);
for (const { start, end, text } of replacements) modifiedContent = modifiedContent.slice(0, start) + text + modifiedContent.slice(end);
} catch (err) {
return {
content: modifiedContent,
count: 0,
error: err instanceof Error ? err.message : "Pattern matching failed"
};
}
return {
content: modifiedContent,
count
};
}
const astEditTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT,
description: `Edit code using AST-based analysis for intelligent transformations.
Use \`transform\` for structured operations (imports, renames). Use \`pattern\`/\`replacement\` only for general find-and-replace.
Transforms:
- add-import: Add or merge imports. Skips duplicates. For default imports, put the default name first in \`names\`.
{ transform: "add-import", importSpec: { module: "react", names: ["useState", "useEffect"] } }
{ transform: "add-import", importSpec: { module: "express", names: ["express"], isDefault: true } }
{ transform: "add-import", importSpec: { module: "express", names: ["express", "Router"], isDefault: true } } → import express, { Router } from 'express'
- remove-import: Remove an import by module name.
{ transform: "remove-import", targetName: "lodash" }
- rename: Rename all occurrences of an identifier (not scope-aware).
{ transform: "rename", targetName: "oldName", newName: "newName" }
Pattern replace (for everything else):
{ pattern: "console.log($ARG)", replacement: "logger.debug($ARG)" }`,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The path to the file to edit"),
pattern: zod_v4.z.string().optional().describe("AST pattern to search for (supports $VARIABLE placeholders, e.g., \"console.log($ARG)\")"),
replacement: zod_v4.z.string().optional().describe("Replacement pattern (can use captured $VARIABLES, e.g., \"logger.debug($ARG)\")"),
transform: zod_v4.z.enum([
"add-import",
"remove-import",
"rename"
]).optional().describe("Structured transformation to apply"),
targetName: zod_v4.z.string().optional().describe("Required for remove-import and rename transforms. The current name to target."),
newName: zod_v4.z.string().optional().describe("Required for rename transform. The new name to replace targetName with."),
importSpec: zod_v4.z.object({
module: zod_v4.z.string().describe("Module to import from"),
names: zod_v4.z.array(zod_v4.z.string()).min(1).describe("Names to import. For default imports, put the default name first."),
isDefault: zod_v4.z.boolean().optional().describe("Whether the first name is a default import")
}).optional().describe("Required for add-import transform. Specifies the module and names to import.")
}),
execute: async ({ path, pattern, replacement, transform, targetName, newName, importSpec }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "astEdit",
input: {
path,
transform,
pattern
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
if (filesystem.readOnly) throw new require_errors.WorkspaceReadOnlyError("ast_edit");
const astGrep = await loadAstGrep();
if (!astGrep) {
span.end({ success: false });
return "@ast-grep/napi is not available. Install it to use AST editing.";
}
const { parse, Lang } = astGrep;
let content;
try {
content = await filesystem.readFile(path, { encoding: "utf-8" });
} catch (error) {
if (error instanceof require_errors.FileNotFoundError) {
span.end({ success: false });
return `File not found: ${path}. Use the write file tool to create it first.`;
}
throw error;
}
if (typeof content !== "string") {
span.end({ success: false });
return `Cannot perform AST edits on binary files. Use the write file tool instead.`;
}
const lang = getLanguageFromPath(path, Lang);
if (!lang) {
span.end({ success: false });
return `Unsupported file type for AST editing: ${path}`;
}
const root = parse(lang, content).root();
let modifiedContent = content;
const changes = [];
if (transform) switch (transform) {
case "add-import":
if (!importSpec) {
span.end({ success: false });
return "Error: importSpec is required for add-import transform";
}
modifiedContent = addImport(content, root, importSpec);
changes.push(`Added import from '${importSpec.module}'`);
break;
case "remove-import":
if (!targetName) {
span.end({ success: false });
return "Error: targetName is required for remove-import transform";
}
modifiedContent = removeImport(content, root, targetName);
changes.push(`Removed import '${targetName}'`);
break;
case "rename": {
if (!targetName || !newName) {
span.end({ success: false });
return "Error: targetName and newName are required for rename transform";
}
const renameResult = renameIdentifiers(content, root, targetName, newName);
modifiedContent = renameResult.content;
changes.push(`Renamed '${targetName}' to '${newName}' (${renameResult.count} occurrences)`);
break;
}
}
else if (pattern && replacement !== void 0) {
const result = patternReplace(content, root, pattern, replacement);
if (result.error) {
span.end({ success: false });
return `Error: AST pattern matching failed: ${result.error}`;
}
modifiedContent = result.content;
changes.push(`Replaced ${result.count} occurrences of pattern`);
} else if (pattern && replacement === void 0) {
span.end({ success: false });
return "Error: replacement is required when pattern is provided";
} else if (!pattern && replacement !== void 0) {
span.end({ success: false });
return "Error: pattern is required when replacement is provided";
} else {
span.end({ success: false });
return "Error: Must provide either transform or pattern/replacement";
}
const wasModified = modifiedContent !== content;
if (wasModified) await filesystem.writeFile(path, modifiedContent, {
overwrite: true,
expectedMtime: context?.__expectedMtime
});
if (!wasModified) {
span.end({ success: true });
return `No changes made to ${path} (${changes.join("; ")})`;
}
let output = `${path}: ${changes.join("; ")}`;
output += await getEditDiagnosticsText(workspace, path, modifiedContent);
span.end({ success: true }, { bytesTransferred: Buffer.byteLength(modifiedContent, "utf-8") });
return output;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/media.ts
function isMediaToolResult(value) {
return typeof value === "object" && value !== null && value.__workspaceMedia === true && typeof value.text === "string" && typeof value.mediaType === "string" && typeof value.data === "string";
}
/**
* Shared `toModelOutput` handler for tools that may return a MediaToolResult.
* Surfaces the media as a native part; returns undefined for plain string
* output so we don't store a duplicate copy on providerMetadata.
*/
function mediaToModelOutput(output) {
if (isMediaToolResult(output)) return {
type: "content",
value: [{
type: "text",
text: output.text
}, {
type: "media",
data: output.data,
mediaType: output.mediaType
}]
};
}
/**
* Extract the computer capability from the workspace sandbox in the tool
* execution context. Throws if the workspace has no sandbox or the sandbox
* doesn't support the computer capability.
*/
function requireComputer(context) {
const { workspace, sandbox } = requireSandbox(context);
if (!supportsComputer(sandbox)) throw new require_errors.SandboxFeatureNotSupportedError("computer");
return {
workspace,
sandbox,
computer: sandbox.computer
};
}
/** Resolve the per-tool ComputerToolConfig from the workspace tools config. */
function getComputerToolConfig(workspace, toolName) {
return workspace.getToolsConfig()?.[toolName];
}
/**
* Format a screenshot as a MediaToolResult, falling back to text-only output
* when the image exceeds the configured size cap (so huge base64 payloads
* don't blow up the model context or storage).
*/
function screenshotToResult(screenshot, text, maxMediaBytes) {
if (screenshot.data.byteLength > maxMediaBytes) return `${text} — screenshot (${screenshot.data.byteLength} bytes, ${screenshot.mediaType}) exceeds maxMediaBytes (${maxMediaBytes}). Returning text only; configure \`maxMediaBytes\` on the computer tool to raise this cap.`;
return {
__workspaceMedia: true,
text,
mediaType: screenshot.mediaType,
data: Buffer.from(screenshot.data).toString("base64")
};
}
/**
* Finish a computer action tool: when `screenshotAfterAction` is enabled
* (default), wait briefly for the UI to react and attach a fresh screenshot
* to the result so computer-use loops see the resulting desktop state.
* Screenshot failures never fail the action itself.
*/
async function finishComputerAction(workspace, computer, toolName, text) {
const config = getComputerToolConfig(workspace, toolName);
if (!(config?.screenshotAfterAction ?? true)) return text;
const delayMs = config?.screenshotDelayMs ?? 500;
if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
try {
return screenshotToResult(await computer.screenshot(), text, config?.maxMediaBytes ?? 10485760);
} catch {
return `${text} (post-action screenshot failed)`;
}
}
// src/workspace/tools/computer-click.ts
const computerClickTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.CLICK,
description: "Left-click at pixel coordinates on the sandbox desktop. Coordinates are measured from the top-left corner of the screen — take a screenshot first to find the right position.",
inputSchema: zod_v4.z.object({
x: zod_v4.z.number().int().min(0).describe("X coordinate in pixels from the left edge of the screen"),
y: zod_v4.z.number().int().min(0).describe("Y coordinate in pixels from the top edge of the screen")
}),
execute: async ({ x, y }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.CLICK);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "click",
input: {
x,
y
},
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.leftClick(x, y);
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.CLICK, `Clicked at (${x}, ${y})`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-double-click.ts
const computerDoubleClickTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK,
description: "Double-click (left button) at pixel coordinates on the sandbox desktop. Use for opening files, folders, and applications.",
inputSchema: zod_v4.z.object({
x: zod_v4.z.number().int().min(0).describe("X coordinate in pixels from the left edge of the screen"),
y: zod_v4.z.number().int().min(0).describe("Y coordinate in pixels from the top edge of the screen")
}),
execute: async ({ x, y }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "doubleClick",
input: {
x,
y
},
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.doubleClick(x, y);
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK, `Double-clicked at (${x}, ${y})`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-drag.ts
const computerDragTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.DRAG,
description: "Drag from one position to another on the sandbox desktop: presses the left button at the start coordinates, moves to the end coordinates, and releases. Use for moving windows, selecting text, and drag-and-drop.",
inputSchema: zod_v4.z.object({
startX: zod_v4.z.number().int().min(0).describe("X coordinate to start the drag from"),
startY: zod_v4.z.number().int().min(0).describe("Y coordinate to start the drag from"),
endX: zod_v4.z.number().int().min(0).describe("X coordinate to drag to"),
endY: zod_v4.z.number().int().min(0).describe("Y coordinate to drag to")
}),
execute: async ({ startX, startY, endX, endY }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.DRAG);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "drag",
input: {
startX,
startY,
endX,
endY
},
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.drag({
x: startX,
y: startY
}, {
x: endX,
y: endY
});
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.DRAG, `Dragged from (${startX}, ${startY}) to (${endX}, ${endY})`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-get-screen-info.ts
const computerGetScreenInfoTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.GET_SCREEN_INFO,
description: "Get the sandbox desktop screen dimensions and current mouse cursor position. Use to understand the coordinate space before clicking.",
inputSchema: zod_v4.z.object({}),
execute: async (_input, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.GET_SCREEN_INFO);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "getScreenInfo",
attributes: { sandboxProvider: sandbox.provider }
});
try {
const [size, cursor] = await Promise.all([computer.getScreenSize(), computer.getCursorPosition()]);
span.end({ success: true });
return `Screen size: ${size.width}x${size.height}\nCursor position: (${cursor.x}, ${cursor.y})`;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/computer-move-mouse.ts
const computerMoveMouseTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE,
description: "Move the mouse cursor to pixel coordinates on the sandbox desktop without clicking. Use for hover states (tooltips, dropdown menus).",
inputSchema: zod_v4.z.object({
x: zod_v4.z.number().int().min(0).describe("X coordinate in pixels from the left edge of the screen"),
y: zod_v4.z.number().int().min(0).describe("Y coordinate in pixels from the top edge of the screen")
}),
execute: async ({ x, y }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "moveMouse",
input: {
x,
y
},
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.moveMouse(x, y);
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE, `Moved mouse to (${x}, ${y})`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-press-key.ts
const computerPressKeyTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.PRESS_KEY,
description: "Press a key or key combination on the sandbox desktop keyboard. Pass a single key (e.g. \"Enter\", \"Tab\", \"Escape\") or an array for a hotkey chord (e.g. [\"ctrl\", \"s\"]).",
inputSchema: zod_v4.z.object({ key: zod_v4.z.union([zod_v4.z.string().min(1), zod_v4.z.array(zod_v4.z.string().min(1)).min(1)]).describe("A single key (e.g. \"Enter\") or an array of keys pressed together as a hotkey (e.g. [\"ctrl\", \"c\"])") }),
execute: async ({ key }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.PRESS_KEY);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "pressKey",
input: { key },
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.press(key);
const label = Array.isArray(key) ? key.join("+") : key;
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.PRESS_KEY, `Pressed ${label}`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-right-click.ts
const computerRightClickTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK,
description: "Right-click at pixel coordinates on the sandbox desktop. Use for opening context menus.",
inputSchema: zod_v4.z.object({
x: zod_v4.z.number().int().min(0).describe("X coordinate in pixels from the left edge of the screen"),
y: zod_v4.z.number().int().min(0).describe("Y coordinate in pixels from the top edge of the screen")
}),
execute: async ({ x, y }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "rightClick",
input: {
x,
y
},
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.rightClick(x, y);
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK, `Right-clicked at (${x}, ${y})`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-screenshot.ts
const computerScreenshotTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.SCREENSHOT,
description: "Take a screenshot of the sandbox desktop display. Returns the current screen as an image. Use this to see the desktop state before and after interacting with it.",
inputSchema: zod_v4.z.object({}),
execute: async (_input, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.SCREENSHOT);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "screenshot",
attributes: { sandboxProvider: sandbox.provider }
});
try {
const screenshot = await computer.screenshot();
const maxMediaBytes = getComputerToolConfig(workspace, WORKSPACE_TOOLS.COMPUTER.SCREENSHOT)?.maxMediaBytes ?? 10485760;
const result = screenshotToResult(screenshot, `Screenshot of the desktop (${screenshot.data.byteLength} bytes, ${screenshot.mediaType})`, maxMediaBytes);
span.end({ success: true }, { bytesTransferred: screenshot.data.byteLength });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-scroll.ts
const computerScrollTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.SCROLL,
description: "Scroll the sandbox desktop display up or down.",
inputSchema: zod_v4.z.object({
direction: zod_v4.z.enum(["up", "down"]).describe("Scroll direction"),
amount: zod_v4.z.number().int().min(1).optional().describe("Scroll amount in ticks (default: 3)")
}),
execute: async ({ direction, amount }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.SCROLL);
const effectiveAmount = amount ?? 3;
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "scroll",
input: {
direction,
amount: effectiveAmount
},
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.scroll(direction, effectiveAmount);
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.SCROLL, `Scrolled ${direction} by ${effectiveAmount}`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-type.ts
const computerTypeTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.TYPE,
description: "Type text into the focused element on the sandbox desktop using the keyboard. Click an input field first to focus it. Use the press-key tool for special keys (Enter, Tab, shortcuts).",
inputSchema: zod_v4.z.object({ text: zod_v4.z.string().describe("The text to type") }),
execute: async ({ text }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.TYPE);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "type",
input: { length: text.length },
attributes: { sandboxProvider: sandbox.provider }
});
try {
await computer.type(text);
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.TYPE, `Typed ${text.length} characters`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/computer-wait.ts
const computerWaitTool = require_tool.createTool({
id: WORKSPACE_TOOLS.COMPUTER.WAIT,
description: "Wait for the sandbox desktop UI to settle (e.g. an application launching or a page loading) before the next action.",
inputSchema: zod_v4.z.object({ seconds: zod_v4.z.number().min(.1).max(30).describe("How long to wait, in seconds (max 30)") }),
execute: async ({ seconds }, context) => {
const { workspace, sandbox, computer } = requireComputer(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.WAIT);
const span = startWorkspaceSpan(context, workspace, {
category: "computer",
operation: "wait",
input: { seconds },
attributes: { sandboxProvider: sandbox.provider }
});
try {
await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
const result = await finishComputerAction(workspace, computer, WORKSPACE_TOOLS.COMPUTER.WAIT, `Waited ${seconds}s`);
span.end({ success: true });
return result;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/delete-file.ts
const deleteFileTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.DELETE,
description: "Delete a file or directory from the workspace filesystem",
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The path to the file or directory to delete"),
recursive: zod_v4.z.boolean().optional().default(false).describe("If true, delete directories and their contents recursively. Required for non-empty directories.")
}),
execute: async ({ path, recursive }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.DELETE);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "delete",
input: {
path,
recursive
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
if (filesystem.readOnly) throw new require_errors.WorkspaceReadOnlyError("delete");
if ((await filesystem.stat(path)).type === "directory") await filesystem.rmdir(path, {
recursive,
force: recursive
});
else await filesystem.deleteFile(path);
span.end({ success: true });
return `Deleted ${path}`;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/line-utils.ts
/**
* Extract lines from content by line range.
*
* @param content - The document content
* @param startLine - Starting line number (1-indexed)
* @param endLine - Ending line number (1-indexed, inclusive)
* @returns Object with extracted content and metadata
*/
function extractLines(content, startLine, endLine) {
const allLines = content.split("\n");
const totalLines = allLines.length;
const start = Math.max(1, startLine ?? 1);
const end = Math.min(totalLines, endLine ?? totalLines);
if (start > end) return {
content: "",
lines: {
start: 0,
end: 0
},
totalLines
};
return {
content: allLines.slice(start - 1, end).join("\n"),
lines: {
start,
end
},
totalLines
};
}
/**
* Extract lines using offset/limit style parameters (like Claude Code).
*
* @param content - The document content
* @param offset - Line number to start from (1-indexed, default: 1)
* @param limit - Maximum number of lines to read (default: all remaining)
* @returns Object with extracted content and metadata
*/
function extractLinesWithLimit(content, offset, limit) {
const startLine = offset ?? 1;
return extractLines(content, startLine, limit ? startLine + limit - 1 : void 0);
}
/**
* Format content with line number prefixes.
* Output format matches Claude Code: " 1→content here"
*
* @param content - The content to format
* @param startLineNumber - The line number of the first line (1-indexed)
* @returns Formatted content with line numbers
*/
function formatWithLineNumbers(content, startLineNumber = 1) {
const lines = content.split("\n");
const maxLineNum = startLineNumber + lines.length - 1;
const padWidth = Math.max(6, String(maxLineNum).length + 1);
return lines.map((line, i) => {
const lineNum = startLineNumber + i;
return `${String(lineNum).padStart(padWidth)}→${line}`;
}).join("\n");
}
/**
* Convert a character index to a line number.
* Useful for converting RAG chunk character offsets to line numbers.
*
* @param content - The full document content
* @param charIndex - The character index (0-indexed)
* @returns The line number (1-indexed), or undefined if charIndex is out of bounds
*/
function charIndexToLineNumber(content, charIndex) {
if (charIndex < 0 || charIndex > content.length) return;
let lineNumber = 1;
for (let i = 0; i < charIndex && i < content.length; i++) if (content[i] === "\n") lineNumber++;
return lineNumber;
}
/**
* Convert character range to line range.
* Useful for converting RAG chunk character offsets to line ranges.
*
* @param content - The full document content
* @param startCharIdx - Start character index (0-indexed)
* @param endCharIdx - End character index (0-indexed, exclusive)
* @returns LineRange (1-indexed) or undefined if indices are out of bounds
*/
function charRangeToLineRange(content, startCharIdx, endCharIdx) {
const startLine = charIndexToLineNumber(content, startCharIdx);
const endLine = charIndexToLineNumber(content, Math.max(0, endCharIdx - 1));
if (startLine === void 0 || endLine === void 0) return;
return {
start: startLine,
end: endLine
};
}
/**
* Count occurrences of a string in content.
*
* @param content - The content to search
* @param searchString - The string to find
* @returns Number of occurrences
*/
function countOccurrences(content, searchString) {
if (!searchString) return 0;
let count = 0;
let position = 0;
while ((position = content.indexOf(searchString, position)) !== -1) {
count++;
position += searchString.length;
}
return count;
}
/**
* Replace a string in content, with validation for uniqueness.
*
* @param content - The content to modify
* @param oldString - The string to find and replace
* @param newString - The replacement string
* @param replaceAll - If true, replace all occurrences; if false, require unique match
* @returns Object with result content and metadata
* @throws Error if oldString is not found or not unique (when replaceAll is false)
*/
function replaceString(content, oldString, newString, replaceAll = false) {
const count = countOccurrences(content, oldString);
if (count === 0) throw new StringNotFoundError(oldString);
if (!replaceAll && count > 1) throw new StringNotUniqueError(oldString, count);
const escapedNewString = newString.replace(/\$/g, "$$$$");
if (replaceAll) return {
content: content.split(oldString).join(newString),
replacements: count
};
return {
content: content.replace(oldString, escapedNewString),
replacements: 1
};
}
/**
* Error thrown when string is not found during replacement.
*/
var StringNotFoundError = class extends Error {
searchString;
constructor(searchString) {
super(`The specified text was not found. Make sure you use the exact text from the file.`);
this.searchString = searchString;
this.name = "StringNotFoundError";
}
};
/**
* Error thrown when string appears multiple times but unique match required.
*/
var StringNotUniqueError = class extends Error {
searchString;
occurrences;
constructor(searchString, occurrences) {
super(`The specified text appears ${occurrences} times. Provide more surrounding context to make the match unique, or use replace_all to replace all occurrences.`);
this.searchString = searchString;
this.occurrences = occurrences;
this.name = "StringNotUniqueError";
}
};
// src/workspace/tools/edit-file.ts
function getEditedLineRanges(content, oldString, newString, replaceAll) {
if (!oldString) return "";
const ranges = [];
let position = 0;
while ((position = content.indexOf(oldString, position)) !== -1) {
const range = charRangeToLineRange(content, position, position + Math.max(oldString.length, 1));
if (range) {
const newLineCount = newString.split("\n").length;
const end = range.start + Math.max(newLineCount, range.end - range.start + 1) - 1;
ranges.push(end === range.start ? String(range.start) : `${range.start}-${end}`);
}
position += oldString.length;
if (!replaceAll) break;
}
if (ranges.length === 0) return "";
return ranges.length === 1 ? ` (lines ${ranges[0]})` : ` (lines ${ranges.join(", ")})`;
}
const editFileTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,
description: `Edit a file by replacing specific text. The old_string must match exactly and be unique in the file.
Usage:
- Read the file first to get the exact text to replace.
- By default, read file output includes line number prefixes (e.g., " 1→"). Ensure you preserve the exact indentation as it appears AFTER the arrow. Never include any part of the line number prefix in old_string or new_string.
- Include enough surrounding context (multiple lines) to make old_string unique. If it still isn't unique, include more lines.
- Use replace_all only when intentionally replacing all occurrences.`,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The path to the file to edit"),
old_string: zod_v4.z.string().describe("The exact text to find and replace. Must be unique in the file."),
new_string: zod_v4.z.string().describe("The text to replace old_string with"),
replace_all: zod_v4.z.boolean().optional().default(false).describe("If true, replace all occurrences. If false (default), old_string must be unique.")
}),
execute: async ({ path, old_string, new_string, replace_all }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "editFile",
input: {
path,
replace_all
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
if (filesystem.readOnly) throw new require_errors.WorkspaceReadOnlyError("edit_file");
const content = await filesystem.readFile(path, { encoding: "utf-8" });
if (typeof content !== "string") {
span.end({ success: false });
return `Cannot edit binary files. Use the write file tool instead.`;
}
const shouldReplaceAll = replace_all ?? false;
const lineRanges = getEditedLineRanges(content, old_string, new_string, shouldReplaceAll);
const result = replaceString(content, old_string, new_string, shouldReplaceAll);
await filesystem.writeFile(path, result.content, {
overwrite: true,
expectedMtime: context?.__expectedMtime
});
let output = `Replaced ${result.replacements} occurrence${result.replacements !== 1 ? "s" : ""} in ${path}${lineRanges}`;
output += await getEditDiagnosticsText(workspace, path, result.content);
span.end({ success: true }, { bytesTransferred: Buffer.byteLength(result.content, "utf-8") });
return output;
} catch (error) {
if (error instanceof StringNotFoundError) {
span.end({ success: false });
return error.message;
}
if (error instanceof StringNotUniqueError) {
span.end({ success: false });
return error.message;
}
span.error(error);
throw error;
}
}
});
// src/browser/cli-handler.ts
/**
* CLI provider patterns for CDP URL injection.
* Maps CLI command prefixes to their CDP URL flag.
* All CLIs accept either port number or full WebSocket URL.
* We use full URL for consistency.
*
* warmupCommand: Some CLIs (like agent-browser) need a "connect" command
* to be run first to establish their daemon's CDP connection before other
* commands will work properly.
*/
const CLI_CDP_PATTERNS = {
"agent-browser": {
pattern: /^agent-browser\b/,
flag: "--cdp",
sessionFlag: "--session",
warmupCommand: (cdpUrl, threadId) => `agent-browser --session ${shellQuote(threadId)} connect ${shellQuote(cdpUrl)}`,
externalCdpPattern: /(?:\bconnect\s+["']?wss?:\/\/|--cdp\s+["']?\S)/,
externalCdpExtractor: /(?:\bconnect|--cdp)\s+["']?(wss?:\/\/[^\s"']+)["']?/
},
"browser-use": {
pattern: /^(?:browser-use|browseruse|browser|bu)\b/,
flag: "--cdp-url",
sessionFlag: "--session",
externalCdpPattern: /--cdp-url\s+["']?\S+/,
externalCdpExtractor: /--cdp-url\s+["']?(wss?:\/\/[^\s"']+)["']?/
},
browse: {
pattern: /^browse\b/,
flag: "--ws",
externalCdpPattern: /--ws\s+["']?\S+/,
externalCdpExtractor: /--ws\s+["']?(wss?:\/\/[^\s"']+)["']?/
}
};
/**
* Handles browser CLI detection, CDP injection, and warmup for execute_command.
* Centralizes all browser CLI-specific logic that was previously in execute-command.ts.
*/
var BrowserCliHandler = class {
/**
* Track which CLI providers have been warmed up per browser instance and thread.
* Key format: `${browserId}:${cliName}:${threadId}`
* Browser ID scopes warmup state so different agents/workspaces don't share state.
* @internal Exposed for testing
*/
warmedUpClis = /* @__PURE__ */ new Set();
/**
* Track cleanup callbacks for warmed up CLIs to avoid duplicate registrations.
* Key format: `${browserId}:${cliName}:${threadId}`
* @internal Exposed for testing
*/
warmupCleanups = /* @__PURE__ */ new Map();
/**
* Build a warmup key scoped to browser instance.
*/
makeWarmupKey(browserId, cliName, threadId) {
return `${browserId}:${cliName}:${threadId}`;
}
/**
* Check if a command is a browser CLI command and return its config.
*/
getBrowserCliConfig(command) {
for (const [name, config] of Object.entries(CLI_CDP_PATTERNS)) if (config.pattern.test(command)) return {
name,
config
};
return null;
}
/**
* Check if any browser CLI command already has a CDP flag specified.
* If so, the agent is managing their own CDP connection and we should skip injection.
*/
hasExternalCdpFlag(parts) {
for (const part of parts) {
const match = this.getBrowserCliConfig(part.trim());
if (match) {
if (match.config.externalCdpPattern) {
if (match.config.externalCdpPattern.test(part)) return true;
} else if (new RegExp(`${match.config.flag}\\s+\\S+`).test(part)) return true;
}
}
return false;
}
/**
* Extract external CDP URL from command parts.
* Returns the first CDP URL found, or null if none.
*/
extractExternalCdpUrl(parts) {
for (const part of parts) {
const match = this.getBrowserCliConfig(part.trim());
if (match?.config.externalCdpExtractor) {
const urlMatch = part.match(match.config.externalCdpExtractor);
if (urlMatch?.[1]) return urlMatch[1];
}
}
return null;
}
/**
* Inject CDP URL and session flag into a single browser CLI command.
* Returns the modified command or the original if no injection needed.
*/
injectCdpUrlIntoSingleCommand(command, cdpUrl, config, threadId) {
if (new RegExp(`${config.flag}\\s+\\S+`).test(command)) return command;
let injection = `${config.flag} ${shellQuote(cdpUrl)}`;
if (config.sessionFlag && threadId) {
if (!new RegExp(`${config.sessionFlag}\\s+\\S+`).test(command)) injection += ` ${config.sessionFlag} ${shellQuote(threadId)}`;
}
return command.replace(config.pattern, `$& ${injection}`);
}
/**
* Inject CDP URL and session flag into all browser CLI commands in a potentially
* chained command string (commands joined by &&, ||, or ;).
*/
injectCdpUrl(command, cdpUrl, threadId) {
const { header, suffix } = this.getShellHeader(command);
const headerParts = splitShellCommand(header);
if (headerParts.parts.some((part) => this.isBrowserUseStdinCommand(part))) {
const modifiedParts = headerParts.parts.map((part) => {
const trimmed = part.trim();
const cliMatch = this.getBrowserCliConfig(trimmed);
return cliMatch && !this.isBrowserUseStdinCommand(trimmed) ? this.injectCdpUrlIntoSingleCommand(trimmed, cdpUrl, cliMatch.config, threadId) : part;
});
const transformed = modifiedParts.some((part, index) => part !== headerParts.parts[index]) ? reassembleShellCommand(modifiedParts, headerParts.operators) + suffix : command;
const name = (0, crypto.createHash)("sha256").update(JSON.stringify([threadId ?? "default", cdpUrl])).digest("hex").slice(0, 16);
return `BU_CDP_WS=${shellQuote(cdpUrl)} BU_NAME=${shellQuote(`mastra-${name}`)} sh -c ${shellQuote(transformed)}`;
}
const { parts, operators } = splitShellCommand(command);
return reassembleShellCommand(parts.map((part) => {
const trimmed = part.trim();
const cliMatch = this.getBrowserCliConfig(trimmed);
if (cliMatch) return this.injectCdpUrlIntoSingleCommand(trimmed, cdpUrl, cliMatch.config, threadId);
return part;
}), operators);
}
/**
* Check if a warmup has been completed for a browser/CLI/thread combination.
*/
isWarmedUp(browserId, cliName, threadId) {
return this.warmedUpClis.has(this.makeWarmupKey(browserId, cliName, threadId));
}
/**
* Mark a browser/CLI/thread combination as warmed up.
*/
markWarmedUp(browserId, cliName, threadId) {
this.warmedUpClis.add(this.makeWarmupKey(browserId, cliName, threadId));
}
/**
* Register a cleanup callback for when a browser closes.
* The cleanup will remove the warmup state for the given browser/CLI/thread.
*/
registerWarmupCleanup(browserId, cliName, threadId, browser) {
const warmupKey = this.makeWarmupKey(browserId, cliName, threadId);
if (!this.warmupCleanups.has(warmupKey)) {
const cleanup = browser.onBrowserClosed(() => {
this.warmedUpClis.delete(warmupKey);
this.warmupCleanups.delete(warmupKey);
}, threadId);
this.warmupCleanups.set(warmupKey, cleanup);
}
}
/**
* Get warmup commands that need to be run for the detected browser CLIs.
*/
getWarmupCommands(browserId, browserClis, cdpUrl, threadId) {
const warmups = [];
const seen = /* @__PURE__ */ new Set();
for (const { name: cliName, config: cliConfig } of browserClis) {
if (seen.has(cliName)) continue;
seen.add(cliName);
if (cliConfig.warmupCommand && !this.isWarmedUp(browserId, cliName, threadId)) warmups.push({
cliName,
command: cliConfig.warmupCommand(cdpUrl, threadId)
});
}
return warmups;
}
getShellHeader(command) {
let header = "";
let quote = "";
let continued = false;
let hasHeredoc = false;
const source = command.trimStart();
let i = 0;
for (; i < source.length; i++) {
const char = source[i];
if (char === "\\" && quote !== "'" && i + 1 < source.length) {
const next = source[++i];
if (next !== "\n") {
header += char + next;
continued = false;
}
continue;
}
if (char === "\n" && !quote) {
if (hasHeredoc || !continued) break;
header += " ";
continue;
}
if (!quote && (source.slice(i, i + 2) === "&&" || source.slice(i, i + 2) === "||")) {
header += source.slice(i, i + 2);
i++;
continued = true;
continue;
}
if (!quote && source.slice(i, i + 2) === "<<") hasHeredoc = true;
if (!/\s/.test(char)) continued = !quote && (char === "|" || char === ";");
if (char === quote) quote = "";
else if (!quote && (char === "'" || char === "\"")) quote = char;
header += char;
}
return {
header,
suffix: source.slice(i)
};
}
isBrowserUseStdinCommand(command) {
const word = String.raw`(?:[^\s<>;&|"'\\]|\\.|"[^"]*"|'[^']*')+`;
const redirection = String.raw`\d*(?:<<-?|>>?|<|[<>]&|<>|>\|)\s*${word}\s*`;
return new RegExp(String.raw`^\s*(?:browser-use|browseruse|browser|bu)(?=\s|[<>]|$)\s*(?:${redirection})*$`).test(command);
}
/**
* Process a command for browser CLI handling.
* Detects browser CLIs, checks for external CDP, and prepares injection.
*
* This is the main entry point - call this from execute-command.ts.
*/
analyzeCommand(command) {
const { header } = this.getShellHeader(command);
const headerParts = splitShellCommand(header).parts;
if (headerParts.some((part) => this.isBrowserUseStdinCommand(part))) {
const browserClis = headerParts.map((part) => this.getBrowserCliConfig(part.trim())).filter((match) => match !== null);
const legacyParts = headerParts.filter((part) => !this.isBrowserUseStdinCommand(part));
const usingExternalCdp = this.hasExternalCdpFlag(legacyParts);
return {
browserClis,
parts: [command],
usingExternalCdp,
externalCdpUrl: usingExternalCdp ? this.extractExternalCdpUrl(legacyParts) : null
};
}
const { parts } = splitShellCommand(command);
const browserClis = parts.map((part) => this.getBrowserCliConfig(part.trim())).filter((match) => match !== null);
const usingExternalCdp = this.hasExternalCdpFlag(parts);
return {
browserClis,
parts,
usingExternalCdp,
externalCdpUrl: usingExternalCdp ? this.extractExternalCdpUrl(parts) : null
};
}
};
/**
* Singleton instance for use across the application.
* This preserves warmup state across command executions.
*/
const browserCliHandler = new BrowserCliHandler();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.6.0/394289cb1bed8c542941f77748eea1a31bd3419018d0fb2ac7029ece2458cdd1/node_modules/tokenx/dist/index.mjs
const PATTERNS = {
whitespace: /^\s+$/,
structuredWhitespace: /\n\s/,
cjk: /[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u30FF\uFF00-\uFFEF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,
numeric: /^\d+$/,
punctuation: /[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/
};
const TOKEN_SPLIT_PATTERN = new RegExp(`(\\s+|${PATTERNS.punctuation.source}+)`);
const DEFAULT_CHARS_PER_TOKEN = 6;
const SHORT_TOKEN_THRESHOLD = 3;
const KANA_CHARS_PER_TOKEN = 1.35;
const DEFAULT_LANGUAGE_CONFIGS = [
{
pattern: /[äöüßẞ]/i,
averageCharsPerToken: 2.6
},
{
pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
averageCharsPerToken: 3
},
{
pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
averageCharsPerToken: 2.5
},
{
pattern: /[\u0430-\u044F\u0451]/i,
averageCharsPerToken: 4
},
{
pattern: /[\u03AC-\u03CE]/i,
averageCharsPerToken: 2.75
},
{
pattern: /^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u,
averageCharsPerToken: .75
}
];
/**
* Walks a text as (segment, estimated token count) pairs. The segments
* concatenate back to the original text; whitespace segments count zero
* tokens unless they carry structure (indentation or blank lines).
*/
function* walkSegments(text, options = {}) {
if (!text) return;
const resolvedOptions = resolveOptions(options);
for (const segment of text.split(TOKEN_SPLIT_PATTERN)) if (segment) yield {
segment,
tokenCount: estimateSegmentTokens(segment, resolvedOptions)
};
}
function resolveOptions(options) {
return {
defaultCharsPerToken: options.defaultCharsPerToken ?? DEFAULT_CHARS_PER_TOKEN,
languageConfigs: options.languageConfigs ?? DEFAULT_LANGUAGE_CONFIGS
};
}
function estimateSegmentTokens(segment, { languageConfigs, defaultCharsPerToken }) {
if (PATTERNS.whitespace.test(segment)) return PATTERNS.structuredWhitespace.test(segment) ? 1 : 0;
const languageCharsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs);
if (languageCharsPerToken !== void 0) return Math.ceil(getCharacterCount(segment) / languageCharsPerToken);
if (PATTERNS.cjk.test(segment)) return estimateCjkTokens(segment);
if (PATTERNS.numeric.test(segment)) return Math.ceil(segment.length / 3);
if (segment.length <= SHORT_TOKEN_THRESHOLD) return 1;
if (PATTERNS.punctuation.test(segment)) return Math.ceil(segment.length / 2);
return Math.ceil(segment.length / defaultCharsPerToken);
}
function getLanguageSpecificCharsPerToken(segment, languageConfigs) {
for (const config of languageConfigs) if (segment.search(config.pattern) !== -1) return config.averageCharsPerToken;
}
function getCharacterCount(text) {
return Array.from(text).length;
}
function estimateCjkTokens(segment) {
let kanaCount = 0;
let otherCount = 0;
for (const character of segment) {
const codePoint = character.codePointAt(0);
if (codePoint >= 12352 && codePoint <= 12543) kanaCount++;
else otherCount++;
}
return otherCount + Math.ceil(kanaCount / KANA_CHARS_PER_TOKEN);
}
/**
* Estimates the number of tokens in a text string using heuristic rules
*/
function estimateTokenCount(text, options = {}) {
if (!text) return 0;
let tokenCount = 0;
for (const segmentEstimate of walkSegments(text, options)) tokenCount += segmentEstimate.tokenCount;
return tokenCount;
}
/**
* Extracts a portion of text based on token positions, similar to Array.prototype.slice()
*/
function sliceByTokens(text, start = 0, end, options = {}) {
if (!text) return "";
let segmentEstimates = walkSegments(text, options);
let totalTokens = 0;
if (start < 0 || end !== void 0 && end < 0) {
const bufferedEstimates = Array.from(segmentEstimates);
for (const { tokenCount } of bufferedEstimates) totalTokens += tokenCount;
segmentEstimates = bufferedEstimates;
}
const normalizedStart = start < 0 ? Math.max(0, totalTokens + start) : Math.max(0, start);
const normalizedEnd = end === void 0 ? Infinity : end < 0 ? Math.max(0, totalTokens + end) : end;
if (normalizedStart >= normalizedEnd) return "";
const parts = [];
let currentTokenPos = 0;
for (const { segment, tokenCount } of segmentEstimates) {
if (currentTokenPos >= normalizedEnd) break;
const extracted = extractSegmentPart(segment, currentTokenPos, tokenCount, normalizedStart, normalizedEnd);
if (extracted) parts.push(extracted);
currentTokenPos += tokenCount;
}
return parts.join("");
}
function extractSegmentPart(segment, segmentTokenStart, segmentTokenCount, targetStart, targetEnd) {
if (segmentTokenCount === 0) return segmentTokenStart >= targetStart && segmentTokenStart < targetEnd ? segment : "";
const segmentTokenEnd = segmentTokenStart + segmentTokenCount;
if (segmentTokenStart >= targetEnd || segmentTokenEnd <= targetStart) return "";
const overlapStart = Math.max(0, targetStart - segmentTokenStart);
const overlapEnd = Math.min(segmentTokenCount, targetEnd - segmentTokenStart);
if (overlapStart === 0 && overlapEnd === segmentTokenCount) return segment;
const charStart = Math.floor(overlapStart / segmentTokenCount * segment.length);
const charEnd = Math.ceil(overlapEnd / segmentTokenCount * segment.length);
return segment.slice(charStart, charEnd);
}
// src/utils/slice-by-tokens.ts
const UNPAIRED_SURROGATE_RE = /[\uD800-\uDFFF]/gu;
/**
* `sliceByTokens` from tokenx cuts on UTF-16 code-unit boundaries, so a cut can
* land inside a surrogate pair (emoji, CJK ext B+, math alphanumerics) and leave
* an unpaired surrogate. That is invalid UTF-16: it degrades to U+FFFD on a UTF-8
* round-trip and strict JSON parsers reject it. Always slice through this helper
* so every truncation site gets the same repair.
*/
function sliceByTokensSafe(text, start, end) {
return sliceByTokens(text, start, end).replace(UNPAIRED_SURROGATE_RE, "�");
}
/** `text.slice(start, end)` by UTF-16 index, with the same repair for a cut inside a surrogate pair. */
function sliceSafe(text, start, end) {
return text.slice(start, end).replace(UNPAIRED_SURROGATE_RE, "�");
}
// src/workspace/tools/output-helpers.ts
/** Default number of lines to return (tail). */
const DEFAULT_TAIL_LINES = 200;
/** Default estimated token limit for tool output. Safety net on top of line-based tail. */
const DEFAULT_MAX_OUTPUT_TOKENS = 2e3;
/**
* Strip ANSI escape codes from text.
* Covers CSI sequences (colors, cursor), OSC sequences (hyperlinks), and C1 controls.
* Based on the pattern from chalk/ansi-regex.
*/
const ANSI_RE = /(?:\u001B\][\s\S]*?(?:\u0007|\u001B\u005C|\u009C))|(?:[\u001B\u009B][\[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~])/g;
function stripAnsi(text) {
return text.replace(ANSI_RE, "");
}
/**
* `toModelOutput` handler for sandbox tools.
* Strips ANSI escape codes so the model sees clean text, while the raw
* output (with colors) is preserved in the stream/TUI.
*
* Returns `{ type: 'text', value: '...' }` to match the AI SDK's
* expected tool-result output format.
*
* Mastra validation-error envelopes (e.g. from output-schema validation
* failures) are tagged as `{ type: 'error-json', value }` so providers
* receive a valid tool-result output instead of an untagged object.
*
* `{ error: string }` results (e.g. substituted by a blocking `beforeToolCall`
* hook) are tagged as `{ type: 'error-text', value }` so the model sees the reason.
*/
function sandboxToModelOutput(output) {
if (typeof output === "string") return {
type: "text",
value: stripAnsi(output)
};
if (require_tool.isValidationError(output)) return {
type: "error-json",
value: output
};
if (typeof output === "object" && output !== null && typeof output.error === "string") return {
type: "error-text",
value: output.error
};
return output;
}
/**
* Return the last N lines of output, similar to `tail -n`.
* - `n > 0`: last N lines
* - `n === 0`: no limit (return all)
* - `undefined/null`: use DEFAULT_TAIL_LINES
*/
function applyTail(output, tail) {
const { header, body } = splitTail(output, tail);
return header ? `${header}\n${body}` : body;
}
function splitTail(output, tail) {
const unchanged = {
header: void 0,
body: output,
firstLine: 1
};
if (!output) return unchanged;
const n = Math.floor(Math.abs(tail ?? 200));
if (n === 0) return unchanged;
const trailingNewline = output.endsWith("\n");
const lines = (trailingNewline ? output.slice(0, -1) : output).split("\n");
if (lines.length <= n) return unchanged;
const sliced = lines.slice(-n).join("\n");
return {
header: `[showing last ${n} of ${lines.length} lines]`,
body: trailingNewline ? sliced + "\n" : sliced,
firstLine: lines.length - n + 1
};
}
/**
* Token-based output limit. Truncates output to fit within a token budget.
* Uses tokenx for fast token estimation and truncates at the token level
* (not line boundaries) to maximise use of the budget.
*
* @param output - The text to truncate
* @param limit - Maximum tokens (default: DEFAULT_MAX_OUTPUT_TOKENS)
* @param from - Which end to truncate from:
* - `'start'` (default): Remove tokens from the start, keep the end
* - `'end'`: Remove tokens from the end, keep the start
*/
async function applyTokenLimit(output, limit = DEFAULT_MAX_OUTPUT_TOKENS, from = "start") {
if (!output) return output;
const totalTokens = estimateTokenCount(output);
if (totalTokens <= limit) return output;
const kept = from === "start" ? sliceByTokensSafe(output, -limit) : sliceByTokensSafe(output, 0, limit);
const position = from === "start" ? "last" : "first";
return from === "start" ? `[output truncated: showing ${position} ~${limit} of ~${totalTokens} tokens]\n${kept}` : `${kept}\n[output truncated: showing ${position} ~${limit} of ~${totalTokens} tokens]`;
}
/**
* Sandwich truncation where line 1 of `output` is line `firstLine` of the text the
* model asked for (after a line-based tail, the kept lines start part-way in).
*/
function sandwich(output, limit, headRatio, firstLine) {
if (!output) return output;
const totalTokens = estimateTokenCount(output);
if (totalTokens <= limit) return output;
const headBudget = Math.floor(limit * headRatio);
const tailBudget = limit - headBudget;
let head = headBudget > 0 ? sliceByTokensSafe(output, 0, headBudget) : "";
let tail = tailBudget > 0 ? sliceByTokensSafe(output, -tailBudget) : "";
const headEnd = head.length;
let tailStart = output.length - tail.length;
head = head.replace(/\r?\n$/, "");
if (head.endsWith("\r") && output[headEnd] === "\n") head = head.slice(0, -1);
const tailBreak = tail.startsWith("\r\n") ? 2 : tail.startsWith("\n") ? 1 : 0;
tail = tail.slice(tailBreak);
tailStart += tailBreak;
const lines = describeCutLines(output, headEnd, tailStart, firstLine - 1);
const notice = `[...output truncated — ${lines.dropped ? `dropped ${lines.dropped}; ` : ""}showing first ~${headBudget} tokens${lines.head} + last ~${tailBudget} tokens${lines.tail} of ~${totalTokens} tokens...]`;
return [
head,
notice,
tail
].filter(Boolean).join("\n");
}
/** 1-based line number of the character at `index`. */
function lineAt(text, index) {
let line = 1;
for (let i = text.indexOf("\n"); i !== -1 && i < index; i = text.indexOf("\n", i + 1)) line++;
return line;
}
function lineRange(from, to) {
return from === to ? `line ${from}` : `lines ${from}-${to}`;
}
function joinClauses(clauses) {
if (clauses.length <= 1) return clauses.join("");
return `${clauses.slice(0, -1).join(", ")} and ${clauses.at(-1)}`;
}
/**
* Describe which lines a sandwich cut kept and dropped. The head keeps
* `output[0, headEnd)` and the tail keeps `output[tailStart, end)`.
* `offset` is added to every line number.
*/
function describeCutLines(output, headEnd, tailStart, offset) {
const trailingNewline = output.endsWith("\n");
const lastLine = lineAt(output, output.length) - (trailingNewline ? 1 : 0);
const hasHead = headEnd > 0;
const hasTail = tailStart < output.length;
const headTo = hasHead ? lineAt(output, headEnd - 1) : 0;
const headWhole = hasHead && (output[headEnd - 1] === "\n" || headEnd >= output.length || output.startsWith("\n", headEnd) || output.startsWith("\r\n", headEnd));
const tailFrom = hasTail ? lineAt(output, tailStart) : lastLine + 1;
const tailWhole = tailStart === 0 || output[tailStart - 1] === "\n";
const n = (line) => line + offset;
const head = hasHead ? ` (${lineRange(n(1), n(headTo))})` : "";
const tail = hasTail ? ` (${lineRange(n(tailFrom), n(lastLine))})` : "";
if (hasHead && hasTail && tailStart <= headEnd) return {
head,
tail,
dropped: ""
};
if (hasHead && hasTail && headTo === tailFrom) return {
head,
tail,
dropped: `the middle of line ${n(headTo)}`
};
const clauses = [];
if (hasHead && !headWhole) clauses.push(`the end of line ${n(headTo)}`);
if (tailFrom - 1 >= headTo + 1) clauses.push(lineRange(n(headTo + 1), n(tailFrom - 1)));
if (hasTail && !tailWhole) clauses.push(`the start of line ${n(tailFrom)}`);
return {
head,
tail,
dropped: joinClauses(clauses)
};
}
/**
* Tell the model when the sandbox dropped the start of a stream (retention limit),
* so it doesn't read the newest output as all of it.
*/
function noteDroppedOutput(output, droppedBytes, stream) {
if (!droppedBytes) return output;
const note = `[${stream}: the first ${droppedBytes} bytes were dropped; only the newest output was kept. Redirect output to a file to read all of it.]`;
return output ? `${note}\n${output}` : note;
}
/**
* Apply both tail (line-based) and token limit (safety net) to output.
*/
async function truncateOutput(output, tail, tokenLimit, tokenFrom) {
if (tokenFrom === "sandwich") {
const { header, body, firstLine } = splitTail(output, tail);
const cut = sandwich(body, tokenLimit ?? 2e3, .1, firstLine);
return header ? `${header}\n${cut}` : cut;
}
return applyTokenLimit(applyTail(output, tail), tokenLimit, tokenFrom);
}
// src/workspace/tools/execute-command.ts
/**
* Base input schema for execute_command (no background param).
* Extended with `background` in tools.ts when sandbox.processes exists.
*/
const executeCommandInputSchema = zod_v4.z.object({
command: zod_v4.z.string().describe("The shell command to execute (e.g., \"npm install\", \"ls -la src/\", \"cat file.txt | grep error\")"),
timeout: zod_v4.z.preprocess(coerceNumericString, zod_v4.z.number()).nullish().describe("Maximum execution time in seconds. Example: 60 for 1 minute."),
cwd: zod_v4.z.string().nullish().describe("Working directory for the command"),
tail: zod_v4.z.preprocess(coerceNumericString, zod_v4.z.number().int()).nullish().describe(`For foreground commands: limit output to the last N lines, similar to tail -n. Defaults to 200. Use 0 for no limit.`)
});
/** Schema with background param included. */
const executeCommandWithBackgroundSchema = executeCommandInputSchema.extend({ background: zod_v4.z.boolean().optional().describe("Run the command in the background. Returns a PID immediately instead of waiting for completion. Use get_process_output to check on it later.") });
const descriptionShape = { description: zod_v4.z.string().min(1).describe("Short plain-language description of what this command does, shown to the user in place of the raw command (5-10 words, e.g. \"Running the auth unit tests\"). Write it first, before `command` and the other arguments, so the user sees it while the rest of the call streams in. Write it as the next step in an ongoing narrative: it can build on your previous commands implicitly, e.g. after \"Searching open PRs for failing CI\" the next command can be \"Drilling into the first of 15 failures\".") };
/** Base schema with a required leading `description` (used when `requireDescription` is set). */
const executeCommandWithDescriptionSchema = zod_v4.z.object({
...descriptionShape,
...executeCommandInputSchema.shape
});
/** Background schema with a required leading `description`. */
const executeCommandWithDescriptionAndBackgroundSchema = zod_v4.z.object({
...descriptionShape,
...executeCommandWithBackgroundSchema.shape
});
/** A command whose final pipeline stage is `tail`, e.g. `make test 2>&1 | tail -20`. */
const TRAILING_TAIL_PIPE = /(?:^|[^|])\|\s*tail(?:\s[^|;&]*)?$/;
/**
* POSIX shells report a pipeline's status from its last command, so `cmd | tail -N` exits 0 even
* when `cmd` fails. Enable `pipefail` (where the shell supports it) for pipelines ending in `tail`
* so the upstream failure is reported. `tail` reads all of its input, so upstream commands are
* not cut off by SIGPIPE. LocalSandbox on Windows runs commands through cmd.exe, which has no
* `set -o`.
*/
function reportUpstreamPipelineFailure(command, sandboxProvider) {
if (sandboxProvider === "local" && process.platform === "win32") return command;
if (!TRAILING_TAIL_PIPE.test(command.trim())) return command;
return `(set -o pipefail) 2>/dev/null && set -o pipefail; ${command}`;
}
const ABORTED_COMMAND_NOTE = "Command aborted: the run was cancelled (by the user or system) while this command was running, so it was killed before it finished.";
const CANCELLED_RUN_NOTE = "The run was cancelled (by the user or system) while this command was running.";
/** Format command streams consistently with get_process_output. */
function formatCommandOutput(stdout, stderr) {
const parts = [];
if (stdout && stderr) parts.push("stdout:", stdout, "", "stderr:", stderr);
else if (stdout) parts.push(stdout);
else if (stderr) parts.push("stderr:", stderr);
return parts;
}
/** Append a terminal status after one blank line without altering streamed output. */
function appendTerminalLine(parts, terminalLine) {
if (parts.length === 0) return terminalLine;
const output = parts.join("\n");
return `${output}${output.endsWith("\n\n") ? "" : output.endsWith("\n") ? "\n" : "\n\n"}${terminalLine}`;
}
/**
* The directory the workspace's file tools resolve relative paths against, when its
* filesystem is sandbox-backed and reports one. Only the configured filesystem is
* consulted: a dynamic filesystem resolver is not invoked just to learn a default cwd, so
* a sandbox-only tool call still resolves nothing it did not resolve before. Every absent
* case — no filesystem, no capability — falls back to `undefined`, which keeps the
* sandbox's own default cwd exactly as before.
*/
async function resolveDefaultCwd(workspace) {
try {
const root = await workspace.filesystem?.getCommandCwd?.();
return root?.startsWith("/") ? root : void 0;
} catch {
return;
}
}
/**
* The cwd a command actually runs in. An explicit absolute `cwd` wins, a relative one is
* resolved under the default root so it means the same thing as a relative path passed to
* the file tools, and an omitted `cwd` becomes the default root.
*/
function resolveCommandCwd(cwd, defaultCwd) {
if (!cwd) return defaultCwd;
if (cwd.startsWith("/")) return cwd;
return defaultCwd ? path.default.posix.join(defaultCwd, cwd) : cwd;
}
/** Shared execute function used by both foreground-only and background-capable tool variants. */
async function executeCommand(input, context) {
let { command } = input;
const { cwd, tail } = input;
const timeout = input.timeout != null ? input.timeout * 1e3 : void 0;
const background = input.background;
const { workspace, sandbox } = requireSandbox(context);
const effectiveCwd = resolveCommandCwd(cwd, await resolveDefaultCwd(workspace));
const browser = workspace.browser;
const { browserClis, usingExternalCdp, externalCdpUrl } = browserCliHandler.analyzeCommand(command);
if (browser && browserClis.length > 0 && !usingExternalCdp) {
const threadId = context?.agent?.threadId ?? context?.threadId ?? "default";
if (!browser.isBrowserRunning(threadId)) await browser.launch(threadId);
const cdpUrl = browser.getCdpUrl(threadId);
const browserId = browser.id;
if (cdpUrl) {
const warmups = browserCliHandler.getWarmupCommands(browserId, browserClis, cdpUrl, threadId);
for (const { cliName, command: warmupCmd } of warmups) try {
if (sandbox.executeCommand) await sandbox.executeCommand(warmupCmd, [], { timeout: 1e4 });
browserCliHandler.markWarmedUp(browserId, cliName, threadId);
browserCliHandler.registerWarmupCleanup(browserId, cliName, threadId, browser);
} catch {}
command = browserCliHandler.injectCdpUrl(command, cdpUrl, threadId);
}
} else if (browser && browserClis.length > 0 && usingExternalCdp && externalCdpUrl) {
const threadId = context?.agent?.threadId ?? context?.threadId ?? "default";
try {
await browser.connectToExternalCdp(externalCdpUrl, threadId);
} catch {}
}
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND);
const toolCallId = context?.agent?.toolCallId;
const toolConfig = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND];
const tokenLimit = toolConfig?.maxOutputTokens;
const tokenFrom = "sandwich";
const span = startWorkspaceSpan(context, workspace, {
category: "sandbox",
operation: background ? "spawnProcess" : "executeCommand",
input: {
command,
cwd: effectiveCwd,
timeout: input.timeout,
background
},
attributes: { sandboxProvider: sandbox.provider }
});
if (background) {
if (!sandbox.processes) {
const err = new require_errors.SandboxFeatureNotSupportedError("processes");
span.error(err);
throw err;
}
const bgConfig = toolConfig?.backgroundProcesses;
const bgAbortSignal = bgConfig?.abortSignal === void 0 ? context?.abortSignal : bgConfig.abortSignal || void 0;
const owner = {
agentId: context?.agent?.agentId || void 0,
threadId: context?.agent?.threadId || context?.threadId || void 0,
resourceId: context?.agent?.resourceId || context?.resourceId || void 0,
runId: context?.runId || void 0
};
let handle;
handle = await sandbox.processes.spawn(command, {
cwd: effectiveCwd,
timeout: timeout ?? void 0,
abortSignal: bgAbortSignal,
stdinMode: "ignore",
onStdout: bgConfig?.onStdout ? (data) => bgConfig.onStdout(data, {
pid: handle.pid,
toolCallId,
...owner
}) : void 0,
onStderr: bgConfig?.onStderr ? (data) => bgConfig.onStderr(data, {
pid: handle.pid,
toolCallId,
...owner
}) : void 0
});
if (bgConfig?.onExit) handle.wait().then(async (result) => {
try {
await bgConfig.onExit({
pid: handle.pid,
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
stdoutDroppedBytes: result.stdoutDroppedBytes,
stderrDroppedBytes: result.stderrDroppedBytes,
killedByAbort: handle.killedByAbort,
toolCallId,
...owner
});
} catch (callbackError) {
workspace.logger?.error("Background process onExit callback threw", {
error: callbackError,
pid: handle.pid,
toolCallId
});
}
}).catch((observeError) => {
workspace.logger?.error("Failed to observe background process exit", {
error: observeError,
pid: handle.pid,
toolCallId
});
});
span.end({ success: true }, { pid: Number(handle.pid) || void 0 });
return `Started background process (PID: ${handle.pid})`;
}
if (!sandbox.executeCommand) {
const err = new require_errors.SandboxFeatureNotSupportedError("executeCommand");
span.error(err);
throw err;
}
const startedAt = Date.now();
const stdout = new RetainedOutputBuffer(DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES);
const stderr = new RetainedOutputBuffer(DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES);
let abortedWhenSettled = false;
try {
const result = await sandbox.executeCommand(reportUpstreamPipelineFailure(command, sandbox.provider), [], {
timeout: timeout ?? void 0,
cwd: effectiveCwd,
abortSignal: context?.abortSignal,
onStdout: async (data) => {
stdout.append(data);
await context?.writer?.custom({
type: "data-sandbox-stdout",
data: {
output: data,
timestamp: Date.now(),
toolCallId
},
transient: true
});
},
onStderr: async (data) => {
stderr.append(data);
await context?.writer?.custom({
type: "data-sandbox-stderr",
data: {
output: data,
timestamp: Date.now(),
toolCallId
},
transient: true
});
}
}).finally(() => {
abortedWhenSettled = context?.abortSignal?.aborted === true;
});
await context?.writer?.custom({
type: "data-sandbox-exit",
data: {
exitCode: result.exitCode,
success: result.success,
executionTimeMs: result.executionTimeMs,
killed: result.killed,
timedOut: result.timedOut,
toolCallId
}
});
span.end({ success: result.success }, { exitCode: result.exitCode });
const stdoutForModel = noteDroppedOutput(await truncateOutput(result.stdout, tail, tokenLimit, tokenFrom), result.stdoutDroppedBytes, "stdout");
const stderrForModel = noteDroppedOutput(await truncateOutput(result.stderr, tail, tokenLimit, tokenFrom), result.stderrDroppedBytes, "stderr");
if (!result.success) {
const parts = formatCommandOutput(stdoutForModel, stderrForModel);
const aborted = abortedWhenSettled && result.killed !== false && !result.timedOut;
const abortNote = result.killed === true ? ABORTED_COMMAND_NOTE : CANCELLED_RUN_NOTE;
const exitLine = `Exit code: ${result.exitCode}`;
return appendTerminalLine(parts, aborted ? `${abortNote}\n${exitLine}` : exitLine);
}
return formatCommandOutput(stdoutForModel, stderrForModel).join("\n") || "(no output)";
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
await context?.writer?.custom({
type: "data-sandbox-exit",
data: {
exitCode: -1,
success: false,
executionTimeMs: Date.now() - startedAt,
error: errorMessage,
toolCallId
}
});
span.end({ success: false }, { exitCode: -1 });
const parts = formatCommandOutput(noteDroppedOutput(await truncateOutput(stdout.toString(), tail, tokenLimit, tokenFrom), stdout.dropped, "stdout"), noteDroppedOutput(await truncateOutput(stderr.toString(), tail, tokenLimit, tokenFrom), stderr.dropped, "stderr"));
const errorLine = `Error: ${errorMessage}\nExit code: -1`;
return appendTerminalLine(parts, abortedWhenSettled ? `${CANCELLED_RUN_NOTE}\n${errorLine}` : errorLine);
}
}
const baseDescription = `Execute a shell command in the workspace sandbox.
Examples:
"npm install && npm run build"
"ls -la src/"
"cat config.json | jq '.database'"
"cd /app && python main.py"
Usage:
- Commands run in a shell, so pipes, redirects, and chaining (&&, ||, ;) all work.
- Always quote file paths that contain spaces (e.g., cd "/path/with spaces").
- Use the timeout parameter (in seconds) to limit execution time. Behavior when omitted depends on the sandbox provider.
- Optionally use cwd to override the working directory. Commands run from the workspace directory if omitted, the same root relative file paths resolve against; a relative cwd is resolved against that directory.`;
/** Foreground-only tool (no background param in schema). */
const executeCommandTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,
description: baseDescription,
inputSchema: executeCommandInputSchema,
outputSchema: zod_v4.z.string(),
execute: executeCommand,
toModelOutput: sandboxToModelOutput
});
const backgroundDescription = `${baseDescription}
Set background: true to run long-running commands (dev servers, watchers) without blocking. You'll get a PID to track the process. On a background command, timeout stops the process after that many seconds: leave it out for dev servers and anything else that should keep running.`;
/** Tool with background param in schema (used when sandbox.processes exists). */
const executeCommandWithBackgroundTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,
description: backgroundDescription,
inputSchema: executeCommandWithBackgroundSchema,
outputSchema: zod_v4.z.string(),
execute: executeCommand,
toModelOutput: sandboxToModelOutput
});
/** Foreground-only tool that requires a leading `description` arg. */
const executeCommandWithDescriptionTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,
description: baseDescription,
inputSchema: executeCommandWithDescriptionSchema,
outputSchema: zod_v4.z.string(),
execute: executeCommand,
toModelOutput: sandboxToModelOutput
});
/** Background-capable tool that requires a leading `description` arg. */
const executeCommandWithDescriptionAndBackgroundTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,
description: backgroundDescription,
inputSchema: executeCommandWithDescriptionAndBackgroundSchema,
outputSchema: zod_v4.z.string(),
execute: executeCommand,
toModelOutput: sandboxToModelOutput
});
// src/workspace/tools/file-stat.ts
const fileStatTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT,
description: "Get file or directory metadata from the workspace. Returns existence, type, size, and modification time.",
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({ path: zod_v4.z.string().describe("The path to check") }),
execute: async ({ path }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "stat",
input: { path },
attributes: { filesystemProvider: filesystem.provider }
});
try {
const stat = await filesystem.stat(path);
const modifiedAt = stat.modifiedAt.toISOString();
const parts = [`${path}`, `Type: ${stat.type}`];
if (stat.size !== void 0) parts.push(`Size: ${stat.size} bytes`);
parts.push(`Modified: ${modifiedAt}`);
span.end({ success: true }, { bytesTransferred: stat.size });
return parts.join(" ");
} catch (error) {
if (error instanceof require_errors.FileNotFoundError) {
span.end({ success: false });
return `${path}: not found`;
}
span.error(error);
throw error;
}
}
});
// src/workspace/tools/get-process-output.ts
const LEFT_BEHIND_NOTE = "The command exited, but a process it started is still running and holding its output open. Call kill_process to stop it.";
const ABORTED_PROCESS_NOTE = "Process aborted: the run that started or was waiting on this process was cancelled (by the user or system), so it was killed before it finished.";
const getProcessOutputTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT,
description: `Get the current output (stdout, stderr) and status of a background process by its PID.
Use this after starting a background command with execute_command (background: true) to check if the process is still running and read its output.`,
toModelOutput: sandboxToModelOutput,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
pid: zod_v4.z.string().describe("The process ID returned when the background command was started"),
tail: zod_v4.z.preprocess(coerceNumericString, zod_v4.z.number().int()).optional().describe(`Number of lines to return, similar to tail -n. Positive or negative returns last N lines from end. Defaults to 200. Use 0 for no limit.`),
wait: zod_v4.z.boolean().optional().describe("If true, block until the process exits and return the final output. Useful for short-lived background commands where you want to wait for the result.")
}),
execute: async ({ pid, tail, wait: shouldWait }, context) => {
const { workspace, sandbox } = requireSandbox(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT);
const span = startWorkspaceSpan(context, workspace, {
category: "sandbox",
operation: "getProcessOutput",
input: {
pid,
tail,
wait: shouldWait
},
attributes: { sandboxProvider: sandbox.provider }
});
const toolCallId = context?.agent?.toolCallId;
try {
if (!sandbox.processes) throw new require_errors.SandboxFeatureNotSupportedError("processes");
const handle = await sandbox.processes.get(pid);
if (!handle) {
span.end({ success: false });
return `No background process found with PID ${pid}.${getDynamicSandboxCacheKeyHint(workspace)}`;
}
if (handle.command) await context?.writer?.custom({
type: "data-sandbox-command",
data: {
command: handle.command,
pid,
toolCallId
}
});
let result;
if (shouldWait && handle.exitCode === void 0) {
result = await handle.wait({
abortSignal: context?.abortSignal,
onStdout: context?.writer ? async (data) => {
await context.writer.custom({
type: "data-sandbox-stdout",
data: {
output: data,
timestamp: Date.now(),
toolCallId
},
transient: true
});
} : void 0,
onStderr: context?.writer ? async (data) => {
await context.writer.custom({
type: "data-sandbox-stderr",
data: {
output: data,
timestamp: Date.now(),
toolCallId
},
transient: true
});
} : void 0
});
await context?.writer?.custom({
type: "data-sandbox-exit",
data: {
exitCode: result.exitCode,
success: result.success,
executionTimeMs: result.executionTimeMs,
toolCallId
}
});
}
const exitCode = handle.exitCode ?? result?.exitCode;
const running = exitCode === void 0;
const tokenLimit = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT]?.maxOutputTokens;
const stdout = noteDroppedOutput(await truncateOutput(handle.stdout, tail, tokenLimit, "sandwich"), handle.stdoutDroppedBytes, "stdout");
const stderr = noteDroppedOutput(await truncateOutput(handle.stderr, tail, tokenLimit, "sandwich"), handle.stderrDroppedBytes, "stderr");
if (running && !stdout && !stderr) {
span.end({ success: true }, { exitCode: handle.exitCode });
return "(no output yet)";
}
const parts = [];
if (stdout && stderr) parts.push("stdout:", stdout, "", "stderr:", stderr);
else if (stdout) parts.push(stdout);
else if (stderr) parts.push("stderr:", stderr);
if (!running) {
const terminalLines = [
...handle.killedByAbort ? [ABORTED_PROCESS_NOTE] : [],
...handle.exitCode === void 0 ? [LEFT_BEHIND_NOTE] : [],
`Exit code: ${exitCode}`
];
parts.push(...parts.length > 0 ? [""] : [], ...terminalLines);
}
span.end({ success: true }, { exitCode });
return parts.join("\n");
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/gitignore.ts
/**
* Gitignore support for workspace tools.
*
* Applies every `.gitignore` relative to the directory that holds it, the way
* git does, so a multi-repo workspace root without its own `.gitignore` still
* honors each repository's rules. `node_modules` is skipped by default.
*/
/** Maximum concurrent `.gitignore` reads while walking. */
const GITIGNORE_READ_CONCURRENCY = 8;
const NODE_MODULES = /(^|\/)node_modules(\/|$)/;
/**
* Load ignore rules for a walk rooted at `target`: the workspace root's
* `.gitignore` plus those of `target`'s ancestors. The walk adds nested ones
* with {@link WorkspaceIgnore.addListings}.
*
* When `target` is itself ignored (e.g. `dist` or `node_modules/x`), nothing
* below it is filtered, so callers can still look inside on purpose.
* Missing nested `.gitignore` files are skipped, and so are unreadable ones;
* an unreadable root `.gitignore` throws.
*/
async function loadWorkspaceIgnore(filesystem, target, options = {}) {
const skipNodeModules = !NODE_MODULES.test(options.requestedPath ?? target);
const useGitignore = options.gitignore ?? true;
const rules = /* @__PURE__ */ new Map();
const addFrom = async (directories) => {
const pMap = (await import("p-map")).default;
await pMap(directories.filter((directory) => !rules.has(pathKey(directory))), async (directory) => {
const content = await readGitignore(filesystem, directory);
if (content?.trim()) rules.set(pathKey(directory), (0, ignore.default)().add(content));
}, { concurrency: GITIGNORE_READ_CONCURRENCY });
};
const matchesRules = (path, isDirectory) => {
const key = pathKey(path);
const applicable = [];
for (const [directory, ig] of rules) {
let relative;
if (directory === "") relative = key;
else if (key.startsWith(`${directory}/`)) relative = key.slice(directory.length + 1);
else continue;
if (relative) applicable.push([isDirectory ? `${relative}/` : relative, ig]);
}
applicable.sort(([a], [b]) => b.length - a.length);
let ignored = false;
for (const [relative, ig] of applicable) {
const result = ig.test(relative);
if (result.ignored) ignored = true;
else if (result.unignored) ignored = false;
}
return ignored;
};
let targetIsIgnored = false;
if (useGitignore) {
const root = await readRootGitignore(filesystem);
if (root?.trim()) rules.set("", (0, ignore.default)().add(root));
await addFrom(ancestorDirectories(target));
targetIsIgnored = pathKey(target) !== "" && matchesRules(target, true);
}
const applyGitignore = useGitignore && !targetIsIgnored;
const isIgnored = (path, isDirectory) => skipNodeModules && NODE_MODULES.test(pathKey(path)) || applyGitignore && matchesRules(path, isDirectory);
return {
ignores: isIgnored,
async addListings(listings) {
if (!applyGitignore) return;
await addFrom(listings.filter(([, entries]) => entries?.some((entry) => entry.type === "file" && entry.name === ".gitignore")).map(([directory]) => directory));
},
async addParentsOf(filePaths) {
if (!applyGitignore) return;
const targetKey = pathKey(target);
const byDepth = /* @__PURE__ */ new Map();
for (const filePath of filePaths) for (const directory of ancestorDirectories(filePath).slice(1)) {
const key = pathKey(directory);
if (key === targetKey || targetKey && !key.startsWith(`${targetKey}/`)) break;
const depth = key.split("/").length;
if (!byDepth.has(depth)) byDepth.set(depth, /* @__PURE__ */ new Set());
byDepth.get(depth).add(directory);
}
for (const depth of [...byDepth.keys()].sort((a, b) => a - b)) await addFrom([...byDepth.get(depth)].filter((directory) => !isIgnored(directory, true)));
}
};
}
/** Rule-matching form of a path: no `./`, leading `/`, or trailing `/`; the root is `''`. */
function pathKey(path) {
const key = path.replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
return key === "." ? "" : key;
}
/** `path` and each directory above it, deepest first, excluding the root. */
function ancestorDirectories(path) {
const directories = [];
let current = path.replace(/\/+$/, "");
while (current && current !== "." && current !== "/") {
directories.push(current);
const slash = current.lastIndexOf("/");
current = slash > 0 ? current.slice(0, slash) : slash === 0 ? "/" : "";
}
return directories;
}
/** Read the root `.gitignore`; only a missing file (ENOENT) is treated as absent. */
async function readRootGitignore(filesystem) {
try {
const content = await filesystem.readFile(".gitignore", { encoding: "utf-8" });
return typeof content === "string" ? content : void 0;
} catch (err) {
if (require_workspace_skills.isEnoentError(err)) return void 0;
throw err;
}
}
/** Read `<directory>/.gitignore`, or undefined when it is missing or unreadable. */
async function readGitignore(filesystem, directory) {
try {
const content = await filesystem.readFile(`${directory.replace(/\/+$/, "")}/.gitignore`, { encoding: "utf-8" });
return typeof content === "string" ? content : void 0;
} catch {
return;
}
}
// src/workspace/tools/grep.ts
const GREP_FILESYSTEM_CONCURRENCY = 8;
/**
* Wall-clock budget for the host-side directory walk. On remote filesystems
* every directory and file is a round trip, so an unbounded walk over a large
* repository can stall an agent run for minutes; past this budget the tool
* returns what it found so far and says the search is incomplete.
*/
const HOST_WALK_BUDGET_MS = 6e4;
/**
* Create a grep tool bound to the given options.
*
* By default read failures are reported honestly in the summary (skip counts)
* rather than throwing. Pass `strict: true` to make any read failure throw.
*/
function createGrepTool(options = {}) {
const strict = options.strict ?? false;
return require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.GREP,
description: `Search file contents using a regex pattern. Walks the filesystem and returns matching lines with file paths and line numbers.
Usage:
- Basic search: { pattern: "TODO" }
- Regex: { pattern: "function\\s+\\w+\\(" }
- Multiple terms: { pattern: "TODO|FIXME|HACK" }
- Case-insensitive: { pattern: "error", caseSensitive: false }
- Search in directory: { pattern: "import", path: "./src" }
- Filter by glob: { pattern: "import", path: "**/*.ts" }
- Combined path + glob: { pattern: "import", path: "src/**/*.ts" }
- Multiple file types: { pattern: "import", path: "**/*.{ts,tsx,js}" }
- Multiple directories: { pattern: "TODO", path: "{src,lib}/**/*.ts" }
- With context: { pattern: "function", contextLines: 2 }`,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
pattern: zod_v4.z.string().describe("Regex pattern to search for"),
path: zod_v4.z.string().optional().default(".").describe("File, directory, or glob pattern to search within (default: \".\"). A plain path searches that file or directory. A glob pattern (e.g., \"**/*.ts\", \"src/**/*.test.ts\") filters which files to search."),
contextLines: zod_v4.z.number().optional().default(0).describe("Number of lines of context to include before and after each match (default: 0)"),
maxCount: zod_v4.z.number().optional().describe("Maximum matches per file. Moves on to the next file after this many matches. Similar to grep -m flag."),
caseSensitive: zod_v4.z.boolean().optional().default(true).describe("Whether the search is case-sensitive (default: true)"),
includeHidden: zod_v4.z.boolean().optional().default(false).describe("Include hidden files and directories (names starting with \".\") in the search (default: false)")
}),
execute: async ({ pattern, path: inputPath = ".", contextLines = 0, maxCount, caseSensitive = true, includeHidden = false }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.GREP);
const isText = (filename) => filesystem.isTextFile ? filesystem.isTextFile(filename) : require_workspace_skills.isTextFile(filename);
let skippedExtensionCount = 0;
let skippedReadErrorCount = 0;
let targetNotFound = false;
let scannedFileCount = 0;
let walkDeadline;
let incomplete;
const shouldStop = () => {
if (!incomplete) {
if (context?.abortSignal?.aborted) incomplete = "aborted";
else if (walkDeadline !== void 0 && Date.now() > walkDeadline) incomplete = "time budget";
}
return incomplete !== void 0;
};
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "grep",
input: {
pattern,
path: inputPath,
contextLines,
maxCount
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
const MAX_PATTERN_LENGTH = 1e3;
if (pattern.length > MAX_PATTERN_LENGTH) {
span.end({ success: false });
return `Error: Pattern too long (${pattern.length} chars, max ${MAX_PATTERN_LENGTH}). Use a shorter pattern.`;
}
let regex;
try {
regex = new RegExp(pattern, caseSensitive ? "g" : "gi");
} catch (e) {
span.end({ success: false });
return `Error: Invalid regex pattern: ${e.message}`;
}
let searchPath;
let globMatcher;
if (require_workspace_skills.isGlobPattern(inputPath)) {
searchPath = require_workspace_skills.extractGlobBase(inputPath);
globMatcher = require_workspace_skills.createGlobMatcher(inputPath, { dot: includeHidden });
} else searchPath = inputPath;
const workspaceIgnore = await loadWorkspaceIgnore(filesystem, searchPath, { requestedPath: inputPath });
const isIgnored = (path, isDirectory) => workspaceIgnore.ignores(path, isDirectory);
const MAX_LINE_LENGTH = 500;
const GLOBAL_CAP = 1e3;
const normalizedContextLines = Math.max(0, Math.floor(contextLines));
let filePaths = [];
let nativeResults;
const normalizedSearch = searchPath.replace(/\/$/, "");
if (normalizedSearch === ".git" || normalizedSearch.endsWith("/.git")) filePaths = [];
else try {
const stat = await filesystem.stat(searchPath);
if (stat.type === "file") {
if (isText(searchPath)) filePaths = [searchPath];
else {
filePaths = [];
skippedExtensionCount++;
}
} else if (typeof filesystem.grep === "function") try {
nativeResults = await filesystem.grep({
pattern,
path: searchPath,
caseSensitive,
includeHidden,
maxCountPerFile: maxCount,
maxTotalMatches: GLOBAL_CAP,
contextLines: normalizedContextLines
});
} catch (error) {
nativeResults = void 0;
const reason = error instanceof Error ? error.message : String(error);
if (error instanceof require_errors.UnsupportedGrepPatternError) workspace.logger?.info(`Native grep on "${filesystem.provider}" filesystem could not run pattern "${pattern}" (${reason}); falling back to host-side search`);
else workspace.logger?.warn(`Native grep failed on "${filesystem.provider}" filesystem; falling back to host-side search for "${searchPath}"`, { error: reason });
}
if (stat.type !== "file" && !nativeResults) {
const entriesByDirectory = /* @__PURE__ */ new Map();
let directoryFrontier = [searchPath];
walkDeadline = Date.now() + HOST_WALK_BUDGET_MS;
const pMap = (await import("p-map")).default;
while (directoryFrontier.length > 0 && !shouldStop()) {
const directoryEntries = await pMap(directoryFrontier, async (dir) => {
if (shouldStop()) return void 0;
try {
return await filesystem.readdir(dir);
} catch (err) {
if (strict) throw err;
skippedReadErrorCount++;
return [];
}
}, { concurrency: GREP_FILESYSTEM_CONCURRENCY });
const nextDirectoryFrontier = [];
await workspaceIgnore.addListings(directoryFrontier.map((dir, directoryIndex) => [dir, directoryEntries[directoryIndex]]));
for (let directoryIndex = 0; directoryIndex < directoryFrontier.length; directoryIndex++) {
const dir = directoryFrontier[directoryIndex];
const entries = directoryEntries[directoryIndex];
if (!entries) continue;
entriesByDirectory.set(dir, entries);
for (const entry of entries) {
if (entry.type !== "directory" || entry.isSymlink || entry.name === ".git") continue;
if (!includeHidden && entry.name.startsWith(".")) continue;
const fullPath = dir.endsWith("/") ? `${dir}${entry.name}` : `${dir}/${entry.name}`;
if (isIgnored(fullPath, true)) continue;
nextDirectoryFrontier.push(fullPath);
}
}
directoryFrontier = nextDirectoryFrontier;
}
const collectFiles = (dir) => {
const files = [];
for (const entry of entriesByDirectory.get(dir) ?? []) {
if (entry.type === "directory" && entry.name === ".git") continue;
if (!includeHidden && entry.name.startsWith(".")) continue;
const fullPath = dir.endsWith("/") ? `${dir}${entry.name}` : `${dir}/${entry.name}`;
if (isIgnored(fullPath, entry.type === "directory")) continue;
if (entry.type === "file") {
if (globMatcher && !globMatcher(fullPath)) continue;
if (!isText(entry.name)) continue;
files.push(fullPath);
} else if (entry.type === "directory" && !entry.isSymlink) files.push(...collectFiles(fullPath));
}
return files;
};
filePaths = collectFiles(searchPath);
}
} catch (err) {
if (strict) throw err;
if (require_workspace_skills.isEnoentError(err) || require_workspace_skills.isEnotdirError(err)) targetNotFound = true;
else skippedReadErrorCount++;
filePaths = [];
}
const outputLines = [];
const filesWithMatches = /* @__PURE__ */ new Set();
let totalMatchCount = 0;
let truncated = false;
let emittedContextHunk = false;
/**
* Format one file's matches into outputLines. Shared between the native
* capability path and the host-side walk so output is byte-identical.
* `getLine` returns the text of a 0-based line index, or undefined when
* the line is unavailable (out of bounds, or outside provider context).
*/
const emitFileMatches = (filePath, fileMatches, getLine) => {
if (normalizedContextLines > 0) {
const hunks = [];
for (const match of fileMatches) {
const start = Math.max(0, match.lineIndex - normalizedContextLines);
const end = match.lineIndex + normalizedContextLines;
const previousHunk = hunks[hunks.length - 1];
if (previousHunk && start <= previousHunk.end + 1) {
previousHunk.end = Math.max(previousHunk.end, end);
previousHunk.matchesByLine.set(match.lineIndex, match.columnIndex);
} else hunks.push({
start,
end,
matchesByLine: /* @__PURE__ */ new Map([[match.lineIndex, match.columnIndex]])
});
}
for (const hunk of hunks) {
if (emittedContextHunk) outputLines.push("--");
emittedContextHunk = true;
for (let i = hunk.start; i <= hunk.end; i++) {
const columnIndex = hunk.matchesByLine.get(i);
const line = getLine(i);
if (line === void 0) continue;
if (columnIndex !== void 0) {
let lineContent = line;
if (lineContent.length > MAX_LINE_LENGTH) lineContent = sliceSafe(lineContent, 0, MAX_LINE_LENGTH) + "...";
outputLines.push(`${filePath}:${i + 1}:${columnIndex + 1}: ${lineContent}`);
} else outputLines.push(`${filePath}:${i + 1}- ${line}`);
}
}
} else for (const match of fileMatches) {
let lineContent = getLine(match.lineIndex) ?? "";
if (lineContent.length > MAX_LINE_LENGTH) lineContent = sliceSafe(lineContent, 0, MAX_LINE_LENGTH) + "...";
outputLines.push(`${filePath}:${match.lineIndex + 1}:${match.columnIndex + 1}: ${lineContent}`);
}
};
if (nativeResults) {
await workspaceIgnore.addParentsOf(nativeResults.map((result) => {
const rel = result.path.replace(/^\.\//, "");
return searchPath.endsWith("/") ? `${searchPath}${rel}` : `${searchPath}/${rel}`;
}));
for (const result of nativeResults) {
if (truncated) break;
const rel = result.path.replace(/^\.\//, "");
const segments = rel.split("/");
if (segments.includes(".git")) continue;
if (!includeHidden && segments.some((segment) => segment.startsWith("."))) continue;
if (!isText(segments[segments.length - 1])) continue;
const fullPath = searchPath.endsWith("/") ? `${searchPath}${rel}` : `${searchPath}/${rel}`;
if (isIgnored(fullPath, false)) continue;
if (globMatcher && !globMatcher(fullPath)) continue;
const lineTextByIndex = /* @__PURE__ */ new Map();
const fileMatches = [];
let fileMatchCount = 0;
for (const match of result.matches) {
const lineIndex = match.line - 1;
lineTextByIndex.set(lineIndex, match.text);
match.before?.forEach((text, i) => lineTextByIndex.set(lineIndex - match.before.length + i, text));
match.after?.forEach((text, i) => lineTextByIndex.set(lineIndex + 1 + i, text));
filesWithMatches.add(fullPath);
fileMatches.push({
lineIndex,
columnIndex: match.column
});
totalMatchCount++;
fileMatchCount++;
if (maxCount !== void 0 && fileMatchCount >= maxCount) break;
if (totalMatchCount >= GLOBAL_CAP) {
truncated = true;
break;
}
}
emitFileMatches(fullPath, fileMatches, (i) => lineTextByIndex.get(i));
}
}
const pMap = (await import("p-map")).default;
for (let batchStart = 0; batchStart < filePaths.length && !truncated && !shouldStop(); batchStart += GREP_FILESYSTEM_CONCURRENCY) {
const batchPaths = filePaths.slice(batchStart, batchStart + GREP_FILESYSTEM_CONCURRENCY);
const batchContents = await pMap(batchPaths, async (filePath) => {
if (shouldStop()) return void 0;
try {
const raw = await filesystem.readFile(filePath, { encoding: "utf-8" });
scannedFileCount++;
return typeof raw === "string" ? raw : void 0;
} catch (err) {
if (strict) throw err;
skippedReadErrorCount++;
return;
}
}, { concurrency: GREP_FILESYSTEM_CONCURRENCY });
for (let fileIndex = 0; fileIndex < batchPaths.length && !truncated; fileIndex++) {
const filePath = batchPaths[fileIndex];
const content = batchContents[fileIndex];
if (content === void 0) continue;
const lines = content.split("\n");
let fileMatchCount = 0;
const fileMatches = [];
for (let i = 0; i < lines.length; i++) {
const currentLine = lines[i];
regex.lastIndex = 0;
const lineMatch = regex.exec(currentLine);
if (!lineMatch) continue;
filesWithMatches.add(filePath);
fileMatches.push({
lineIndex: i,
columnIndex: lineMatch.index
});
totalMatchCount++;
fileMatchCount++;
if (maxCount !== void 0 && fileMatchCount >= maxCount) break;
if (totalMatchCount >= GLOBAL_CAP) {
truncated = true;
break;
}
}
emitFileMatches(filePath, fileMatches, (i) => lines[i]);
}
}
const summaryParts = [`${totalMatchCount} match${totalMatchCount !== 1 ? "es" : ""}`];
summaryParts.push(`across ${filesWithMatches.size} file${filesWithMatches.size !== 1 ? "s" : ""}`);
if (truncated) summaryParts.push(`(truncated at ${GLOBAL_CAP})`);
if (incomplete) {
const scanned = `${scannedFileCount} file${scannedFileCount !== 1 ? "s" : ""} scanned`;
summaryParts.push(incomplete === "aborted" ? `(search incomplete: aborted, ${scanned}; results are partial)` : `(search incomplete: host-side search stopped after ${HOST_WALK_BUDGET_MS / 1e3}s, ${scanned}; results are partial, narrow the path or pattern to search everything)`);
}
if (skippedExtensionCount > 0) summaryParts.push(`(${skippedExtensionCount} file${skippedExtensionCount !== 1 ? "s" : ""} skipped: unsupported extension)`);
if (targetNotFound) summaryParts.push("(target path not found: nothing searched)");
if (skippedReadErrorCount > 0) summaryParts.push(`(${skippedReadErrorCount} path${skippedReadErrorCount !== 1 ? "s" : ""} skipped: read error)`);
const summary = summaryParts.join(" ");
outputLines.unshift(summary, "---");
const output = await applyTokenLimit(outputLines.join("\n"), workspace.getToolsConfig()?.[WORKSPACE_TOOLS.FILESYSTEM.GREP]?.maxOutputTokens, "end");
span.end({ success: true }, { resultCount: totalMatchCount });
return output;
} catch (err) {
span.error(err);
throw err;
}
}
});
}
createGrepTool();
// src/workspace/tools/index-content.ts
const indexContentTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SEARCH.INDEX,
description: "Index content for search. The path becomes the document ID in search results.",
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The document ID/path for search results"),
content: zod_v4.z.string().describe("The text content to index"),
metadata: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.unknown()).optional().describe("Optional metadata to store with the document")
}),
execute: async ({ path, content, metadata }, context) => {
const workspace = requireWorkspace(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SEARCH.INDEX);
const span = startWorkspaceSpan(context, workspace, {
category: "search",
operation: "index",
input: {
path,
contentLength: content.length
},
attributes: {}
});
try {
await workspace.index(path, content, { metadata });
span.end({ success: true }, { bytesTransferred: Buffer.byteLength(content, "utf-8") });
return `Indexed ${path}`;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/kill-process.ts
const KILL_TAIL_LINES = 50;
const killProcessTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS,
description: `Kill a background process by its PID.
Use this to stop a long-running background process that was started with execute_command (background: true). Returns the last ${KILL_TAIL_LINES} lines of output.`,
toModelOutput: sandboxToModelOutput,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({ pid: zod_v4.z.string().describe("The process ID of the background process to kill") }),
execute: async ({ pid }, context) => {
const { workspace, sandbox } = requireSandbox(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS);
const span = startWorkspaceSpan(context, workspace, {
category: "sandbox",
operation: "killProcess",
input: { pid },
attributes: { sandboxProvider: sandbox.provider }
});
const toolCallId = context?.agent?.toolCallId;
try {
if (!sandbox.processes) throw new require_errors.SandboxFeatureNotSupportedError("processes");
const handle = await sandbox.processes.get(pid);
if (handle?.command) await context?.writer?.custom({
type: "data-sandbox-command",
data: {
command: handle.command,
pid,
toolCallId
}
});
if (!await sandbox.processes.kill(pid)) {
if (handle?.exitCode !== void 0) await context?.writer?.custom({
type: "data-sandbox-exit",
data: {
exitCode: handle.exitCode,
success: false,
killed: false,
toolCallId
}
});
span.end({ success: false });
return `Process ${pid} was not found or had already exited.${getDynamicSandboxCacheKeyHint(workspace)}`;
}
await context?.writer?.custom({
type: "data-sandbox-exit",
data: {
exitCode: handle?.exitCode ?? 137,
success: false,
killed: true,
toolCallId
}
});
const parts = [`Process ${pid} has been killed.`];
if (handle) {
const tokenLimit = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS]?.maxOutputTokens;
const stdout = handle.stdout ? await truncateOutput(handle.stdout, KILL_TAIL_LINES, tokenLimit, "sandwich") : "";
const stderr = handle.stderr ? await truncateOutput(handle.stderr, KILL_TAIL_LINES, tokenLimit, "sandwich") : "";
if (stdout) parts.push("", "--- stdout (last output) ---", stdout);
if (stderr) parts.push("", "--- stderr (last output) ---", stderr);
}
span.end({ success: true }, { exitCode: handle?.exitCode ?? 137 });
return parts.join("\n");
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/tree-formatter.ts
/** Maximum concurrent `readdir` calls while walking the tree. */
const TREE_FILESYSTEM_CONCURRENCY = 8;
/**
* Format a directory as an ASCII tree.
*
* @param fs - WorkspaceFilesystem implementation
* @param path - Root path to format
* @param options - Formatting options
* @returns Tree result with formatted string and counts
*/
async function formatAsTree(fs, path, options) {
const maxDepth = options?.maxDepth ?? Infinity;
const showHidden = options?.showHidden ?? false;
const dirsOnly = options?.dirsOnly ?? false;
const exclude = options?.exclude;
const extension = options?.extension;
const pattern = options?.pattern;
const respectGitignore = options?.respectGitignore ?? true;
const customFilter = options?.ignoreFilter;
const workspaceIgnore = respectGitignore ? await loadWorkspaceIgnore(fs, path, { gitignore: !customFilter }) : void 0;
const isIgnored = (entryPath, isDirectory) => {
if (workspaceIgnore?.ignores(entryPath, isDirectory)) return true;
if (!customFilter) return false;
const relativePath = getRelativePath("", "", entryPath);
return customFilter(isDirectory ? `${relativePath}/` : relativePath);
};
const skipNodeModules = respectGitignore && !/(^|\/)node_modules(\/|$)/.test(path);
let globMatcher;
if (pattern) globMatcher = require_workspace_skills.createGlobMatcher(Array.isArray(pattern) ? pattern : [pattern], { dot: showHidden });
const lines = ["."];
const paths = [];
let dirCount = 0;
let fileCount = 0;
let truncated = false;
const excludePatterns = exclude ? Array.isArray(exclude) ? exclude : exclude.split("|").map((p) => p.trim()).filter(Boolean) : void 0;
/**
* Whether the walk should descend into a directory entry. Mirrors the
* filtering applied before recursion in `buildTree` — directories filtered
* out there are never listed, so their contents are never needed.
*/
function shouldDescend(currentPath, entry) {
if (entry.type !== "directory" || entry.isSymlink) return false;
if (entry.name === ".git") return false;
if (!showHidden && entry.name.startsWith(".")) return false;
if (excludePatterns && excludePatterns.some((pattern) => entry.name.includes(pattern))) return false;
if (isIgnored(joinPath$1(currentPath, entry.name), true)) return false;
return true;
}
const entriesByPath = /* @__PURE__ */ new Map();
let rootError;
const normalizedRoot = path.replace(/\/$/, "");
const shouldWalk = !(normalizedRoot === ".git" || normalizedRoot.endsWith("/.git")) && maxDepth > 0;
let prefetched = false;
if (shouldWalk && typeof fs.walk === "function") try {
const walkEntries = await fs.walk(path, {
maxDepth: Number.isFinite(maxDepth) ? maxDepth : void 0,
includeHidden: showHidden,
...workspaceIgnore && !customFilter ? { includeGitignoreFiles: true } : {},
...skipNodeModules ? { skipDirectoryNames: ["node_modules"] } : {}
});
entriesByPath.set(path, []);
for (const entry of walkEntries) {
const separatorIndex = entry.path.lastIndexOf("/");
const parentPath = separatorIndex === -1 ? path : joinPath$1(path, entry.path.slice(0, separatorIndex));
let siblings = entriesByPath.get(parentPath);
if (!siblings) {
siblings = [];
entriesByPath.set(parentPath, siblings);
}
siblings.push(entry);
if (entry.type === "directory" && !entry.isSymlink) {
const dirPath = joinPath$1(path, entry.path);
if (!entriesByPath.has(dirPath)) entriesByPath.set(dirPath, []);
}
}
prefetched = true;
} catch (error) {
entriesByPath.clear();
if (!(error instanceof require_errors.DirectoryNotFoundError) && !(error instanceof require_errors.NotDirectoryError)) options?.logger?.warn(`Native walk failed on "${fs.provider}" filesystem; falling back to per-directory readdir walk for "${path}"`, { error: error instanceof Error ? error.message : String(error) });
}
if (prefetched) await workspaceIgnore?.addListings([...entriesByPath.entries()]);
let frontier = !shouldWalk || prefetched ? [] : [{
path,
depth: 0
}];
const pMap = (await import("p-map")).default;
while (frontier.length > 0) {
const results = await pMap(frontier, async (dir) => {
try {
return { entries: await fs.readdir(dir.path) };
} catch (error) {
return { error };
}
}, { concurrency: TREE_FILESYSTEM_CONCURRENCY });
await workspaceIgnore?.addListings(frontier.map((dir, i) => {
const result = results[i];
return [dir.path, "entries" in result ? result.entries : void 0];
}));
const nextFrontier = [];
for (let i = 0; i < frontier.length; i++) {
const { path: dirPath, depth } = frontier[i];
const result = results[i];
if ("error" in result) {
if (depth === 0) rootError = result.error;
continue;
}
entriesByPath.set(dirPath, result.entries);
if (depth + 1 >= maxDepth) continue;
for (const entry of result.entries) if (shouldDescend(dirPath, entry)) nextFrontier.push({
path: joinPath$1(dirPath, entry.name),
depth: depth + 1
});
}
frontier = nextFrontier;
}
/**
* Build tree recursively using tab indentation
*/
function buildTree(currentPath, depth) {
const normalizedCurrentPath = currentPath.replace(/\/$/, "");
if (normalizedCurrentPath === ".git" || normalizedCurrentPath.endsWith("/.git")) return;
if (depth >= maxDepth) {
truncated = true;
return;
}
const entries = entriesByPath.get(currentPath);
if (!entries) {
if (depth === 0 && rootError !== void 0) throw rootError;
return;
}
let filtered = entries;
filtered = filtered.filter((e) => !(e.type === "directory" && e.name === ".git"));
if (!showHidden) filtered = filtered.filter((e) => !e.name.startsWith("."));
if (excludePatterns) filtered = filtered.filter((e) => {
return !excludePatterns.some((pattern) => e.name.includes(pattern));
});
filtered = filtered.filter((e) => !isIgnored(joinPath$1(currentPath, e.name), e.type === "directory"));
if (dirsOnly) filtered = filtered.filter((e) => e.type === "directory");
if (extension && !dirsOnly) {
const extensions = Array.isArray(extension) ? extension : [extension];
filtered = filtered.filter((e) => {
if (e.type === "directory") return true;
return extensions.some((ext) => {
const normalizedExt = ext.startsWith(".") ? ext : `.${ext}`;
return e.name.endsWith(normalizedExt);
});
});
}
if (globMatcher && !dirsOnly) filtered = filtered.filter((e) => {
if (e.type === "directory") return true;
const relativePath = getRelativePath(path, currentPath, e.name);
return globMatcher(relativePath);
});
filtered.sort((a, b) => {
if (a.type === "directory" && b.type !== "directory") return -1;
if (a.type !== "directory" && b.type === "directory") return 1;
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
const indent = " ".repeat(depth);
for (let i = 0; i < filtered.length; i++) {
const entry = filtered[i];
const displayName = entry.isSymlink && entry.symlinkTarget ? `${entry.name} -> ${entry.symlinkTarget}` : entry.name;
lines.push(`${indent}${displayName}`);
paths.push(getRelativePath(path, currentPath, entry.name));
if (entry.type === "directory") {
dirCount++;
if (!entry.isSymlink) buildTree(joinPath$1(currentPath, entry.name), depth + 1);
} else fileCount++;
}
}
buildTree(path, 0);
let summary = `${dirCount === 1 ? "1 directory" : `${dirCount} directories`}, ${fileCount === 1 ? "1 file" : `${fileCount} files`}`;
if (truncated) summary += ` (truncated at depth ${maxDepth})`;
return {
tree: lines.join("\n"),
summary,
dirCount,
fileCount,
truncated,
paths
};
}
function getRelativePath(rootPath, currentPath, entryName) {
const isRootEquivalent = (p) => p === "/" || p === "" || p === ".";
const entryPath = currentPath === rootPath || isRootEquivalent(currentPath) && isRootEquivalent(rootPath) ? entryName : `${currentPath === "/" ? "" : currentPath}/${entryName}`;
if (isRootEquivalent(rootPath)) {
const cleaned = entryPath.replace(/^\.\//, "");
return cleaned.startsWith("/") ? cleaned.slice(1) : cleaned;
}
return (entryPath.startsWith(rootPath + "/") ? entryPath.slice(rootPath.length + 1) : entryPath) || entryPath;
}
/**
* Join path segments, handling root paths correctly
*/
function joinPath$1(base, name) {
if (base === "" || base === "./" || base === ".") return name;
if (base === "/") return `/${name}`;
return `${base}/${name}`;
}
// src/workspace/tools/list-files.ts
const listFilesTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES,
description: `List files and directories in the workspace filesystem.
Returns a compact tab-indented listing for efficient token usage.
Options mirror common tree command flags for familiarity.
Examples:
- List workspace root: { path: "." }
- Deep listing: { path: "src", maxDepth: 5 }
- Directories only: { path: ".", dirsOnly: true }
- Exclude node_modules: { path: ".", exclude: "node_modules" }
- Find TypeScript files: { path: "src", pattern: "**/*.ts" }
- Find config files: { path: ".", pattern: "*.config.{js,ts}" }
- Multiple patterns: { path: ".", pattern: ["**/*.ts", "**/*.tsx"] }
To list ALL files, omit the pattern parameter — do NOT pass pattern: "*".`,
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().default(".").describe("Directory path to list"),
maxDepth: zod_v4.z.number().optional().default(2).describe("Maximum depth to descend (default: 2). Similar to tree -L flag."),
showHidden: zod_v4.z.boolean().optional().default(false).describe("Show hidden files starting with \".\" (default: false). Similar to tree -a flag."),
dirsOnly: zod_v4.z.boolean().optional().default(false).describe("List directories only, no files (default: false). Similar to tree -d flag."),
exclude: zod_v4.z.string().optional().describe("Pattern to exclude (e.g., \"node_modules\"). Similar to tree -I flag."),
extension: zod_v4.z.string().optional().describe("Filter by file extension (e.g., \".ts\"). Similar to tree -P flag."),
pattern: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.array(zod_v4.z.string())]).optional().describe("Glob pattern(s) to filter files. Omit this parameter to list all files (do NOT pass \"*\"). Use \"**/*.ext\" to match files recursively across directories. \"*\" only matches within a single directory level (standard glob). Glob patterns only filter files — directories are always shown to preserve tree structure. Examples: \"**/*.ts\", \"src/**/*.test.ts\", \"*.config.{js,ts}\"."),
respectGitignore: zod_v4.z.boolean().optional().default(true).describe("Respect .gitignore in the listed directory (default: true).")
}),
execute: async ({ path = ".", maxDepth = 2, showHidden, dirsOnly, exclude, extension, pattern, respectGitignore }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES);
const normalizedPattern = (() => {
if (pattern === void 0) return void 0;
if (Array.isArray(pattern)) {
const cleaned = pattern.filter((p) => typeof p === "string" && p.trim().length > 0);
return cleaned.length > 0 ? cleaned : void 0;
}
return pattern.trim().length > 0 ? pattern : void 0;
})();
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "listFiles",
input: {
path,
maxDepth,
pattern: normalizedPattern
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
const result = await formatAsTree(filesystem, path, {
maxDepth,
showHidden,
dirsOnly,
exclude: exclude || void 0,
extension: extension || void 0,
pattern: normalizedPattern,
respectGitignore,
logger: workspace.logger
});
const output = await applyTokenLimit(`${result.tree}\n\n${result.summary}`, workspace.getToolsConfig()?.[WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES]?.maxOutputTokens ?? 1e3, "end");
span.end({ success: true }, { resultCount: result.fileCount });
return output;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/lsp-inspect.ts
/**
* LSP Inspect Tool
*
* Inspect code at a specific position using the Language Server Protocol.
* The agent provides a file path, line number, and a `<<<` marker in the
* line content to indicate the cursor position.
*/
const CURSOR_MARKER = "<<<";
/**
* Get a single line preview from a file at the specified line number.
* Returns the trimmed line content, or null if the line cannot be read.
*/
async function getLinePreview(filePath, lineNumber) {
try {
return (await fs_promises.default.readFile(filePath, "utf-8")).split("\n")[lineNumber - 1]?.trim() ?? null;
} catch {
return null;
}
}
function getAbsolutePath(workspacePath, lspRoot, resolveAbsolutePath) {
const resolvedPath = resolveAbsolutePath?.(workspacePath);
if (resolvedPath) return resolvedPath;
if (path.default.isAbsolute(workspacePath)) return workspacePath;
return path.default.resolve(lspRoot, workspacePath);
}
function locationUriToPath(uri) {
if (!uri.startsWith("file://")) return null;
try {
return (0, url.fileURLToPath)(uri);
} catch {
return null;
}
}
function locationKey(location) {
return `${location.path}:L${location.line}`;
}
/**
* Compress a file path by replacing the current working directory prefix with $cwd
*/
function compressPath(filePath) {
const cwd = process.cwd();
if (filePath.startsWith(cwd)) return "$cwd" + filePath.slice(cwd.length);
return filePath;
}
const lspInspectTool = require_tool.createTool({
id: WORKSPACE_TOOLS.LSP.LSP_INSPECT,
description: "Inspect code at a specific symbol position using the Language Server Protocol. Provide an absolute file path, a 1-indexed line number, and the exact line content with <<< marking the cursor position. Exactly one <<< marker is required. Returns hover information, any diagnostics reported on that line, plus definition and implementation locations when available. Use this for type information, symbol navigation, and go-to-definition; use view to read the surrounding implementation.",
outputSchema: zod_v4.z.object({
hover: zod_v4.z.object({
value: zod_v4.z.string(),
kind: zod_v4.z.string()
}).optional(),
diagnostics: zod_v4.z.array(zod_v4.z.object({
severity: zod_v4.z.string(),
message: zod_v4.z.string(),
source: zod_v4.z.string().nullable()
})).optional(),
definition: zod_v4.z.array(zod_v4.z.object({
location: zod_v4.z.string(),
preview: zod_v4.z.string().nullable()
})).optional(),
implementation: zod_v4.z.array(zod_v4.z.string()).optional(),
error: zod_v4.z.string().optional()
}),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("Absolute path to the file"),
line: zod_v4.z.number().int().positive().describe("Line number (1-indexed)"),
match: zod_v4.z.string().describe("Line content with <<< marking the cursor position. Exactly one <<< marker is required. Example: \"const foo = <<<bar()\" means cursor is at bar")
}),
execute: async ({ path: filePath, line, match }, context) => {
const workspace = requireWorkspace(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.LSP.LSP_INSPECT);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "lspInspect",
input: {
path: filePath,
line
},
attributes: {}
});
const cursorPositions = [];
let searchStart = 0;
while (true) {
const pos = match.indexOf(CURSOR_MARKER, searchStart);
if (pos === -1) break;
cursorPositions.push(pos);
searchStart = pos + 3;
}
if (cursorPositions.length === 0) {
span.end({ success: false });
return { error: `No <<< cursor marker found in match` };
}
if (cursorPositions.length > 1) {
span.end({ success: false });
return { error: `Multiple <<< markers found (found ${cursorPositions.length}, expected 1)` };
}
const character = cursorPositions[0] + 1;
const lspManager = workspace.lsp;
if (!lspManager) {
span.end({ success: false });
return { error: "LSP is not configured for this workspace. Enable LSP in workspace config to use this tool." };
}
const absolutePath = getAbsolutePath(filePath, lspManager.root, workspace.filesystem?.resolveAbsolutePath?.bind(workspace.filesystem));
let fileContent = "";
try {
fileContent = await fs_promises.default.readFile(absolutePath, "utf-8");
} catch {
fileContent = "";
}
let queryResult;
try {
queryResult = await lspManager.prepareQuery(absolutePath);
} catch (err) {
span.end({ success: false });
return { error: `Failed to initialize LSP client: ${err instanceof Error ? err.message : String(err)}` };
}
if (!queryResult) {
span.end({ success: false });
return { error: `No language server available for files of this type: ${filePath}` };
}
const { client, uri, release } = queryResult;
const position = {
line: line - 1,
character: character - 1
};
const result = {};
try {
const hoverResult = await client.queryHover(uri, position).catch(() => null);
if (hoverResult) {
const contents = hoverResult.contents;
if (contents) {
if (typeof contents === "string") result.hover = {
value: contents,
kind: "plaintext"
};
else if (Array.isArray(contents)) {
const first = contents[0];
if (typeof first === "string") result.hover = {
value: first,
kind: "plaintext"
};
else if (first?.value) result.hover = {
value: first.value,
kind: first.kind ?? "markdown"
};
} else if (contents.value) result.hover = {
value: contents.value,
kind: contents.kind ?? "markdown"
};
}
}
const diagnosticsPromise = fileContent ? Promise.resolve().then(() => {
client.notifyChange(absolutePath, fileContent, 1);
return client.waitForDiagnostics(absolutePath, 5e3, true);
}).catch(() => []) : Promise.resolve([]);
const [diagnosticsResult, definitionResult, implResult] = await Promise.all([
diagnosticsPromise,
client.queryDefinition(uri, position).catch(() => []),
client.queryImplementation(uri, position).catch(() => [])
]);
if (diagnosticsResult && diagnosticsResult.length > 0) {
const lineDiagnostics = diagnosticsResult.map((diagnostic) => ({
line: typeof diagnostic.line === "number" ? diagnostic.line : (diagnostic.range?.start?.line ?? -1) + 1,
severity: typeof diagnostic.severity === "number" ? diagnostic.severity === 1 ? "error" : diagnostic.severity === 2 ? "warning" : diagnostic.severity === 3 ? "info" : "hint" : typeof diagnostic.severity === "string" ? diagnostic.severity : "error",
message: diagnostic.message,
source: diagnostic.source ?? null
})).filter((diagnostic) => diagnostic.line === line).map(({ severity, message, source }) => ({
severity,
message,
source
}));
if (lineDiagnostics.length > 0) result.diagnostics = lineDiagnostics;
}
const definitionLocations = definitionResult.map((loc) => ({
uri: loc.uri ?? loc.targetUri,
range: loc.range ?? loc.targetRange
})).map((loc) => {
const resolvedPath = loc.uri ? locationUriToPath(String(loc.uri)) : null;
return resolvedPath ? {
path: resolvedPath,
line: (loc.range?.start?.line ?? 0) + 1,
character: (loc.range?.start?.character ?? 0) + 1
} : null;
}).filter((loc) => Boolean(loc)).filter((loc) => !(loc.path === absolutePath && loc.line === line));
if (definitionLocations.length > 0) {
const previews = await Promise.all(definitionLocations.map((loc) => getLinePreview(loc.path, loc.line)));
result.definition = definitionLocations.map((loc, i) => ({
location: `${compressPath(loc.path)}:L${loc.line}:C${loc.character}`,
preview: previews[i]
}));
}
const definitionKeys = new Set(definitionLocations.map(locationKey));
const implementationLocations = implResult.map((loc) => ({
uri: loc.uri ?? loc.targetUri,
range: loc.range ?? loc.targetRange
})).map((loc) => {
const resolvedPath = loc.uri ? locationUriToPath(String(loc.uri)) : null;
return resolvedPath ? {
path: resolvedPath,
line: (loc.range?.start?.line ?? 0) + 1,
character: (loc.range?.start?.character ?? 0) + 1
} : null;
}).filter((loc) => Boolean(loc)).filter((loc) => !definitionKeys.has(locationKey(loc)) && !(loc.path === absolutePath && loc.line === line));
if (implementationLocations.length > 0) result.implementation = implementationLocations.map((loc) => `${compressPath(loc.path)}:L${loc.line}:C${loc.character}`);
} catch (err) {
result.error = `LSP query failed: ${err instanceof Error ? err.message : String(err)}`;
} finally {
client.notifyClose(absolutePath);
release();
}
span.end({ success: !result.error });
return result;
}
});
// src/workspace/tools/mkdir.ts
const mkdirTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.MKDIR,
description: "Create a directory in the workspace filesystem",
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The path of the directory to create"),
recursive: zod_v4.z.boolean().optional().default(true).describe("Whether to create parent directories if they do not exist")
}),
execute: async ({ path, recursive }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.MKDIR);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "mkdir",
input: {
path,
recursive
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
if (filesystem.readOnly) throw new require_errors.WorkspaceReadOnlyError("mkdir");
await filesystem.mkdir(path, { recursive });
span.end({ success: true });
return `Created directory ${path}`;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/read-file.ts
/**
* Default mime types surfaced to the model as media parts. The list is
* intentionally the intersection of image formats supported by the major
* model providers (Anthropic, OpenAI, Gemini) plus `application/pdf`.
* `image/*` is *not* used so we don't surface exotic subtypes like SVG/BMP
* that some providers reject. Override `mediaTypes` to broaden this.
*/
const DEFAULT_MEDIA_TYPES = [
"image/png",
"image/jpeg",
"image/webp",
"application/pdf"
];
/**
* `application/*` mime types that are actually text content and safe to read
* as utf-8. Anything not matching `text/*` and not in this list is treated
* as opaque binary when there's no explicit encoding and no media match.
*/
const TEXT_APPLICATION_TYPES = /* @__PURE__ */ new Set([
"application/json",
"application/javascript",
"application/typescript",
"application/xml",
"application/graphql",
"application/x-sh",
"application/x-yaml",
"application/yaml",
"application/ld+json",
"application/sql",
"application/jsonl",
"application/x-jsonl",
"application/ndjson",
"application/x-ndjson",
"application/jsonlines",
"application/json-lines",
"application/x-jsonlines",
"application/x-php",
"application/dart"
]);
/**
* Charsets whose bytes decode correctly as utf-8. Text content declared with
* any other charset (e.g. `utf-16le`) would be garbled by a utf-8 read.
*/
const UTF8_COMPATIBLE_CHARSETS = /* @__PURE__ */ new Set([
"utf-8",
"utf8",
"us-ascii",
"ascii"
]);
/** Matches `; name=value` MIME parameters, keeping quoted values (which may contain `;`) whole. */
const MIME_PARAMETER_PATTERN = /;\s*([^\s;=]+)\s*=\s*("(?:[^"\\]|\\.)*"|[^;]*)/g;
function getMimeCharset(mimeType) {
for (const [, name, value] of mimeType.matchAll(MIME_PARAMETER_PATTERN)) {
if (name.toLowerCase() !== "charset") continue;
return (value.startsWith("\"") ? value.slice(1, -1).replace(/\\(.)/g, "$1") : value).trim().toLowerCase();
}
}
function isTextLikeMimeType(mimeType) {
if (!mimeType) return true;
const charset = getMimeCharset(mimeType);
if (charset !== void 0 && !UTF8_COMPATIBLE_CHARSETS.has(charset)) return false;
mimeType = mimeType.split(";", 1)[0].trim().toLowerCase();
if (mimeType === "application/octet-stream") return true;
if (mimeType.startsWith("text/")) return true;
if (TEXT_APPLICATION_TYPES.has(mimeType)) return true;
if (mimeType.endsWith("+json") || mimeType.endsWith("+xml")) return true;
return false;
}
/**
* Validates a single `mediaTypes` pattern. Accepts:
* - `*` or `*/*` — match anything
* - `type/*` — match all subtypes of a top-level type (e.g. `image/*`)
* - `type/subtype` — exact mime type (e.g. `application/pdf`, `application/vnd.api+json`)
*
* Throws a descriptive error for anything else so misconfigurations surface
* immediately instead of silently failing to match.
*/
const MEDIA_TYPE_PATTERN = /^(?:\*|\*\/\*|[a-z0-9!#$&^_.+-]+\/(?:\*|[a-z0-9!#$&^_.+-]+))$/i;
function validateMediaTypePatterns(patterns) {
for (const pattern of patterns) if (typeof pattern !== "string" || !MEDIA_TYPE_PATTERN.test(pattern)) throw new Error(`Invalid \`mediaTypes\` pattern: ${JSON.stringify(pattern)}. Expected \`*\`, \`*/*\`, \`type/*\`, or a full mime type like \`application/pdf\`.`);
}
/**
* Build a predicate from the `mediaTypes` config option.
* Supports glob patterns (e.g. `'image/*'`), custom functions, and `false`
* to disable media parts entirely.
*/
function buildMediaTypeCheck(config) {
if (config === false) return () => false;
if (typeof config === "function") return (mimeType) => mimeType ? config(mimeType) : false;
const patterns = config ?? DEFAULT_MEDIA_TYPES;
validateMediaTypePatterns(patterns);
return (mimeType) => {
if (!mimeType) return false;
return patterns.some((pattern) => {
if (pattern === "*" || pattern === "*/*") return true;
if (pattern.endsWith("/*")) return mimeType.startsWith(pattern.slice(0, -1));
return mimeType === pattern;
});
};
}
/** Bytes decoded from the start of a media file to check its signature. PDF allows its header anywhere in the first 1 KiB. */
const MEDIA_SNIFF_BYTES = 1024;
const startsWithBytes = (bytes, prefix, offset = 0) => bytes.length >= offset + prefix.length && prefix.every((byte, index) => bytes[offset + index] === byte);
/**
* Media types with a fixed signature, and how to recognize each from a file's first bytes.
* Other configured types (e.g. SVG, HEIC, audio) have no reliable signature here and are
* trusted by extension.
*/
const MEDIA_SIGNATURES = [
["image/png", (bytes) => startsWithBytes(bytes, [
137,
80,
78,
71
])],
["image/jpeg", (bytes) => startsWithBytes(bytes, [
255,
216,
255
])],
["image/gif", (bytes) => startsWithBytes(bytes, [
71,
73,
70,
56,
55,
97
]) || startsWithBytes(bytes, [
71,
73,
70,
56,
57,
97
])],
["image/webp", (bytes) => startsWithBytes(bytes, [
82,
73,
70,
70
]) && startsWithBytes(bytes, [
87,
69,
66,
80
], 8)],
["application/pdf", (bytes) => /%PDF-\d\.\d/.test(Buffer.from(bytes).toString("latin1"))]
];
const SIGNED_MEDIA_TYPES = /* @__PURE__ */ new Set([...MEDIA_SIGNATURES.map(([mediaType]) => mediaType), "image/jpg"]);
/**
* The media type to send for a file whose extension maps to `declared`. For types with a known
* signature, this is the type the bytes show (so a PNG named `.jpg` goes as `image/png`), or
* undefined when they show none: an HTML error page saved as `.pdf` is not a PDF, and providers
* reject it with a 400 that also fails every later call carrying the same history.
*/
function contentMediaType(head, declared) {
if (!SIGNED_MEDIA_TYPES.has(declared.split(";", 1)[0].trim().toLowerCase())) return declared;
return MEDIA_SIGNATURES.find(([, matches]) => matches(head))?.[0];
}
/** Whether a whole file is UTF-8 text: no NUL bytes and no invalid sequences. */
function isUtf8Text(content) {
if (content.includes(0)) return false;
try {
new TextDecoder("utf-8", { fatal: true }).decode(content);
return true;
} catch {
return false;
}
}
const readFileTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.READ_FILE,
description: "Read a file from the workspace filesystem. Text files come back as text — use offset/limit to read a line range from large files. Supported media files come back as a native file part you can view directly. Other binary files return only their metadata (path, size, mime type) since their raw contents are not useful to read.",
outputSchema: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.object({
__workspaceMedia: zod_v4.z.literal(true),
text: zod_v4.z.string(),
mediaType: zod_v4.z.string(),
data: zod_v4.z.string()
})]),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The path to the file to read (e.g., \"data/config.json\")"),
offset: zod_v4.z.number().int().min(1).optional().describe("Line number to start reading from (1-indexed). Only used when reading text files; ignored for media and other binary files. Defaults to line 1 if omitted."),
limit: zod_v4.z.number().int().min(1).optional().describe("Maximum number of lines to read. Only used when reading text files; ignored for media and other binary files. Defaults to the end of the file if omitted."),
showLineNumbers: zod_v4.z.boolean().optional().default(true).describe("Prefix each line with its line number. Only used when reading text files; ignored for media and other binary files. Defaults to true if omitted."),
encoding: zod_v4.z.enum([
"utf-8",
"utf8",
"base64",
"hex",
"binary"
]).optional().describe("Usually omit this — text files and supported media are handled automatically. Pass `base64` or `hex` to get the file's raw bytes encoded as text when you need to inspect an unsupported binary file that would otherwise only return metadata (e.g. checking a file header or magic bytes).")
}),
execute: async ({ path, encoding, offset, limit, showLineNumbers }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.READ_FILE);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "readFile",
input: {
path,
encoding,
offset,
limit
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
const stat = await filesystem.stat(path);
const readFileConfig = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.FILESYSTEM.READ_FILE];
const shouldReturnAsMedia = buildMediaTypeCheck(readFileConfig?.mediaTypes);
let mislabeledNote;
if (shouldReturnAsMedia(stat.mimeType)) {
const maxMediaBytes = readFileConfig?.maxMediaBytes ?? 10485760;
if (stat.size <= maxMediaBytes) {
const base64 = await filesystem.readFile(path, { encoding: "base64" });
const mediaType = contentMediaType(Buffer.from(base64.slice(0, Math.ceil(MEDIA_SNIFF_BYTES / 3) * 4), "base64"), stat.mimeType);
if (mediaType && shouldReturnAsMedia(mediaType)) {
const header = `${stat.path} (${stat.size} bytes, ${mediaType})`;
span.end({ success: true }, { bytesTransferred: stat.size });
return {
__workspaceMedia: true,
text: header,
mediaType,
data: base64
};
}
const mismatch = `the extension says ${stat.mimeType}, but the content is ${mediaType ?? "not a valid file of that type"}`;
if (isUtf8Text(Buffer.from(base64, "base64"))) mislabeledNote = mismatch;
else if (!encoding) {
span.end({ success: true }, { bytesTransferred: 0 });
return `${stat.path} (${stat.size} bytes) — ${mismatch}, so it was not sent as media. Pass an explicit \`encoding\` (e.g. \`hex\`) to read the raw bytes.`;
}
} else if (!encoding) {
span.end({ success: true }, { bytesTransferred: 0 });
return `${stat.path} (${stat.size} bytes, ${stat.mimeType}) — exceeds maxMediaBytes (${maxMediaBytes}). Returning metadata only; configure \`maxMediaBytes\` on the read_file tool to raise this cap.`;
}
}
if (!encoding && !mislabeledNote && !isTextLikeMimeType(stat.mimeType)) {
span.end({ success: true }, { bytesTransferred: 0 });
return `${stat.path} (${stat.size} bytes, ${stat.mimeType ?? "unknown"}) — binary file not readable as text. Pass an explicit \`encoding\` (e.g. \`base64\`) to read the raw bytes, or configure \`mediaTypes\` on the read_file tool to surface it as a media part.`;
}
const effectiveEncoding = encoding ?? "utf-8";
const fullContent = await filesystem.readFile(path, { encoding: effectiveEncoding });
const isTextEncoding = !encoding || encoding === "utf-8" || encoding === "utf8";
const tokenLimit = readFileConfig?.maxOutputTokens;
if (!isTextEncoding) {
const output = await applyTokenLimit(`${stat.path} (${stat.size} bytes, ${effectiveEncoding})\n${fullContent}`, tokenLimit, "end");
span.end({ success: true }, { bytesTransferred: stat.size });
return output;
}
if (typeof fullContent !== "string") {
const output = await applyTokenLimit(`${stat.path} (${stat.size} bytes, base64)\n${fullContent.toString("base64")}`, tokenLimit, "end");
span.end({ success: true }, { bytesTransferred: stat.size });
return output;
}
const hasLineRange = offset !== void 0 || limit !== void 0;
const result = extractLinesWithLimit(fullContent, offset, limit);
const shouldShowLineNumbers = showLineNumbers !== false;
const hasExtractedLines = result.lines.start !== 0 || result.lines.end !== 0;
const formattedContent = shouldShowLineNumbers && hasExtractedLines ? formatWithLineNumbers(result.content, result.lines.start) : result.content;
let header;
if (hasLineRange) header = `${stat.path} (lines ${result.lines.start}-${result.lines.end} of ${result.totalLines}, ${stat.size} bytes)`;
else header = `${stat.path} (${stat.size} bytes)`;
if (mislabeledNote) header += ` — ${mislabeledNote}; showing it as text`;
const output = await applyTokenLimit(`${header}\n${formattedContent}`, tokenLimit, "end");
span.end({ success: true }, { bytesTransferred: stat.size });
return output;
} catch (err) {
span.error(err);
throw err;
}
},
toModelOutput: mediaToModelOutput
});
// src/workspace/tools/search.ts
const searchInputSchema = zod_v4.z.object({
query: zod_v4.z.string().describe("The search query string"),
topK: zod_v4.z.number().optional().default(5).describe("Maximum number of results to return"),
mode: zod_v4.z.enum([
"bm25",
"vector",
"hybrid"
]).optional().describe("Search mode: bm25 for keyword search, vector for semantic search, hybrid for both combined"),
minScore: zod_v4.z.number().optional().describe("Minimum score threshold (0-1 for normalized scores)")
});
const searchTool = require_tool.createTool({
id: WORKSPACE_TOOLS.SEARCH.SEARCH,
description: "Search indexed content in the workspace. Supports keyword (BM25), semantic (vector), and hybrid search modes.",
outputSchema: zod_v4.z.string(),
inputSchema: searchInputSchema,
execute: async ({ query, topK, mode, minScore }, context) => {
const workspace = requireWorkspace(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SEARCH.SEARCH);
const span = startWorkspaceSpan(context, workspace, {
category: "search",
operation: "search",
input: {
query,
topK,
mode,
minScore
},
attributes: {}
});
try {
const effectiveMode = mode === "hybrid" && !workspace.canHybrid ? workspace.canVector ? "vector" : "bm25" : mode === "vector" && !workspace.canVector ? "bm25" : mode ?? (workspace.canHybrid ? "hybrid" : workspace.canVector ? "vector" : "bm25");
const results = await workspace.search(query, {
topK,
mode: effectiveMode,
minScore
});
const lines = results.map((r) => {
const lineInfo = r.lineRange ? `:${r.lineRange.start}-${r.lineRange.end}` : "";
return `${r.id}${lineInfo}: ${r.content}`;
});
lines.push("---");
lines.push(`${results.length} result${results.length !== 1 ? "s" : ""} (${effectiveMode} search)`);
span.end({ success: true }, { resultCount: results.length });
return lines.join("\n");
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/write-file.ts
const writeFileTool = require_tool.createTool({
id: WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,
description: "Write content to a file in the workspace filesystem. Creates parent directories if needed.",
outputSchema: zod_v4.z.string(),
inputSchema: zod_v4.z.object({
path: zod_v4.z.string().describe("The path where to write the file (e.g., \"data/output.txt\")"),
content: zod_v4.z.string().describe("The content to write to the file"),
overwrite: zod_v4.z.boolean().optional().default(true).describe("Whether to overwrite the file if it already exists")
}),
execute: async ({ path: path$5, content, overwrite }, context) => {
const { workspace, filesystem } = requireFilesystem(context);
await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE);
const span = startWorkspaceSpan(context, workspace, {
category: "filesystem",
operation: "writeFile",
input: {
path: path$5,
overwrite,
contentLength: content.length
},
attributes: { filesystemProvider: filesystem.provider }
});
try {
if (filesystem.readOnly) throw new require_errors.WorkspaceReadOnlyError("write_file");
await filesystem.writeFile(path$5, content, {
overwrite,
expectedMtime: context?.__expectedMtime
});
const size = Buffer.byteLength(content, "utf-8");
let output = `Wrote ${size} bytes to ${path$5}`;
const resolvedPath = path.default.isAbsolute(path$5) ? filesystem.resolveAbsolutePath?.(path$5) : void 0;
if (resolvedPath && resolvedPath !== path$5) output += ` (resolved to ${resolvedPath})`;
output += await getEditDiagnosticsText(workspace, path$5, content);
span.end({ success: true }, { bytesTransferred: size });
return output;
} catch (err) {
span.error(err);
throw err;
}
}
});
// src/workspace/tools/tools.ts
/**
* Workspace Tools — Factory
*
* Creates the built-in workspace tools for agents. Individual tools are
* defined in their own files; this module applies WorkspaceToolsConfig
* (enabled, requireApproval, requireReadBeforeWrite) and injects workspace
* into the tool execution context.
*/
/**
* Resolve a DynamicToolConfigValue to a boolean.
* If it's a function, calls it with the provided context.
* On error, returns the safeDefault.
*/
async function resolveDynamicValue(value, context, safeDefault) {
if (value === void 0) return safeDefault;
if (typeof value === "boolean") return value;
if (!context) return safeDefault;
try {
return await value(context);
} catch (error) {
console.warn("[Workspace Tools] Dynamic config function threw, using safe default:", error);
return safeDefault;
}
}
function hasFilesystemConfig(workspace) {
if (typeof workspace?.hasFilesystemConfig === "function") return workspace.hasFilesystemConfig();
return !!workspace.filesystem;
}
function hasSandboxConfig(workspace) {
if (typeof workspace?.hasSandboxConfig === "function") return workspace.hasSandboxConfig();
return !!workspace.sandbox;
}
/**
* Normalize a requestContext value to a plain Record.
* Callers may pass a Map-like RequestContext (with `.entries()`) or a plain
* object. Dynamic config functions always receive a plain object so that
* bracket-notation access (`requestContext['key']`) works consistently.
*/
function toPlainRequestContext(requestContext) {
if (!requestContext) return {};
if (typeof requestContext.entries === "function") return Object.fromEntries(requestContext.entries());
return requestContext;
}
/**
* Resolves the effective configuration for a specific tool.
*
* Resolution order (later overrides earlier):
* 1. Built-in defaults (enabled: true, requireApproval: false)
* 2. Top-level config (tools.enabled, tools.requireApproval)
* 3. Per-tool config (tools[toolName].enabled, tools[toolName].requireApproval)
*
* `enabled` is resolved to a boolean immediately (requires context if dynamic).
* `requireApproval` and `requireReadBeforeWrite` are passed through as-is
* for execution-time evaluation (they may need args).
*/
async function resolveToolConfig(toolsConfig, toolName, context) {
let enabled = true;
let requireApproval = false;
let background;
let requireReadBeforeWrite;
let maxOutputTokens;
let name;
const hooks = toolsConfig?.hooks;
if (toolsConfig) {
if (toolsConfig.enabled !== void 0) enabled = toolsConfig.enabled;
if (toolsConfig.requireApproval !== void 0) requireApproval = toolsConfig.requireApproval;
const perToolConfig = toolsConfig[toolName];
if (perToolConfig) {
if (perToolConfig.enabled !== void 0) enabled = perToolConfig.enabled;
if (perToolConfig.requireApproval !== void 0) requireApproval = perToolConfig.requireApproval;
if (perToolConfig.background !== void 0) background = perToolConfig.background;
if (perToolConfig.requireReadBeforeWrite !== void 0) requireReadBeforeWrite = perToolConfig.requireReadBeforeWrite;
if (perToolConfig.maxOutputTokens !== void 0) maxOutputTokens = perToolConfig.maxOutputTokens;
if (perToolConfig.name !== void 0) name = perToolConfig.name;
}
}
return {
enabled: await resolveDynamicValue(enabled, context, false),
requireApproval,
background,
requireReadBeforeWrite,
maxOutputTokens,
name,
hooks
};
}
/**
* Resolve the effective workspace for tool execution. When a dynamic resolver
* is configured for a requested provider (no static instance), resolves it from
* requestContext and returns a proxy workspace that exposes the resolved value.
* Returns the workspace unchanged when no resolution is needed, so tools that
* don't touch a given provider don't pay the cost of calling its resolver.
*/
async function resolveEffectiveWorkspace(workspace, context, targets) {
workspace.lastAccessedAt = /* @__PURE__ */ new Date();
const needsFilesystem = !!(targets.filesystem && !workspace.filesystem && hasFilesystemConfig(workspace));
const needsSandbox = !!(targets.sandbox && !workspace.sandbox && hasSandboxConfig(workspace));
if (!needsFilesystem && !needsSandbox) return workspace;
const requestContext = context?.requestContext ?? new require_request_context.RequestContext();
const overrides = {};
if (needsFilesystem) {
const resolvedFs = await workspace.resolveFilesystem({ requestContext });
if (resolvedFs) overrides.filesystem = resolvedFs;
}
if (needsSandbox) {
const resolvedSandbox = await workspace.resolveSandbox({ requestContext });
if (resolvedSandbox) overrides.sandbox = resolvedSandbox;
}
if (!overrides.filesystem && !overrides.sandbox) return workspace;
return new Proxy(workspace, { get(target, prop) {
if (prop === "filesystem" && overrides.filesystem) return overrides.filesystem;
if (prop === "sandbox" && overrides.sandbox) return overrides.sandbox;
return target[prop];
} });
}
/**
* Clone a standalone tool with config overrides and inject workspace into context.
* `targets` declares which providers the tool needs resolved per request.
*/
function wrapTool(tool, workspace, targets) {
return {
...tool,
execute: async (input, context = {}) => {
const effectiveWorkspace = await resolveEffectiveWorkspace(context?.workspace ?? workspace, context, targets);
const enrichedContext = {
...context,
workspace: effectiveWorkspace
};
return tool.execute(input, enrichedContext);
}
};
}
/**
* Wrap a tool with read-before-write tracking (readTracker).
*
* - mode 'read': records the read after execution
* - mode 'write': checks before execution, clears after
*/
function wrapWithReadTracker(tool, workspace, readTracker, config, mode, getWritePaths, didWrite) {
return {
...tool,
execute: async (input, context = {}) => {
const effectiveWorkspace = await resolveEffectiveWorkspace(context?.workspace ?? workspace, context, { filesystem: true });
let enrichedContext = {
...context,
workspace: effectiveWorkspace
};
const fs = effectiveWorkspace.filesystem;
const scope = fs ? deriveReadScope(fs) : void 0;
const writePaths = getWritePaths ? getWritePaths(input) : [input.path];
if (mode === "write" && fs) {
const shouldRequireRead = config.requireReadBeforeWrite !== void 0 && await resolveDynamicValue(config.requireReadBeforeWrite, {
args: input,
requestContext: enrichedContext.requestContext ?? {},
workspace: effectiveWorkspace
}, true);
const expectedMtimes = {};
for (const path of shouldRequireRead ? writePaths : []) {
const record = await readTracker.getReadRecord(path);
if (record && record.scope === scope) expectedMtimes[path] = record.modifiedAtRead;
try {
const stat = await fs.stat(path);
const check = await readTracker.needsReRead(path, stat.modifiedAt, scope);
if (check.needsReRead) throw new require_errors.FileReadRequiredError(path, check.reason);
} catch (error) {
if (!(error instanceof require_errors.FileNotFoundError)) throw error;
}
}
if (getWritePaths) enrichedContext = {
...enrichedContext,
__expectedMtimes: expectedMtimes
};
else if (expectedMtimes[input.path]) enrichedContext = {
...enrichedContext,
__expectedMtime: expectedMtimes[input.path]
};
}
const result = await tool.execute(input, enrichedContext);
if (mode === "read" && fs) try {
const stat = await fs.stat(input.path);
await readTracker.recordRead(input.path, stat.modifiedAt, scope);
} catch {}
else if (mode === "write" && (didWrite?.(result) ?? true)) for (const path of writePaths) await readTracker.clearReadRecord(path);
return result;
}
};
}
/**
* Wrap a tool with a per-file write lock.
*
* The lock serializes the entire execute pipeline (including any
* read-before-write checks) so concurrent calls to the same path
* run one at a time.
*/
function wrapWithToolHooks(tool, hooks, toolName, workspaceToolName) {
return {
...tool,
execute: async (input, context = {}) => {
const hookContext = {
toolName,
workspaceToolName,
input,
context
};
const beforeResult = await hooks.beforeToolCall?.(hookContext);
if (beforeResult?.proceed === false) return beforeResult.output;
let output;
try {
output = await tool.execute(input, context);
} catch (error) {
await hooks.afterToolCall?.({
...hookContext,
output,
error
});
throw error;
}
await hooks.afterToolCall?.({
...hookContext,
output
});
return output;
}
};
}
function wrapWithWriteLock(tool, writeLock, getWritePaths) {
return {
...tool,
execute: async (input, context = {}) => {
if (getWritePaths) {
const keys = [...new Set(getWritePaths(input).map((p) => path.posix.normalize(p.replace(/\\/g, "/"))))].sort();
const run = (i) => i === keys.length ? tool.execute(input, context) : writeLock.withLock(keys[i], () => run(i + 1));
return run(0);
}
if (!input.path) throw new Error("wrapWithWriteLock: input.path is required");
return writeLock.withLock(input.path, () => tool.execute(input, context));
}
};
}
const ALL_WORKSPACE_TOOL_NAMES = Object.values(WORKSPACE_TOOLS).flatMap((group) => Object.values(group));
/**
* True when every workspace tool is disabled by static configuration, so no
* tool config needs resolving. Dynamic `enabled` functions and per-tool
* `enabled` overrides are never short-circuited.
*/
function isStaticallyDisabled(toolsConfig) {
if (toolsConfig?.enabled !== false) return false;
return ALL_WORKSPACE_TOOL_NAMES.every((name) => toolsConfig[name]?.enabled === void 0);
}
/**
* Creates workspace tools that will be auto-injected into agents.
*
* @param workspace - The workspace instance to bind tools to
* @param configContext - Optional tool config context
* @param options - Optional tool construction options (e.g. grep strict mode)
* @returns Record of workspace tools
*/
async function createWorkspaceTools(workspace, configContext, options) {
let effectiveConfigContext;
let contextReadTracker;
if (configContext) {
const { readTracker: providedReadTracker, ...rest } = configContext;
contextReadTracker = providedReadTracker;
effectiveConfigContext = {
...rest,
requestContext: toPlainRequestContext(configContext.requestContext)
};
} else effectiveConfigContext = {
requestContext: {},
workspace
};
const tools = {};
const toolsConfig = workspace.getToolsConfig();
if (isStaticallyDisabled(toolsConfig)) return tools;
const isReadOnly = workspace.filesystem?.readOnly ?? false;
let writeLock;
const getWriteLock = () => writeLock ??= new InMemoryFileWriteLock({ timeoutMs: toolsConfig?.writeLockTimeoutMs });
let readTracker = contextReadTracker;
const getReadTracker = () => readTracker ??= new InMemoryFileReadTracker();
const addTool = async (name, createTool, opts) => {
if (opts?.optIn && toolsConfig?.[name]?.enabled === void 0) return;
const config = await resolveToolConfig(toolsConfig, name, effectiveConfigContext);
if (!config.enabled) return;
if (opts?.requireWrite && isReadOnly) return;
if (opts?.isAvailable && !opts.isAvailable()) return;
const tool = createTool();
let wrapped;
if (typeof config.requireApproval === "function") {
const approvalFn = config.requireApproval;
wrapped = {
...tool,
requireApproval: true,
needsApprovalFn: async (args, ctx) => resolveDynamicValue(approvalFn, {
args,
requestContext: toPlainRequestContext(ctx?.requestContext),
workspace: ctx?.workspace ?? workspace
}, true)
};
} else wrapped = {
...tool,
requireApproval: config.requireApproval
};
if (config.background) wrapped = {
...wrapped,
background: config.background
};
if (opts?.readTrackerMode) wrapped = wrapWithReadTracker(wrapped, workspace, getReadTracker(), config, opts.readTrackerMode, opts.getWritePaths, opts.didWrite);
else wrapped = wrapTool(wrapped, workspace, opts?.targets ?? {});
const exposedName = config.name ?? name;
if (tools[exposedName]) throw new Error(`Duplicate workspace tool name "${exposedName}": tool "${name}" conflicts with an already-registered tool. Check your tools config for duplicate "name" values.`);
if (exposedName !== name && "id" in wrapped) wrapped = {
...wrapped,
id: exposedName
};
if (config.hooks) wrapped = wrapWithToolHooks(wrapped, config.hooks, exposedName, name);
if (opts?.useWriteLock) wrapped = wrapWithWriteLock(wrapped, getWriteLock(), opts.getWritePaths);
tools[exposedName] = wrapped;
};
if (hasFilesystemConfig(workspace)) {
await addTool(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE, () => readFileTool, { readTrackerMode: "read" });
await addTool(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE, () => writeFileTool, {
requireWrite: true,
readTrackerMode: "write",
useWriteLock: true
});
await addTool(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE, () => editFileTool, {
requireWrite: true,
readTrackerMode: "write",
useWriteLock: true
});
await addTool(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES, () => listFilesTool, { targets: { filesystem: true } });
await addTool(WORKSPACE_TOOLS.FILESYSTEM.DELETE, () => deleteFileTool, {
requireWrite: true,
useWriteLock: true,
targets: { filesystem: true }
});
await addTool(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT, () => fileStatTool, { targets: { filesystem: true } });
await addTool(WORKSPACE_TOOLS.FILESYSTEM.MKDIR, () => mkdirTool, {
requireWrite: true,
targets: { filesystem: true }
});
await addTool(WORKSPACE_TOOLS.FILESYSTEM.GREP, () => createGrepTool(options?.grep), { targets: { filesystem: true } });
await addTool(WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT, () => astEditTool, {
requireWrite: true,
readTrackerMode: "write",
useWriteLock: true,
isAvailable: isAstGrepAvailable
});
await addTool(WORKSPACE_TOOLS.FILESYSTEM.APPLY_PATCH, () => applyPatchTool, {
requireWrite: true,
readTrackerMode: "write",
useWriteLock: true,
optIn: true,
getWritePaths: getApplyPatchWritePaths,
didWrite: applyPatchDidWrite
});
}
if (workspace.canBM25 || workspace.canVector) {
await addTool(WORKSPACE_TOOLS.SEARCH.SEARCH, () => {
const availableModes = [
workspace.canBM25 ? "bm25" : null,
workspace.canVector ? "vector" : null,
workspace.canHybrid ? "hybrid" : null
].filter((m) => m !== null);
return {
...searchTool,
inputSchema: searchInputSchema.extend({ mode: zod_v4.z.enum(availableModes).optional().describe(`Search mode: ${availableModes.join(", ")}`) })
};
});
await addTool(WORKSPACE_TOOLS.SEARCH.INDEX, () => indexContentTool, { requireWrite: true });
}
const requireCommandDescription = toolsConfig?.[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]?.requireDescription === true;
const backgroundExecuteCommandTool = requireCommandDescription ? executeCommandWithDescriptionAndBackgroundTool : executeCommandWithBackgroundTool;
if (workspace.sandbox) {
if (workspace.sandbox.executeCommand) {
const foregroundExecuteCommandTool = requireCommandDescription ? executeCommandWithDescriptionTool : executeCommandTool;
const baseTool = workspace.sandbox.processes ? backgroundExecuteCommandTool : foregroundExecuteCommandTool;
await addTool(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND, () => baseTool, { targets: { sandbox: true } });
}
if (workspace.sandbox.processes) {
await addTool(WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT, () => getProcessOutputTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS, () => killProcessTool, { targets: { sandbox: true } });
}
if (supportsComputer(workspace.sandbox)) {
await addTool(WORKSPACE_TOOLS.COMPUTER.SCREENSHOT, () => computerScreenshotTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.CLICK, () => computerClickTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK, () => computerDoubleClickTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK, () => computerRightClickTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE, () => computerMoveMouseTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.DRAG, () => computerDragTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.TYPE, () => computerTypeTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.PRESS_KEY, () => computerPressKeyTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.SCROLL, () => computerScrollTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.GET_SCREEN_INFO, () => computerGetScreenInfoTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.COMPUTER.WAIT, () => computerWaitTool, { targets: { sandbox: true } });
}
} else if (hasSandboxConfig(workspace)) {
await addTool(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND, () => backgroundExecuteCommandTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT, () => getProcessOutputTool, { targets: { sandbox: true } });
await addTool(WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS, () => killProcessTool, { targets: { sandbox: true } });
}
if (workspace.lsp) await addTool(WORKSPACE_TOOLS.LSP.LSP_INSPECT, () => lspInspectTool, { targets: { filesystem: true } });
return tools;
}
// src/workspace/lsp/language.ts
/**
* Language Detection
*
* Maps file extensions to LSP language identifiers.
* Browser-safe — no Node.js dependencies.
*/
/**
* Maps file extensions (including the dot) to LSP language identifiers.
*/
const LANGUAGE_EXTENSIONS = {
".ts": "typescript",
".tsx": "typescriptreact",
".js": "javascript",
".jsx": "javascriptreact",
".mjs": "javascript",
".cjs": "javascript",
".py": "python",
".pyi": "python",
".go": "go",
".rs": "rust",
".c": "c",
".cpp": "cpp",
".cc": "cpp",
".cxx": "cpp",
".h": "c",
".hpp": "cpp",
".java": "java",
".json": "json",
".jsonc": "jsonc",
".yaml": "yaml",
".yml": "yaml",
".md": "markdown",
".html": "html",
".css": "css",
".scss": "scss",
".sass": "sass",
".less": "less"
};
/**
* Get the LSP language ID for a file path based on its extension.
* Returns undefined if the extension is not recognized.
*
* When `customExtensions` is provided, it is checked first, allowing
* custom servers to register new file extensions or override built-in mappings.
*/
function getLanguageId(filePath, customExtensions) {
const dotIndex = filePath.lastIndexOf(".");
if (dotIndex === -1) return void 0;
const ext = filePath.substring(dotIndex);
return customExtensions?.[ext] ?? LANGUAGE_EXTENSIONS[ext];
}
// src/workspace/lsp/client.ts
/**
* LSP Client
*
* JSON-RPC client wrapper for communicating with language servers.
* Uses dynamic imports for vscode-jsonrpc and vscode-languageserver-protocol
* to keep them as optional dependencies.
*
* Spawns LSP servers via a SandboxProcessManager, so it works with any
* sandbox backend (local, E2B, etc.) that has a process manager.
*/
/** Cached module references — undefined means not yet checked, null means unavailable */
let jsonrpcModule;
let lspProtocolModule;
/**
* Check if vscode-jsonrpc is available without importing it.
* Synchronous check — safe to call at registration time.
*/
function isLSPAvailable() {
if (jsonrpcModule !== void 0) return jsonrpcModule !== null;
try {
const req = (0, module$1.createRequire)(require("url").pathToFileURL(__filename).href);
req.resolve("vscode-jsonrpc/node");
req.resolve("vscode-languageserver-protocol");
return true;
} catch {
return false;
}
}
/**
* Load vscode-jsonrpc and vscode-languageserver-protocol.
* Returns null if not available. Caches result after first call.
*/
async function loadLSPDeps() {
if (jsonrpcModule !== void 0 && lspProtocolModule !== void 0) {
if (jsonrpcModule === null || lspProtocolModule === null) return null;
return {
...jsonrpcModule,
...lspProtocolModule
};
}
try {
const req = (0, module$1.createRequire)(require("url").pathToFileURL(__filename).href);
const jsonrpc = req("vscode-jsonrpc/node");
const protocol = req("vscode-languageserver-protocol");
jsonrpcModule = {
StreamMessageReader: jsonrpc.StreamMessageReader,
StreamMessageWriter: jsonrpc.StreamMessageWriter,
createMessageConnection: jsonrpc.createMessageConnection
};
lspProtocolModule = {
TextDocumentIdentifier: protocol.TextDocumentIdentifier,
Position: protocol.Position
};
return {
...jsonrpcModule,
...lspProtocolModule
};
} catch {
jsonrpcModule = null;
lspProtocolModule = null;
return null;
}
}
/** Convert a filesystem path to a properly encoded file:// URI. */
function toFileUri(fsPath) {
return (0, url.pathToFileURL)(fsPath).toString();
}
/**
* Normalize a file:// URI to a canonical fs-path-based key for diagnostics
* map storage/lookup. On Windows, different LSP servers emit different
* canonical forms for the same path (e.g. `file:///C:/...` vs
* `file:///c%3A/...`), so we convert back to an OS path and compare those
* instead of comparing URI strings directly.
*/
function diagnosticsKey(uriOrPath) {
let fsPath;
try {
fsPath = uriOrPath.startsWith("file:") ? (0, url.fileURLToPath)(uriOrPath) : uriOrPath;
} catch {
return uriOrPath;
}
const driveMatch = fsPath.match(/^[\\/]?([a-zA-Z]):([\\/].*)$/);
if (driveMatch) return `${driveMatch[1].toLowerCase()}:${driveMatch[2]}`;
return fsPath;
}
async function withTimeout(promise, ms, errorMessage) {
let timer;
return Promise.race([promise, new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(errorMessage)), ms);
})]).finally(() => clearTimeout(timer));
}
/**
* Wraps a JSON-RPC connection to a single LSP server process.
* Uses a SandboxProcessManager to spawn the server process.
*/
var LSPClient = class {
connection = null;
handle = null;
serverDef;
workspaceRoot;
processManager;
diagnostics = /* @__PURE__ */ new Map();
initializationOptions = null;
supportsPullDiagnostics = false;
constructor(serverDef, workspaceRoot, processManager) {
this.serverDef = serverDef;
this.workspaceRoot = workspaceRoot;
this.processManager = processManager;
}
/** Whether the underlying server process is still running. */
get isAlive() {
return this.handle !== null && this.handle.exitCode === void 0;
}
/** Name of the LSP server. */
get serverName() {
return this.serverDef.name;
}
/**
* Initialize the LSP connection — spawns the server and performs the handshake.
*/
async initialize(initTimeout = 1e4) {
const deps = await loadLSPDeps();
if (!deps) throw new Error("LSP dependencies (vscode-jsonrpc) are not available");
const { StreamMessageReader, StreamMessageWriter, createMessageConnection } = deps;
const command = this.serverDef.command(this.workspaceRoot);
if (!command) throw new Error("Failed to resolve LSP server command");
this.handle = await this.processManager.spawn(command, { cwd: this.workspaceRoot });
const initializationOptions = this.serverDef.initialization?.(this.workspaceRoot);
const reader = new StreamMessageReader(this.handle.reader);
const writer = new StreamMessageWriter(this.handle.writer);
const originalWrite = writer.write.bind(writer);
writer.write = (msg) => originalWrite(msg).catch(() => {});
this.connection = createMessageConnection(reader, writer);
this.connection.onError(() => {});
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
this.diagnostics.set(diagnosticsKey(params.uri), params.diagnostics);
});
this.connection.listen();
const initParams = {
processId: process.pid,
rootUri: toFileUri(this.workspaceRoot),
workspaceFolders: [{
name: "workspace",
uri: toFileUri(this.workspaceRoot)
}],
capabilities: {
window: { workDoneProgress: true },
workspace: { configuration: true },
textDocument: {
publishDiagnostics: {
relatedInformation: true,
tagSupport: { valueSet: [1, 2] },
versionSupport: false
},
synchronization: {
didOpen: true,
didChange: true,
dynamicRegistration: false,
willSave: false,
willSaveWaitUntil: false,
didSave: false
},
completion: {
dynamicRegistration: false,
completionItem: {
snippetSupport: false,
commitCharactersSupport: false,
documentationFormat: ["markdown", "plaintext"],
deprecatedSupport: false,
preselectSupport: false
}
},
definition: {
dynamicRegistration: false,
linkSupport: true
},
typeDefinition: {
dynamicRegistration: false,
linkSupport: true
},
implementation: {
dynamicRegistration: false,
linkSupport: true
},
references: { dynamicRegistration: false },
documentHighlight: { dynamicRegistration: false },
documentSymbol: {
dynamicRegistration: false,
hierarchicalDocumentSymbolSupport: true
},
codeAction: {
dynamicRegistration: false,
codeActionLiteralSupport: { codeActionKind: { valueSet: [
"quickfix",
"refactor",
"refactor.extract",
"refactor.inline",
"refactor.rewrite",
"source",
"source.organizeImports"
] } }
},
hover: {
dynamicRegistration: false,
contentFormat: ["markdown", "plaintext"]
}
}
}
};
if (initializationOptions) {
initParams.initializationOptions = initializationOptions;
this.initializationOptions = initializationOptions;
}
this.connection.onRequest("workspace/configuration", (params) => {
return params.items?.map(() => ({})) || [];
});
this.connection.onRequest("window/workDoneProgress/create", () => null);
this.connection.onRequest("client/registerCapability", () => null);
let initTimer;
if ((await Promise.race([this.connection.sendRequest("initialize", initParams), new Promise((_, reject) => {
initTimer = setTimeout(() => reject(/* @__PURE__ */ new Error("LSP initialize request timed out")), initTimeout);
})]).finally(() => clearTimeout(initTimer)))?.capabilities?.diagnosticProvider) this.supportsPullDiagnostics = true;
this.connection.sendNotification("initialized", {});
this.connection.sendNotification("workspace/didChangeConfiguration", { settings: this.initializationOptions ?? {} });
}
/**
* Notify the server that a document has been opened.
*/
notifyOpen(filePath, content, languageId) {
if (!this.connection) return;
const uri = toFileUri(filePath);
this.diagnostics.delete(diagnosticsKey(uri));
this.connection.sendNotification("textDocument/didOpen", { textDocument: {
uri,
languageId,
version: 0,
text: content
} });
}
/**
* Notify the server that a document has changed.
*/
notifyChange(filePath, content, version) {
if (!this.connection) return;
this.connection.sendNotification("textDocument/didChange", {
textDocument: {
uri: toFileUri(filePath),
version
},
contentChanges: [{ text: content }]
});
}
/**
* Wait for diagnostics to arrive for a file.
*
* For servers that support pull diagnostics (e.g. TypeScript 7+ native LSP),
* sends a `textDocument/diagnostic` request directly instead of waiting for
* push notifications.
*
* For push-based servers (e.g. TypeScript ≤6 via typescript-language-server),
* returns as soon as diagnostics are available. To avoid returning a premature
* empty array (servers may publish `[]` first while still analysing), empty
* results trigger a short settle window: polling continues for up to `settleMs`
* (default 500ms) to see if non-empty diagnostics arrive. Non-empty results
* are returned immediately.
*/
async waitForDiagnostics(filePath, timeoutMs = 5e3, waitForChange = false, settleMs = 500) {
if (!this.connection) return [];
if (this.supportsPullDiagnostics) try {
const items = (await withTimeout(this.connection.sendRequest("textDocument/diagnostic", { textDocument: { uri: toFileUri(filePath) } }), timeoutMs, "Pull diagnostics request timed out"))?.items ?? [];
this.diagnostics.set(diagnosticsKey(toFileUri(filePath)), items);
return items;
} catch {
return [];
}
const uri = diagnosticsKey(toFileUri(filePath));
const startTime = Date.now();
const initialDiagnostics = this.diagnostics.get(uri);
let emptyReceivedAt;
while (Date.now() - startTime < timeoutMs) {
const currentDiagnostics = this.diagnostics.get(uri);
if (waitForChange) {
if (currentDiagnostics !== void 0 && currentDiagnostics !== initialDiagnostics) return currentDiagnostics;
} else if (currentDiagnostics !== void 0) {
if (currentDiagnostics.length > 0) return currentDiagnostics;
if (emptyReceivedAt === void 0) emptyReceivedAt = Date.now();
if (Date.now() - emptyReceivedAt >= settleMs) return currentDiagnostics;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
return waitForChange ? initialDiagnostics || [] : this.diagnostics.get(uri) || [];
}
/**
* Notify the server that a document was closed.
*/
notifyClose(filePath) {
if (!this.connection) return;
const uri = toFileUri(filePath);
this.diagnostics.delete(diagnosticsKey(uri));
this.connection.sendNotification("textDocument/didClose", { textDocument: { uri } });
}
/**
* Query hover information at a position.
*/
async queryHover(uri, position, timeoutMs = 5e3) {
if (!this.connection) return null;
return withTimeout(this.connection.sendRequest("textDocument/hover", {
textDocument: { uri },
position
}), timeoutMs, "Hover request timed out");
}
/**
* Query definition(s) at a position.
*/
async queryDefinition(uri, position, timeoutMs = 5e3) {
if (!this.connection) return [];
const result = await withTimeout(this.connection.sendRequest("textDocument/definition", {
textDocument: { uri },
position
}), timeoutMs, "Definition request timed out");
if (!result) return [];
return Array.isArray(result) ? result : result.uri ? [result] : [];
}
/**
* Query type definition(s) at a position.
*/
async queryTypeDefinition(uri, position, timeoutMs = 5e3) {
if (!this.connection) return [];
const result = await withTimeout(this.connection.sendRequest("textDocument/typeDefinition", {
textDocument: { uri },
position
}), timeoutMs, "Type definition request timed out");
if (!result) return [];
return Array.isArray(result) ? result : result.uri ? [result] : [];
}
/**
* Query implementation(s) at a position.
*/
async queryImplementation(uri, position, timeoutMs = 5e3) {
if (!this.connection) return [];
const result = await withTimeout(this.connection.sendRequest("textDocument/implementation", {
textDocument: { uri },
position
}), timeoutMs, "Implementation request timed out");
if (!result) return [];
return Array.isArray(result) ? result : result.uri ? [result] : [];
}
/**
* Shutdown the connection and kill the process.
*/
async shutdown() {
if (this.connection) {
try {
if (this.handle && this.handle.exitCode === void 0) {
let shutdownTimer;
await Promise.race([this.connection.sendRequest("shutdown"), new Promise((_, reject) => {
shutdownTimer = setTimeout(() => reject(/* @__PURE__ */ new Error("Shutdown request timed out")), 1e3);
})]).finally(() => clearTimeout(shutdownTimer));
this.connection.sendNotification("exit");
}
} catch {}
try {
this.connection.dispose();
} catch {}
this.connection = null;
}
if (this.handle) {
try {
await this.handle.kill();
} catch {}
this.handle = null;
}
this.diagnostics = /* @__PURE__ */ new Map();
}
};
// src/workspace/lsp/servers.ts
/**
* Built-in LSP Server Definitions
*
* Defines how to locate language servers and build command strings for supported languages.
* Server definitions are pure data — they don't spawn processes themselves.
* The LSPClient uses a SandboxProcessManager to spawn from these command strings.
*/
/** Check if a binary exists on PATH. */
function whichSync(binary) {
try {
const cmd = process.platform === "win32" ? "where" : "which";
(0, child_process.execFileSync)(cmd, [binary], { stdio: "ignore" });
return true;
} catch {
return false;
}
}
/**
* Try to resolve a module from the given directory, then fall back to process.cwd().
* Returns the createRequire instance that succeeded, or null.
*/
function resolveRequire(root, moduleId) {
try {
const req = (0, module$1.createRequire)((0, url.pathToFileURL)((0, path.join)(root, "package.json")));
return {
require: req,
resolved: req.resolve(moduleId)
};
} catch {}
try {
const req = (0, module$1.createRequire)((0, url.pathToFileURL)((0, path.join)(process.cwd(), "package.json")));
return {
require: req,
resolved: req.resolve(moduleId)
};
} catch {
return null;
}
}
/**
* Extend resolveRequire to also search additional directories after root and cwd.
* Each entry in searchPaths should be a directory whose node_modules contains the module.
*/
function resolveRequireFromPaths(root, moduleId, searchPaths) {
const fromBase = resolveRequire(root, moduleId);
if (fromBase) return fromBase;
for (const searchPath of searchPaths ?? []) try {
const req = (0, module$1.createRequire)((0, url.pathToFileURL)((0, path.join)(searchPath, "package.json")));
return {
require: req,
resolved: req.resolve(moduleId)
};
} catch {}
return null;
}
/** Find a binary in node_modules/.bin, searching root, cwd, then any searchPaths. */
function resolveNodeBin(root, binary, searchPaths) {
const local = (0, path.join)(root, "node_modules", ".bin", binary);
const cwd = (0, path.join)(process.cwd(), "node_modules", ".bin", binary);
if ((0, fs.existsSync)(local)) return local;
if ((0, fs.existsSync)(cwd)) return cwd;
for (const dir of searchPaths ?? []) {
const p = (0, path.join)(dir, "node_modules", ".bin", binary);
if ((0, fs.existsSync)(p)) return p;
}
}
/**
* Walk up from a starting directory looking for any of the given markers.
* Returns the first directory that contains a marker, or null.
*/
function walkUp(startDir, markers) {
let current = startDir;
const fsRoot = (0, path.parse)(current).root;
while (true) {
for (const marker of markers) if ((0, fs.existsSync)((0, path.join)(current, marker))) return current;
if (current === fsRoot) break;
const parent = (0, path.dirname)(current);
if (parent === current) break;
current = parent;
}
return null;
}
/**
* Async version of walkUp that uses a filesystem's exists() method.
* Works with any filesystem (local, S3, GCS, composite) that implements exists().
*/
async function walkUpAsync(startDir, markers, fs) {
let current = startDir;
const fsRoot = (0, path.parse)(current).root;
while (true) {
for (const marker of markers) if (await fs.exists((0, path.join)(current, marker))) return current;
if (current === fsRoot) break;
const parent = (0, path.dirname)(current);
if (parent === current) break;
current = parent;
}
return null;
}
/** Default markers used to find a project root when no server-specific markers are available. */
const DEFAULT_MARKERS = [
"tsconfig.json",
"package.json",
"pyproject.toml",
"go.mod",
"Cargo.toml",
"composer.json",
".git"
];
/**
* Find a project root by walking up from a starting directory.
* Uses default markers (tsconfig.json, package.json, go.mod, etc.).
* Used by Workspace to resolve the default LSP root at construction time.
*/
function findProjectRoot(startDir) {
return walkUp(startDir, DEFAULT_MARKERS);
}
/**
* Build an extension → language ID map from custom server definitions.
* Each extension is mapped to the first language ID of the server that declares it.
*
* When multiple servers declare the same extension, the last server wins
* (iteration order of `Object.values`). A warning is emitted on collision
* so the user can spot misconfiguration.
*/
function buildCustomExtensions(servers) {
if (!servers) return {};
const extensions = {};
for (const server of Object.values(servers)) {
const languageId = server.languageIds[0];
if (!languageId) continue;
for (const ext of server.extensions) {
const existing = extensions[ext];
if (existing && existing !== languageId) console.warn(`[LSP] Extension "${ext}" is claimed by language "${existing}" and "${languageId}" (server "${server.id}") — using "${languageId}"`);
extensions[ext] = languageId;
}
}
return extensions;
}
/**
* Convert a public custom server config to an internal server definition.
*/
function toServerDef(custom) {
return {
id: custom.id,
name: custom.name,
languageIds: custom.languageIds,
markers: custom.markers,
command: () => custom.command,
initialization: custom.initializationOptions ? () => custom.initializationOptions : void 0
};
}
/**
* Build a set of server definitions that incorporate LSP config overrides.
*
* Resolution order per server:
* 1. `config.binaryOverrides[id]` — explicit binary command override
* 2. Project `node_modules/.bin/` binary
* 3. `process.cwd()` `node_modules/.bin/` binary
* 4. `config.searchPaths` `node_modules/.bin/` binary lookup
* 5. Global PATH lookup (system-installed binaries)
* 6. `config.packageRunner` — package runner fallback (off by default)
*
* `config.searchPaths` also extends TypeScript module resolution
* (used to locate typescript/lib/tsserver.js for TS ≤6, and tsc for TS 7+).
*
* When `config.servers` is provided, custom servers are merged after built-in
* definitions. Custom servers with the same ID as a built-in will replace it.
*/
function buildServerDefs(config) {
const { binaryOverrides, searchPaths, packageRunner } = config ?? {};
const builtins = {
typescript: {
id: "typescript",
name: "TypeScript Language Server",
languageIds: [
"typescript",
"typescriptreact",
"javascript",
"javascriptreact"
],
markers: ["tsconfig.json", "package.json"],
command: (root) => {
if (binaryOverrides?.typescript) return binaryOverrides.typescript;
if (!!resolveRequireFromPaths(root, "typescript/lib/tsserver.js", searchPaths)) {
const bin = resolveNodeBin(root, "typescript-language-server", searchPaths);
if (bin) return `${bin} --stdio`;
if (whichSync("typescript-language-server")) return "typescript-language-server --stdio";
if (packageRunner) return `${packageRunner} typescript-language-server --stdio`;
return;
}
const pkg = resolveRequireFromPaths(root, "typescript/package.json", searchPaths);
if (!pkg) return void 0;
const manifest = pkg.require(pkg.resolved);
if (!(parseInt(manifest.version ?? "", 10) >= 7)) return void 0;
const binRel = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.tsc;
if (!binRel) return void 0;
const tscEntry = (0, path.join)((0, path.dirname)(pkg.resolved), binRel);
if (!(0, fs.existsSync)(tscEntry)) return void 0;
return `node ${tscEntry} --lsp --stdio`;
},
initialization: (root) => {
const ts = resolveRequireFromPaths(root, "typescript/lib/tsserver.js", searchPaths);
if (!ts) return void 0;
return { tsserver: {
path: ts.resolved,
logVerbosity: "off"
} };
}
},
eslint: {
id: "eslint",
name: "ESLint Language Server",
languageIds: [
"typescript",
"typescriptreact",
"javascript",
"javascriptreact"
],
markers: [
"package.json",
".eslintrc.js",
".eslintrc.json",
".eslintrc.yml",
".eslintrc.yaml",
"eslint.config.js",
"eslint.config.mjs",
"eslint.config.ts"
],
command: (root) => {
if (binaryOverrides?.eslint) return binaryOverrides.eslint;
const bin = resolveNodeBin(root, "vscode-eslint-language-server", searchPaths);
if (bin) return `${bin} --stdio`;
if (whichSync("vscode-eslint-language-server")) return "vscode-eslint-language-server --stdio";
if (packageRunner) return `${packageRunner} vscode-eslint-language-server --stdio`;
}
},
python: {
id: "python",
name: "Python Language Server (Pyright)",
languageIds: ["python"],
markers: [
"pyproject.toml",
"setup.py",
"requirements.txt",
"setup.cfg"
],
command: (root) => {
if (binaryOverrides?.python) return binaryOverrides.python;
const bin = resolveNodeBin(root, "pyright-langserver", searchPaths);
if (bin) return `${bin} --stdio`;
if (whichSync("pyright-langserver")) return "pyright-langserver --stdio";
if (packageRunner) return `${packageRunner} pyright-langserver --stdio`;
}
},
go: {
id: "go",
name: "Go Language Server (gopls)",
languageIds: ["go"],
markers: ["go.mod"],
command: () => {
if (binaryOverrides?.go) return binaryOverrides.go;
return whichSync("gopls") ? "gopls serve" : void 0;
}
},
rust: {
id: "rust",
name: "Rust Language Server (rust-analyzer)",
languageIds: ["rust"],
markers: ["Cargo.toml"],
command: () => {
if (binaryOverrides?.rust) return binaryOverrides.rust;
return whichSync("rust-analyzer") ? "rust-analyzer --stdio" : void 0;
}
}
};
if (config?.servers) for (const custom of Object.values(config.servers)) builtins[custom.id] = toServerDef(custom);
return builtins;
}
/**
* Built-in LSP server definitions with no config overrides.
* Use `buildServerDefs(config)` when you need binaryOverrides, searchPaths, or packageRunner.
*/
const BUILTIN_SERVERS = buildServerDefs();
/**
* Get all server definitions that can handle the given file.
* Filters by language ID match only — the manager resolves the root and checks command availability.
* Pass `defs` to use config-aware server definitions from `buildServerDefs()`.
* Pass `customExtensions` to recognize file extensions registered by custom servers.
*/
function getServersForFile(filePath, disabledServers, defs, customExtensions) {
const languageId = getLanguageId(filePath, customExtensions);
if (!languageId) return [];
const disabled = new Set(disabledServers ?? []);
return Object.values(defs ?? BUILTIN_SERVERS).filter((server) => !disabled.has(server.id) && server.languageIds.includes(languageId));
}
// src/workspace/lsp/manager.ts
/**
* LSP Manager
*
* Per-workspace manager that owns LSP server clients.
* NOT a singleton — each Workspace instance creates its own LSPManager.
*
* Resolves the project root per-file by walking up from the file's directory
* using language-specific markers defined on each server (e.g. tsconfig.json
* for TypeScript, go.mod for Go). Falls back to the default root when
* walkup finds nothing.
*/
const CLIENT_LEASE_ACQUIRE_TIMEOUT_MS = 5e3;
const CLIENT_LEASE_SHUTDOWN_TIMEOUT_MS = 5e3;
/** Map LSP DiagnosticSeverity (numeric) to our string severity */
function mapSeverity(severity) {
switch (severity) {
case 1: return "error";
case 2: return "warning";
case 3: return "info";
case 4: return "hint";
default: return "warning";
}
}
var LSPManager = class {
clients = /* @__PURE__ */ new Map();
initPromises = /* @__PURE__ */ new Map();
clientInitQueue = Promise.resolve();
clientLeaseAcquisitionQueue = Promise.resolve();
activeClientLeases = /* @__PURE__ */ new Map();
clientLeaseWaiters = /* @__PURE__ */ new Set();
shutdownPromise;
shuttingDown = false;
fileLocks = /* @__PURE__ */ new Map();
processManager;
_root;
config;
serverDefs;
customExtensions;
filesystem;
constructor(processManager, root, config = {}, filesystem) {
if (config.maxOpenClients !== void 0 && (!Number.isInteger(config.maxOpenClients) || config.maxOpenClients < 1)) throw new RangeError("maxOpenClients must be a positive integer");
this.processManager = processManager;
this._root = root;
this.config = config;
this.serverDefs = buildServerDefs(config);
this.customExtensions = buildCustomExtensions(config.servers);
this.filesystem = filesystem;
}
/** Default project root (fallback when per-file walkup finds nothing). */
get root() {
return this._root;
}
/**
* Resolve the project root for a given file path using the server's markers.
* Uses the workspace filesystem when available (supports remote filesystems),
* falls back to sync walkUp (local disk) otherwise.
*/
async resolveRoot(filePath, markers) {
const fileDir = path.default.dirname(filePath);
if (this.filesystem) return await walkUpAsync(fileDir, markers, this.filesystem) ?? this._root;
return walkUp(fileDir, markers) ?? this._root;
}
/** Mark a client as most recently used. */
touchClient(key, client) {
this.clients.delete(key);
this.clients.set(key, client);
}
/** Shut down idle least recently used clients until another one can be opened. */
async ensureClientCapacity() {
const maxOpenClients = this.config.maxOpenClients;
if (maxOpenClients === void 0) return !this.shuttingDown;
while (this.clients.size >= maxOpenClients) {
if (this.shuttingDown) return false;
const oldestIdle = Array.from(this.clients.entries()).find(([, client]) => !this.activeClientLeases.has(client));
if (!oldestIdle) {
if (!await this.waitForClientLeaseRelease(CLIENT_LEASE_ACQUIRE_TIMEOUT_MS)) return false;
continue;
}
const [key, client] = oldestIdle;
this.clients.delete(key);
await client.shutdown().catch(() => {});
}
return !this.shuttingDown;
}
/** Acquire a client and lease it before another capped acquisition can evict it. */
async acquireClientLease(acquire) {
const previous = this.clientLeaseAcquisitionQueue;
let finishAcquisition;
const current = new Promise((resolve) => {
finishAcquisition = resolve;
});
this.clientLeaseAcquisitionQueue = previous.then(() => current);
await previous;
try {
if (this.shuttingDown) return null;
const client = await acquire((acquired) => {
this.activeClientLeases.set(acquired, (this.activeClientLeases.get(acquired) ?? 0) + 1);
});
if (!client) return null;
let released = false;
return {
client,
release: () => {
if (released) return;
released = true;
const remaining = (this.activeClientLeases.get(client) ?? 1) - 1;
if (remaining > 0) {
this.activeClientLeases.set(client, remaining);
return;
}
this.activeClientLeases.delete(client);
this.wakeClientLeaseWaiters();
}
};
} finally {
finishAcquisition();
}
}
/** Keep an acquired client alive while an operation is using it. */
async withClientLease(acquire, operation) {
const lease = await this.acquireClientLease(acquire);
if (!lease) return null;
try {
return await operation(lease.client);
} finally {
lease.release();
}
}
wakeClientLeaseWaiters() {
const waiters = Array.from(this.clientLeaseWaiters);
this.clientLeaseWaiters.clear();
waiters.forEach((resolve) => resolve());
}
/** Wait for a lease release without allowing leaked leases to block new clients indefinitely. */
async waitForClientLeaseRelease(timeoutMs) {
return new Promise((resolve) => {
let settled = false;
let timeout;
const finish = (released) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
this.clientLeaseWaiters.delete(onRelease);
resolve(released);
};
const onRelease = () => finish(true);
timeout = setTimeout(() => finish(false), timeoutMs);
this.clientLeaseWaiters.add(onRelease);
});
}
/** Wait for active operations to release their clients, then force teardown after a bounded delay. */
async waitForClientLeasesToDrain() {
if (this.activeClientLeases.size === 0) return;
await new Promise((resolve) => {
let timeout;
const checkLeases = () => {
if (this.activeClientLeases.size > 0) {
this.clientLeaseWaiters.add(checkLeases);
return;
}
clearTimeout(timeout);
resolve();
};
timeout = setTimeout(() => {
this.clientLeaseWaiters.delete(checkLeases);
resolve();
}, CLIENT_LEASE_SHUTDOWN_TIMEOUT_MS);
this.clientLeaseWaiters.add(checkLeases);
});
}
/**
* Acquire a per-file lock so that concurrent getDiagnostics calls for the
* same file are serialized (preventing interleaved open/change/close) and
* are served in the order they arrived. Different files run in parallel.
*/
async acquireFileLock(filePath) {
const previous = this.fileLocks.get(filePath) ?? Promise.resolve();
let release;
const current = new Promise((resolve) => {
release = resolve;
});
const tail = previous.then(() => current);
this.fileLocks.set(filePath, tail);
await previous;
return () => {
release();
if (this.fileLocks.get(filePath) === tail) this.fileLocks.delete(filePath);
};
}
/**
* Initialize an LSP client for the given server definition and project root.
* Handles timeout, deduplication of concurrent init calls, and caching.
*/
async initClient(serverDef, projectRoot, key, onAcquired) {
if (this.shuttingDown) return null;
if (this.initPromises.has(key)) {
await this.initPromises.get(key);
const client = this.shuttingDown ? null : this.clients.get(key) ?? null;
if (client) onAcquired?.(client);
return client;
}
const initialize = async () => {
if (!await this.ensureClientCapacity()) return;
const initTimeout = this.config.initTimeout ?? 15e3;
let timedOut = false;
let client;
let cleanupPromise;
const cleanupClient = async () => {
if (!client) return;
cleanupPromise ??= client.shutdown().catch(() => {});
await cleanupPromise;
cleanupPromise = void 0;
};
const startPromise = (async () => {
client = new LSPClient(serverDef, projectRoot, this.processManager);
try {
await client.initialize(initTimeout);
} catch (error) {
await cleanupClient();
throw error;
}
if (timedOut || this.shuttingDown) {
await cleanupClient();
return;
}
this.clients.set(key, client);
})();
startPromise.catch(() => {});
try {
let initTimer;
await Promise.race([startPromise, new Promise((_, reject) => {
initTimer = setTimeout(() => reject(/* @__PURE__ */ new Error("LSP client initialization timed out")), initTimeout + 1e3);
})]).finally(() => clearTimeout(initTimer));
} catch (err) {
timedOut = true;
await cleanupClient();
this.clients.delete(key);
const command = serverDef.command(projectRoot);
const hint = this.config.binaryOverrides?.[serverDef.id] ? ` (using binaryOverrides: "${this.config.binaryOverrides[serverDef.id]}")` : command ? ` (command: "${command}")` : "";
console.warn(`[LSP] Failed to start ${serverDef.name}${hint}: ${err instanceof Error ? err.message : err}`);
}
if (client && this.clients.get(key) === client) onAcquired?.(client);
};
const initPromise = this.config.maxOpenClients === void 0 ? initialize() : this.clientInitQueue.then(initialize);
if (this.config.maxOpenClients !== void 0) this.clientInitQueue = initPromise.catch(() => {});
this.initPromises.set(key, initPromise);
try {
await initPromise;
return this.clients.get(key) || null;
} finally {
this.initPromises.delete(key);
}
}
/**
* Get or create an LSP client for a file path.
* Resolves the project root per-file using the server's markers.
* Returns null if no server is available.
*/
async getClientInternal(filePath, onAcquired) {
if (this.shuttingDown) return null;
const servers = getServersForFile(filePath, this.config.disableServers, this.serverDefs, this.customExtensions);
if (servers.length === 0) return null;
const serverDef = servers.find((s) => s.languageIds.includes("typescript") || s.languageIds.includes("javascript") || s.languageIds.includes("python") || s.languageIds.includes("go")) ?? servers[0];
const projectRoot = await this.resolveRoot(filePath, serverDef.markers);
if (this.shuttingDown) return null;
if (serverDef.command(projectRoot) === void 0) return null;
const key = `${serverDef.name}:${projectRoot}`;
if (this.clients.has(key)) {
const existing = this.clients.get(key);
if (!existing.isAlive) {
this.clients.delete(key);
existing.shutdown().catch(() => {});
} else {
this.touchClient(key, existing);
onAcquired?.(existing);
return existing;
}
}
return this.initClient(serverDef, projectRoot, key, onAcquired);
}
/**
* Get LSP client ready to query a file.
* Opens the file in the client so queries can be made. Call `release` after
* closing the file to allow the client to be evicted.
* Returns null when no LSP client is available.
*/
async prepareQuery(filePath) {
const lease = await this.acquireClientLease((onAcquired) => this.getClientInternal(filePath, onAcquired));
if (!lease) return null;
const { client, release } = lease;
const languageId = getLanguageId(filePath, this.customExtensions);
if (!languageId) {
release();
return null;
}
try {
const fs = await import("fs/promises");
let content = "";
try {
content = await fs.readFile(filePath, "utf-8");
} catch {
content = "";
}
client.notifyOpen(filePath, content, languageId);
const { pathToFileURL } = await import("url");
return {
client,
uri: pathToFileURL(filePath).toString(),
languageId,
serverName: client.serverName,
release
};
} catch (error) {
release();
throw error;
}
}
/**
* Convenience method: open file, send content, wait for diagnostics, return normalized results.
* Returns null when no LSP client is available; otherwise returns diagnostics
* (or an empty array on runtime failures after client acquisition).
* Uses a per-file lock to serialize concurrent calls for the same file.
*/
async getDiagnostics(filePath, content) {
const release = await this.acquireFileLock(filePath);
try {
return await this.withClientLease((onAcquired) => this.getClientInternal(filePath, onAcquired), async (client) => {
const languageId = getLanguageId(filePath, this.customExtensions);
if (!languageId) return [];
client.notifyOpen(filePath, content, languageId);
client.notifyChange(filePath, content, 1);
const diagnosticTimeout = this.config.diagnosticTimeout ?? 5e3;
let rawDiagnostics;
try {
rawDiagnostics = await client.waitForDiagnostics(filePath, diagnosticTimeout);
} finally {
client.notifyClose(filePath);
}
return rawDiagnostics.map((d) => ({
severity: mapSeverity(d.severity),
message: d.message,
line: (d.range?.start?.line ?? 0) + 1,
character: (d.range?.start?.character ?? 0) + 1,
source: d.source
}));
});
} catch {
return [];
} finally {
release();
}
}
/**
* Get diagnostics from ALL matching language servers for a file.
* Deduplicates results by (line, character, message).
* Individual server failures don't block other servers.
*/
async getDiagnosticsMulti(filePath, content) {
if (this.shuttingDown) return [];
const servers = getServersForFile(filePath, this.config.disableServers, this.serverDefs, this.customExtensions);
if (servers.length === 0) return [];
const release = await this.acquireFileLock(filePath);
try {
const languageId = getLanguageId(filePath, this.customExtensions);
if (!languageId) return [];
const allDiagnostics = [];
const results = await Promise.allSettled(servers.map(async (serverDef) => {
const projectRoot = await this.resolveRoot(filePath, serverDef.markers);
if (serverDef.command(projectRoot) === void 0) return [];
const key = `${serverDef.name}:${projectRoot}`;
return await this.withClientLease(async (onAcquired) => {
if (this.clients.has(key)) {
const existing = this.clients.get(key);
if (!existing.isAlive) {
this.clients.delete(key);
existing.shutdown().catch(() => {});
} else {
this.touchClient(key, existing);
onAcquired(existing);
return existing;
}
}
return this.initClient(serverDef, projectRoot, key, onAcquired);
}, (client) => this.collectDiagnostics(client, filePath, content, languageId)) ?? [];
}));
for (const result of results) if (result.status === "fulfilled") allDiagnostics.push(...result.value);
const seen = /* @__PURE__ */ new Set();
return allDiagnostics.filter((d) => {
const key = `${d.line}:${d.character}:${d.message}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
} finally {
release();
}
}
/**
* Collect diagnostics from a single client for a file.
*/
async collectDiagnostics(client, filePath, content, languageId) {
client.notifyOpen(filePath, content, languageId);
client.notifyChange(filePath, content, 1);
const diagnosticTimeout = this.config.diagnosticTimeout ?? 5e3;
let rawDiagnostics;
try {
rawDiagnostics = await client.waitForDiagnostics(filePath, diagnosticTimeout);
} finally {
client.notifyClose(filePath);
}
return rawDiagnostics.map((d) => ({
severity: mapSeverity(d.severity),
message: d.message,
line: (d.range?.start?.line ?? 0) + 1,
character: (d.range?.start?.character ?? 0) + 1,
source: d.source
}));
}
/**
* Shutdown all managed LSP clients.
*/
shutdownAll() {
if (this.shutdownPromise) return this.shutdownPromise;
this.shuttingDown = true;
this.wakeClientLeaseWaiters();
this.shutdownPromise = (async () => {
await Promise.allSettled([
...this.initPromises.values(),
this.clientInitQueue,
this.clientLeaseAcquisitionQueue
]);
await this.waitForClientLeasesToDrain();
await Promise.allSettled(Array.from(this.clients.values()).map((client) => client.shutdown()));
this.clients.clear();
this.initPromises.clear();
this.activeClientLeases.clear();
this.fileLocks.clear();
this.shuttingDown = false;
this.shutdownPromise = void 0;
})();
return this.shutdownPromise;
}
};
// src/workspace/skills/versioned-skill-source.ts
/**
* Trim leading `.`/`/`/`\` characters and trailing `/`/`\` separators from a
* path. Index scan instead of regex to avoid backtracking (CodeQL
* js/polynomial-redos).
*/
function trimPathEdges(path) {
let start = 0;
let end = path.length;
while (start < end && (path[start] === "." || path[start] === "/" || path[start] === "\\")) start++;
while (end > start && (path[end - 1] === "/" || path[end - 1] === "\\")) end--;
return path.slice(start, end);
}
/**
* A SkillSource implementation that reads skill files from a versioned
* content-addressable blob store, using a SkillVersionTree manifest.
*
* This is used by production agents to read from published skill versions
* rather than the live filesystem. The SkillVersionTree maps file paths
* to blob hashes, and the BlobStore provides the actual content.
*/
var VersionedSkillSource = class {
#tree;
#blobStore;
#versionCreatedAt;
/** Computed set of directory paths from the tree entries */
#directories;
constructor(tree, blobStore, versionCreatedAt) {
this.#tree = tree;
this.#blobStore = blobStore;
this.#versionCreatedAt = versionCreatedAt;
this.#directories = this.#computeDirectories();
}
/**
* Compute all directory paths implied by the file tree.
* For a file at "references/api.md", this adds "" (root), "references".
*/
#computeDirectories() {
const dirs = /* @__PURE__ */ new Set();
dirs.add("");
dirs.add(".");
for (const filePath of Object.keys(this.#tree.entries)) {
const parts = filePath.split("/");
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join("/"));
}
return dirs;
}
/**
* Normalize a path by stripping leading/trailing slashes and dots.
*/
#normalizePath(path) {
return trimPathEdges(path);
}
async exists(path) {
const normalized = this.#normalizePath(path);
if (this.#tree.entries[normalized]) return true;
return this.#directories.has(normalized);
}
async stat(path) {
const normalized = this.#normalizePath(path);
const name = normalized.split("/").pop() || normalized || ".";
const entry = this.#tree.entries[normalized];
if (entry) return {
name,
type: "file",
size: entry.size,
createdAt: this.#versionCreatedAt,
modifiedAt: this.#versionCreatedAt,
mimeType: entry.mimeType
};
if (this.#directories.has(normalized)) return {
name,
type: "directory",
size: 0,
createdAt: this.#versionCreatedAt,
modifiedAt: this.#versionCreatedAt
};
throw new Error(`Path not found in skill version tree: ${path}`);
}
async readFile(path) {
const normalized = this.#normalizePath(path);
const entry = this.#tree.entries[normalized];
if (!entry) throw new Error(`File not found in skill version tree: ${path}`);
const blob = await this.#blobStore.get(entry.blobHash);
if (!blob) throw new Error(`Blob not found for hash ${entry.blobHash} (file: ${path})`);
if (entry.encoding === "base64") return Buffer.from(blob.content, "base64");
return blob.content;
}
async readdir(path) {
const normalized = this.#normalizePath(path);
if (!this.#directories.has(normalized)) throw new Error(`Directory not found in skill version tree: ${path}`);
const prefix = normalized === "" ? "" : normalized + "/";
const seen = /* @__PURE__ */ new Set();
const entries = [];
for (const filePath of Object.keys(this.#tree.entries)) {
if (!filePath.startsWith(prefix)) continue;
const remaining = filePath.slice(prefix.length);
const nextSegment = remaining.split("/")[0];
if (!nextSegment || seen.has(nextSegment)) continue;
seen.add(nextSegment);
const isDirectory = remaining.includes("/");
entries.push({
name: nextSegment,
type: isDirectory ? "directory" : "file"
});
}
return entries;
}
async realpath(path) {
return this.#normalizePath(path);
}
};
// src/workspace/skills/composite-versioned-skill-source.ts
/**
* A SkillSource that composes multiple versioned skill trees into a virtual directory.
*
* Each skill is mounted under a directory name, so the composite source looks like:
* / (root - virtual)
* /brand-guidelines/ (skill 1 root)
* /brand-guidelines/SKILL.md (skill 1 files from blob store)
* /tone-of-voice/ (skill 2 root)
* /tone-of-voice/SKILL.md (skill 2 files from blob store)
*
* This allows WorkspaceSkillsImpl to discover skills normally by scanning the root
* for subdirectories containing SKILL.md.
*
* Can also include a fallback source for "live" skills that read from the filesystem.
*/
var CompositeVersionedSkillSource = class {
#sources = /* @__PURE__ */ new Map();
#fallback;
#fallbackSkills;
#maxVersionCreatedAt;
constructor(entries, blobStore, options) {
let maxTime = 0;
for (const entry of entries) {
this.#sources.set(entry.dirName, new VersionedSkillSource(entry.tree, blobStore, entry.versionCreatedAt));
const t = entry.versionCreatedAt.getTime();
if (t > maxTime) maxTime = t;
}
this.#maxVersionCreatedAt = maxTime > 0 ? new Date(maxTime) : /* @__PURE__ */ new Date(0);
this.#fallback = options?.fallback;
this.#fallbackSkills = new Set(options?.fallbackSkills ?? []);
}
#normalizePath(path) {
let start = 0;
while (start < path.length) {
const c = path.charCodeAt(start);
if (c === 46 || c === 47 || c === 92) start++;
else break;
}
let end = path.length;
while (end > start) {
const c = path.charCodeAt(end - 1);
if (c === 47 || c === 92) end--;
else break;
}
return start === 0 && end === path.length ? path : path.slice(start, end);
}
/**
* Route a path to the correct source.
* Returns the source and the remaining path within that source.
*/
#routePath(path) {
const normalized = this.#normalizePath(path);
if (normalized === "") return null;
const segments = normalized.split("/");
const skillDir = segments[0];
const subPath = segments.slice(1).join("/");
if (this.#fallbackSkills.has(skillDir) && this.#fallback) return {
source: this.#fallback,
subPath: normalized,
mountDir: ""
};
const versionedSource = this.#sources.get(skillDir);
if (versionedSource) return {
source: versionedSource,
subPath,
mountDir: skillDir
};
if (this.#fallback) return {
source: this.#fallback,
subPath: normalized,
mountDir: ""
};
return null;
}
async exists(path) {
if (this.#normalizePath(path) === "") return true;
const route = this.#routePath(path);
if (!route) return false;
return route.source.exists(route.subPath);
}
async stat(path) {
if (this.#normalizePath(path) === "") return {
name: ".",
type: "directory",
size: 0,
createdAt: this.#maxVersionCreatedAt,
modifiedAt: this.#maxVersionCreatedAt
};
const route = this.#routePath(path);
if (!route) throw new Error(`Path not found in composite skill source: ${path}`);
return route.source.stat(route.subPath);
}
async readFile(path) {
const route = this.#routePath(path);
if (!route) throw new Error(`File not found in composite skill source: ${path}`);
return route.source.readFile(route.subPath);
}
async readdir(path) {
if (this.#normalizePath(path) === "") {
const entries = [];
const seen = /* @__PURE__ */ new Set();
for (const dirName of this.#sources.keys()) {
entries.push({
name: dirName,
type: "directory"
});
seen.add(dirName);
}
for (const dirName of this.#fallbackSkills) if (!seen.has(dirName)) {
entries.push({
name: dirName,
type: "directory"
});
seen.add(dirName);
}
return entries;
}
const route = this.#routePath(path);
if (!route) throw new Error(`Directory not found in composite skill source: ${path}`);
return route.source.readdir(route.subPath);
}
async realpath(path) {
if (this.#normalizePath(path) === "") return "";
const route = this.#routePath(path);
if (!route) throw new Error(`Path not found in composite skill source: ${path}`);
const realSubPath = route.source.realpath ? await route.source.realpath(route.subPath) : route.subPath;
return [route.mountDir, realSubPath].filter(Boolean).join("/");
}
};
// src/workspace/skills/publish.ts
/**
* Compute SHA-256 hex hash of content (string or Buffer).
*/
async function hashContent(content) {
const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", data));
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
/**
* Simple extension-based MIME type detection.
*/
function detectMimeType(filename) {
return {
".md": "text/markdown",
".txt": "text/plain",
".json": "application/json",
".yaml": "text/yaml",
".yml": "text/yaml",
".sh": "text/x-shellscript",
".py": "text/x-python",
".js": "text/javascript",
".ts": "text/typescript",
".html": "text/html",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".svg": "image/svg+xml"
}[filename.slice(filename.lastIndexOf(".")).toLowerCase()];
}
/**
* Whether a MIME type represents binary content that cannot be safely stored as UTF-8 text.
*/
function isBinaryMimeType(mimeType) {
if (!mimeType) return false;
if (mimeType.startsWith("text/")) return false;
if (mimeType === "application/json") return false;
if (mimeType === "image/svg+xml") return false;
return true;
}
/**
* Recursively walk a directory in a SkillSource, returning all files
* with their relative paths and content. Binary files are returned as Buffers.
*/
async function walkSkillDirectory(source, basePath, currentPath = basePath) {
const entries = await source.readdir(currentPath);
const files = [];
for (const entry of entries) {
const entryPath = joinPath(currentPath, entry.name);
if (entry.type === "directory") {
const subFiles = await walkSkillDirectory(source, basePath, entryPath);
files.push(...subFiles);
} else {
const rawContent = await source.readFile(entryPath);
const relativePath = entryPath.substring(basePath.length + 1);
if (isBinaryMimeType(detectMimeType(entry.name))) {
const buf = Buffer.isBuffer(rawContent) ? rawContent : Buffer.from(rawContent, "utf-8");
files.push({
path: relativePath,
content: buf,
isBinary: true
});
} else {
const content = typeof rawContent === "string" ? rawContent : rawContent.toString("utf-8");
files.push({
path: relativePath,
content,
isBinary: false
});
}
}
}
return files;
}
/**
* Trim slashes from a segment without regex backtracking (CodeQL js/polynomial-redos).
*/
function trimSlashes(segment, trimLeading) {
let start = 0;
let end = segment.length;
if (trimLeading) while (start < end && segment[start] === "/") start++;
while (end > start && segment[end - 1] === "/") end--;
return segment.slice(start, end);
}
/**
* Join path segments using forward slashes.
*/
function joinPath(...segments) {
return segments.map((seg, i) => trimSlashes(seg, i > 0)).filter(Boolean).join("/");
}
/**
* Collect file paths under a specific subdirectory prefix.
*/
function collectSubdirPaths(allPaths, subdir) {
const prefix = subdir + "/";
return allPaths.filter((p) => p.startsWith(prefix)).map((p) => p.substring(prefix.length));
}
/**
* Build a nested folder/file tree from a flat list of walked files for the
* UI-facing `files` column on the stored skill record. Binary file content is
* base64-encoded so it can round-trip through the string-typed `content` field.
*/
function buildSkillFileNodes(files) {
const root = [];
for (const file of files) {
const segments = file.path.split("/").filter(Boolean);
if (segments.length === 0) continue;
let cursor = root;
for (let i = 0; i < segments.length - 1; i++) {
const segment = segments[i];
let folder = cursor.find((node) => node.type === "folder" && node.name === segment);
if (!folder) {
folder = {
name: segment,
type: "folder",
children: []
};
cursor.push(folder);
}
if (!folder.children) folder.children = [];
cursor = folder.children;
}
const fileName = segments[segments.length - 1];
const content = file.isBinary ? (Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content)).toString("base64") : file.content;
cursor.push({
name: fileName,
type: "file",
content
});
}
return root;
}
/**
* Parse a flat array of skill files into a denormalized snapshot.
*
* Finds `SKILL.md`, parses its YAML frontmatter into structured fields
* (name, description, license, compatibility, metadata), and uses the
* markdown body as `instructions`. Discovers `references/`, `scripts/`,
* and `assets/` subdirectory paths from the file list.
*
* Used by both the publish flow (which has files from a SkillSource walk)
* and the registry install flow (which has files fetched from an external
* registry like skills.sh). The Agent Skills spec puts metadata in
* frontmatter and agent-facing prose in the body — this helper enforces
* that split so frontmatter never leaks into the runtime instructions.
*
* @throws if `SKILL.md` is missing from the file list
*/
function parseSkillSnapshotFromFiles(files) {
const skillMdFile = files.find((f) => f.path === "SKILL.md");
if (!skillMdFile) throw new Error("SKILL.md not found in skill files");
const skillMdContent = typeof skillMdFile.content === "string" ? skillMdFile.content : skillMdFile.content.toString("utf-8");
const { metadata: frontmatter, instructions } = require_workspace_skills.extractSkillFrontmatter(skillMdContent);
const allPaths = files.map((f) => f.path);
const references = collectSubdirPaths(allPaths, "references");
const scripts = collectSubdirPaths(allPaths, "scripts");
const assets = collectSubdirPaths(allPaths, "assets");
return {
name: frontmatter.name,
description: frontmatter.description,
instructions,
license: frontmatter.license,
compatibility: frontmatter.compatibility,
metadata: frontmatter.metadata,
...references.length > 0 ? { references } : {},
...scripts.length > 0 ? { scripts } : {},
...assets.length > 0 ? { assets } : {}
};
}
/**
* Collect a skill from a SkillSource for publishing.
* Walks the skill directory, hashes all files, parses SKILL.md frontmatter,
* and returns everything needed to create a new version.
*
* @param source - The SkillSource to read from (live filesystem or any other source)
* @param skillPath - Path to the skill directory (containing SKILL.md)
*/
async function collectSkillForPublish(source, skillPath) {
const files = await walkSkillDirectory(source, skillPath);
const treeEntries = {};
const blobMap = /* @__PURE__ */ new Map();
const now = /* @__PURE__ */ new Date();
for (const file of files) {
const hash = await hashContent(file.content);
const mimeType = detectMimeType(file.path);
if (file.isBinary) {
const buf = Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content);
const size = buf.length;
const base64Content = buf.toString("base64");
treeEntries[file.path] = {
blobHash: hash,
size,
mimeType,
encoding: "base64"
};
if (!blobMap.has(hash)) blobMap.set(hash, {
hash,
content: base64Content,
size,
mimeType,
createdAt: now
});
} else {
const content = file.content;
const size = Buffer.byteLength(content, "utf-8");
treeEntries[file.path] = {
blobHash: hash,
size,
mimeType
};
if (!blobMap.has(hash)) blobMap.set(hash, {
hash,
content,
size,
mimeType,
createdAt: now
});
}
}
const tree = { entries: treeEntries };
const blobs = Array.from(blobMap.values());
const fileNodes = buildSkillFileNodes(files);
let snapshot;
try {
snapshot = parseSkillSnapshotFromFiles(files);
} catch (err) {
if (err instanceof Error && err.message.includes("SKILL.md not found")) throw new Error(`SKILL.md not found in ${skillPath}`);
throw err;
}
return {
snapshot,
tree,
blobs,
files: fileNodes
};
}
/**
* Publish a skill: collect files, store blobs, create version.
* This is the full publish flow.
*
* @param source - The SkillSource to read from
* @param skillPath - Path to the skill directory
* @param blobStore - Where to store file blobs
*/
async function publishSkillFromSource(source, skillPath, blobStore) {
const result = await collectSkillForPublish(source, skillPath);
await blobStore.putMany(result.blobs);
return result;
}
// src/workspace/skills/tools.ts
/**
* Skill Tools — Factory
*
* Creates the built-in skill tools for agents. These tools let the model
* discover and read skill instructions on demand.
*
* Design: stateless. The `skill` tool returns the full skill instructions
* in its tool result — no activation state tracking needed. Instructions
* persist naturally in conversation history. If context gets compacted,
* the model just calls the tool again.
*/
/**
* Create all skill tools for a workspace with skills.
* Returns an empty object if the workspace has no skills.
*
* Tools are added at the Agent level (like workspace tools), not inside
* a processor, to avoid losing tool execute functions on serialization.
*/
function createSkillTools(skills) {
return {
skill: createSkillTool(skills),
skill_search: createSkillSearchTool(skills),
skill_read: createSkillReadTool(skills)
};
}
/**
* Format a skill into the activation payload: instructions followed by
* any references/scripts/assets listings. Shared between the `skill` tool
* and explicit user activations so both paths produce identical output.
*/
function formatSkillActivation(skill) {
const parts = [skill.instructions];
if (skill.references?.length) parts.push(`\n\n## References\n${skill.references.map((r) => `- references/${r}`).join("\n")}`);
if (skill.scripts?.length) parts.push(`\n\n## Scripts\n${skill.scripts.map((s) => `- scripts/${s}`).join("\n")}`);
if (skill.assets?.length) parts.push(`\n\n## Assets\n${skill.assets.map((a) => `- assets/${a}`).join("\n")}`);
return parts.join("");
}
/** Above this many skills, a not-found skill lists suggestions instead of every skill. */
const MAX_LISTED_SKILLS = 20;
const MAX_SUGGESTED_SKILLS = 5;
async function getScopedSkills(skills, requestContext) {
return skills.getScoped ? skills.getScoped({ requestContext }) : skills;
}
/**
* Resolve a skill identifier (name or path) to a Skill.
* The `skills.get()` method handles both name-based lookup (with tie-breaking)
* and path-based lookup (escape hatch for disambiguation).
*
* Calls `maybeRefresh()` first so edits on disk are picked up between tool
* invocations without restarting the server. Refresh is gated by an internal
* staleness check + cooldown, so the cost is a small directory `stat` rather
* than a full re-walk. File-level reloads (SKILL.md content edits) only
* trigger when the workspace is configured with `checkSkillFileMtime: true`.
*/
async function resolveSkill(skills, identifier) {
await skills.maybeRefresh();
const skill = await skills.get(identifier);
if (skill) return { skill };
const notFound = `Skill "${identifier}" not found.`;
const allSkills = await skills.list();
if (allSkills.length <= MAX_LISTED_SKILLS) return { notFound: `${notFound} Available skills: ${allSkills.map((s) => `${s.name} (${s.path})`).join(", ")}` };
const query = (identifier.split("/").filter(Boolean).pop() ?? "").replace(/[-_.]+/g, " ").trim();
const matches = query ? await skills.search(query, {
topK: MAX_SUGGESTED_SKILLS,
includeReferences: false
}).catch(() => []) : [];
const suggestions = [...new Set(matches.map((m) => `${m.skillName} (${m.skillPath})`))];
return { notFound: `${notFound}${suggestions.length > 0 ? ` Closest matches: ${suggestions.join(", ")}.` : ""} Use the \`skill_search\` tool to find other skills.` };
}
function createSkillTool(skills) {
return require_tool.createTool({
id: "skill",
description: "Activate a skill to load its full instructions. You should activate skills proactively when they are relevant to the user's request without asking for permission first.",
inputSchema: zod_v4.z.object({ name: zod_v4.z.string().describe("The name or path of the skill to activate. Use the path when multiple skills share the same name.") }),
execute: async ({ name }, context) => {
const span = startSkillSpan(context, {
operation: "activate",
input: { name },
attributes: { skillName: name }
});
try {
const result = await resolveSkill(await getScopedSkills(skills, context?.requestContext), name);
if ("notFound" in result) {
span.end({ success: false });
return result.notFound;
}
const { skill } = result;
const output = formatSkillActivation(skill);
span.end({ success: true });
return output;
} catch (err) {
span.error(err);
throw err;
}
}
});
}
function createSkillSearchTool(skills) {
return require_tool.createTool({
id: "skill_search",
description: "Search skills by name, description, and content. Use it to find which skill to load with the `skill` tool, or to find specific details inside skills.",
inputSchema: zod_v4.z.object({
query: zod_v4.z.string().describe("The search query"),
skillNames: zod_v4.z.array(zod_v4.z.string()).optional().describe("Optional list of skill names to search within"),
topK: zod_v4.z.number().optional().describe("Maximum number of results to return (default: 5)")
}),
execute: async ({ query, skillNames, topK }, context) => {
const span = startSkillSpan(context, {
operation: "search",
input: {
query,
skillNames,
topK
},
attributes: {}
});
try {
const scopedSkills = await getScopedSkills(skills, context?.requestContext);
await scopedSkills.maybeRefresh();
const results = await scopedSkills.search(query, {
topK,
skillNames
});
if (results.length === 0) {
span.end({ success: true }, { resultCount: 0 });
return "No results found.";
}
span.end({ success: true }, { resultCount: results.length });
return results.map((r) => {
const preview = r.content.substring(0, 200) + (r.content.length > 200 ? "..." : "");
const file = r.source !== "SKILL.md" ? ` ${r.source}` : "";
const location = r.lineRange ? ` (lines ${r.lineRange.start}-${r.lineRange.end})` : "";
return `[${r.skillName}]${file}${location} (score: ${r.score.toFixed(2)})\n${preview}`;
}).join("\n\n");
} catch (err) {
span.error(err);
throw err;
}
}
});
}
function createSkillReadTool(skills) {
return require_tool.createTool({
id: "skill_read",
description: "Read a file from a skill directory (references, scripts, or assets). The path is relative to the skill root.",
inputSchema: zod_v4.z.object({
skillName: zod_v4.z.string().describe("The name or path of the skill. Use the path when multiple skills share the same name."),
path: zod_v4.z.string().describe("Path to the file relative to the skill root (e.g. \"references/colors.md\", \"scripts/run.sh\")"),
startLine: zod_v4.z.number().optional().describe("Starting line number (1-indexed). If omitted, starts from the beginning."),
endLine: zod_v4.z.number().optional().describe("Ending line number (1-indexed, inclusive). If omitted, reads to the end.")
}),
execute: async ({ skillName, path, startLine, endLine }, context) => {
const span = startSkillSpan(context, {
operation: "read",
input: {
skillName,
path,
startLine,
endLine
},
attributes: { skillName }
});
try {
const scopedSkills = await getScopedSkills(skills, context?.requestContext);
const resolved = await resolveSkill(scopedSkills, skillName);
if ("notFound" in resolved) {
span.end({ success: false });
return resolved.notFound;
}
const resolvedPath = resolved.skill.path;
const bytes = await scopedSkills.getAsset(resolvedPath, path);
if (bytes === null) {
const refs = (await scopedSkills.listReferences(resolvedPath)).map((f) => `references/${f}`);
const scriptsList = (await scopedSkills.listScripts(resolvedPath)).map((f) => `scripts/${f}`);
const assets = (await scopedSkills.listAssets(resolvedPath)).map((f) => `assets/${f}`);
const allFiles = [
...refs,
...scriptsList,
...assets
];
const fileList = allFiles.length > 0 ? `\nAvailable files: ${allFiles.join(", ")}` : "";
span.end({ success: false });
return `File "${path}" not found in skill "${skillName}".${fileList}`;
}
const text = bytes.toString("utf-8");
if (bytes.includes(0) || !bytes.equals(Buffer.from(text, "utf-8"))) {
const fullPath = `${resolved.skill.path}/${path}`;
span.end({ success: true }, { bytesTransferred: bytes.length });
return `Binary file: ${fullPath} (${bytes.length} bytes)`;
}
const result = extractLines(text, startLine, endLine);
if (result.lines.start === 0 && result.lines.end === 0) {
const reason = (startLine ?? 1) > result.totalLines ? `Requested startLine ${startLine} is past the end of the file. The file has been fully read; stop paginating.` : `Requested range ${startLine}-${endLine} is empty because startLine is greater than endLine.`;
span.end({ success: true }, { bytesTransferred: 0 });
return `File "${path}" has ${result.totalLines} lines (valid range 1-${result.totalLines}). ${reason}`;
}
const output = startLine !== void 0 || endLine !== void 0 ? `${path} (lines ${result.lines.start}-${result.lines.end} of ${result.totalLines})\n${result.content}` : result.content;
span.end({ success: true }, { bytesTransferred: Buffer.byteLength(result.content, "utf-8") });
return output;
} catch (err) {
span.error(err);
throw err;
}
}
});
}
// src/workspace/workspace.ts
/**
* Workspace Class
*
* A Workspace combines a Filesystem and a Sandbox to provide agents
* with a complete environment for storing files and executing code.
*
* Users pass provider instances directly to the Workspace constructor.
*
* @example
* ```typescript
* import { LocalFilesystem, Workspace } from '@mastra/core/workspace';
* import { E2BSandbox } from '@mastra/e2b';
* import { S3Filesystem } from '@mastra/s3';
*
* // Local filesystems use paths relative to their base directory.
* const localWorkspace = new Workspace({
* filesystem: new LocalFilesystem({ basePath: './workspace' }),
* });
*
* await localWorkspace.init();
* await localWorkspace.filesystem?.writeFile('app.py', 'print("Hello locally!")');
*
* // Mounted cloud filesystems use their absolute mount paths.
* const cloudWorkspace = new Workspace({
* mounts: {
* '/code': new S3Filesystem({ bucket: 'my-code', region: 'us-east-1' }),
* },
* sandbox: new E2BSandbox(),
* });
*
* await cloudWorkspace.init();
* await cloudWorkspace.filesystem?.writeFile('/code/app.py', 'print("Hello from E2B!")');
* const result = await cloudWorkspace.sandbox?.executeCommand?.('python3', ['app.py'], { cwd: '/code' });
* ```
*/
/** Workspace instructions for a resolver-backed sandbox in `'placeholder'` mode. */
const DYNAMIC_SANDBOX_INSTRUCTIONS = "Dynamic sandbox configured. Shell commands execute in a request-scoped sandbox resolved at tool execution time.";
/**
* Maximum concurrent `readFile` calls when batch-loading files for search auto-indexing
* (`batchReadFiles`).
*/
const FS_READ_CONCURRENCY = 8;
/** Mirrors SearchEngine.search default when no topK is supplied. */
const DEFAULT_SEARCH_TOP_K = 10;
/**
* Parse the user-facing `bm25` config union into the `BM25SearchConfig` shape
* that `SearchEngine` expects.
*/
function parseBM25Config(bm25) {
if (typeof bm25 === "boolean") return {};
if ("bm25" in bm25 || "tokenize" in bm25) return {
bm25: bm25.bm25,
tokenize: bm25.tokenize
};
return { bm25 };
}
/**
* Provides agents with filesystem and execution capabilities through configured providers.
*
* Supply a filesystem, a sandbox, or both. File operations require a filesystem;
* command execution requires a sandbox.
*
* @example
* ```typescript
* import { Workspace, LocalFilesystem } from '@mastra/core/workspace';
*
* const workspace = new Workspace({
* filesystem: new LocalFilesystem({ basePath: './my-workspace' }),
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Workspace documentation](https://mastra.ai/docs/workspace/overview)
* if packaged docs are unavailable.
*/
var Workspace = class {
id;
name;
createdAt;
lastAccessedAt;
_status = "pending";
_destroyPromise;
_stopPromise;
_fs;
_filesystemResolver;
_sandbox;
_sandboxResolver;
_filesystemRequestCache = /* @__PURE__ */ new WeakMap();
_sandboxRequestCache = /* @__PURE__ */ new WeakMap();
_sandboxKeyCache = /* @__PURE__ */ new Map();
_sandboxCacheKey;
_dynamicSandboxInstructions;
_browser;
_config;
_searchEngine;
_skills;
/** Set as soon as `destroy()` begins, and never cleared. */
_teardownStarted = false;
_lsp;
_logger;
constructor(config) {
this.id = config.id ?? this.generateId();
this.name = config.name ?? `workspace-${this.id.slice(0, 8)}`;
this.createdAt = /* @__PURE__ */ new Date();
this.lastAccessedAt = /* @__PURE__ */ new Date();
this._config = config;
if (typeof config.sandbox === "function") this._sandboxResolver = config.sandbox;
else this._sandbox = config.sandbox;
this._sandboxCacheKey = config.sandboxCacheKey;
this._dynamicSandboxInstructions = config.instructions?.dynamicSandbox ?? "placeholder";
if (config.mounts && Object.keys(config.mounts).length > 0) {
if (config.filesystem) throw new require_errors.WorkspaceError("Cannot use both \"filesystem\" and \"mounts\"", "INVALID_CONFIG");
if (this._sandboxResolver) throw new require_errors.WorkspaceError("Cannot use \"mounts\" with a dynamic sandbox resolver. Mounts are attached to a sandbox instance at construction time. Either pass a static sandbox instance, or have your resolver return a sandbox with its mounts already configured.", "INVALID_CONFIG");
for (const [mountPath, fs] of Object.entries(config.mounts)) if (fs instanceof LocalFilesystem && !fs.contained) console.warn(`[Workspace] LocalFilesystem at mount "${mountPath}" has contained: false, which is incompatible with mounts. CompositeFilesystem strips mount prefixes and produces absolute paths (e.g. "/file.txt"), which a non-contained LocalFilesystem interprets as real host paths instead of paths relative to basePath. Use contained: true (default) or allowedPaths for specific exceptions.`);
this._fs = new CompositeFilesystem({ mounts: config.mounts });
if (this._sandbox?.mounts) {
this._sandbox.mounts.setContext({
sandbox: this._sandbox,
workspace: this
});
this._sandbox.mounts.add(config.mounts);
if (config.onMount) this._sandbox.mounts.setOnMount(config.onMount);
}
} else if (typeof config.filesystem === "function") {
if (/^class\s/.test(Function.prototype.toString.call(config.filesystem))) throw new require_errors.WorkspaceError("filesystem received a class constructor instead of an instance or resolver function. Pass an instance (e.g., new LocalFilesystem(...)) or a resolver function (({ requestContext }) => fs).", "INVALID_CONFIG");
this._filesystemResolver = config.filesystem;
} else this._fs = config.filesystem;
if (config.browser) {
if (config.browser.providerType !== "cli") throw new require_errors.WorkspaceError(`Workspace.browser requires a CLI provider (providerType: 'cli'), but got '${config.browser.providerType}'. SDK providers should be used with Agent.browser instead.`, "INVALID_CONFIG", this.id);
this._browser = config.browser;
}
const embedsServerSide = !config.embedder && config.vectorStore?.isSelfEmbedding === true;
if (config.vectorStore && !config.embedder && !embedsServerSide) throw new require_errors.WorkspaceError("vectorStore requires an embedder", "INVALID_SEARCH_CONFIG");
if (config.bm25 || config.vectorStore && (config.embedder || embedsServerSide)) {
const buildIndexName = () => {
const defaultName = `${this.id}_search${embedsServerSide ? "_selfembed" : ""}`.replace(/[^a-zA-Z0-9_]/g, "_");
const indexName = config.searchIndexName ?? defaultName;
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)) throw new require_errors.WorkspaceError(`Invalid searchIndexName: "${indexName}". Must start with a letter or underscore, and contain only letters, numbers, or underscores.`, "INVALID_SEARCH_CONFIG", this.id);
if (indexName.length > 63) throw new require_errors.WorkspaceError(`searchIndexName exceeds 63 characters (got ${indexName.length})`, "INVALID_SEARCH_CONFIG", this.id);
return indexName;
};
this._searchEngine = new require_workspace_skills.SearchEngine({
bm25: config.bm25 ? parseBM25Config(config.bm25) : void 0,
vector: config.vectorStore && (config.embedder || embedsServerSide) ? {
vectorStore: config.vectorStore,
embedder: config.embedder,
indexName: buildIndexName()
} : void 0
});
}
if (config.lsp) {
const processes = this._sandbox?.processes;
if (this._sandboxResolver) console.warn(`[Workspace "${this.name}"] lsp: true is incompatible with a dynamic sandbox resolver — LSP needs a process manager at construction time, but the sandbox is resolved per request. LSP disabled.`);
else if (!this._sandbox) console.warn(`[Workspace "${this.name}"] lsp: true requires a sandbox with a process manager. No sandbox configured — LSP disabled.`);
else if (!processes) console.warn(`[Workspace "${this.name}"] lsp: true requires a sandbox with a process manager. Sandbox "${this._sandbox.name ?? "unknown"}" does not provide one — LSP disabled.`);
else if (!isLSPAvailable()) console.warn(`[Workspace "${this.name}"] lsp: true requires vscode-jsonrpc and vscode-languageserver-protocol packages. Install them to enable LSP diagnostics.`);
else {
const lspConfig = config.lsp === true ? {} : config.lsp;
const defaultRoot = lspConfig.root ?? findProjectRoot(process.cwd()) ?? process.cwd();
this._lsp = new LSPManager(processes, defaultRoot, lspConfig, this._fs);
}
}
if (!this._fs && !this._filesystemResolver && !this._sandbox && !this._sandboxResolver && !this.hasSkillsConfig()) throw new require_errors.WorkspaceError("Workspace requires at least a filesystem, sandbox, or skills", "NO_PROVIDERS");
}
generateId() {
return `ws-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
hasSkillsConfig() {
return this._config.skills !== void 0 && (typeof this._config.skills === "function" || this._config.skills.length > 0);
}
get status() {
return this._status;
}
/**
* Compact span representation. Without it, the trace serializer would walk the
* workspace's config and its filesystem/sandbox providers, which can hold credentials.
*/
serializeForSpan() {
return {
id: this.id,
name: this.name,
status: this._status
};
}
/**
* The filesystem provider (if configured).
*
* Returns the concrete type you passed to the constructor.
* When `mounts` is used instead of `filesystem`, returns `CompositeFilesystem`
* parameterized with the concrete mount types.
*/
get filesystem() {
return this._fs;
}
/**
* The sandbox provider (if configured).
*
* Returns the concrete type you passed to the constructor.
*/
get sandbox() {
return this._sandbox;
}
/**
* The browser provider (if configured).
*
* Returns the MastraBrowser instance (must be a CLI provider like BrowserViewer).
*/
get browser() {
return this._browser;
}
/**
* Get the per-tool configuration for this workspace.
* Returns undefined if no tools config was provided.
*/
getToolsConfig() {
return this._config.tools;
}
/**
* The LSP manager (if configured, initialized, and a process manager is available).
* Returns undefined if LSP is not configured, deps are missing, or sandbox has no process manager.
*/
get lsp() {
return this._lsp;
}
/**
* Update the per-tool configuration for this workspace.
* Takes effect on the next `createWorkspaceTools()` call.
*
* @example
* ```typescript
* // Disable write tools for read-only mode
* workspace.setToolsConfig({
* mastra_workspace_write_file: { enabled: false },
* mastra_workspace_edit_file: { enabled: false },
* });
*
* // Re-enable all tools
* workspace.setToolsConfig(undefined);
* ```
*/
setToolsConfig(config) {
this._config.tools = config;
}
/**
* Returns true if a filesystem is configured, either as a static instance or a resolver function.
*/
hasFilesystemConfig() {
return this._fs !== void 0 || this._filesystemResolver !== void 0;
}
/**
* Resolve the filesystem for a given request context.
* When a resolver function is configured, calls it with the provided requestContext.
* When a static filesystem is configured, returns it directly.
* Returns undefined if no filesystem is configured.
*/
async resolveFilesystem({ requestContext }) {
if (!this._filesystemResolver) return this._fs;
let pending = this._filesystemRequestCache.get(requestContext);
if (!pending) {
pending = Promise.resolve().then(() => this._filesystemResolver({ requestContext }));
this._filesystemRequestCache.set(requestContext, pending);
pending.catch(() => {
if (this._filesystemRequestCache.get(requestContext) === pending) this._filesystemRequestCache.delete(requestContext);
});
}
return pending;
}
/**
* Returns true if a sandbox is configured, either as a static instance or a resolver function.
*/
hasSandboxConfig() {
return this._sandbox !== void 0 || this._sandboxResolver !== void 0;
}
/**
* Returns true when the sandbox is resolved dynamically per request.
*/
hasSandboxResolver() {
return this._sandboxResolver !== void 0;
}
/**
* Returns true when resolver-backed sandboxes are cached by a stable key.
*/
hasSandboxCacheKey() {
return this._sandboxCacheKey !== void 0;
}
/**
* Resolve the sandbox for a given request context. Calls the resolver function
* if configured, otherwise returns the static sandbox (or undefined). Results
* are memoized by `sandboxCacheKey` when set, else per RequestContext instance.
*/
async resolveSandbox({ requestContext }) {
if (!this._sandboxResolver) return this._sandbox;
const cacheKey = this._sandboxCacheKey?.({ requestContext });
if (cacheKey != null) {
let keyed = this._sandboxKeyCache.get(cacheKey);
if (!keyed) {
keyed = Promise.resolve().then(() => this._sandboxResolver({ requestContext }));
this._sandboxKeyCache.set(cacheKey, keyed);
keyed.catch(() => {
if (this._sandboxKeyCache.get(cacheKey) === keyed) this._sandboxKeyCache.delete(cacheKey);
});
}
return keyed;
}
let pending = this._sandboxRequestCache.get(requestContext);
if (!pending) {
pending = Promise.resolve().then(() => this._sandboxResolver({ requestContext }));
this._sandboxRequestCache.set(requestContext, pending);
pending.catch(() => {
if (this._sandboxRequestCache.get(requestContext) === pending) this._sandboxRequestCache.delete(requestContext);
});
}
return pending;
}
/**
* Clear cached resolver-backed sandboxes stored by `sandboxCacheKey`.
*
* This only clears the keyed cache. Per-RequestContext WeakMap entries are
* garbage-collection managed and cannot be cleared by this method.
*
* The workspace does not own resolver-returned sandboxes, so this only drops
* references from the workspace cache. Callers remain responsible for
* destroying any sandbox instances they created.
*/
clearSandboxCache(cacheKey) {
if (cacheKey === void 0) {
this._sandboxKeyCache.clear();
return;
}
this._sandboxKeyCache.delete(cacheKey);
}
/**
* Access skills stored in this workspace.
* Skills are SKILL.md files discovered from the configured skillPaths.
*
* Returns undefined if no skillPaths are configured.
*
* @example
* ```typescript
* const skills = await workspace.skills?.list();
* const skill = await workspace.skills?.get('skills/brand-guidelines');
* const results = await workspace.skills?.search('brand colors');
* ```
*/
get skills() {
if (!this.hasSkillsConfig()) return;
this.assertSearchWritable();
if (!this._skills) {
const baseConfig = {
skills: this._config.skills,
searchEngine: this._searchEngine,
validateOnLoad: true,
assertAvailable: () => this.assertSearchWritable(),
checkSkillFileMtime: this._config.checkSkillFileMtime
};
if (!this._config.skillSource && this._filesystemResolver) this._skills = new require_workspace_skills.ResolvedSourceWorkspaceSkills({
...baseConfig,
source: async ({ requestContext }) => {
const fs = await this.resolveFilesystem({ requestContext: requestContext ?? new require_request_context.RequestContext() });
if (!fs) throw new require_errors.WorkspaceError("Filesystem resolver returned no filesystem; cannot discover skills", "FILESYSTEM_NOT_RESOLVED", this.id);
return fs;
}
});
else this._skills = new require_workspace_skills.WorkspaceSkillsImpl({
...baseConfig,
source: this._config.skillSource ?? this._fs ?? new require_workspace_skills.LocalSkillSource()
});
}
return this._skills;
}
/**
* Check if BM25 keyword search is available.
*/
get canBM25() {
return this._searchEngine?.canBM25 ?? false;
}
/**
* Check if vector semantic search is available.
*/
get canVector() {
return this._searchEngine?.canVector ?? false;
}
/**
* Check if hybrid search is available.
*/
get canHybrid() {
return this._searchEngine?.canHybrid ?? false;
}
/**
* Index content for search.
* The path becomes the document ID in search results.
*
* @param path - File path (used as document ID)
* @param content - Text content to index
* @param options - Index options (metadata, type hints)
* @throws {SearchNotAvailableError} if search is not configured
*/
async index(path, content, options) {
this.assertSearchWritable();
if (!this._searchEngine) throw new require_errors.SearchNotAvailableError();
this.lastAccessedAt = /* @__PURE__ */ new Date();
const doc = {
id: path,
content,
metadata: {
type: options?.type,
mimeType: options?.mimeType,
...options?.metadata
},
startLineOffset: options?.startLineOffset
};
await this._searchEngine.index(doc);
}
/**
* Search indexed content.
*
* @param query - Search query string
* @param options - Search options (topK, mode, filters)
* @returns Array of search results
* @throws {SearchNotAvailableError} if search is not configured
*/
async search(query, options) {
if (!this._searchEngine) throw new require_errors.SearchNotAvailableError();
this.lastAccessedAt = /* @__PURE__ */ new Date();
const scopedCount = this._searchEngine.countByPrefix(require_workspace_skills.SKILL_SCOPE_DOCUMENT_PREFIX);
const topK = options?.topK ?? DEFAULT_SEARCH_TOP_K;
const unscopedFilter = { skillScope: { $exists: false } };
const filter = options?.filter ? { $and: [options.filter, unscopedFilter] } : unscopedFilter;
return (await this._searchEngine.search(query, {
...options,
topK: topK + scopedCount,
filter
})).filter((result) => result.metadata?.skillScope === void 0).slice(0, topK);
}
/**
* Rebuild the search index from filesystem paths without starting the sandbox.
*
* Defaults to the configured `autoIndexPaths`, or accepts explicit paths for a
* one-off rebuild. Paths can be plain directories, single files, or glob patterns.
* Uses resolvePathPattern for unified resolution: file matches are indexed directly,
* and directory matches are recursed. Does nothing when search is not configured,
* the workspace has no static filesystem, or no paths are provided.
*/
async rebuildSearchIndex(paths = this._config.autoIndexPaths ?? []) {
this.assertSearchWritable();
if (!this._searchEngine || !this._fs || paths.length === 0) return;
this._searchEngine.clear();
const readdir = async (dir) => {
return (await this._fs.readdir(dir)).map((e) => ({
name: e.name,
type: e.type,
isSymlink: e.isSymlink
}));
};
const indexedPaths = /* @__PURE__ */ new Set();
for (const pathOrGlob of paths) try {
const resolved = await require_workspace_skills.resolvePathPattern(pathOrGlob, readdir);
const filesToIndex = /* @__PURE__ */ new Set();
const directoryRoots = [];
for (const entry of resolved) {
if (entry.type === "file") {
filesToIndex.add(entry.path);
continue;
}
if (!directoryRoots.some((root) => entry.path === root || entry.path.startsWith(`${root}/`))) directoryRoots.push(entry.path);
}
const indexed = await this.indexFilesForSearch(Array.from(filesToIndex).filter((filePath) => !indexedPaths.has(filePath)));
for (const filePath of indexed) indexedPaths.add(filePath);
for (const dir of directoryRoots) try {
const files = (await this.getAllFiles(dir)).filter((filePath) => !indexedPaths.has(filePath));
const indexed = await this.indexFilesForSearch(files);
for (const filePath of indexed) indexedPaths.add(filePath);
} catch {}
} catch {}
}
/**
* Load file contents for search indexing in parallel (bounded by {@link FS_READ_CONCURRENCY}).
* Paths that cannot be read as UTF-8 text are omitted (same behavior as {@link indexFileForSearch}).
*/
async batchReadFiles(files) {
if (!this._fs || files.length === 0) return [];
const fs = this._fs;
const { default: pMap, pMapSkip } = await import("p-map");
return pMap(files, async (filePath) => {
try {
const content = await fs.readFile(filePath, { encoding: "utf-8" });
const chunks = require_workspace_skills.splitIntoChunks(content);
return {
filePath,
docs: chunks.length === 1 ? [{
id: filePath,
content
}] : chunks.map((chunk, i) => ({
id: `${filePath}#chunk-${i}`,
content: chunk.content,
startLineOffset: chunk.startLine,
metadata: { sourceFile: filePath }
}))
};
} catch {
return pMapSkip;
}
}, {
stopOnError: false,
concurrency: FS_READ_CONCURRENCY
});
}
/**
* Batch-read paths and {@link SearchEngine.indexMany}
*
* @returns paths that were indexed successfully.
* @remarks Falls back to one-at-a-time indexing on failure of {@link SearchEngine.indexMany}
*/
async indexFilesForSearch(paths) {
const engine = this._searchEngine;
if (!engine) return [];
try {
const entries = await this.batchReadFiles(paths);
const pMap = (await import("p-map")).default;
await pMap(entries, ({ filePath }) => engine.removeSource(filePath), { concurrency: FS_READ_CONCURRENCY });
const docs = entries.flatMap(({ docs }) => docs);
await engine.indexMany(docs);
return entries.map(({ filePath }) => filePath);
} catch {
const indexed = [];
for (const filePath of paths) {
const id = await this.indexFileForSearch(filePath);
if (id !== void 0) indexed.push(id);
}
return indexed;
}
}
/**
* Index a single file for search. Skips files that can't be read as text.
* Large files are automatically split into chunks to stay within embedding
* model token limits.
*
* @returns `filePath` when indexed, or `undefined` if read/index failed.
*/
async indexFileForSearch(filePath) {
let content;
try {
content = await this._fs.readFile(filePath, { encoding: "utf-8" });
} catch {
return;
}
await this._searchEngine.removeSource(filePath);
const chunks = require_workspace_skills.splitIntoChunks(content);
if (chunks.length === 1) try {
await this._searchEngine.index({
id: filePath,
content
});
return filePath;
} catch (error) {
this._logger?.warn(`Failed to index file "${filePath}" for search`, { error });
return;
}
let anyIndexed = false;
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
try {
await this._searchEngine.index({
id: `${filePath}#chunk-${i}`,
content: chunk.content,
startLineOffset: chunk.startLine,
metadata: { sourceFile: filePath }
});
anyIndexed = true;
} catch (error) {
this._logger?.warn(`Failed to index chunk ${i} of file "${filePath}" for search`, { error });
}
}
return anyIndexed ? filePath : void 0;
}
async getAllFiles(dir, depth = 0, maxDepth = 10, filesystem = this._fs) {
if (!filesystem || depth >= maxDepth) return [];
const files = [];
const entries = await filesystem.readdir(dir);
for (const entry of entries) {
const fullPath = dir === "." || dir === "" ? entry.name : `${dir}/${entry.name}`;
if (entry.type === "file") files.push(fullPath);
else if (entry.type === "directory" && !entry.isSymlink) files.push(...await this.getAllFiles(fullPath, depth + 1, maxDepth, filesystem));
}
return files;
}
/**
* Initialize the workspace.
* Starts the sandbox, initializes the filesystem, and auto-mounts filesystems.
*
* Resolver-backed providers are skipped because there is no instance until
* the resolver runs.
*/
async init() {
this._status = "initializing";
try {
if (this._fs) await callLifecycle(this._fs, "init");
if (this._sandbox) await callLifecycle(this._sandbox, "start");
if (this._searchEngine && this._config.autoIndexPaths && this._config.autoIndexPaths.length > 0) await this.rebuildSearchIndex(this._config.autoIndexPaths ?? []);
this._status = "ready";
} catch (error) {
this._status = "error";
throw error;
}
}
/**
* Reject search writes once teardown has begun, so that a late caller cannot
* repopulate an index that `destroy()` has already released.
*
* Keyed off `_teardownStarted` rather than `_status`: a failed teardown ends
* in `'error'`, which is also the status of a failed `init()`, and the index
* has been released either way once `destroy()` has run.
*/
assertSearchWritable() {
if (this._teardownStarted) throw new require_errors.WorkspaceNotReadyError(this.id, this._status);
}
/**
* Stop the workspace's live resources without destroying them.
*
* Shuts down LSP clients, closes the browser, and stops the sandbox
* (`stop`, not `destroy` — remote providers pause/suspend so the sandbox
* can be resumed later; {@link LocalSandbox} kills its background
* processes). The workspace itself stays usable: filesystem, search index,
* and skills are untouched, and a later sandbox operation may start the
* sandbox again.
*
* This is what `Mastra.shutdown()` calls for registered workspaces, so a
* process restart suspends remote sandboxes instead of deleting them.
*/
async stop() {
if (this._teardownStarted || this._status === "destroyed") return;
if (this._stopPromise) return await this._stopPromise;
this._stopPromise = this._performStop();
try {
await this._stopPromise;
} finally {
this._stopPromise = void 0;
}
}
async _performStop() {
if (this._lsp) try {
await this._lsp.shutdownAll();
} catch {}
if (this._browser) try {
await this._browser.close();
} catch {}
if (this._sandbox) await callLifecycle(this._sandbox, "stop");
}
/**
* Destroy the workspace and clean up all resources.
*/
async destroy() {
if (this._status === "destroyed") return;
if (this._status === "destroying" && this._destroyPromise) return await this._destroyPromise;
this._teardownStarted = true;
this._status = "destroying";
this._destroyPromise = (async () => {
if (this._stopPromise) await this._stopPromise.catch(() => {});
await this._performDestroy();
})();
try {
await this._destroyPromise;
} finally {
this._destroyPromise = void 0;
}
}
async _performDestroy() {
try {
if (this._lsp) {
try {
await this._lsp.shutdownAll();
} catch {}
this._lsp = void 0;
}
if (this._browser) try {
await this._browser.close();
} catch {}
if (this._sandbox) await callLifecycle(this._sandbox, "destroy");
if (this._fs) await callLifecycle(this._fs, "destroy");
this.clearSandboxCache();
this._status = "destroyed";
} catch (error) {
this._status = "error";
throw error;
} finally {
this._searchEngine?.clear();
this._skills = void 0;
}
}
/**
* Get workspace information.
* @param options.includeFileCount - Whether to count total files (can be slow for large workspaces)
*/
async getInfo(options) {
const info = {
id: this.id,
name: this.name,
status: this._status,
createdAt: this.createdAt,
lastAccessedAt: this.lastAccessedAt
};
const shouldResolveDynamicProviders = options?.resolveDynamicProviders ?? true;
const filesystem = this.filesystem ?? (this._filesystemResolver && shouldResolveDynamicProviders ? await this.resolveFilesystem({ requestContext: options?.requestContext ?? new require_request_context.RequestContext() }) : void 0);
if (filesystem) {
const fsInfo = await filesystem.getInfo?.();
info.filesystem = {
id: fsInfo?.id ?? filesystem.id,
name: fsInfo?.name ?? filesystem.name,
provider: fsInfo?.provider ?? filesystem.provider,
readOnly: fsInfo?.readOnly ?? filesystem.readOnly,
status: fsInfo?.status,
error: fsInfo?.error,
icon: fsInfo?.icon,
metadata: fsInfo?.metadata
};
if (options?.includeFileCount) try {
const files = await this.getAllFiles(".", 0, 10, filesystem);
info.filesystem.totalFiles = files.length;
} catch {}
} else if (this._filesystemResolver) info.filesystem = {
id: `${this.id}-dynamic-filesystem`,
name: "DynamicFilesystem",
provider: "dynamic",
status: "pending"
};
const sandbox = this.sandbox;
if (sandbox) {
const sandboxInfo = await sandbox.getInfo?.();
info.sandbox = {
provider: sandbox.provider,
status: sandboxInfo?.status ?? sandbox.status,
resources: sandboxInfo?.resources
};
} else if (this._sandboxResolver) info.sandbox = {
provider: "dynamic",
status: "pending"
};
return info;
}
/**
* Get human-readable instructions describing the workspace environment.
*
* When both a sandbox with mounts and a filesystem exist, each mount path
* is classified as sandbox-accessible (state === 'mounted') or
* workspace-only (pending / mounting / error / unsupported). When there's
* no sandbox or no mounts, falls back to provider-level instructions.
*
* @param opts - Optional options including request context for per-request customisation
* @returns Combined instructions string (may be empty)
*/
getInstructionsForProviders(filesystem, sandbox, opts) {
const parts = [];
const sandboxInstructions = sandbox?.getInstructions?.(opts);
if (sandboxInstructions) parts.push(sandboxInstructions);
const mountEntries = sandbox?.mounts?.entries;
if (mountEntries && mountEntries.size > 0) {
const sandboxAccessible = [];
const workspaceOnly = [];
const workingDir = sandbox instanceof LocalSandbox ? sandbox.workingDirectory : void 0;
for (const [mountPath, entry] of mountEntries) {
const fsName = entry.filesystem.displayName || entry.filesystem.provider;
const access = entry.filesystem.readOnly ? "read-only" : "read-write";
const displayPath = workingDir ? path.join(workingDir, mountPath.replace(/^\/+/, "")) : mountPath;
if (entry.state === "mounted" || entry.state === "pending" || entry.state === "mounting") sandboxAccessible.push(` - ${displayPath}: ${fsName} (${access})`);
else workspaceOnly.push(` - ${mountPath}: ${fsName} (${access})`);
}
if (sandboxAccessible.length) parts.push(`Sandbox-mounted filesystems (accessible in shell commands):\n${sandboxAccessible.join("\n")}`);
if (workspaceOnly.length) parts.push(`Workspace-only filesystems (use file tools, NOT available in shell commands):\n${workspaceOnly.join("\n")}`);
} else {
const fsInstructions = filesystem?.getInstructions?.(opts);
if (fsInstructions) parts.push(fsInstructions);
}
return parts.join("\n\n");
}
getInstructions(opts) {
return this.getInstructionsForProviders(this._fs, this._sandbox, opts);
}
/**
* Get human-readable instructions describing the workspace environment.
*
* Resolves a dynamic filesystem per request. A resolver-backed sandbox is not
* resolved here unless `instructions.dynamicSandbox` is `'resolve'`.
*/
async getInstructionsAsync(opts) {
const requestContext = opts?.requestContext ?? new require_request_context.RequestContext();
const filesystem = this._filesystemResolver ? await this.resolveFilesystem({ requestContext }) : this._fs;
const resolvedOpts = {
...opts,
requestContext
};
if (this._sandboxResolver && this._dynamicSandboxInstructions !== "resolve") return [typeof this._dynamicSandboxInstructions === "function" ? this._dynamicSandboxInstructions({ requestContext }) : DYNAMIC_SANDBOX_INSTRUCTIONS, this.getInstructionsForProviders(filesystem, void 0, resolvedOpts)].filter(Boolean).join("\n\n");
const sandbox = this._sandboxResolver ? await this.resolveSandbox({ requestContext }) : this._sandbox;
return this.getInstructionsForProviders(filesystem, sandbox, resolvedOpts);
}
/**
* Get information about how filesystem and sandbox paths relate.
* Useful for understanding how to access workspace files from sandbox code.
*
* @deprecated Use {@link getInstructions} instead. `getInstructions()` is
* mount-state-aware and feeds into the system message via
* `WorkspaceInstructionsProcessor`.
*
* @returns PathContext with paths and instructions from providers
*/
getPathContext() {
return this.getPathContextForProviders(this._fs, this._sandbox);
}
getPathContextForProviders(filesystem, sandbox) {
const fsInstructions = filesystem?.getInstructions?.();
const sandboxInstructions = sandbox?.getInstructions?.();
return {
filesystem: filesystem ? {
provider: filesystem.provider,
basePath: filesystem.basePath
} : void 0,
sandbox: sandbox ? {
provider: sandbox.provider,
workingDirectory: sandbox instanceof LocalSandbox ? sandbox.workingDirectory : void 0
} : void 0,
instructions: [fsInstructions, sandboxInstructions].filter(Boolean).join(" ")
};
}
/**
* Set the logger for this workspace and propagate to providers.
* Called by Mastra when the logger is set.
* @internal
*/
/** Logger set by Mastra, if any. */
get logger() {
return this._logger;
}
__setLogger(logger) {
this._logger = logger;
if (this._fs instanceof MastraFilesystem) this._fs.__setLogger(logger);
if (this._sandbox instanceof MastraSandbox) this._sandbox.__setLogger(logger);
}
};
// src/workspace/factory-sandbox.ts
/**
* Brand every `FactorySandbox` carries. A `Symbol.for` key so two copies of
* `@mastra/core` in one process agree on it. Factory detects the contract by
* this brand alone, never by `instanceof` or by the presence of `create`.
*/
const FACTORY_SANDBOX_BRAND = Symbol.for("mastra.factory.sandbox");
/** The settings schema of a provider with nothing to tune. */
const NO_SETTINGS = {
type: "object",
properties: {},
additionalProperties: false
};
/**
* The one object a host hands factory for its sandboxes. Extend it to get the
* brand. It owns the session sandbox constructor, the repo template factory, the schema of user-tunable
* settings, and optionally the builds capability.
*
* `create` is synchronous and returns a `MastraSandbox`: factory constructs
* the sandbox inside a synchronous memo and relies on the base class for the
* start lifecycle and the runtime env. Construction must be cheap and
* side-effect-free; VMs are provisioned on `start()` only. Local sandboxes
* should root their `workingDirectory` at a per-session directory.
*
* `settings` is authored in any flavor `PublicSchema` accepts (zod, JSON
* Schema, or a Standard Schema that can emit JSON Schema). Factory normalizes
* it and serves the input-side JSON Schema on the wire. Every field must be
* optional: an absent setting means the provider default. Providers may
* ignore `ctx.resolveHead` and resolve heads themselves.
*/
var FactorySandbox = class {
/** Brand factory detects the class by; never test by shape. */
[FACTORY_SANDBOX_BRAND] = true;
/** Defaults to no settings; override with the provider's schema. */
settings = NO_SETTINGS;
builds;
};
/** True for any object carrying the `FactorySandbox` brand. */
function isFactorySandbox(value) {
return typeof value === "object" && value !== null && FACTORY_SANDBOX_BRAND in value && value[FACTORY_SANDBOX_BRAND] === true;
}
/** The settings schema as a Standard Schema with JSON Schema output. */
function normalizeFactorySandboxSettings(sandbox) {
return (0, _mastra_schema_compat_schema.toStandardSchema)(sandbox.settings);
}
/** The wire description of a `FactorySandbox`: provider, JSON Schema settings, capabilities. */
function describeFactorySandbox(sandbox) {
return {
provider: sandbox.provider,
settingsSchema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(normalizeFactorySandboxSettings(sandbox), {
target: "draft-07",
io: "input"
}),
capabilities: {
template: typeof sandbox.template === "function",
builds: {
available: sandbox.builds !== void 0,
history: typeof sandbox.builds?.list === "function"
}
}
};
}
Object.defineProperty(exports, "BrowserCliHandler", {
enumerable: true,
get: function() {
return BrowserCliHandler;
}
});
Object.defineProperty(exports, "CompositeFilesystem", {
enumerable: true,
get: function() {
return CompositeFilesystem;
}
});
Object.defineProperty(exports, "CompositeVersionedSkillSource", {
enumerable: true,
get: function() {
return CompositeVersionedSkillSource;
}
});
Object.defineProperty(exports, "DEFAULT_TAIL_LINES", {
enumerable: true,
get: function() {
return DEFAULT_TAIL_LINES;
}
});
Object.defineProperty(exports, "FACTORY_SANDBOX_BRAND", {
enumerable: true,
get: function() {
return FACTORY_SANDBOX_BRAND;
}
});
Object.defineProperty(exports, "FactorySandbox", {
enumerable: true,
get: function() {
return FactorySandbox;
}
});
Object.defineProperty(exports, "FilesystemNotMountableError", {
enumerable: true,
get: function() {
return FilesystemNotMountableError;
}
});
Object.defineProperty(exports, "IsolationUnavailableError", {
enumerable: true,
get: function() {
return IsolationUnavailableError;
}
});
Object.defineProperty(exports, "LocalFilesystem", {
enumerable: true,
get: function() {
return LocalFilesystem;
}
});
Object.defineProperty(exports, "LocalSandbox", {
enumerable: true,
get: function() {
return LocalSandbox;
}
});
Object.defineProperty(exports, "MAX_SANDBOX_FILE_MODE", {
enumerable: true,
get: function() {
return MAX_SANDBOX_FILE_MODE;
}
});
Object.defineProperty(exports, "MastraFilesystem", {
enumerable: true,
get: function() {
return MastraFilesystem;
}
});
Object.defineProperty(exports, "MastraSandbox", {
enumerable: true,
get: function() {
return MastraSandbox;
}
});
Object.defineProperty(exports, "MountError", {
enumerable: true,
get: function() {
return MountError;
}
});
Object.defineProperty(exports, "MountManager", {
enumerable: true,
get: function() {
return MountManager;
}
});
Object.defineProperty(exports, "MountNotSupportedError", {
enumerable: true,
get: function() {
return MountNotSupportedError;
}
});
Object.defineProperty(exports, "ProcessHandle", {
enumerable: true,
get: function() {
return ProcessHandle;
}
});
Object.defineProperty(exports, "SandboxAbortError", {
enumerable: true,
get: function() {
return SandboxAbortError;
}
});
Object.defineProperty(exports, "SandboxError", {
enumerable: true,
get: function() {
return SandboxError;
}
});
Object.defineProperty(exports, "SandboxExecutionError", {
enumerable: true,
get: function() {
return SandboxExecutionError;
}
});
Object.defineProperty(exports, "SandboxNotReadyError", {
enumerable: true,
get: function() {
return SandboxNotReadyError;
}
});
Object.defineProperty(exports, "SandboxProcessManager", {
enumerable: true,
get: function() {
return SandboxProcessManager;
}
});
Object.defineProperty(exports, "SandboxTimeoutError", {
enumerable: true,
get: function() {
return SandboxTimeoutError;
}
});
Object.defineProperty(exports, "SandboxUnsupportedFeatureError", {
enumerable: true,
get: function() {
return SandboxUnsupportedFeatureError;
}
});
Object.defineProperty(exports, "UnsupportedStdinCloseError", {
enumerable: true,
get: function() {
return UnsupportedStdinCloseError;
}
});
Object.defineProperty(exports, "VersionedSkillSource", {
enumerable: true,
get: function() {
return VersionedSkillSource;
}
});
Object.defineProperty(exports, "WORKSPACE_TOOLS", {
enumerable: true,
get: function() {
return WORKSPACE_TOOLS;
}
});
Object.defineProperty(exports, "WORKSPACE_TOOLS_PREFIX", {
enumerable: true,
get: function() {
return WORKSPACE_TOOLS_PREFIX;
}
});
Object.defineProperty(exports, "Workspace", {
enumerable: true,
get: function() {
return Workspace;
}
});
Object.defineProperty(exports, "applyPatchTool", {
enumerable: true,
get: function() {
return applyPatchTool;
}
});
Object.defineProperty(exports, "assertModesUnsupported", {
enumerable: true,
get: function() {
return assertModesUnsupported;
}
});
Object.defineProperty(exports, "browserCliHandler", {
enumerable: true,
get: function() {
return browserCliHandler;
}
});
Object.defineProperty(exports, "callLifecycle", {
enumerable: true,
get: function() {
return callLifecycle;
}
});
Object.defineProperty(exports, "collectSkillForPublish", {
enumerable: true,
get: function() {
return collectSkillForPublish;
}
});
Object.defineProperty(exports, "createSkillTools", {
enumerable: true,
get: function() {
return createSkillTools;
}
});
Object.defineProperty(exports, "createWorkspaceTools", {
enumerable: true,
get: function() {
return createWorkspaceTools;
}
});
Object.defineProperty(exports, "deleteFileTool", {
enumerable: true,
get: function() {
return deleteFileTool;
}
});
Object.defineProperty(exports, "describeFactorySandbox", {
enumerable: true,
get: function() {
return describeFactorySandbox;
}
});
Object.defineProperty(exports, "detectIsolation", {
enumerable: true,
get: function() {
return detectIsolation;
}
});
Object.defineProperty(exports, "editFileTool", {
enumerable: true,
get: function() {
return editFileTool;
}
});
Object.defineProperty(exports, "estimateTokenCount", {
enumerable: true,
get: function() {
return estimateTokenCount;
}
});
Object.defineProperty(exports, "evaluateReadRecord", {
enumerable: true,
get: function() {
return evaluateReadRecord;
}
});
Object.defineProperty(exports, "executeCommandTool", {
enumerable: true,
get: function() {
return executeCommandTool;
}
});
Object.defineProperty(exports, "fileStatTool", {
enumerable: true,
get: function() {
return fileStatTool;
}
});
Object.defineProperty(exports, "formatSkillActivation", {
enumerable: true,
get: function() {
return formatSkillActivation;
}
});
Object.defineProperty(exports, "getRecommendedIsolation", {
enumerable: true,
get: function() {
return getRecommendedIsolation;
}
});
Object.defineProperty(exports, "indexContentTool", {
enumerable: true,
get: function() {
return indexContentTool;
}
});
Object.defineProperty(exports, "isFactorySandbox", {
enumerable: true,
get: function() {
return isFactorySandbox;
}
});
Object.defineProperty(exports, "isIsolationAvailable", {
enumerable: true,
get: function() {
return isIsolationAvailable;
}
});
Object.defineProperty(exports, "listFilesTool", {
enumerable: true,
get: function() {
return listFilesTool;
}
});
Object.defineProperty(exports, "mkdirTool", {
enumerable: true,
get: function() {
return mkdirTool;
}
});
Object.defineProperty(exports, "normalizeFactorySandboxSettings", {
enumerable: true,
get: function() {
return normalizeFactorySandboxSettings;
}
});
Object.defineProperty(exports, "normalizeReadTrackerPath", {
enumerable: true,
get: function() {
return normalizeReadTrackerPath;
}
});
Object.defineProperty(exports, "publishSkillFromSource", {
enumerable: true,
get: function() {
return publishSkillFromSource;
}
});
Object.defineProperty(exports, "readFileTool", {
enumerable: true,
get: function() {
return readFileTool;
}
});
Object.defineProperty(exports, "requireFilesystem", {
enumerable: true,
get: function() {
return requireFilesystem;
}
});
Object.defineProperty(exports, "requireSandbox", {
enumerable: true,
get: function() {
return requireSandbox;
}
});
Object.defineProperty(exports, "requireWorkspace", {
enumerable: true,
get: function() {
return requireWorkspace;
}
});
Object.defineProperty(exports, "resolveToolConfig", {
enumerable: true,
get: function() {
return resolveToolConfig;
}
});
Object.defineProperty(exports, "searchTool", {
enumerable: true,
get: function() {
return searchTool;
}
});
Object.defineProperty(exports, "shellQuote", {
enumerable: true,
get: function() {
return shellQuote;
}
});
Object.defineProperty(exports, "sliceByTokens", {
enumerable: true,
get: function() {
return sliceByTokens;
}
});
Object.defineProperty(exports, "sliceByTokensSafe", {
enumerable: true,
get: function() {
return sliceByTokensSafe;
}
});
Object.defineProperty(exports, "supportsComputer", {
enumerable: true,
get: function() {
return supportsComputer;
}
});
Object.defineProperty(exports, "supportsNetworking", {
enumerable: true,
get: function() {
return supportsNetworking;
}
});
Object.defineProperty(exports, "truncateOutput", {
enumerable: true,
get: function() {
return truncateOutput;
}
});
Object.defineProperty(exports, "validateSandboxFileMode", {
enumerable: true,
get: function() {
return validateSandboxFileMode;
}
});
Object.defineProperty(exports, "writeFileTool", {
enumerable: true,
get: function() {
return writeFileTool;
}
});
//# sourceMappingURL=workspace-BVFsqhNw.cjs.map