fix(tools): isolate tool schemas and waterfall failures

This commit is contained in:
Tianyi Cui
2026-06-17 21:26:12 +08:00
parent 922e2f913e
commit 87df09e3c3
4 changed files with 66 additions and 3 deletions

View File

@@ -123,8 +123,11 @@ export class SystemPrompt extends Service {
*/
assemble(): Promise<PromptAssembly> {
const assembly: PromptAssembly = {
sections: [...this.sections].sort((a, b) => a.order - b.order),
tools: this.toolProviders.flatMap(provider => provider()),
sections: this.sections
.map(section => ({ ...section }))
.sort((a, b) => a.order - b.order),
tools: this.toolProviders.flatMap(provider =>
provider().map(tool => ({ ...tool, parameters: structuredClone(tool.parameters) }))),
}
return this.ctx.waterfall(this, 'system-prompt/assemble', assembly, () => Promise.resolve(assembly))
}

View File

@@ -107,6 +107,23 @@ describe('SystemPrompt', () => {
expect(assembly.sections).toHaveLength(0)
})
it('assembles snapshots so one-step mutations do not leak into future assemblies', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
ctx.systemPrompt.section({ name: 'base', order: 0, text: 'base' })
ctx.systemPrompt.tools(() => [{ name: 't', description: 'tool', parameters: { type: 'object', properties: {} } }])
const first = await ctx.systemPrompt.assemble()
first.sections[0]!.name = 'mutated'
first.tools[0]!.description = 'mutated'
const firstParameters = first.tools[0]!.parameters as { properties: Record<string, unknown> }
firstParameters.properties['leak'] = { type: 'string' }
const second = await ctx.systemPrompt.assemble()
expect(second.sections.map(section => section.name)).toEqual(['base'])
expect(second.tools).toEqual([{ name: 't', description: 'tool', parameters: { type: 'object', properties: {} } }])
})
it('filters out empty section text from renderPrompt', () => {
// Direct test of renderPrompt: function returning empty string, and empty static text
const result = renderPrompt({