feat(agent): type-safe CREATION_CONTEXT metadata on create_file/create_version (#303)

* 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.
This commit is contained in:
Yiling-J
2026-08-13 20:06:09 +08:00
committed by GitHub
parent 94582c9001
commit 7f185ca23c
27 changed files with 632 additions and 401 deletions
+2 -119
View File
@@ -1512,7 +1512,7 @@ describe('Agent Database Activities Integration', () => {
expect(val?.stringValue).toBe('Generated using gemini')
})
it('should reject metadata with keys that are not CREATION_CONTEXT fields', async () => {
it('should reject metadata with keys that are not valid in this project', async () => {
const folder = await prisma.asset.create({
data: {
name: 'WorkspaceFolder',
@@ -1538,7 +1538,7 @@ describe('Agent Database Activities Integration', () => {
},
userId: user.id,
}),
).rejects.toThrow(/not CREATION_CONTEXT fields/)
).rejects.toThrow(/not valid in this project/)
// No metadata value should have been written for the unknown key
const val = await prisma.assetMetadataValue.findFirst({
@@ -1708,123 +1708,6 @@ describe('Agent Database Activities Integration', () => {
expect(val?.stringValue).toBe('Generated using seedance')
})
})
describe('list_autofill_fields', () => {
it('should return only CREATION_CONTEXT fields with their options', async () => {
const folder = await prisma.asset.create({
data: {
name: 'WorkspaceFolder',
type: AssetType.folder,
status: AssetStatus.uploaded,
projectId: project.id,
},
})
await prisma.metadataField.create({
data: {
key: 'source',
scope: 'PROJECT',
projectId: project.id,
teamId: team.id,
config: {
name: 'Source',
type: 'select',
autofillSource: 'CREATION_CONTEXT',
select: {
options: [
{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' },
{ id: 'seedance', displayName: 'Seedance', color: '#ffffff' },
],
},
},
description: 'Generation source',
},
})
await prisma.metadataField.create({
data: {
key: 'prompt',
scope: 'PROJECT',
projectId: project.id,
teamId: team.id,
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
},
})
await prisma.metadataField.create({
data: {
key: 'manual_notes',
scope: 'PROJECT',
projectId: project.id,
teamId: team.id,
config: { name: 'Manual Notes', type: 'text', autofillSource: 'NONE' },
},
})
const res = await executeAgentToolActivity({
taskId: 'task-1',
toolName: 'list_autofill_fields',
args: { parent: folder.id },
userId: user.id,
})
expect(res.fields).toHaveLength(2)
const source = res.fields.find((f: { name: string }) => f.name === 'Source')
expect(source?.key).toBe('source')
expect(source?.name).toBe('Source')
expect(source?.type).toBe('select')
expect(source?.description).toBe('Generation source')
expect(source?.options).toEqual([{ displayName: 'Gemini' }, { displayName: 'Seedance' }])
expect(res.fields.find((f: { name: string }) => f.name === 'Manual Notes')).toBeUndefined()
})
it('should resolve the project through the ancestor chain', async () => {
const rootFolder = await prisma.asset.create({
data: {
name: 'Root',
type: AssetType.folder,
status: AssetStatus.uploaded,
projectId: project.id,
},
})
const subFolder = await prisma.asset.create({
data: {
name: 'Sub',
type: AssetType.folder,
status: AssetStatus.uploaded,
parentId: rootFolder.id,
},
})
await prisma.metadataField.create({
data: {
key: 'title_2',
scope: 'PROJECT',
projectId: project.id,
teamId: team.id,
config: { name: 'Title 2', type: 'text', autofillSource: 'CREATION_CONTEXT' },
},
})
const res = await executeAgentToolActivity({
taskId: 'task-1',
toolName: 'list_autofill_fields',
args: { parent: subFolder.id },
userId: user.id,
})
expect(res.fields.length).toBeGreaterThan(0)
})
it('should fail when parent is missing', async () => {
await expect(
executeAgentToolActivity({
taskId: 'task-1',
toolName: 'list_autofill_fields',
args: {},
userId: user.id,
}),
).rejects.toThrow('parent parameter is required')
})
})
})
describe('generateSessionNameActivity', () => {
+16 -65
View File
@@ -74,6 +74,7 @@ async function executeAgentPrompt(params: {
agentsInstruction: string
sessionId?: string
userId?: string
projectId?: string
userCommentId?: string | null
tools?: AgentTool[]
context: AgentExecutionContext
@@ -104,7 +105,7 @@ shumai has its own cloud file system. If a user asks you to perform file system
If you need to create files in the local filesystem (for example, a temporary file for uploading), only the '.pi' folder in the current directory has write permissions. Do NOT attempt to create files in any other directories.
When creating a file or version, first use 'list_autofill_fields' to inspect the project's CREATION_CONTEXT metadata fields. If relevant metadata depends on information unavailable from the file content (for example, the AI model or prompt used to generate the asset), pass those field keys and their values in the 'metadata' dictionary parameter of 'create_file' or 'create_version'. Only include keys returned by 'list_autofill_fields', and keep values short and relevant to those fields.`
When creating a file or version, you may attach metadata (for example, the AI model or prompt used to generate the asset). The allowed field keys and value types are declared directly in the 'metadata' parameter of the 'create_file' and 'create_version' tools.`
if (agent.soul) {
systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}`
@@ -144,6 +145,7 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
allowedDomains,
sessionId: params.sessionId,
userId: params.userId,
projectId: params.projectId,
userCommentId: params.userCommentId,
customTools: [...(params.tools || []), ...mcpTools],
providers: dbProviders.map((p) => ({
@@ -411,6 +413,7 @@ export async function agentChatActivity(params: AgentChatParams) {
agentsInstruction: params.agentsInstruction || '',
sessionId,
userId: params.userId,
projectId: params.projectId,
userCommentId: params.userCommentId,
context: params.context,
attachedAssets: params.attachedAssets,
@@ -1107,8 +1110,9 @@ async function validateCreationContextMetadata(
if (invalidKeys.length > 0) {
throw ApplicationFailure.create({
message:
`metadata contains keys that are not CREATION_CONTEXT fields of this project: ${invalidKeys.join(', ')}. ` +
'Use list_autofill_fields to see the available keys.',
`metadata contains keys that are not valid in this project: ${invalidKeys.join(', ')}. ` +
"The valid metadata fields are fixed to the current conversation's project. " +
'If the target folder or file belongs to a different project, call the tool WITHOUT the metadata parameter.',
nonRetryable: true,
})
}
@@ -1326,7 +1330,9 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
// Persist creation context metadata provided by the agent
if (metadata) {
const metadataUpdates = Object.entries(metadata).map(([key, value]) => ({ key, value }))
const metadataUpdates = Object.entries(metadata)
.filter(([, value]) => value !== null)
.map(([key, value]) => ({ key, value }))
if (metadataUpdates.length > 0) {
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
}
@@ -1428,7 +1434,9 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
})
// Persist creation context metadata provided by the agent
if (metadata) {
const metadataUpdates = Object.entries(metadata).map(([key, value]) => ({ key, value }))
const metadataUpdates = Object.entries(metadata)
.filter(([, value]) => value !== null)
.map(([key, value]) => ({ key, value }))
if (metadataUpdates.length > 0) {
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
}
@@ -1493,7 +1501,9 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
})
// Persist creation context metadata provided by the agent
if (metadata) {
const metadataUpdates = Object.entries(metadata).map(([key, value]) => ({ key, value }))
const metadataUpdates = Object.entries(metadata)
.filter(([, value]) => value !== null)
.map(([key, value]) => ({ key, value }))
if (metadataUpdates.length > 0) {
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
}
@@ -1520,50 +1530,6 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
}
}
case 'list_autofill_fields': {
const parent = args.parent
if (!parent) {
throw ApplicationFailure.create({
message: 'parent parameter is required',
nonRetryable: true,
})
}
// Authz check
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: parent,
})
// Resolve projectId from the parent asset (climb ancestor chain if needed)
const projectId = await resolveAssetProjectId(parent)
if (!projectId) {
throw ApplicationFailure.create({
message: `Could not resolve project for parent: ${parent}`,
nonRetryable: true,
})
}
const fields = await metadataService.listProjectFields(userId, projectId)
const autofillFields = fields
.filter((f) => f.field.config?.autofillSource === 'CREATION_CONTEXT')
.map((f) => ({
key: f.field.key,
name: f.field.config?.name,
type: f.field.config?.type,
description: f.field.description,
options: (
f.field.config?.select?.options ??
f.field.config?.selectMulti?.options ??
[]
).map((o) => ({ displayName: o.displayName })),
}))
return { fields: autofillFields }
}
default:
throw ApplicationFailure.create({
message: `Unsupported tool name: ${toolName}`,
@@ -1572,21 +1538,6 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
}
}
async function resolveAssetProjectId(assetId: string): Promise<string | null> {
let currentId: string | null = assetId
while (currentId) {
/* prettier-ignore */
const assetNode = (await prisma.asset.findUnique({
where: { id: currentId },
select: { id: true, projectId: true, parentId: true },
})) as { id: string; projectId: string | null; parentId: string | null } | null
if (!assetNode) break
if (assetNode.projectId) return assetNode.projectId
currentId = assetNode.parentId
}
return null
}
export interface GenerateSessionNameParams {
teamId: string
agentId: string