{"version":3,"file":"index.mjs","names":["extension","result: FileEntry[]","parts: string[]","quote: \"single\" | \"double\" | undefined"],"sources":["../../src/mastra/index.ts"],"sourcesContent":["import {\n  DirectoryNotEmptyError,\n  DirectoryNotFoundError,\n  FileExistsError,\n  FileNotFoundError,\n  IsDirectoryError,\n  MastraFilesystem,\n  MastraSandbox,\n  NotDirectoryError,\n  PermissionError,\n  ProcessHandle,\n  SandboxNotReadyError,\n  SandboxProcessManager,\n  StaleFileError,\n  Workspace,\n  WorkspaceReadOnlyError,\n} from \"@mastra/core/workspace\";\nimport type {\n  CommandResult,\n  CopyOptions,\n  FileContent,\n  FileEntry,\n  FilesystemInfo,\n  InstructionsOption,\n  ListOptions,\n  MastraFilesystemOptions,\n  MastraSandboxOptions,\n  ProcessInfo,\n  ProviderStatus,\n  ReadOptions,\n  RemoveOptions,\n  SandboxInfo,\n  SpawnProcessOptions,\n  WorkspaceConfig,\n  WriteOptions,\n} from \"@mastra/core/workspace\";\nimport type { RequestContext } from \"@mastra/core/di\";\nimport { isSandboxError, SandboxError } from \"../core/errors\";\nimport type {\n  ManagedSandboxProvider,\n  ManagedSandboxSession,\n  SandboxProvider,\n} from \"../core/provider\";\nimport type { Sandbox, SandboxDirectoryEntry, SandboxProcess } from \"../core/types\";\n\ntype WorkspaceOptions = Omit<\n  WorkspaceConfig<SandboxSDKMastraFilesystem, SandboxSDKMastraSandbox>,\n  \"filesystem\" | \"sandbox\" | \"mounts\"\n>;\n\nexport interface CreateMastraSandboxOptions extends Omit<MastraSandboxOptions, \"processes\"> {\n  provider: SandboxProvider<unknown>;\n  id?: string;\n  identity?: string;\n  cwd?: string;\n  env?: Readonly<Record<string, string>>;\n  ports?: ReadonlyArray<number>;\n  instructions?: InstructionsOption;\n  onFirstCreate?: (sandbox: Sandbox) => void | Promise<void>;\n}\n\nexport interface CreateMastraWorkspaceOptions extends CreateMastraSandboxOptions {\n  filesystem?: Omit<CreateMastraFilesystemOptions, \"sandbox\">;\n  workspace?: WorkspaceOptions;\n}\n\nexport interface CreateMastraFilesystemOptions extends MastraFilesystemOptions {\n  sandbox: SandboxSDKMastraSandbox;\n  readOnly?: boolean;\n  instructions?: InstructionsOption;\n}\n\n/** Create a Mastra sandbox backed by any managed Sandbox SDK provider. */\nexport function createMastraSandbox(options: CreateMastraSandboxOptions): SandboxSDKMastraSandbox {\n  return new SandboxSDKMastraSandbox(options);\n}\n\n/**\n * Create a Mastra workspace whose filesystem and commands share one Sandbox SDK\n * session. The workspace owns and destroys the session.\n */\nexport function createMastraWorkspace(\n  options: CreateMastraWorkspaceOptions,\n): Workspace<SandboxSDKMastraFilesystem, SandboxSDKMastraSandbox> {\n  const sandbox = createMastraSandbox(options);\n  const filesystem = new SandboxSDKMastraFilesystem({ ...options.filesystem, sandbox });\n  return new Workspace({ ...options.workspace, filesystem, sandbox });\n}\n\n/** Mastra WorkspaceSandbox implementation for Sandbox SDK providers. */\nexport class SandboxSDKMastraSandbox extends MastraSandbox {\n  readonly id: string;\n  readonly name: string;\n  readonly provider: string;\n  readonly cwd: string;\n  readonly processes: SandboxSDKProcessManager;\n  status: ProviderStatus = \"pending\";\n\n  private readonly managed: ManagedSandboxProvider;\n  private readonly identity?: string;\n  private readonly env: Readonly<Record<string, string>>;\n  private readonly ports: ReadonlyArray<number>;\n  private readonly instructions?: InstructionsOption;\n  private readonly onFirstCreate?: (sandbox: Sandbox) => void | Promise<void>;\n  private readonly createdAt = new Date();\n  private session?: ManagedSandboxSession;\n\n  constructor(options: CreateMastraSandboxOptions) {\n    const processes = new SandboxSDKProcessManager({ env: options.env });\n    super({ ...options, name: \"Sandbox SDK\", processes });\n    this.managed = requireManaged(options.provider);\n    this.id = options.id ?? `mastra-${options.provider.id}-${crypto.randomUUID()}`;\n    this.name = `Sandbox SDK (${options.provider.id})`;\n    this.provider = options.provider.id;\n    this.cwd = normalizeCwd(options.cwd ?? \"/workspace\");\n    this.env = options.env ?? {};\n    this.ports = options.ports ?? [];\n    this.identity = options.identity;\n    this.instructions = options.instructions;\n    this.onFirstCreate = options.onFirstCreate;\n    this.processes = processes;\n  }\n\n  /** The live normalized Sandbox SDK session. */\n  get sandboxSdk(): Sandbox {\n    if (!this.session) throw new SandboxNotReadyError(this.id);\n    return this.session.sandbox;\n  }\n\n  async start(): Promise<void> {\n    if (this.session) {\n      await this.session.resume();\n      return;\n    }\n    this.session = await this.managed.create({\n      sessionId: this.id,\n      identity: this.identity,\n      cwd: this.cwd,\n      env: this.env,\n      ports: this.ports,\n      onFirstCreate: this.onFirstCreate,\n    });\n  }\n\n  async stop(): Promise<void> {\n    if (!this.session) return;\n    await this.killTrackedProcesses();\n    await this.session.stop();\n  }\n\n  async destroy(): Promise<void> {\n    if (!this.session) return;\n    await this.killTrackedProcesses();\n    const session = this.session;\n    this.session = undefined;\n    await session.destroy();\n  }\n\n  async getPortUrl(port: number, protocol?: \"http\" | \"https\" | \"ws\"): Promise<string> {\n    await this.ensureRunning();\n    return this.session!.getPortUrl({ port, protocol });\n  }\n\n  getInfo(): SandboxInfo {\n    return {\n      id: this.id,\n      name: this.name,\n      provider: this.provider,\n      status: this.status,\n      createdAt: this.createdAt,\n      metadata: {\n        sandboxId: this.session?.sandbox.id,\n        sandboxProvider: this.provider,\n        cwd: this.cwd,\n        capabilities: this.session?.sandbox.capabilities,\n      },\n    };\n  }\n\n  getInstructions(options?: { requestContext?: RequestContext }): string {\n    const defaultInstructions =\n      `Commands run in an isolated ${this.provider} sandbox. ` +\n      `The default working directory is ${this.cwd}.`;\n    if (this.instructions === undefined) return defaultInstructions;\n    if (typeof this.instructions === \"string\") return this.instructions;\n    return this.instructions({\n      defaultInstructions,\n      requestContext: options?.requestContext,\n    });\n  }\n\n  /** @deprecated Use `status === \"running\"` instead. */\n  isReady(): boolean {\n    return this.status === \"running\" && this.session !== undefined;\n  }\n\n  private async killTrackedProcesses(): Promise<void> {\n    const processes = await this.processes.list().catch(() => []);\n    await Promise.all(\n      processes\n        .filter((process) => process.running)\n        .map((process) => this.processes.kill(process.pid).catch(() => false)),\n    );\n  }\n}\n\n/** Mastra background-process bridge for normalized Sandbox SDK processes. */\nexport class SandboxSDKProcessManager extends SandboxProcessManager<SandboxSDKMastraSandbox> {\n  async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n    const env = Object.fromEntries(\n      Object.entries({ ...this.env, ...options.env }).filter(\n        (entry): entry is [string, string] => entry[1] !== undefined,\n      ),\n    );\n    const process = await this.sandbox.sandboxSdk.processes.start(\n      parseSimpleCommand(command) ?? command,\n      {\n        cwd: options.cwd,\n        env,\n        timeout: options.timeout,\n        signal: options.abortSignal,\n      },\n    );\n    const handle = new SandboxSDKProcessHandle(process, options);\n    this._tracked.set(handle.pid, handle);\n    return handle;\n  }\n\n  async list(): Promise<ProcessInfo[]> {\n    return Promise.all(\n      [...this._tracked.values()].map(async (handle) => {\n        const adapter = handle as SandboxSDKProcessHandle;\n        return {\n          pid: handle.pid,\n          command: handle.command,\n          running: await adapter.isRunning(),\n          ...(handle.exitCode === undefined ? {} : { exitCode: handle.exitCode }),\n        };\n      }),\n    );\n  }\n}\n\nclass SandboxSDKProcessHandle extends ProcessHandle {\n  readonly pid: string;\n  private readonly process: SandboxProcess;\n  private readonly startedAt = performance.now();\n  private readonly completed: Promise<CommandResult>;\n  private currentExitCode?: number;\n  private killed = false;\n  private timedOut = false;\n  private timeoutId?: ReturnType<typeof setTimeout>;\n\n  constructor(process: SandboxProcess, options: SpawnProcessOptions) {\n    super(options);\n    this.process = process;\n    this.pid = process.id;\n    if (options.timeout !== undefined && options.timeout > 0) {\n      this.timeoutId = setTimeout(() => {\n        this.timedOut = true;\n        void this.kill();\n      }, options.timeout);\n    }\n    this.completed = this.collect();\n  }\n\n  get exitCode(): number | undefined {\n    return this.currentExitCode;\n  }\n\n  async wait(): Promise<CommandResult> {\n    return this.completed;\n  }\n\n  async kill(): Promise<boolean> {\n    if (this.currentExitCode !== undefined) return false;\n    this.killed = true;\n    await this.process.kill();\n    return true;\n  }\n\n  async sendStdin(data: string): Promise<void> {\n    if (this.currentExitCode !== undefined) {\n      throw new Error(`Process ${this.pid} has already exited with code ${this.currentExitCode}`);\n    }\n    await this.process.write(data);\n  }\n\n  async isRunning(): Promise<boolean> {\n    if (this.currentExitCode !== undefined) return false;\n    const status = await this.process.status();\n    return status === \"starting\" || status === \"running\";\n  }\n\n  private async collect(): Promise<CommandResult> {\n    const output = this.pumpOutput();\n    try {\n      const result = await this.process.wait();\n      this.currentExitCode = this.timedOut ? 124 : result.exitCode;\n      await output;\n    } catch (error) {\n      await output.catch(() => undefined);\n      if (isSandboxError(error) && error.code === \"timeout\") {\n        this.timedOut = true;\n      }\n      this.currentExitCode = this.timedOut ? 124 : 1;\n      this.emitStderr(error instanceof Error ? error.message : String(error));\n    } finally {\n      if (this.timeoutId) clearTimeout(this.timeoutId);\n    }\n    return {\n      success: this.currentExitCode === 0,\n      exitCode: this.currentExitCode,\n      stdout: this.stdout,\n      stderr: this.stderr,\n      executionTimeMs: Math.round(performance.now() - this.startedAt),\n      ...(this.killed ? { killed: true } : {}),\n      ...(this.timedOut ? { timedOut: true } : {}),\n    };\n  }\n\n  private async pumpOutput(): Promise<void> {\n    const decoders = {\n      stdout: new TextDecoder(),\n      stderr: new TextDecoder(),\n    };\n    try {\n      for await (const event of this.process.output()) {\n        const data =\n          typeof event.data === \"string\"\n            ? event.data\n            : decoders[event.stream].decode(event.data, { stream: true });\n        if (data) {\n          if (event.stream === \"stdout\") this.emitStdout(data);\n          else this.emitStderr(data);\n        }\n      }\n    } finally {\n      const stdout = decoders.stdout.decode();\n      const stderr = decoders.stderr.decode();\n      if (stdout) this.emitStdout(stdout);\n      if (stderr) this.emitStderr(stderr);\n    }\n  }\n}\n\n/** Mastra WorkspaceFilesystem implementation sharing a Mastra sandbox session. */\nexport class SandboxSDKMastraFilesystem extends MastraFilesystem {\n  readonly id: string;\n  readonly name = \"Sandbox SDK Filesystem\";\n  readonly provider = \"sandbox-sdk\";\n  readonly readOnly: boolean;\n  readonly basePath: string;\n  status: ProviderStatus = \"pending\";\n\n  private readonly sandbox: SandboxSDKMastraSandbox;\n  private readonly instructions?: InstructionsOption;\n\n  constructor(options: CreateMastraFilesystemOptions) {\n    super({ ...options, name: \"Sandbox SDK Filesystem\" });\n    this.sandbox = options.sandbox;\n    this.id = `${options.sandbox.id}-filesystem`;\n    this.basePath = options.sandbox.cwd;\n    this.readOnly = options.readOnly ?? false;\n    this.instructions = options.instructions;\n  }\n\n  async init(): Promise<void> {}\n\n  async destroy(): Promise<void> {}\n\n  getInfo(): FilesystemInfo {\n    return {\n      id: this.id,\n      name: this.name,\n      provider: this.provider,\n      status: this.status,\n      readOnly: this.readOnly,\n      metadata: {\n        sandboxId: this.sandbox.id,\n        sandboxProvider: this.sandbox.provider,\n        basePath: this.basePath,\n      },\n    };\n  }\n\n  getInstructions(options?: { requestContext?: RequestContext }): string {\n    const defaultInstructions =\n      `Files are stored in the same ${this.sandbox.provider} sandbox used for commands. ` +\n      `Filesystem path / maps to ${this.basePath} inside the sandbox.`;\n    if (this.instructions === undefined) return defaultInstructions;\n    if (typeof this.instructions === \"string\") return this.instructions;\n    return this.instructions({\n      defaultInstructions,\n      requestContext: options?.requestContext,\n    });\n  }\n\n  async realpath(path: string): Promise<string> {\n    await this.ready();\n    const virtual = toVirtualPath(this.basePath, path);\n    const result = await this.sandbox.sandboxSdk.run({\n      command: \"realpath\",\n      args: [\"-m\", toSandboxPath(this.basePath, virtual)],\n    });\n    if (!result.success) return virtual;\n    const resolved = result.stdout.trim();\n    if (!isWithin(this.basePath, resolved)) {\n      throw new PermissionError(path, \"realpath\");\n    }\n    return fromSandboxPath(this.basePath, resolved);\n  }\n\n  async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n    await this.ready();\n    const stat = await this.stat(path);\n    if (stat.type === \"directory\") throw new IsDirectoryError(path);\n    try {\n      const content = Buffer.from(\n        await this.sandbox.sandboxSdk.files.read(toSandboxPath(this.basePath, path)),\n      );\n      return options?.encoding ? content.toString(options.encoding) : content;\n    } catch (error) {\n      throw mapFileError(path, \"read\", error);\n    }\n  }\n\n  async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n    await this.ready();\n    this.assertWritable(\"writeFile\");\n    const target = toSandboxPath(this.basePath, path);\n    const exists = await this.exists(path);\n    if (exists && options?.overwrite === false) throw new FileExistsError(path);\n    if (exists) {\n      const current = await this.stat(path);\n      if (current.type === \"directory\") throw new IsDirectoryError(path);\n      if (\n        options?.expectedMtime &&\n        current.modifiedAt.getTime() !== options.expectedMtime.getTime()\n      ) {\n        throw new StaleFileError(path, options.expectedMtime, current.modifiedAt);\n      }\n    }\n    await this.ensureParent(path, options?.recursive !== false);\n    try {\n      await this.sandbox.sandboxSdk.files.write(target, toBytes(content));\n    } catch (error) {\n      throw mapFileError(path, \"write\", error);\n    }\n  }\n\n  async appendFile(path: string, content: FileContent): Promise<void> {\n    await this.ready();\n    this.assertWritable(\"appendFile\");\n    const current = (await this.exists(path))\n      ? Buffer.from(await this.readFile(path))\n      : Buffer.alloc(0);\n    const added = Buffer.from(toBytes(content));\n    const combined = new Uint8Array(current.byteLength + added.byteLength);\n    combined.set(current);\n    combined.set(added, current.byteLength);\n    await this.writeFile(path, combined);\n  }\n\n  async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n    await this.ready();\n    this.assertWritable(\"deleteFile\");\n    if (!(await this.exists(path))) {\n      if (options?.force) return;\n      throw new FileNotFoundError(path);\n    }\n    if ((await this.stat(path)).type === \"directory\") {\n      throw new IsDirectoryError(path);\n    }\n    try {\n      await this.sandbox.sandboxSdk.files.remove(toSandboxPath(this.basePath, path));\n    } catch (error) {\n      throw mapFileError(path, \"delete\", error);\n    }\n  }\n\n  async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n    await this.ready();\n    this.assertWritable(\"copyFile\");\n    if (!(await this.exists(src))) throw new FileNotFoundError(src);\n    if ((await this.exists(dest)) && options?.overwrite === false) {\n      throw new FileExistsError(dest);\n    }\n    const source = await this.stat(src);\n    if (source.type === \"directory\") {\n      if (!options?.recursive) throw new IsDirectoryError(src);\n      await this.mkdir(dest, { recursive: true });\n      for (const entry of await this.readdir(src)) {\n        await this.copyFile(joinVirtual(src, entry.name), joinVirtual(dest, entry.name), options);\n      }\n      return;\n    }\n    await this.writeFile(dest, await this.readFile(src), {\n      recursive: true,\n      overwrite: options?.overwrite,\n    });\n  }\n\n  async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n    this.assertWritable(\"moveFile\");\n    const source = await this.stat(src);\n    await this.copyFile(src, dest, {\n      ...options,\n      recursive: source.type === \"directory\" ? true : options?.recursive,\n    });\n    if (source.type === \"directory\") {\n      await this.rmdir(src, { recursive: true });\n    } else {\n      await this.deleteFile(src);\n    }\n  }\n\n  async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n    await this.ready();\n    this.assertWritable(\"mkdir\");\n    if (await this.exists(path)) {\n      if ((await this.stat(path)).type !== \"directory\") {\n        throw new FileExistsError(path);\n      }\n      return;\n    }\n    if (options?.recursive === false) await this.requireParent(path);\n    try {\n      await this.sandbox.sandboxSdk.files.mkdir(toSandboxPath(this.basePath, path));\n    } catch (error) {\n      throw mapFileError(path, \"mkdir\", error);\n    }\n  }\n\n  async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n    await this.ready();\n    this.assertWritable(\"rmdir\");\n    if (!(await this.exists(path))) {\n      if (options?.force) return;\n      throw new DirectoryNotFoundError(path);\n    }\n    if ((await this.stat(path)).type !== \"directory\") {\n      throw new NotDirectoryError(path);\n    }\n    if (!options?.recursive && (await this.readdir(path)).length > 0) {\n      throw new DirectoryNotEmptyError(path);\n    }\n    try {\n      await this.sandbox.sandboxSdk.files.remove(toSandboxPath(this.basePath, path));\n    } catch (error) {\n      throw mapFileError(path, \"rmdir\", error);\n    }\n  }\n\n  async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n    await this.ready();\n    if (!(await this.exists(path))) throw new DirectoryNotFoundError(path);\n    if ((await this.stat(path)).type !== \"directory\") {\n      throw new NotDirectoryError(path);\n    }\n    const extensions = options?.extension\n      ? new Set(\n          (Array.isArray(options.extension) ? options.extension : [options.extension]).map(\n            (extension) => (extension.startsWith(\".\") ? extension : `.${extension}`),\n          ),\n        )\n      : undefined;\n    return this.listDirectory(path, options?.recursive ? (options.maxDepth ?? 100) : 0, extensions);\n  }\n\n  async exists(path: string): Promise<boolean> {\n    await this.ready();\n    return this.sandbox.sandboxSdk.files.exists(toSandboxPath(this.basePath, path));\n  }\n\n  async stat(path: string) {\n    await this.ready();\n    const virtual = toVirtualPath(this.basePath, path);\n    const target = toSandboxPath(this.basePath, virtual);\n    if (virtual === \"/\") {\n      return directoryStat(\"\", \"/\");\n    }\n    if (!(await this.sandbox.sandboxSdk.files.exists(target))) {\n      throw new FileNotFoundError(path);\n    }\n    const native = await this.nativeStat(target);\n    if (native) {\n      return {\n        name: basename(virtual),\n        path: virtual,\n        type: native.type,\n        size: native.size,\n        createdAt: native.createdAt,\n        modifiedAt: native.modifiedAt,\n      };\n    }\n    const entry = await this.findEntry(target);\n    if (!entry) throw new FileNotFoundError(path);\n    const timestamp = new Date(0);\n    return {\n      name: entry.name,\n      path: virtual,\n      type: entry.type === \"directory\" ? (\"directory\" as const) : (\"file\" as const),\n      size: entry.size ?? 0,\n      createdAt: timestamp,\n      modifiedAt: timestamp,\n    };\n  }\n\n  private async ready(): Promise<void> {\n    await this.ensureReady();\n    await this.sandbox.ensureRunning();\n  }\n\n  private assertWritable(operation: string): void {\n    if (this.readOnly) throw new WorkspaceReadOnlyError(operation);\n  }\n\n  private async ensureParent(path: string, recursive: boolean): Promise<void> {\n    const parent = dirname(toVirtualPath(this.basePath, path));\n    if (parent === \"/\") return;\n    if (recursive) await this.mkdir(parent, { recursive: true });\n    else await this.requireParent(path);\n  }\n\n  private async requireParent(path: string): Promise<void> {\n    const parent = dirname(toVirtualPath(this.basePath, path));\n    if (!(await this.exists(parent))) throw new DirectoryNotFoundError(parent);\n    if ((await this.stat(parent)).type !== \"directory\") {\n      throw new NotDirectoryError(parent);\n    }\n  }\n\n  private async listDirectory(\n    path: string,\n    depth: number,\n    extensions?: ReadonlySet<string>,\n  ): Promise<FileEntry[]> {\n    const entries = await this.sandbox.sandboxSdk.files.list(toSandboxPath(this.basePath, path));\n    const result: FileEntry[] = [];\n    for (const entry of entries) {\n      const type = entry.type === \"directory\" ? \"directory\" : \"file\";\n      if (type === \"file\" && extensions && !extensions.has(extension(entry.name))) {\n        continue;\n      }\n      result.push({\n        name: entry.name,\n        type,\n        ...(entry.size === undefined ? {} : { size: entry.size }),\n        ...(entry.type === \"symlink\" ? { isSymlink: true } : {}),\n      });\n      if (depth > 0 && type === \"directory\") {\n        const childPath = joinVirtual(path, entry.name);\n        const children = await this.listDirectory(childPath, depth - 1, extensions);\n        result.push(\n          ...children.map((child) => ({\n            ...child,\n            name: `${entry.name}/${child.name}`,\n          })),\n        );\n      }\n    }\n    return result;\n  }\n\n  private async findEntry(target: string): Promise<SandboxDirectoryEntry | undefined> {\n    const parent = dirname(target);\n    const entries = await this.sandbox.sandboxSdk.files.list(parent);\n    return entries.find((entry) => entry.path === target);\n  }\n\n  private async nativeStat(target: string): Promise<\n    | {\n        type: \"file\" | \"directory\";\n        size: number;\n        createdAt: Date;\n        modifiedAt: Date;\n      }\n    | undefined\n  > {\n    try {\n      const result = await this.sandbox.sandboxSdk.run({\n        command: \"stat\",\n        args: [\"-c\", \"%F|%s|%W|%Y\", target],\n      });\n      if (!result.success) return undefined;\n      const [kind, sizeValue, createdValue, modifiedValue] = result.stdout.trim().split(\"|\");\n      if (!kind || !sizeValue || !createdValue || !modifiedValue) {\n        return undefined;\n      }\n      const modified = Number(modifiedValue) * 1_000;\n      const createdSeconds = Number(createdValue);\n      return {\n        type: kind.includes(\"directory\") ? \"directory\" : \"file\",\n        size: Number(sizeValue),\n        createdAt: new Date((createdSeconds > 0 ? createdSeconds : Number(modifiedValue)) * 1_000),\n        modifiedAt: new Date(modified),\n      };\n    } catch {\n      return undefined;\n    }\n  }\n}\n\nfunction requireManaged(provider: SandboxProvider<unknown>): ManagedSandboxProvider {\n  if (!provider.managed) {\n    throw new SandboxError({\n      code: \"unsupported\",\n      provider: provider.id,\n      operation: \"mastra.createSandbox\",\n      message: `Provider ${provider.id} does not implement managed sandbox sessions`,\n    });\n  }\n  return provider.managed;\n}\n\nfunction normalizeCwd(value: string): string {\n  if (!value.startsWith(\"/\") || value.includes(\"\\0\")) {\n    throw new SandboxError({\n      code: \"invalid_input\",\n      provider: \"mastra\",\n      operation: \"cwd\",\n      message: \"cwd must be an absolute path\",\n    });\n  }\n  return value.replace(/\\/$/, \"\") || \"/\";\n}\n\nfunction toVirtualPath(cwd: string, value: string): string {\n  assertPath(value);\n  if (value === cwd) return \"/\";\n  if (value.startsWith(`${cwd}/`)) return `/${value.slice(cwd.length + 1)}`;\n  const absolute = value.startsWith(\"/\") ? value : `/${value}`;\n  return absolute.replace(/\\/{2,}/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n}\n\nfunction toSandboxPath(cwd: string, value: string): string {\n  const virtual = toVirtualPath(cwd, value);\n  return virtual === \"/\" ? cwd : `${cwd}${virtual}`;\n}\n\nfunction fromSandboxPath(cwd: string, value: string): string {\n  if (value === cwd) return \"/\";\n  if (!value.startsWith(`${cwd}/`)) throw new PermissionError(value, \"access\");\n  return `/${value.slice(cwd.length + 1)}`;\n}\n\nfunction assertPath(value: string): void {\n  if (!value || value.includes(\"\\0\") || value.split(\"/\").includes(\"..\")) {\n    throw new PermissionError(value, \"access\");\n  }\n}\n\nfunction isWithin(root: string, path: string): boolean {\n  return path === root || path.startsWith(`${root}/`);\n}\n\nfunction toBytes(content: FileContent): Uint8Array {\n  return typeof content === \"string\" ? new TextEncoder().encode(content) : new Uint8Array(content);\n}\n\nfunction basename(path: string): string {\n  return path.split(\"/\").filter(Boolean).at(-1) ?? \"\";\n}\n\nfunction dirname(path: string): string {\n  const parts = path.split(\"/\").filter(Boolean);\n  parts.pop();\n  return `/${parts.join(\"/\")}`.replace(/\\/$/, \"\") || \"/\";\n}\n\nfunction joinVirtual(parent: string, child: string): string {\n  return `${parent.replace(/\\/$/, \"\")}/${child}`.replace(/\\/{2,}/g, \"/\");\n}\n\nfunction extension(path: string): string {\n  const name = basename(path);\n  const index = name.lastIndexOf(\".\");\n  return index <= 0 ? \"\" : name.slice(index);\n}\n\n/**\n * Preserve argument boundaries for ordinary commands. Commands that use shell\n * syntax deliberately fall back to the provider's shell-string execution path.\n */\nfunction parseSimpleCommand(value: string): { command: string; args: string[] } | undefined {\n  const parts: string[] = [];\n  let current = \"\";\n  let tokenStarted = false;\n  let quote: \"single\" | \"double\" | undefined;\n\n  const finish = () => {\n    if (!tokenStarted) return;\n    parts.push(current);\n    current = \"\";\n    tokenStarted = false;\n  };\n\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index]!;\n    if (quote === \"single\") {\n      if (character === \"'\") quote = undefined;\n      else current += character;\n      tokenStarted = true;\n      continue;\n    }\n    if (quote === \"double\") {\n      if (character === '\"') {\n        quote = undefined;\n      } else if (character === \"\\\\\") {\n        const next = value[++index];\n        if (next === undefined) return undefined;\n        current += next;\n      } else if (character === \"$\" || character === \"`\") {\n        return undefined;\n      } else {\n        current += character;\n      }\n      tokenStarted = true;\n      continue;\n    }\n    if (/\\s/.test(character)) {\n      finish();\n      continue;\n    }\n    if (character === \"'\") {\n      quote = \"single\";\n      tokenStarted = true;\n      continue;\n    }\n    if (character === '\"') {\n      quote = \"double\";\n      tokenStarted = true;\n      continue;\n    }\n    if (character === \"\\\\\") {\n      const next = value[++index];\n      if (next === undefined) return undefined;\n      current += next;\n      tokenStarted = true;\n      continue;\n    }\n    if (\"|&;<>()$`*?[]{}~#\\n\\r\".includes(character)) return undefined;\n    current += character;\n    tokenStarted = true;\n  }\n  if (quote) return undefined;\n  finish();\n  const [command, ...args] = parts;\n  return command ? { command, args } : undefined;\n}\n\nfunction directoryStat(name: string, path: string) {\n  const timestamp = new Date(0);\n  return {\n    name,\n    path,\n    type: \"directory\" as const,\n    size: 0,\n    createdAt: timestamp,\n    modifiedAt: timestamp,\n  };\n}\n\nfunction mapFileError(path: string, operation: string, error: unknown): Error {\n  if (!isSandboxError(error)) return error instanceof Error ? error : new Error(String(error));\n  if (error.code === \"not_found\") return new FileNotFoundError(path);\n  if (error.code === \"permission\") return new PermissionError(path, operation);\n  if (error.code === \"conflict\") return new FileExistsError(path);\n  return error;\n}\n"],"mappings":";;;;;AAyEA,SAAgB,oBAAoB,SAA8D;AAChG,QAAO,IAAI,wBAAwB,QAAQ;;;;;;AAO7C,SAAgB,sBACd,SACgE;CAChE,MAAM,UAAU,oBAAoB,QAAQ;CAC5C,MAAM,aAAa,IAAI,2BAA2B;EAAE,GAAG,QAAQ;EAAY;EAAS,CAAC;AACrF,QAAO,IAAI,UAAU;EAAE,GAAG,QAAQ;EAAW;EAAY;EAAS,CAAC;;;AAIrE,IAAa,0BAAb,cAA6C,cAAc;CACzD,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,SAAyB;CAEzB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB,4BAAY,IAAI,MAAM;CACvC,AAAQ;CAER,YAAY,SAAqC;EAC/C,MAAM,YAAY,IAAI,yBAAyB,EAAE,KAAK,QAAQ,KAAK,CAAC;AACpE,QAAM;GAAE,GAAG;GAAS,MAAM;GAAe;GAAW,CAAC;AACrD,OAAK,UAAU,eAAe,QAAQ,SAAS;AAC/C,OAAK,KAAK,QAAQ,MAAM,UAAU,QAAQ,SAAS,GAAG,GAAG,OAAO,YAAY;AAC5E,OAAK,OAAO,gBAAgB,QAAQ,SAAS,GAAG;AAChD,OAAK,WAAW,QAAQ,SAAS;AACjC,OAAK,MAAM,aAAa,QAAQ,OAAO,aAAa;AACpD,OAAK,MAAM,QAAQ,OAAO,EAAE;AAC5B,OAAK,QAAQ,QAAQ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