2026-05-30 17:09:18 +08:00
import { type AgentTool } from '@earendil-works/pi-agent-core'
2026-08-29 15:19:08 +08:00
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService , Permission , ResourceType } from '@shumai/core/src/authz/authz'
2026-06-01 23:16:22 +08:00
import { s3Service } from '@shumai/core/src/s3/s3'
2026-08-04 21:16:33 +08:00
import { getFileMimeType , readFileMimeType } from '@shumai/core/src/utils/file-mime'
2026-07-02 15:26:10 +08:00
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
2026-08-29 15:19:08 +08:00
import { type User } from '@shumai/db'
2026-08-13 20:06:09 +08:00
import { Type , type TSchema } from 'typebox'
2026-08-05 12:01:04 +08:00
import * as fs from 'fs'
import * as path from 'path'
import { ulid } from 'ulid'
2026-05-30 19:24:04 +08:00
2026-08-13 20:06:09 +08:00
interface CreateFileToolParams {
parent : string
path : string | null
data : { name : string ; content : string } | null
metadata? : Record < string , unknown > | null
}
2026-05-30 17:09:18 +08:00
2026-08-13 20:06:09 +08:00
function assertExactlyOneSource ( params : CreateFileToolParams ) {
const hasPath = params . path !== null
const hasData = params . data !== null
2026-08-04 21:16:33 +08:00
if ( hasPath === hasData ) {
throw new Error ( 'Provide exactly one of "path" (a local file) or "data" (name and content).' )
}
return hasPath ? params . path ! : params . data !
}
2026-08-13 20:06:09 +08:00
export function createCreateFileTool ( userId : string , metadataSchema? : TSchema ) : AgentTool {
const createFileSchema = Type . Object (
{
parent : Type.String ({
description :
'The parent folder ID under which to create the file. This parameter is required.' ,
}),
path : Type.Union ([
Type . String ({
description :
'The absolute or relative local path to an existing file on disk. Provide a value here OR in "data", but not both. Use null if you are providing "data".' ,
}),
Type . Null (),
]),
data : Type.Union ([
Type . Object (
{
name : Type.String ({
minLength : 1 ,
description :
'The desired name for the new file, including its extension (e.g. "notes.md").' ,
}),
content : Type.String ({
description : 'The full content of the file as a plain string.' ,
}),
},
{ additionalProperties : false },
),
Type . Null (),
]),
...( metadataSchema ? { metadata : Type.Union ([ metadataSchema , Type . Null ()]) } : {}),
},
{ additionalProperties : false },
)
const tool : AgentTool = {
2026-05-30 17:09:18 +08:00
name : 'create_file' ,
label : 'Create File' ,
2026-08-04 21:16:33 +08:00
description :
2026-08-05 12:01:04 +08:00
'Create a new file under a folder. You MUST choose exactly ONE creation method: ' +
'(1) provide "path" to upload an existing local file, OR ' +
'(2) provide "data" with name and content to create a new text file. ' +
2026-08-13 20:06:09 +08:00
'Set the unused parameter to null. ' +
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.' ,
2026-05-30 17:09:18 +08:00
parameters : createFileSchema ,
execute : async ( _toolCallId , params ) => {
2026-08-13 20:06:09 +08:00
// The harness validates tool args against `createFileSchema` before calling
// execute, so `params` is guaranteed to match this shape.
const p = params as CreateFileToolParams
const source = assertExactlyOneSource ( p )
2026-08-04 21:16:33 +08:00
let name : string
let size : number
let mimeType : string
let s3Key : string
if ( typeof source === 'string' ) {
// Branch A: upload an existing local file
const absolutePath = path . resolve ( process . cwd (), source )
if ( ! fs . existsSync ( absolutePath )) {
throw new Error ( `Local file not found at path: ${ source } ` )
}
name = path . basename ( absolutePath )
size = fs . statSync ( absolutePath ). size
mimeType = readFileMimeType ( absolutePath )
// Generate compliant S3 key matching normal file upload format
s3Key = `files/ ${ ulid () } / ${ sanitizeFilename ( name ) } `
await s3Service . uploadFileToKey ( absolutePath , s3Key , mimeType )
} else {
// Branch B: create the file directly from provided name and content
name = sanitizeFilename ( source . name )
const content = Buffer . from ( source . content , 'utf-8' )
size = content . byteLength
mimeType = getFileMimeType ( null , source . name , 'text/plain' )
s3Key = `files/ ${ ulid () } / ${ name } `
await s3Service . putObject ( process . env . S3_BUCKET || 'shumai' , s3Key , content , size , mimeType )
2026-07-22 10:47:47 +08:00
}
2026-05-30 19:24:04 +08:00
2026-08-29 15:19:08 +08:00
await authzService . hasPermission ({
user : { id : userId } as User ,
permission : Permission.Edit ,
type : ResourceType . Asset ,
id : p.parent ,
2026-07-22 10:47:47 +08:00
})
2026-08-29 15:19:08 +08:00
const asset = await assetService . createFile ({
parentId : p.parent ,
name ,
key : s3Key ,
sizeByte : size ,
contentType : mimeType ,
creatorId : userId ,
metadata : p.metadata ?? undefined ,
})
const result = {
id : asset.id ,
name : asset.name ,
type : asset . type ,
size : Number ( asset . sizeByte ),
}
2026-07-22 10:47:47 +08:00
return {
content : [{ type : 'text' , text : JSON.stringify ( result , null , 2 ) }],
2026-08-31 20:43:05 +08:00
details : {},
2026-05-30 17:09:18 +08:00
}
},
}
2026-08-13 20:06:09 +08:00
return tool
2026-05-30 17:09:18 +08:00
}