mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 04:44:28 +00:00
* feat(agent): type-safe CREATION_CONTEXT metadata on create_file/create_version
Build the create_file and create_version tool metadata parameter from the
project's CREATION_CONTEXT fields at harness creation time, instead of the
schemaless key-value map that required the agent to call list_autofill_fields
first.
- Thread projectId from the chat workflow into createAgentSession and build
a strict, all-required (nullable) metadata schema via fieldsToTypeBoxSchema
(additionalProperties: false, option IDs enforced via enum).
- Remove the list_autofill_fields tool and its activity case.
- Reject metadata keys that are not CREATION_CONTEXT fields of the target
project with a clear non-retryable error telling the agent to omit metadata.
- Skip null metadata values when persisting (create_file/create_version and
the autofill workflow).
- Switch the touched schemas from @sinclair/typebox 0.34 to typebox v1 to
match the harness validator.
* refactor(agent): migrate remaining tools from @sinclair/typebox 0.34 to typebox v1
All agent tool schemas now use the same typebox v1 package as the harness
validator; drop the @sinclair/typebox 0.34 dependency from @shumai/agent.
* test(agent): reproduce null coercion in harness tool validation
The pi-ai harness (<=0.82.1) coerces null values in [string, null] unions to
'' during tool argument validation for typebox v1 schemas. A valid create_file
call with path: null + data: {...} therefore arrives at execute with path: ''
and fails with 'Provide exactly one of path or data'. Null metadata values
(the 'unknown' sentinel) are likewise turned into ''.
This test reproduces both failures. It is expected to fail until
@earendil-works/pi-ai is upgraded to >=0.84.0 (#7328), which preserves values
that already match a union arm.
* fix(agent): patch pi-ai 0.82.1 to preserve null in nullable union tool args
Apply the upstream fix for earendil-works/pi#7328 (PR #7373) via a bun
patch instead of upgrading pi-ai. coerceWithUnionSchema now returns the
original value when it already validates against any union member,
instead of coercing null in [string, null] unions into "".
Fixes the create_file false "Provide exactly one of path or data" error
when the model passes path: null with data. Reproduced by
packages/agent/src/reproduce-tool-null-coercion.test.ts, which now passes.
* fix(docker): copy bun patch dir before frozen-lockfile install
The pi-ai patchedDependencies entry makes bun install --frozen-lockfile
fail in the builder stage because patches/ was not present in the image
yet. Copy it alongside package.json/bun.lock so the patch applies.
* refactor(agent): simplify metadata guidance in system prompt and error message
Shorten the create_file/create_version metadata instructions in the system
prompt and reword the invalid-metadata-key error to not reference
CREATION_CONTEXT internals. Update the matching test assertion.
122 lines
4.0 KiB
TypeScript
122 lines
4.0 KiB
TypeScript
import { Type } from 'typebox'
|
|
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
|
import { prisma, type User } from '@shumai/db'
|
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
|
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
|
import * as fs from 'fs'
|
|
import * as path from 'path'
|
|
|
|
const downloadAssetSchema = Type.Object({
|
|
assetId: Type.String({
|
|
description:
|
|
'The asset ID of the workspace asset to download to local disk. This parameter is required.',
|
|
}),
|
|
})
|
|
|
|
export function createDownloadAssetTool(userId: string): AgentTool<typeof downloadAssetSchema> {
|
|
return {
|
|
name: 'download_asset',
|
|
label: 'Download Asset',
|
|
description:
|
|
'Downloads a workspace asset (proxy version if available) to the local .pi directory for processing with local scripts or bash commands. Remember to delete the temporary downloaded file when finished.',
|
|
parameters: downloadAssetSchema,
|
|
execute: async (_toolCallId, params) => {
|
|
const assetId = params.assetId
|
|
|
|
if (!userId) {
|
|
throw new Error('User ID is required for authorization.')
|
|
}
|
|
|
|
await authzService.hasPermission({
|
|
user: { id: userId } as User,
|
|
permission: Permission.Read,
|
|
type: ResourceType.Asset,
|
|
id: assetId,
|
|
})
|
|
|
|
let asset = await prisma.asset.findUnique({
|
|
where: { id: assetId },
|
|
include: { storageKey: true },
|
|
})
|
|
|
|
if (!asset) {
|
|
throw new Error(`Asset with ID ${assetId} not found.`)
|
|
}
|
|
|
|
if (asset.type === 'version_stack') {
|
|
const latestVersion = await prisma.asset.findFirst({
|
|
where: { parentId: asset.id, isDeleted: false },
|
|
orderBy: { sortIndex: 'asc' },
|
|
include: { storageKey: true },
|
|
})
|
|
if (latestVersion) {
|
|
asset = latestVersion
|
|
}
|
|
}
|
|
|
|
let mediaKey = asset.storageKey?.key
|
|
|
|
if (asset.media) {
|
|
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
|
if (
|
|
mediaInfo.proxyType === 'image' ||
|
|
(mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0)
|
|
) {
|
|
if (mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0) {
|
|
mediaKey = mediaInfo.imageTranscodes[0].key || mediaKey
|
|
}
|
|
} else if (
|
|
mediaInfo.proxyType === 'video' ||
|
|
(mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) ||
|
|
mediaInfo.videoPreview?.key
|
|
) {
|
|
if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) {
|
|
mediaKey = mediaInfo.videoTranscodes[0].key || mediaKey
|
|
} else if (mediaInfo.videoPreview?.key) {
|
|
mediaKey = mediaInfo.videoPreview.key
|
|
}
|
|
} else if (mediaInfo.original?.key) {
|
|
mediaKey = mediaInfo.original.key || mediaKey
|
|
}
|
|
}
|
|
|
|
if (!mediaKey) {
|
|
throw new Error(`No media content found for asset ${assetId}.`)
|
|
}
|
|
|
|
const piDir = path.join(process.cwd(), '.pi')
|
|
if (!fs.existsSync(piDir)) {
|
|
fs.mkdirSync(piDir, { recursive: true })
|
|
}
|
|
|
|
const safeName = sanitizeFilename(asset.name || 'file')
|
|
const filename = `${asset.id}_${safeName}`
|
|
const targetFilePath = path.join(piDir, filename)
|
|
const relativePath = path.join('.pi', filename)
|
|
|
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
|
const { buffer, contentType } = await s3Service.getObject(bucket, mediaKey)
|
|
|
|
fs.writeFileSync(targetFilePath, buffer)
|
|
|
|
return {
|
|
content: [
|
|
{
|
|
type: 'text',
|
|
text: `Downloaded asset "${asset.name}" (ID: ${assetId}) to "${relativePath}". Remember to delete this temporary file when finished.`,
|
|
},
|
|
],
|
|
details: {
|
|
assetId,
|
|
name: asset.name,
|
|
filePath: relativePath,
|
|
absolutePath: targetFilePath,
|
|
contentType: contentType || 'application/octet-stream',
|
|
size: buffer.length,
|
|
},
|
|
}
|
|
},
|
|
}
|
|
}
|