본문으로 건너뛰기

로컬파일시스템

추가된 항목: @mastra/core@1.1.0

로컬 파일 시스템의 디렉터리에 파일을 저장합니다. 인터페이스에 대한 자세한 내용은 다음을 참조하세요.WorkspaceFilesystem Interface.

용법
용법에 대한 직접 링크

Workspace에 LocalFilesystem을 추가하고 Agent에 할당합니다. 그러면 Agent가 작업의 일부로 파일을 읽고 쓰고 관리할 수 있습니다:

import { Agent } from '@mastra/core/agent'
import { Workspace, LocalFilesystem } from '@mastra/core/workspace'

const workspace = new Workspace({
filesystem: new LocalFilesystem({
basePath: './workspace',
}),
})

const agent = new Agent({
id: 'file-agent',
model: 'openai/gpt-5.6-sol',
workspace,
})

// The agent now has filesystem tools available
const response = await agent.generate('List all files in the workspace')

생성자 매개변수
생성자 매개변수에 대한 직접 링크

basePath:

string
디스크의 기본 디렉터리 경로입니다. 모든 파일 경로는 이 디렉터리를 기준으로 해석됩니다.

id?:

string
= 자동 생성
이 파일 시스템 인스턴스의 고유 식별자

contained?:

boolean
= true
true이면 모든 파일 작업이 basePath 내부로 제한됩니다. 경로 순회 공격과 심볼릭 링크 이탈을 방지합니다. 격리를 참조하세요.

allowedPaths?:

string[]
= []
Agent가 basePath 외부에서 액세스할 수 있는 추가 디렉터리입니다.

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
getInstructions()에서 반환되는 기본 지침을 재정의하는 사용자 지정 지침입니다. 완전히 대체하려면 문자열을 전달하고, 요청별 사용자 지정을 위해 현재 requestContext에 액세스하면서 확장하려면 함수를 전달합니다.

readOnly?:

boolean
= false
true이면 모든 쓰기 작업이 차단됩니다. 읽기 작업은 계속 허용됩니다.

속성
속성에 대한 직접 링크

id:

string
파일 시스템 인스턴스 식별자

name:

string
Provider 이름('LocalFilesystem')

provider:

string
Provider 식별자('local')

basePath:

string
디스크의 절대 기본 경로

readOnly:

boolean | undefined
파일 시스템이 읽기 전용 모드인지 여부

allowedPaths:

readonly string[]
현재 해석된 허용 경로 집합입니다. 격리가 활성화된 경우 basePath 외부에서 이 경로들이 허용됩니다.

행동 양식
행동 양식에 대한 직접 링크

init()
init에 대한 직접 링크

파일 시스템을 초기화합니다. 존재하지 않는 경우 기본 디렉터리를 만듭니다.

await filesystem.init()

호출자workspace.init().

지연 초기화
지연 초기화에 대한 직접 링크

LocalFilesystem은 아직 초기화되지 않은 경우 첫 번째 작업에서 초기화되어 기본 디렉터리를 자동으로 생성합니다. init()을 명시적으로 호출하는 것은 선택 사항이지만 첫 번째 작업 전에 디렉터리를 미리 생성할 때 유용할 수 있습니다.

destroy()
destroy에 대한 직접 링크

파일 시스템 리소스를 정리합니다.

await filesystem.destroy()

호출자workspace.destroy().

setAllowedPaths(pathsOrUpdater)
setallowedpathspathsorupdater에 대한 직접 링크

런타임 시 허용된 경로를 업데이트합니다. 새 경로 배열(현재 대체) 또는 현재 경로를 수신하고 새 세트를 반환하는 업데이트 콜백을 허용합니다.

// Set directly
filesystem.setAllowedPaths(['/home/user/.config'])

// Update with callback
filesystem.setAllowedPaths(prev => [...prev, '/home/user/documents'])

// Clear all allowed paths
filesystem.setAllowedPaths([])

매개변수:

pathsOrUpdater:

string[] | ((current: readonly string[]) => string[])
새 허용 경로 배열 또는 현재 경로를 받는 업데이터 함수

readFile(path, options?)
readfilepath-options에 대한 직접 링크

파일 내용을 읽습니다.

const content = await filesystem.readFile('/docs/guide.md')
const buffer = await filesystem.readFile('/image.png', { encoding: 'binary' })

매개변수:

path:

string
basePath 기준 상대 파일 경로

options?:

Options
구성 옵션입니다.
Options

encoding?:

'utf-8' | 'binary'
텍스트 또는 바이너리 인코딩

writeFile(path, content, options?)
writefilepath-content-options에 대한 직접 링크

파일에 콘텐츠를 씁니다.

await filesystem.writeFile('/docs/new.md', '# New Document')
await filesystem.writeFile('/nested/path/file.md', content, { recursive: true })

매개변수:

path:

string
basePath 기준 상대 파일 경로

content:

string | Buffer
파일 콘텐츠

options?:

Options
구성 옵션입니다.
Options

recursive?:

boolean
상위 디렉터리가 없으면 생성

overwrite?:

boolean
기존 파일 덮어쓰기

expectedMtime?:

Date
제공된 경우 파일의 현재 수정 시간이 일치하지 않으면 StaleFileError와 함께 쓰기가 실패합니다. 읽기와 쓰기 사이의 외부 수정을 감지하는 낙관적 동시성 제어에 사용합니다.

appendFile(path, content)
appendfilepath-content에 대한 직접 링크

기존 파일에 콘텐츠를 추가합니다.

await filesystem.appendFile('/logs/app.log', 'New log entry\n')

매개변수:

path:

string
basePath 기준 상대 파일 경로

content:

string | Buffer
추가할 콘텐츠

deleteFile(path, options?)
deletefilepath-options에 대한 직접 링크

파일을 삭제합니다.

await filesystem.deleteFile('/docs/old.md')
await filesystem.deleteFile('/docs/maybe.md', { force: true }) // Don't throw if missing

매개변수:

path:

string
파일 경로

options?:

Options
구성 옵션입니다.
Options

force?:

boolean
파일이 없어도 오류를 발생시키지 않음

copyFile(src, dest, options?)
copyfilesrc-dest-options에 대한 직접 링크

파일을 새 위치에 복사합니다.

await filesystem.copyFile('/docs/template.md', '/docs/new-doc.md')
await filesystem.copyFile('/src/config.json', '/backup/config.json', { overwrite: false })

매개변수:

src:

string
원본 파일 경로

dest:

string
대상 파일 경로

options?:

Options
구성 옵션입니다.
Options

overwrite?:

boolean
대상이 존재하면 덮어쓰기

moveFile(src, dest, options?)
movefilesrc-dest-options에 대한 직접 링크

파일을 이동하거나 이름을 바꿉니다.

await filesystem.moveFile('/docs/draft.md', '/docs/final.md')
await filesystem.moveFile('/temp/upload.txt', '/files/document.txt')

매개변수:

src:

string
원본 파일 경로

dest:

string
대상 파일 경로

options?:

Options
구성 옵션입니다.
Options

overwrite?:

boolean
대상이 존재하면 덮어쓰기

mkdir(path, options?)
mkdirpath-options에 대한 직접 링크

디렉터리를 만듭니다.

await filesystem.mkdir('/docs/api')
await filesystem.mkdir('/deeply/nested/path', { recursive: true })

매개변수:

path:

string
디렉터리 경로

options?:

Options
구성 옵션입니다.
Options

recursive?:

boolean
상위 디렉터리 생성

rmdir(path, options?)
rmdirpath-options에 대한 직접 링크

디렉터리를 제거합니다.

await filesystem.rmdir('/docs/old')
await filesystem.rmdir('/docs/nested', { recursive: true })

매개변수:

path:

string
디렉터리 경로

options?:

Options
구성 옵션입니다.
Options

recursive?:

boolean
콘텐츠를 재귀적으로 제거

force?:

boolean
디렉터리가 없어도 예외를 발생시키지 않음

readdir(path, options?)
readdirpath-options에 대한 직접 링크

디렉터리 내용을 나열합니다.

const entries = await filesystem.readdir('/docs')
// [{ name: 'guide.md', type: 'file' }, { name: 'api', type: 'directory' }]

exists(path)
existspath에 대한 직접 링크

경로가 존재하는지 확인하십시오.

const exists = await filesystem.exists('/docs/guide.md')

stat(path)
statpath에 대한 직접 링크

파일 또는 디렉터리 메타데이터를 가져옵니다.

const stat = await filesystem.stat('/docs/guide.md')
// { type: 'file', size: 1234, modifiedAt: Date, createdAt: Date, path: '/docs/guide.md' }

getInfo()
getinfo에 대한 직접 링크

이 파일 시스템 인스턴스에 대한 메타데이터를 반환합니다.

const info = filesystem.getInfo()
// { id: '...', name: 'LocalFilesystem', provider: 'local', basePath: '/workspace', readOnly: false }

getInstructions(opts?)
getinstructionsopts에 대한 직접 링크

이 파일 시스템에서 경로가 작동하는 방식에 대한 설명을 반환합니다. Agent에 할당되면 Agent의 시스템 메시지에 삽입됩니다.

const instructions = filesystem.getInstructions()
// 'Local filesystem at "/workspace". Files at workspace path "/foo" are stored at "/workspace/foo" on disk.'

instructions 생성자 옵션이 함수인 경우 요청별 사용자 지정을 활성화하려면 requestContext를 전달합니다:

const instructions = filesystem.getInstructions({ requestContext })

매개변수:

opts.requestContext?:

RequestContext
생성자에 instructions 함수가 제공된 경우 해당 함수로 전달됩니다.

보고: string

기본 출력을 재정의하려면 생성자에 instructions 옵션을 전달합니다. 생성자 매개변수를 참조하세요.

경로 확인
경로 확인에 대한 직접 링크

어떻게basePath works
how-basepath-works에 대한 직접 링크

basePath 옵션은 모든 파일 작업의 루트 디렉터리를 설정합니다. readFile() 같은 메서드에 전달된 파일 경로는 이 기본 경로를 기준으로 해석됩니다:

  • 선행 슬래시는 제거됩니다./docs/guide.mddocs/guide.md
  • 경로가 정규화되고 basePath와 결합됩니다.
  • 결과:./workspace + docs/guide.md./workspace/docs/guide.md
const filesystem = new LocalFilesystem({
basePath: './workspace',
})

// These all resolve to ./workspace/docs/guide.md
await filesystem.readFile('/docs/guide.md')
await filesystem.readFile('docs/guide.md')

상대 경로 및 실행 컨텍스트
상대 경로 및 실행 컨텍스트에 대한 직접 링크

상대 basePath를 사용하면 process.cwd()를 기준으로 해석됩니다. Mastra 프로젝트에서는 코드 실행 방식에 따라 cwd가 달라집니다:

컨텍스트작업 디렉터리./workspace가 해석되는 경로
mastra dev./src/mastra/public/./src/mastra/public/workspace
mastra start./.mastra/output/./.mastra/output/workspace
직접 실행한 스크립트명령을 실행한 위치해당 위치 기준 상대 경로
동일한 상대 경로가 다른 위치로 확인되면 혼란이 발생할 수 있습니다.

모든 실행 컨텍스트에서 일관된 경로를 얻으려면 절대 경로와 함께 환경 변수를 사용하십시오.

import { LocalFilesystem } from '@mastra/core/workspace'

const filesystem = new LocalFilesystem({
basePath: process.env.WORKSPACE_PATH!,
})

환경의 WORKSPACE_PATH/home/user/my-project/workspace 같은 절대 경로로 설정합니다. 이렇게 하면 코드를 실행하는 방식과 관계없이 Workspace 경로가 일관되게 유지됩니다.