diff --git a/Dockerfile b/Dockerfile index c9706fc5..4db9511f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,6 +8,7 @@ WORKDIR /app COPY package.json bun.lock ./ COPY --parents packages/*/package.json ./ COPY --parents apps/*/package.json ./ +COPY patches/ ./patches/ # Install dependencies (including devDependencies for build tools) RUN bun install --frozen-lockfile diff --git a/bun.lock b/bun.lock index c17f5f85..11a67669 100644 --- a/bun.lock +++ b/bun.lock @@ -33,7 +33,7 @@ }, "apps/agent": { "name": "@shumai/agent-app", - "version": "0.3.5", + "version": "0.3.6", "bin": { "shumai-agent": "./src/index.ts", }, @@ -45,7 +45,7 @@ }, "apps/cli": { "name": "@shumai/cli", - "version": "0.3.5", + "version": "0.3.6", "bin": { "shumai-cli": "./src/index.ts", }, @@ -60,7 +60,7 @@ }, "apps/transcode": { "name": "@shumai/transcode-app", - "version": "0.3.5", + "version": "0.3.6", "bin": { "shumai-transcode": "./src/index.ts", }, @@ -72,7 +72,7 @@ }, "apps/web": { "name": "@shumai/web-app", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@shumai/agent": "workspace:*", "@shumai/api": "workspace:*", @@ -92,7 +92,7 @@ }, "packages/agent": { "name": "@shumai/agent", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@anthropic-ai/sandbox-runtime": "0.0.66", "@earendil-works/pi-agent-core": "0.82.1", @@ -102,12 +102,12 @@ "@shumai/db": "workspace:*", "@shumai/dtos": "workspace:*", "@shumai/workflow-core": "workspace:*", - "@sinclair/typebox": "0.34.49", "@temporalio/activity": "1.17.2", "@temporalio/worker": "1.17.2", "@temporalio/workflow": "1.17.2", "adm-zip": "0.5.17", "jittered-fractional-indexing": "1.0.1", + "typebox": "1.1.38", "ulid": "3.0.2", "zod": "4.4.3", }, @@ -117,7 +117,7 @@ }, "packages/api": { "name": "@shumai/api", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@hono/zod-validator": "0.7.6", "@shumai/core": "workspace:*", @@ -131,7 +131,7 @@ }, "packages/core": { "name": "@shumai/core", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "@earendil-works/pi-ai": "0.82.1", @@ -166,7 +166,7 @@ }, "packages/db": { "name": "@shumai/db", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "@prisma/adapter-pg": "7.8.0", @@ -182,7 +182,7 @@ }, "packages/dtos": { "name": "@shumai/dtos", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "zod": "4.4.3", @@ -190,7 +190,7 @@ }, "packages/e2e": { "name": "@shumai/e2e", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "@google/genai": "1.52.0", @@ -205,11 +205,11 @@ }, "packages/tableprinter": { "name": "@shumai/tableprinter", - "version": "0.3.5", + "version": "0.3.6", }, "packages/transcode": { "name": "@shumai/transcode", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -223,7 +223,7 @@ }, "packages/webui": { "name": "@shumai/webui", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@base-ui/react": "1.5.0", "@dnd-kit/abstract": "0.4.0", @@ -321,7 +321,7 @@ }, "packages/workflow-core": { "name": "@shumai/workflow-core", - "version": "0.3.5", + "version": "0.3.6", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -333,6 +333,9 @@ }, }, }, + "patchedDependencies": { + "@earendil-works/pi-ai@0.82.1": "patches/@earendil-works%2Fpi-ai@0.82.1.patch", + }, "packages": { "@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="], diff --git a/package.json b/package.json index 636911df..1db6c060 100644 --- a/package.json +++ b/package.json @@ -65,5 +65,8 @@ "typescript-eslint": "8.60.1", "vite-tsconfig-paths": "6.1.1", "vitest": "4.1.8" + }, + "patchedDependencies": { + "@earendil-works/pi-ai@0.82.1": "patches/@earendil-works%2Fpi-ai@0.82.1.patch" } } diff --git a/packages/agent/package.json b/packages/agent/package.json index 552aa910..8e1ed7d5 100644 --- a/packages/agent/package.json +++ b/packages/agent/package.json @@ -14,12 +14,12 @@ "@shumai/db": "workspace:*", "@shumai/dtos": "workspace:*", "@shumai/workflow-core": "workspace:*", - "@sinclair/typebox": "0.34.49", "@temporalio/activity": "1.17.2", "@temporalio/worker": "1.17.2", "@temporalio/workflow": "1.17.2", "adm-zip": "0.5.17", "jittered-fractional-indexing": "1.0.1", + "typebox": "1.1.38", "ulid": "3.0.2", "zod": "4.4.3" }, diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index bd942d2f..3fe6165e 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -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', () => { diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index d5d848ed..6487e217 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -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 { - 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 diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index fb8f66fa..f4373821 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -10,6 +10,8 @@ import { createSandboxedBashTool } from './tools/sandboxed-bash' import { SandboxManager, type SandboxAskCallback } from '@anthropic-ai/sandbox-runtime' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' +import { type TSchema } from 'typebox' +import { Value } from 'typebox/value' import * as path from 'path' import * as childProcess from 'node:child_process' import * as fs from 'fs' @@ -814,6 +816,149 @@ describe('createAgentSession bash restriction for non-owner users', () => { }) }) +describe('createAgentSession typed metadata schema', () => { + setupTestDbHooks() + + afterEach(() => { + vi.restoreAllMocks() + }) + + async function setupSessionWithProject(opts: { withCreationFields: boolean }) { + const team = await prisma.team.create({ data: { name: 'Typed Metadata Team' } }) + const project = await prisma.project.create({ + data: { name: 'Typed Metadata Project', teamId: team.id }, + }) + const user = await prisma.user.create({ + data: { name: 'Typed Metadata User', email: 'typed-metadata@shumai.ai' }, + }) + await prisma.teamMember.create({ + data: { teamId: team.id, userId: user.id, role: 'owner' }, + }) + await prisma.user.create({ + data: { + id: 'typed-metadata-agent', + name: 'Ai Agent Typed Metadata', + email: 'typed-metadata-agent@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'typed-metadata-agent', + teamId: team.id, + type: 'chat', + config: { provider: 'google', model: 'gemini' }, + }, + }) + + if (opts.withCreationFields) { + 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: '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' }], + }, + }, + }, + }) + await prisma.metadataField.create({ + data: { + key: 'manualNotes', + scope: 'PROJECT', + projectId: project.id, + teamId: team.id, + config: { name: 'Manual Notes', type: 'text', autofillSource: 'NONE' }, + }, + }) + } + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + agentId: 'typed-metadata-agent', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + allowedDomains: [], + providers: mockProviders, + userId: user.id, + projectId: project.id, + }) + return { harness } + } finally { + initializeSpy.mockRestore() + } + } + + it('should build create_file/create_version with the project CREATION_CONTEXT fields', async () => { + const { harness } = await setupSessionWithProject({ withCreationFields: true }) + const tools = harness.getTools() + + expect(tools.some((t) => t.name === 'list_autofill_fields')).toBe(false) + + const createFile = tools.find((t) => t.name === 'create_file') + const createVersion = tools.find((t) => t.name === 'create_version') + expect(createFile).toBeDefined() + expect(createVersion).toBeDefined() + + const checkFile = (args: Record) => + Value.Check(createFile!.parameters as unknown as TSchema, { + parent: 'f1', + path: '/tmp/x.md', + data: null, + ...args, + }) + const checkVersion = (args: Record) => + Value.Check(createVersion!.parameters as unknown as TSchema, { + parent: 'f1', + path: '/tmp/x.md', + ...args, + }) + + for (const check of [checkFile, checkVersion]) { + // Declared CREATION_CONTEXT fields (all-required, nullable) validate; other keys do not + expect(check({ metadata: { prompt: 'hello', source: null } })).toBe(true) + expect(check({ metadata: { prompt: null, source: 'gemini' } })).toBe(true) + expect(check({ metadata: null })).toBe(true) + expect(check({ metadata: { prompt: null, source: null, manualNotes: 'no' } })).toBe(false) + expect(check({ metadata: { prompt: null, source: null, bogus: 1 } })).toBe(false) + expect(check({ metadata: { prompt: 'hello' } })).toBe(false) + } + }) + + it('should omit the metadata parameter when the project has no CREATION_CONTEXT fields', async () => { + const { harness } = await setupSessionWithProject({ withCreationFields: false }) + const createFile = harness.getTools().find((t) => t.name === 'create_file') + const createVersion = harness.getTools().find((t) => t.name === 'create_version') + expect(createFile).toBeDefined() + expect(createVersion).toBeDefined() + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool + const fileProps = (createFile!.parameters as any).properties + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool + const versionProps = (createVersion!.parameters as any).properties + expect('metadata' in fileProps).toBe(false) + expect('metadata' in versionProps).toBe(false) + }) +}) + describe('createAgentSession enabled skill filtering', () => { setupTestDbHooks() diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 7067573a..ec738aa3 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -10,14 +10,14 @@ import { createModels, InMemoryCredentialStore } from '@earendil-works/pi-ai' import { builtinProviders } from '@earendil-works/pi-ai/providers/all' import { agentService } from '@shumai/core/src/agent/agent' import { prisma, type TeamMemberRole } from '@shumai/db' -import { Type, type TSchema } from '@sinclair/typebox' +import { Type, type TSchema } from 'typebox' import * as fs from 'fs' import * as os from 'os' import * as path from 'path' import { DatabaseSessionStorage } from './database-session-storage' +import { metadataService } from '@shumai/core/src/metadata/metadata' import { createAnalyzeImageTool } from './tools/analyze-image' import { createCreateFileTool } from './tools/create-file' -import { createListAutofillFieldsTool } from './tools/list-autofill-fields' import { createCreateFolderTool } from './tools/create-folder' import { createCreateVersionTool } from './tools/create-version' import { createDownloadAssetTool } from './tools/download-asset' @@ -102,6 +102,7 @@ export interface CreateAgentSessionParams { allowedDomains: string[] sessionId?: string userId?: string + projectId?: string userCommentId?: string | null customTools?: AgentTool[] thinkingLevel?: string @@ -150,6 +151,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { allowedDomains, sessionId, userId, + projectId, userCommentId: passedUserCommentId, customTools = [], thinkingLevel, @@ -324,13 +326,13 @@ export async function createAgentSession(params: CreateAgentSessionParams) { const systemTools: AgentTool[] = [] if (userId) { + const metadataSchema = await buildProjectMetadataSchema(projectId) systemTools.push( createListAssetsTool(userId), createCreateFolderTool(userId), - createCreateFileTool(userId), - createCreateVersionTool(userId), + createCreateFileTool(userId, metadataSchema), + createCreateVersionTool(userId, metadataSchema), createDownloadAssetTool(userId), - createListAutofillFieldsTool(userId), ) } @@ -415,53 +417,79 @@ export function fieldsToTypeBoxSchema(fields: AutofillField[]) { let schema: TSchema const fieldName = f.config.name const fieldDesc = f.description || fieldName + const baseDescription = `The field '${fieldName}' represents ${fieldDesc}.` switch (f.config.type) { case 'text': case 'longText': - schema = Type.String() + schema = Type.String({ description: baseDescription }) break case 'number': case 'rating': - schema = Type.Number() + schema = Type.Number({ description: baseDescription }) break case 'toggle': - schema = Type.Boolean() + schema = Type.Boolean({ description: baseDescription }) break case 'select': { const options = f.config.select?.options || [] + const description = + options.length > 0 + ? `${baseDescription}\nSelect one option and return the option ID as the value.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}` + : baseDescription schema = Type.String({ enum: options.map((o) => o.id), + description, }) - if (options.length > 0) { - const optionLines = options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n') - schema.description = `The field '${fieldName}' represents ${fieldDesc}.\nSelect one option and return the option ID as the value.\n\nAvailable options:\n${optionLines}` - } break } case 'selectMulti': { const options = f.config.selectMulti?.options || [] + const description = + options.length > 0 + ? `${baseDescription}\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}` + : baseDescription schema = Type.Array( Type.String({ enum: options.map((o) => o.id), }), + { description }, ) - if (options.length > 0) { - const optionLines = options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n') - schema.description = `The field '${fieldName}' represents ${fieldDesc}.\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n${optionLines}` - } break } default: - schema = Type.String() + schema = Type.String({ description: baseDescription }) } - - if (!schema.description) { - schema.description = `The field '${fieldName}' represents ${fieldDesc}.` - } - properties[f.id] = schema + // Every field is required but nullable: the agent must return each field key, + // using `null` for values it does not know. Nulls are skipped when persisting. + // This matches the OpenAI structured-outputs strict-mode convention (all + // properties required, optionality expressed via `null`). + properties[f.id] = Type.Union([schema, Type.Null()]) } - return Type.Object(properties) + return Type.Object(properties, { additionalProperties: false }) +} + +/** + * Builds the strict, all-optional metadata schema for the project's CREATION_CONTEXT + * fields (the same field set the agent may attach when creating files/versions). + * Returns undefined when no project is known or the project defines no fields, in + * which case the `metadata` parameter is omitted from the tools entirely. + */ +async function buildProjectMetadataSchema(projectId?: string): Promise { + if (!projectId) return undefined + const fields = await metadataService.listProjectFields('', projectId) + const creationFields: AutofillField[] = [] + for (const f of fields) { + const config = f.field.config + if (!config || config.autofillSource !== 'CREATION_CONTEXT') continue + creationFields.push({ + id: f.field.key, + config, + description: f.field.description, + }) + } + if (creationFields.length === 0) return undefined + return fieldsToTypeBoxSchema(creationFields) } function escapeXml(str: string): string { diff --git a/packages/agent/src/reproduce-tool-null-coercion.test.ts b/packages/agent/src/reproduce-tool-null-coercion.test.ts new file mode 100644 index 00000000..2765873c --- /dev/null +++ b/packages/agent/src/reproduce-tool-null-coercion.test.ts @@ -0,0 +1,97 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { validateToolArguments } from '@earendil-works/pi-ai' +import { createCreateFileTool } from './tools/create-file' +import { fieldsToTypeBoxSchema } from './index' +import { s3Service } from '@shumai/core/src/s3/s3' +import { executeAgentToolWorkflow } from './tools/utils' + +vi.mock('@shumai/core/src/s3/s3', () => ({ + s3Service: { + uploadFileToKey: vi.fn(), + putObject: vi.fn(), + }, +})) + +vi.mock('./tools/utils', () => ({ + executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }), +})) + +/** + * Reproduce: pi-ai <= 0.82.1 runs its lenient coercion on typebox v1 schemas and + * converts `null` in a `[string, null]` union into `""` (see + * coerceWithUnionSchema in @earendil-works/pi-ai/dist/utils/validation.js). + * + * When the agent calls create_file with `path: null, data: {...}`, the harness + * validates first: the `null` path becomes `""`, so the tool's + * assertExactlyOneSource believes BOTH path and data were provided and throws + * "Provide exactly one of ..." even though the call is valid. + * + * Fixed upstream in pi-ai 0.84.0 (#7328): values that already match a union arm + * are preserved before coercion. This test should pass once @earendil-works/pi-ai + * is upgraded to >= 0.84.0. + */ +describe('reproduce null coercion in harness tool validation', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('keeps path: null when data is provided (no false "exactly one" error)', async () => { + const tool = createCreateFileTool('user-1') + + const validated = validateToolArguments( + { + name: 'create_file', + description: '', + parameters: tool.parameters, + } as Parameters[0], + { + type: 'toolCall', + id: 'call-1', + name: 'create_file', + arguments: { + parent: '01KYKNP52YERGJ6Q4GTPF5FRQF', + path: null, + data: { name: 'random_text.txt', content: 'hello' }, + }, + } as Parameters[1], + ) as { path?: unknown; data?: unknown } + + // The `null` path must survive validation untouched; coercion to "" makes + // the tool think both path and data were provided. + expect(validated.path).toBeNull() + expect(validated.data).toEqual({ name: 'random_text.txt', content: 'hello' }) + + // execute must accept the valid call (data-only) without throwing + const result = await tool.execute('call-1', validated as never) + expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' }) + expect(s3Service.putObject).toHaveBeenCalledTimes(1) + expect(executeAgentToolWorkflow).toHaveBeenCalledTimes(1) + }) + + it('keeps null metadata values (the "unknown" sentinel) through validation', () => { + const tool = createCreateFileTool( + 'user-1', + fieldsToTypeBoxSchema([{ id: 'prompt', config: { name: 'Prompt', type: 'text' } }]), + ) + const validated = validateToolArguments( + { + name: 'create_file', + description: '', + parameters: tool.parameters, + } as Parameters[0], + { + type: 'toolCall', + id: 'call-1', + name: 'create_file', + arguments: { + parent: 'folder-1', + path: null, + data: { name: 'a.md', content: 'x' }, + metadata: { prompt: null }, + }, + } as Parameters[1], + ) as { metadata?: Record } + + expect(validated.metadata).toEqual({ prompt: null }) + }) +}) diff --git a/packages/agent/src/schema-conversion.test.ts b/packages/agent/src/schema-conversion.test.ts index 9a101659..2a5f44cb 100644 --- a/packages/agent/src/schema-conversion.test.ts +++ b/packages/agent/src/schema-conversion.test.ts @@ -1,6 +1,22 @@ import { describe, it, expect } from 'vitest' +import { type TSchema } from 'typebox' +import { Value } from 'typebox/value' import { fieldsToTypeBoxSchema, type AutofillField } from './index' +interface AnyOfFieldSchema { + type?: string + enum?: string[] + const?: string + description?: string + items?: { enum?: string[]; type?: string } + anyOf?: AnyOfFieldSchema[] +} + +function propsOf(schema: TSchema): Record { + return (schema as unknown as { properties: Record }) + .properties +} + describe('fieldsToTypeBoxSchema', () => { it('converts text fields', () => { const fields: AutofillField[] = [ @@ -8,10 +24,12 @@ describe('fieldsToTypeBoxSchema', () => { { id: 'f2', config: { name: 'Desc', type: 'longText' } }, ] const schema = fieldsToTypeBoxSchema(fields) - expect(schema.properties.f1.type).toBe('string') - expect(schema.properties.f1.description).toBe("The field 'Title' represents The title.") - expect(schema.properties.f2.type).toBe('string') - expect(schema.properties.f2.description).toBe("The field 'Desc' represents Desc.") + const props = propsOf(schema) + expect(props.f1.anyOf![0].type).toBe('string') + expect(props.f1.anyOf![1].type).toBe('null') + expect(props.f1.anyOf![0].description).toBe("The field 'Title' represents The title.") + expect(props.f2.anyOf![0].type).toBe('string') + expect(props.f2.anyOf![0].description).toBe("The field 'Desc' represents Desc.") }) it('converts numeric fields', () => { @@ -20,14 +38,15 @@ describe('fieldsToTypeBoxSchema', () => { { id: 'f2', config: { name: 'Rating', type: 'rating' } }, ] const schema = fieldsToTypeBoxSchema(fields) - expect(schema.properties.f1.type).toBe('number') - expect(schema.properties.f2.type).toBe('number') + const props = propsOf(schema) + expect(props.f1.anyOf![0].type).toBe('number') + expect(props.f2.anyOf![0].type).toBe('number') }) it('converts toggle fields', () => { const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Active', type: 'toggle' } }] const schema = fieldsToTypeBoxSchema(fields) - expect(schema.properties.f1.type).toBe('boolean') + expect(propsOf(schema).f1.anyOf![0].type).toBe('boolean') }) it('converts select fields with enums and option descriptions', () => { @@ -48,11 +67,16 @@ describe('fieldsToTypeBoxSchema', () => { }, ] const schema = fieldsToTypeBoxSchema(fields) - expect(schema.properties.f1.type).toBe('string') - expect(schema.properties.f1.enum).toEqual(['opt1', 'opt2']) - expect(schema.properties.f1.description).toBe( + const selectSchema = propsOf(schema).f1.anyOf![0] + expect(selectSchema.type).toBe('string') + expect(selectSchema.enum).toEqual(['opt1', 'opt2']) + expect(selectSchema.description).toBe( "The field 'Species' represents Species of animal.\nSelect one option and return the option ID as the value.\n\nAvailable options:\n- Option 1 => opt1\n- Option 2 => opt2", ) + // Only the declared option IDs are valid (enforced by the typebox validator) + expect(Value.Check(schema, { f1: 'opt1' })).toBe(true) + expect(Value.Check(schema, { f1: null })).toBe(true) + expect(Value.Check(schema, { f1: 'not-an-option' })).toBe(false) }) it('converts selectMulti fields with array enums and option descriptions', () => { @@ -72,11 +96,15 @@ describe('fieldsToTypeBoxSchema', () => { }, ] const schema = fieldsToTypeBoxSchema(fields) - expect(schema.properties.f1.type).toBe('array') - expect(schema.properties.f1.items.enum).toEqual(['opt1', 'opt2']) - expect(schema.properties.f1.description).toBe( + const selectMultiSchema = propsOf(schema).f1.anyOf![0] + expect(selectMultiSchema.type).toBe('array') + expect(selectMultiSchema.items!.enum).toEqual(['opt1', 'opt2']) + expect(selectMultiSchema.description).toBe( "The field 'Tags' represents Tags.\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n- Tag 1 => opt1\n- Tag 2 => opt2", ) + expect(Value.Check(schema, { f1: ['opt1', 'opt2'] })).toBe(true) + expect(Value.Check(schema, { f1: null })).toBe(true) + expect(Value.Check(schema, { f1: ['opt1', 'bad'] })).toBe(false) }) it('defaults to string for unknown types', () => { @@ -85,6 +113,22 @@ describe('fieldsToTypeBoxSchema', () => { { id: 'f1', config: { name: 'Unknown', type: 'invalid' } }, ] const schema = fieldsToTypeBoxSchema(fields) - expect(schema.properties.f1.type).toBe('string') + expect(propsOf(schema).f1.anyOf![0].type).toBe('string') + }) + + it('marks every property required (nullable) and rejects unknown keys', () => { + const fields: AutofillField[] = [ + { id: 'f1', config: { name: 'Title', type: 'text' } }, + { id: 'f2', config: { name: 'Rating', type: 'rating' } }, + ] + const schema = fieldsToTypeBoxSchema(fields) + const props = propsOf(schema) + // typebox v1 objects are strict by default: unknown keys are rejected + expect(props.f1.anyOf![0].type).toBe('string') + expect(props.f1.anyOf![1].type).toBe('null') + expect(Value.Check(schema, { f1: 'x', f2: null })).toBe(true) + expect(Value.Check(schema, { f1: null, f2: 3 })).toBe(true) + expect(Value.Check(schema, { f1: 'x' })).toBe(false) + expect(Value.Check(schema, { f1: 'x', f2: null, extra: 1 })).toBe(false) }) }) diff --git a/packages/agent/src/tools/analyze-image.ts b/packages/agent/src/tools/analyze-image.ts index 2401d6db..46da5b51 100644 --- a/packages/agent/src/tools/analyze-image.ts +++ b/packages/agent/src/tools/analyze-image.ts @@ -1,4 +1,4 @@ -import { Type } from '@sinclair/typebox' +import { Type } from 'typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' import { type ImageContent } from '@earendil-works/pi-ai' import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db' diff --git a/packages/agent/src/tools/create-file.test.ts b/packages/agent/src/tools/create-file.test.ts index 03e2e233..5d54537c 100644 --- a/packages/agent/src/tools/create-file.test.ts +++ b/packages/agent/src/tools/create-file.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { createCreateFileTool } from './create-file' +import { fieldsToTypeBoxSchema } from '../index' import { s3Service } from '@shumai/core/src/s3/s3' import { executeAgentToolWorkflow } from './utils' +import { Value } from 'typebox/value' import * as fs from 'fs' import * as os from 'os' import * as path from 'path' @@ -44,7 +46,7 @@ describe('createCreateFileTool', () => { const filePath = createTempFile('# Hello from disk', 'create-file-test.md') const tool = createCreateFileTool('user-1') - const result = await tool.execute('call-1', { parent: 'folder-1', path: filePath }) + const result = await tool.execute('call-1', { parent: 'folder-1', path: filePath, data: null }) expect(s3Service.uploadFileToKey).toHaveBeenCalledTimes(1) expect(s3Service.putObject).not.toHaveBeenCalled() @@ -70,13 +72,17 @@ describe('createCreateFileTool', () => { expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' }) }) - it('should forward the optional metadata to the agent tool workflow when provided', async () => { + it('should forward the metadata to the agent tool workflow when provided', async () => { const filePath = createTempFile('# Hello from disk', 'create-file-metadata.md') + const metadataSchema = fieldsToTypeBoxSchema([ + { id: 'prompt', config: { name: 'Prompt', type: 'text' } }, + ]) - const tool = createCreateFileTool('user-1') + const tool = createCreateFileTool('user-1', metadataSchema) await tool.execute('call-1', { parent: 'folder-1', path: filePath, + data: null, metadata: { prompt: 'Generated using gemini' }, }) @@ -87,11 +93,19 @@ describe('createCreateFileTool', () => { ) }) - it('should not include metadata in args when not provided', async () => { + it('should not include metadata in args when metadata is null', async () => { const filePath = createTempFile('# Hello from disk', 'create-file-no-metadata.md') + const metadataSchema = fieldsToTypeBoxSchema([ + { id: 'prompt', config: { name: 'Prompt', type: 'text' } }, + ]) - const tool = createCreateFileTool('user-1') - await tool.execute('call-1', { parent: 'folder-1', path: filePath }) + const tool = createCreateFileTool('user-1', metadataSchema) + await tool.execute('call-1', { + parent: 'folder-1', + path: filePath, + data: null, + metadata: null, + }) const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args expect(callArgs).not.toHaveProperty('metadata') @@ -100,7 +114,7 @@ describe('createCreateFileTool', () => { it('should throw when the local file does not exist', async () => { const tool = createCreateFileTool('user-1') await expect( - tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md' }), + tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md', data: null }), ).rejects.toThrow('Local file not found at path: /nonexistent/file.md') expect(s3Service.uploadFileToKey).not.toHaveBeenCalled() expect(executeAgentToolWorkflow).not.toHaveBeenCalled() @@ -110,6 +124,7 @@ describe('createCreateFileTool', () => { const tool = createCreateFileTool('user-1') const result = await tool.execute('call-1', { parent: 'folder-1', + path: null, data: { name: 'notes.md', content: '# Notes\n\nHello' }, }) @@ -145,6 +160,7 @@ describe('createCreateFileTool', () => { const tool = createCreateFileTool('user-1') await tool.execute('call-1', { parent: 'folder-1', + path: null, data: { name: 'script.ts', content: 'const x = 1' }, }) @@ -162,6 +178,7 @@ describe('createCreateFileTool', () => { const tool = createCreateFileTool('user-1') await tool.execute('call-1', { parent: 'folder-1', + path: null, data: { name: 'my/notes.md', content: 'hello' }, }) @@ -183,9 +200,9 @@ describe('createCreateFileTool', () => { it('should throw when neither "path" nor "data" is provided', async () => { const tool = createCreateFileTool('user-1') - await expect(tool.execute('call-1', { parent: 'folder-1' })).rejects.toThrow( - 'Provide exactly one of "path" (a local file) or "data" (name and content).', - ) + await expect( + tool.execute('call-1', { parent: 'folder-1', path: null, data: null }), + ).rejects.toThrow('Provide exactly one of "path" (a local file) or "data" (name and content).') }) it('should throw when both "path" and "data" are provided', async () => { @@ -201,4 +218,51 @@ describe('createCreateFileTool', () => { expect(s3Service.putObject).not.toHaveBeenCalled() expect(executeAgentToolWorkflow).not.toHaveBeenCalled() }) + + it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => { + const metadataSchema = fieldsToTypeBoxSchema([ + { id: 'prompt', config: { name: 'Prompt', type: 'text' } }, + { + id: 'source', + config: { + name: 'Source', + type: 'select', + select: { options: [{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' }] }, + }, + }, + { id: 'rating', config: { name: 'Rating', type: 'rating' } }, + ]) + + const tool = createCreateFileTool('user-1', metadataSchema) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool + const meta = (tool.parameters as any).properties.metadata + // `metadata` is a nullable union: [strict object, null] + const metaObject = meta.anyOf[0] + + expect(meta).toBeDefined() + expect(metaObject.required).toEqual(['prompt', 'source', 'rating']) + expect(metaObject.additionalProperties).toBe(false) + expect(metaObject.properties.prompt.anyOf[0].type).toBe('string') + expect(metaObject.properties.prompt.anyOf[1].type).toBe('null') + expect(metaObject.properties.source.anyOf[0].enum).toEqual(['gemini']) + expect(metaObject.properties.rating.anyOf[0].type).toBe('number') + + // Every field must be present (use null when unknown); unknown keys and bad enums are rejected + expect(Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5 })).toBe(true) + expect(Value.Check(meta, { prompt: null, source: null, rating: null })).toBe(true) + expect(Value.Check(meta, { prompt: 'hello', source: null, rating: null })).toBe(true) + expect(Value.Check(meta, { prompt: 'hello' })).toBe(false) + expect( + Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5, unknownKey: 'x' }), + ).toBe(false) + expect(Value.Check(meta, { prompt: 'hello', source: 'not-an-option', rating: null })).toBe( + false, + ) + }) + + it('should omit the metadata parameter when no schema is provided', () => { + const tool = createCreateFileTool('user-1') + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool + expect((tool.parameters as any).properties.metadata).toBeUndefined() + }) }) diff --git a/packages/agent/src/tools/create-file.ts b/packages/agent/src/tools/create-file.ts index 4b5c919c..64bd8cc0 100644 --- a/packages/agent/src/tools/create-file.ts +++ b/packages/agent/src/tools/create-file.ts @@ -2,67 +2,78 @@ import { type AgentTool } from '@earendil-works/pi-agent-core' import { s3Service } from '@shumai/core/src/s3/s3' import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime' import { sanitizeFilename } from '@shumai/core/src/utils/filename' -import { Type } from '@sinclair/typebox' +import { Type, type TSchema } from 'typebox' import * as fs from 'fs' import * as path from 'path' import { ulid } from 'ulid' import { executeAgentToolWorkflow } from './utils' -const createFileSchema = Type.Object({ - parent: Type.String({ - description: 'The parent folder ID under which to create the file. This parameter is required.', - }), - path: Type.Optional( - Type.String({ - description: - 'The absolute or relative local path to an existing file on disk. Provide either this or "data", but not both.', - }), - ), - data: Type.Optional( - 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.', - }), - }), - ), - metadata: Type.Optional( - Type.Record(Type.String(), Type.Any(), { - description: - 'Key-value map of metadata field keys and their values. Use the "key" field from list_autofill_fields data as the map key.' + - 'Use list_autofill_fields first to inspect available fields.', - }), - ), -}) +interface CreateFileToolParams { + parent: string + path: string | null + data: { name: string; content: string } | null + metadata?: Record | null +} -function assertExactlyOneSource(params: { - path?: string - data?: { name: string; content: string } -}) { - const hasPath = params.path !== undefined - const hasData = params.data !== undefined +function assertExactlyOneSource(params: CreateFileToolParams) { + const hasPath = params.path !== null + const hasData = params.data !== null 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! } -export function createCreateFileTool(userId: string): AgentTool { - return { +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 = { name: 'create_file', label: 'Create File', description: '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. ' + - 'Never provide both "path" and "data" together. Never omit both.', + '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.', parameters: createFileSchema, execute: async (_toolCallId, params) => { - const source = assertExactlyOneSource(params) + // 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) let name: string let size: number @@ -97,15 +108,15 @@ export function createCreateFileTool(userId: string): AgentTool { expect(result.details).toEqual({ id: 'file-1', name: 'v2', type: 'file' }) }) - it('should forward the optional metadata to the agent tool workflow when provided', async () => { + it('should forward the metadata to the agent tool workflow when provided', async () => { const filePath = createTempFile('# Hello from disk', 'create-version-metadata.md') + const metadataSchema = fieldsToTypeBoxSchema([ + { id: 'prompt', config: { name: 'Prompt', type: 'text' } }, + ]) - const tool = createCreateVersionTool('user-1') + const tool = createCreateVersionTool('user-1', metadataSchema) await tool.execute('call-1', { parent: 'file-1', path: filePath, @@ -84,11 +89,14 @@ describe('createCreateVersionTool', () => { ) }) - it('should not include metadata in args when not provided', async () => { + it('should not include metadata in args when metadata is null', async () => { const filePath = createTempFile('# Hello from disk', 'create-version-no-metadata.md') + const metadataSchema = fieldsToTypeBoxSchema([ + { id: 'prompt', config: { name: 'Prompt', type: 'text' } }, + ]) - const tool = createCreateVersionTool('user-1') - await tool.execute('call-1', { parent: 'file-1', path: filePath }) + const tool = createCreateVersionTool('user-1', metadataSchema) + await tool.execute('call-1', { parent: 'file-1', path: filePath, metadata: null }) const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args expect(callArgs).not.toHaveProperty('metadata') @@ -102,4 +110,34 @@ describe('createCreateVersionTool', () => { expect(s3Service.uploadFileToKey).not.toHaveBeenCalled() expect(executeAgentToolWorkflow).not.toHaveBeenCalled() }) + + it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => { + const metadataSchema = fieldsToTypeBoxSchema([ + { id: 'prompt', config: { name: 'Prompt', type: 'text' } }, + { id: 'toggle', config: { name: 'Active', type: 'toggle' } }, + ]) + + const tool = createCreateVersionTool('user-1', metadataSchema) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool + const meta = (tool.parameters as any).properties.metadata + // `metadata` is a nullable union: [strict object, null] + const metaObject = meta.anyOf[0] + + expect(meta).toBeDefined() + expect(metaObject.required).toEqual(['prompt', 'toggle']) + expect(metaObject.additionalProperties).toBe(false) + expect(metaObject.properties.prompt.anyOf[0].type).toBe('string') + expect(metaObject.properties.prompt.anyOf[1].type).toBe('null') + expect(metaObject.properties.toggle.anyOf[0].type).toBe('boolean') + + expect(Value.Check(meta, { prompt: 'p', toggle: true })).toBe(true) + expect(Value.Check(meta, { prompt: null, toggle: null })).toBe(true) + expect(Value.Check(meta, { prompt: 'p', toggle: null, unknownKey: 'x' })).toBe(false) + }) + + it('should omit the metadata parameter when no schema is provided', () => { + const tool = createCreateVersionTool('user-1') + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool + expect((tool.parameters as any).properties.metadata).toBeUndefined() + }) }) diff --git a/packages/agent/src/tools/create-version.ts b/packages/agent/src/tools/create-version.ts index c54b6829..5c0c174f 100644 --- a/packages/agent/src/tools/create-version.ts +++ b/packages/agent/src/tools/create-version.ts @@ -1,4 +1,4 @@ -import { Type } from '@sinclair/typebox' +import { Type, type TSchema } from 'typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' import { executeAgentToolWorkflow } from './utils' import * as fs from 'fs' @@ -8,34 +8,42 @@ import { readFileMimeType } from '@shumai/core/src/utils/file-mime' import { ulid } from 'ulid' import { sanitizeFilename } from '@shumai/core/src/utils/filename' -const createVersionSchema = Type.Object({ - parent: Type.String({ - description: - 'The parent file ID for which to create a new version. This parameter is required.', - }), - path: Type.String({ - description: - 'The absolute or relative local path to the file on disk. This parameter is required.', - }), - metadata: Type.Optional( - Type.Record(Type.String(), Type.Any(), { - description: - 'Key-value map of CREATION_CONTEXT metadata field keys and their values (e.g. prompt, model, provider). ' + - 'Use list_autofill_fields first to inspect available CREATION_CONTEXT fields.', - }), - ), -}) +interface CreateVersionToolParams { + parent: string + path: string + metadata?: Record | null +} -export function createCreateVersionTool(userId: string): AgentTool { - return { +export function createCreateVersionTool(userId: string, metadataSchema?: TSchema): AgentTool { + const createVersionSchema = Type.Object( + { + parent: Type.String({ + description: + 'The parent file ID for which to create a new version. This parameter is required.', + }), + path: Type.String({ + description: + 'The absolute or relative local path to the file on disk. This parameter is required.', + }), + ...(metadataSchema ? { metadata: Type.Union([metadataSchema, Type.Null()]) } : {}), + }, + { additionalProperties: false }, + ) + + const tool: AgentTool = { name: 'create_version', label: 'Create Version', - description: 'Create a new version of an existing file from a local file path.', + description: + 'Create a new version of an existing file from a local file path. ' + + '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.', parameters: createVersionSchema, execute: async (_toolCallId, params) => { - const absolutePath = path.resolve(process.cwd(), params.path) + // The harness validates tool args against `createVersionSchema` before calling + // execute, so `params` is guaranteed to match this shape. + const p = params as CreateVersionToolParams + const absolutePath = path.resolve(process.cwd(), p.path) if (!fs.existsSync(absolutePath)) { - throw new Error(`Local file not found at path: ${params.path}`) + throw new Error(`Local file not found at path: ${p.path}`) } const fileSize = fs.statSync(absolutePath).size @@ -48,15 +56,15 @@ export function createCreateVersionTool(userId: string): AgentTool ({ - executeAgentToolWorkflow: vi.fn().mockResolvedValue({ - fields: [{ name: 'Source', type: 'select', options: [{ displayName: 'Gemini' }] }], - }), -})) - -describe('createListAutofillFieldsTool', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('should list autofill fields for the parent folder via the agent tool workflow', async () => { - const tool = createListAutofillFieldsTool('user-1') - const result = await tool.execute('call-1', { parent: 'folder-1' }) - - expect(executeAgentToolWorkflow).toHaveBeenCalledWith({ - toolName: 'list_autofill_fields', - args: { parent: 'folder-1' }, - userId: 'user-1', - assetId: 'folder-1', - }) - - expect(result.details).toEqual({ - fields: [{ name: 'Source', type: 'select', options: [{ displayName: 'Gemini' }] }], - }) - }) -}) diff --git a/packages/agent/src/tools/list-autofill-fields.ts b/packages/agent/src/tools/list-autofill-fields.ts deleted file mode 100644 index dc4de77b..00000000 --- a/packages/agent/src/tools/list-autofill-fields.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { Type } from '@sinclair/typebox' -import { type AgentTool } from '@earendil-works/pi-agent-core' -import { executeAgentToolWorkflow } from './utils' - -const listAutofillFieldsSchema = Type.Object({ - parent: Type.String({ - description: - 'The parent folder ID whose project autofillable metadata fields to list. This parameter is required.', - }), -}) - -export function createListAutofillFieldsTool( - userId: string, -): AgentTool { - return { - name: 'list_autofill_fields', - label: 'List Autofill Fields', - description: - 'List the CREATION_CONTEXT metadata fields defined for the project of a parent folder (e.g. model or prompt used to generate the asset). ' + - 'Use this before calling create_file or create_version so you can populate their field keys and values in the "metadata" dictionary parameter.', - parameters: listAutofillFieldsSchema, - execute: async (_toolCallId, params) => { - const result = await executeAgentToolWorkflow({ - toolName: 'list_autofill_fields', - args: params, - userId, - assetId: params.parent, - }) - return { - content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], - details: result, - } - }, - } -} diff --git a/packages/agent/src/tools/read-pdf-pages.ts b/packages/agent/src/tools/read-pdf-pages.ts index 14575905..d9cad2bb 100644 --- a/packages/agent/src/tools/read-pdf-pages.ts +++ b/packages/agent/src/tools/read-pdf-pages.ts @@ -1,4 +1,4 @@ -import { Type } from '@sinclair/typebox' +import { Type } from 'typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' import { type ImageContent } from '@earendil-works/pi-ai' import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db' diff --git a/packages/agent/src/tools/read-skill.ts b/packages/agent/src/tools/read-skill.ts index 381300e7..d6952893 100644 --- a/packages/agent/src/tools/read-skill.ts +++ b/packages/agent/src/tools/read-skill.ts @@ -1,5 +1,5 @@ import { prisma } from '@shumai/db' -import { Type } from '@sinclair/typebox' +import { Type } from 'typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' import { agentService } from '@shumai/core/src/agent/agent' diff --git a/packages/agent/src/tools/read-thread.ts b/packages/agent/src/tools/read-thread.ts index f1683f24..50855308 100644 --- a/packages/agent/src/tools/read-thread.ts +++ b/packages/agent/src/tools/read-thread.ts @@ -1,5 +1,5 @@ import { prisma } from '@shumai/db' -import { Type } from '@sinclair/typebox' +import { Type } from 'typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' const readThreadSchema = Type.Object({ diff --git a/packages/agent/src/tools/sandboxed-bash.ts b/packages/agent/src/tools/sandboxed-bash.ts index 30357b4e..a30d8cba 100644 --- a/packages/agent/src/tools/sandboxed-bash.ts +++ b/packages/agent/src/tools/sandboxed-bash.ts @@ -1,7 +1,7 @@ import { logger } from '@shumai/core/src/logger' import { SandboxManager } from '@anthropic-ai/sandbox-runtime' import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core' -import { Type } from '@sinclair/typebox' +import { Type } from 'typebox' import { spawn } from 'node:child_process' import { OutputAccumulator } from '../utils/output-accumulator' import { diff --git a/packages/agent/src/tools/screenshot.ts b/packages/agent/src/tools/screenshot.ts index bf4d00e6..d0905ee0 100644 --- a/packages/agent/src/tools/screenshot.ts +++ b/packages/agent/src/tools/screenshot.ts @@ -1,4 +1,4 @@ -import { Type } from '@sinclair/typebox' +import { Type } from 'typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' import { type ImageContent } from '@earendil-works/pi-ai' import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db' diff --git a/packages/agent/src/workflows/agent-autofill.ts b/packages/agent/src/workflows/agent-autofill.ts index 27c58277..27c29b91 100644 --- a/packages/agent/src/workflows/agent-autofill.ts +++ b/packages/agent/src/workflows/agent-autofill.ts @@ -157,10 +157,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { // 6. Update Asset Metadata const result = JSON.parse(aiResult.text) - const metadataUpdates = Object.entries(result).map(([key, value]) => ({ - key, - value, - })) + const metadataUpdates = Object.entries(result) + .filter(([, value]) => value !== null) + .map(([key, value]) => ({ + key, + value, + })) if (metadataUpdates.length > 0) { await executeActivity(agentWorkerQueue, updateAssetMetadataActivity, { diff --git a/patches/@earendil-works%2Fpi-ai@0.82.1.patch b/patches/@earendil-works%2Fpi-ai@0.82.1.patch new file mode 100644 index 00000000..07653a21 --- /dev/null +++ b/patches/@earendil-works%2Fpi-ai@0.82.1.patch @@ -0,0 +1,17 @@ +diff --git a/dist/utils/validation.js b/dist/utils/validation.js +index 6cffb0855554b0f53d9ca76eba3bd1641dcc19ef..bcd7991bb59163e6f2f2819827790227f8b69e8c 100644 +--- a/dist/utils/validation.js ++++ b/dist/utils/validation.js +@@ -150,6 +150,12 @@ function applySchemaArrayCoercion(value, schema) { + } + } + function coerceWithUnionSchema(value, schemas) { ++ for (const schema of schemas) { ++ const validator = getSubSchemaValidator(schema); ++ if (validator?.Check(value)) { ++ return value; ++ } ++ } + for (const schema of schemas) { + const candidate = structuredClone(value); + const coerced = coerceWithJsonSchema(candidate, schema);