initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
@@ -0,0 +1,70 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { analyzeAssetMediaTool } from './analyze-asset-media'
import { s3Service } from '@/services/s3/s3'
vi.mock('@/services/s3/s3')
describe('analyzeAssetMediaTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should analyze media by S3 key and return image content', async () => {
// Mock S3 with WEBP magic bytes
const buffer = Buffer.from([
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'image/webp' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/test.webp' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('image/webp')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.details as any).sourceKey).toBe('assets/test.webp')
})
it('should infer mimeType from content if S3 response has generic mimeType', async () => {
// Mock S3 with MP4 magic bytes
const buffer = Buffer.from([
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'application/octet-stream' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/no-extension-but-mp4' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image') // Wrapped as image type for base64
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('video/mp4')
})
it('should return error if S3 getObject fails', async () => {
// Mock S3 failure
vi.mocked(s3Service.getObject).mockRejectedValue(new Error('S3 error'))
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/non-existent' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const textContent = (result.content[0] as any).text
expect(textContent).toContain('Error analyzing media: S3 error')
})
})
+74
View File
@@ -0,0 +1,74 @@
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import { ImageContent, TextContent } from '@mariozechner/pi-ai'
import { detectSupportedMimeType } from '@/utils/mime'
const analyzeAssetMediaSchema = Type.Object({
key: Type.String({
description:
'The S3 key of the media file to analyze. This MUST be a key obtained from the asset media info.',
}),
})
export interface MediaAnalysisDetails {
sourceKey: string
}
export const analyzeAssetMediaTool = defineTool<
typeof analyzeAssetMediaSchema,
MediaAnalysisDetails
>({
name: 'analyze_asset_media',
label: 'Analyze Asset Media',
description:
'Retrieves and views the media content (images/video) by its S3 key. The key must be obtained from the asset media info provided in the context.',
parameters: analyzeAssetMediaSchema,
execute: async (_toolCallId, params) => {
try {
const { key } = params
if (!key) {
return {
content: [{ type: 'text', text: 'S3 key is required.' }],
details: { sourceKey: '' },
}
}
const bucket = process.env.S3_BUCKET || 'shumai'
const { buffer, contentType } = await s3Service.getObject(bucket, key)
const uint8Array = new Uint8Array(buffer)
let mimeType = contentType
if (mimeType === 'application/octet-stream') {
mimeType = detectSupportedMimeType(uint8Array) || 'application/octet-stream'
}
const content: (TextContent | ImageContent)[] = [
{
type: 'image',
data: buffer.toString('base64'),
mimeType,
},
]
return {
content,
details: {
sourceKey: key,
},
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error analyzing media: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { sourceKey: params.key || '' },
}
}
},
})
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { readSkillTool } from './read-skill'
import { s3Service } from '@/services/s3/s3'
import * as fs from 'fs'
vi.mock('@/services/s3/s3')
vi.mock('fs')
vi.mock('adm-zip', () => {
return {
default: class {
extractAllTo = vi.fn()
},
}
})
describe('readSkillTool', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should return error if skill not found', async () => {
const result = await readSkillTool.execute(
'1',
{ skillId: 'non-existent' },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toContain('not found')
})
it('should read skill from cache if hash matches', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Test Skill',
assetId: 'asset1',
hash: 'match-hash',
teamId: team.id,
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'match-hash'
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
return ''
})
const result = await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
expect(s3Service.getObject).not.toHaveBeenCalled()
})
it('should download and extract skill if cache missing or hash mismatch', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'New Skill',
assetId: 'asset1',
hash: 'new-hash',
teamId: team.id,
},
})
await prisma.asset.create({
data: {
id: 'asset1',
name: 'skill.zip',
key: 'skills/skill.zip',
type: 'file',
status: 'uploaded',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return false
if (path.toString().endsWith('SKILL.md')) return true
return true
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({ buffer: Buffer.from('zipdata'), contentType: 'application/zip' })
const result = await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
expect(s3Service.getObject).toHaveBeenCalled()
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
})
})
+101
View File
@@ -0,0 +1,101 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import * as path from 'path'
import * as fs from 'fs'
import AdmZip from 'adm-zip'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
})
export const readSkillTool = defineTool<typeof readSkillSchema, { skillId: string }>({
name: 'read_skill',
label: 'Read Agent Skill',
description: 'Downloads and reads an agent skill to understand how to use it.',
parameters: readSkillSchema,
execute: async (_toolCallId, params) => {
try {
const skill = await prisma.skill.findUnique({
where: { id: params.skillId },
})
if (!skill) {
return {
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
details: { skillId: params.skillId },
}
}
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
const hashFile = path.join(skillDir, '.hash')
let needsDownload = true
if (fs.existsSync(hashFile)) {
const localHash = fs.readFileSync(hashFile, 'utf8')
if (localHash === skill.hash) {
needsDownload = false
}
}
if (needsDownload) {
if (fs.existsSync(skillDir)) {
fs.rmSync(skillDir, { recursive: true, force: true })
}
fs.mkdirSync(skillDir, { recursive: true })
const asset = await prisma.asset.findUnique({
where: { id: skill.assetId },
})
if (!asset || !asset.key) {
throw new Error('Skill asset not found or has no key')
}
const { buffer: zipBuffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.key)
const zip = new AdmZip(zipBuffer)
zip.extractAllTo(skillDir, true)
fs.writeFileSync(hashFile, skill.hash)
}
// Read SKILL.md
let skillMdPath = path.join(skillDir, 'SKILL.md')
if (!fs.existsSync(skillMdPath)) {
skillMdPath = path.join(skillDir, 'skill.md')
}
if (!fs.existsSync(skillMdPath)) {
return {
content: [
{
type: 'text',
text: `Skill downloaded but SKILL.md not found in ${skillDir}`,
},
],
details: { skillId: params.skillId },
}
}
const skillMdContent = fs.readFileSync(skillMdPath, 'utf8')
return {
content: [{ type: 'text', text: skillMdContent }],
details: { skillId: params.skillId },
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error reading skill ${params.skillId}: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { skillId: params.skillId },
}
}
},
})