178 lines
10 KiB
JavaScript
178 lines
10 KiB
JavaScript
import { sessionSystemPrompt } from '../src/agent.mjs';
|
|
import assert from 'node:assert/strict';
|
|
import test from 'node:test';
|
|
import { validateToolArguments } from '@earendil-works/pi-ai';
|
|
import { anthropicMessagesApi, normalizeContext, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat';
|
|
import { convertTools as googleTools } from '@earendil-works/pi-ai/api/google-shared';
|
|
import { renderToolSample } from '@earendil-works/pi-codemode';
|
|
import { openProductionOperations } from '../src/production-operations.mjs';
|
|
import { reviewProductionCandidate } from '../src/candidate-review.mjs';
|
|
import { reviewOutputScreen } from '../src/screen-review.mjs';
|
|
import { completeCanvas, openAgent } from './fake-canvas.mjs';
|
|
import { piInfo, piProject } from './pi-compat-fixture.mjs';
|
|
import { normalizeToolArgs } from '../src/tool-schema.mjs';
|
|
|
|
function inspectSchema(schema, name) {
|
|
assert.ok(schema.type || schema.anyOf || schema.oneOf || schema.allOf || schema.$ref,`untyped schema: ${name}`);
|
|
assert.notEqual(schema.type,'null',name);
|
|
for (const keyword of ['const','minProperties','uniqueItems','exclusiveMinimum','multipleOf','prefixItems','nullable']) {
|
|
assert.ok(!Object.hasOwn(schema,keyword),`${keyword}: ${name}`);
|
|
}
|
|
assert.doesNotMatch(schema.pattern??'',/\\u[0-9a-f]{4}/i,name);
|
|
assert.ok(!Array.isArray(schema.items),`tuple items: ${name}`);
|
|
if (schema.type==='array') assert.ok(schema.items,`array without items: ${name}`);
|
|
if (schema.additionalProperties===true && schema.properties) {
|
|
assert.ok(Object.keys(schema.properties).length,`empty open properties: ${name}`);
|
|
}
|
|
for (const [key,child] of Object.entries(schema.properties??{})) inspectSchema(child,name+'.'+key);
|
|
if (schema.items) inspectSchema(schema.items,name+'[]');
|
|
for (const child of [...(schema.anyOf??[]),...(schema.oneOf??[]),...(schema.allOf??[])]) inspectSchema(child,name);
|
|
if (typeof schema.additionalProperties==='object') inspectSchema(schema.additionalProperties,name+'.*');
|
|
}
|
|
|
|
function sample(schema) {
|
|
if (schema.default!==undefined) return schema.default;
|
|
if (schema.enum) return schema.enum[0];
|
|
if (schema.anyOf) return sample(schema.anyOf[0]);
|
|
if (schema.type==='object') return Object.fromEntries((schema.required??[]).map(key=>[key,sample(schema.properties[key])]));
|
|
if (schema.type==='array') return Array.from({length:schema.minItems??0},()=>sample(schema.items));
|
|
if (schema.type==='boolean') return true;
|
|
if (schema.type==='integer' || schema.type==='number') return Math.max(schema.minimum??1,0);
|
|
if (schema.pattern) {
|
|
const example=['P01','1:1','#111111','a'.repeat(64),'a'.repeat(36)].find(value=>new RegExp(schema.pattern).test(value));
|
|
assert.ok(example,schema.pattern);
|
|
return example;
|
|
}
|
|
return 'x'.repeat(Math.max(1,schema.minLength??0));
|
|
}
|
|
|
|
async function wireSchemas(api, factory, tools) {
|
|
let payload;
|
|
const model={id:'schema-test',name:'schema-test',api,provider:'fixture',
|
|
baseUrl:api==='anthropic-messages'?'https://example.invalid':'https://example.invalid/v1',
|
|
input:['text'],maxTokens:512,contextWindow:12_000,reasoning:false,
|
|
cost:{input:0,output:0,cacheRead:0,cacheWrite:0}};
|
|
const stream=factory().streamSimple(model,normalizeContext({tools,messages:[
|
|
{role:'user',content:'schema fixture',timestamp:1},
|
|
]}),{apiKey:'fixture',maxRetries:0,onPayload(value){payload=value;},
|
|
fetch:async()=>new Response('{}',{status:400})});
|
|
await stream.result();
|
|
assert.ok(payload?.tools,api);
|
|
return payload.tools.map(tool=>api==='anthropic-messages'?[tool.name,tool.input_schema] :
|
|
api==='openai-responses'?[tool.name,tool.parameters]:[tool.function.name,tool.function.parameters]);
|
|
}
|
|
|
|
test('all registered chat, production and worker tool schemas pass Pi validation and four wire converters',async t=>{
|
|
const store=await piProject(t);
|
|
const model=piInfo(store);
|
|
const productionGoal={workspaceId:'schema-test',requestedOutputs:[{outputId:'detail',variantId:'natural'}]};
|
|
const modes=[];
|
|
for (const goal of [undefined,productionGoal]) {
|
|
const host=await openAgent({store,transport:{info:model},productionGoal:goal});
|
|
try {
|
|
const registered=host.session.getAllTools();
|
|
const names=new Set(registered.map(tool=>tool.name));
|
|
const declared=[...sessionSystemPrompt(Boolean(goal)).matchAll(/「([a-z][a-z0-9_]+)」/gu)];
|
|
assert.ok(declared.length);
|
|
for (const [,name] of declared) assert.ok(names.has(name),name);
|
|
modes.push(registered);
|
|
}
|
|
finally { await host.dispose(); }
|
|
}
|
|
const image={type:'image',data:'fixture',mimeType:'image/png'};
|
|
const slot={id:'slot',fieldId:'field',label:'首屏'};
|
|
const screen={image,content:[image],details:{page:0,revision:1,screenFingerprint:'fixture',
|
|
slots:[slot],overlayLayers:[],screenCopy:[]}};
|
|
const workerTools=[];
|
|
await reviewProductionCandidate({canvas:{detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image]})},
|
|
slot,candidateId:'candidate',screen,rule:{structureGuides:{edge:'部件边缘'}},
|
|
async runAgent(_id,_system,_prompt,[tool]){
|
|
workerTools.push(tool);
|
|
const args={verdict:'pass',reason:'已核对',checks:{templateStyle:null,viewpoint:null},
|
|
canvasTransform:{crop:[0,0,1000,1000]},structureGuides:{edge:[[10,20]]}};
|
|
const checked=validateToolArguments(tool,{name:tool.name,arguments:args});
|
|
assert.notEqual(checked.checks.viewpoint,false);
|
|
assert.notEqual(checked.checks.templateStyle,false);
|
|
await tool.execute('review',args);
|
|
}});
|
|
await reviewOutputScreen({page:1,screen,slots:[slot],outputId:'detail',variantId:'natural',
|
|
references:async()=>({photos:[]}),async runAgent(_id,_system,_prompt,[tool]){
|
|
workerTools.push(tool);
|
|
await tool.execute('review',{verdict:'pass',summary:'已核对',templateStyle:null});
|
|
}});
|
|
|
|
const slots=[slot,{id:'slot-2',fieldId:'field-2',label:'细节图'},{id:'slot-3',fieldId:'field-3',label:'局部图'}];
|
|
const delegateTools=[];
|
|
const delegated=[];
|
|
const canvas=completeCanvas({
|
|
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'natural',
|
|
template:{contentHash:'schema-test'},slots,totalSlots:slots.length}),
|
|
imageRequest:async()=>[],
|
|
});
|
|
const operations=await openProductionOperations({canvas,store,
|
|
productionGoal:{outputId:'detail',variantId:'natural'},
|
|
runDetailAgent:async(id,_system,_prompt,tools)=>{
|
|
if(!delegated.length)delegateTools.push(...tools);
|
|
delegated.push(id);
|
|
}});
|
|
try {
|
|
await operations.delegate_image_slots({jobs:[
|
|
{slotId:'slot',goal:'展示商品'},
|
|
{slotId:'slot-2',goal:'展示结构',reuseTargets:[{slotId:'slot-3'}]},
|
|
]});
|
|
while (operations.active) await operations.await_image_slots({});
|
|
} finally { await operations.close(); }
|
|
assert.deepEqual(delegated.sort(),['slot','slot-2','slot-3']);
|
|
assert.ok(delegateTools.some(tool=>tool.name==='prepare_image_request'));
|
|
assert.ok(delegateTools.some(tool=>tool.name==='list_project_images'));
|
|
const delegateSchema=modes[1].find(tool=>tool.name==='delegate_image_slots');
|
|
assert.equal(delegateSchema.parameters.properties.jobs.items.properties.reuseTargets,undefined);
|
|
for(const tool of delegateTools){
|
|
const main=modes[1].find(main=>main.name===tool.name);
|
|
assert.deepEqual(tool.parameters,main.parameters,tool.name);
|
|
assert.equal(tool.description,main.description,tool.name);
|
|
}
|
|
const productionArgs=(name,args)=>{
|
|
const tool=modes[1].find(tool=>tool.name===name);
|
|
return validateToolArguments(tool,{name,arguments:normalizeToolArgs(args,tool.parameters)});
|
|
};
|
|
assert.deepEqual(productionArgs('delegate_image_slots',{jobs:[{slotId:'slot-2',goal:'复用',reuseTargets:[{slotId:'slot-3'}]}]}).jobs[0].reuseTargets,[{slotId:'slot-3'}]);
|
|
const oldPhoto=productionArgs('use_product_image',{id:'hero',productVariantId:'oak',reference:'P01'});
|
|
assert.equal(oldPhoto.slotId,'hero');
|
|
assert.equal(oldPhoto.variantId,'oak');
|
|
assert.deepEqual(oldPhoto.productReferences,['P01']);
|
|
assert.deepEqual(productionArgs('prepare_image_request',{prompt:'场景',references:['P02','P01']}).productReferences,['P02','P01']);
|
|
assert.deepEqual(productionArgs('prepare_image_request',{prompt:'场景',productReferences:[]}).productReferences,[]);
|
|
assert.equal(productionArgs('transform_slot_image',{slotId:'detail',sourceCandidateId:'medium'}).candidateId,'medium');
|
|
assert.equal(productionArgs('adopt_production_image',{fieldId:'main',id:'candidate'}).candidateId,'candidate');
|
|
assert.equal(productionArgs('dispatch_image_request',{operationId:'request'}).requestId,'request');
|
|
assert.deepEqual(productionArgs('await_image_slots',{operationIds:['request']}).requestIds,['request']);
|
|
assert.equal(productionArgs('await_image_slots',{candidateId:'candidate'}).requestId,undefined);
|
|
modes.push(workerTools,delegateTools);
|
|
|
|
const preview=modes[0].find(tool=>tool.name==='canvas_preview');
|
|
const args={command:'type.edit',params:{layer:1,box:[1,2,3,4],
|
|
runs:[{start:0,end:2,font:'Inter',kerning:-20,features:{ss01:true},variations:{wght:650}}]}};
|
|
assert.deepEqual(validateToolArguments(preview,{name:preview.name,arguments:args}),args);
|
|
const productImage=delegateTools.find(tool=>tool.name==='use_product_image');
|
|
assert.throws(()=>validateToolArguments(productImage,{name:productImage.name,arguments:{referenceCrop:[1,2,3]}}));
|
|
|
|
for (const tools of modes) {
|
|
for (const tool of tools) {
|
|
inspectSchema(tool.parameters,tool.name);
|
|
const args=sample(tool.parameters);
|
|
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:args}),args,tool.name);
|
|
assert.ok(renderToolSample({name:tool.name,description:tool.description,inputSchema:tool.parameters}).includes(tool.name));
|
|
}
|
|
const google=googleTools(tools)[0].functionDeclarations.map(tool=>[tool.name,tool.parametersJsonSchema]);
|
|
for (const declarations of [
|
|
await wireSchemas('anthropic-messages',anthropicMessagesApi,tools),
|
|
await wireSchemas('openai-responses',openAIResponsesApi,tools),
|
|
await wireSchemas('openai-completions',openAICompletionsApi,tools),google,
|
|
]) {
|
|
assert.deepEqual(declarations.map(([name])=>name),tools.map(tool=>tool.name));
|
|
for (const [name,schema] of declarations) inspectSchema(schema,name);
|
|
}
|
|
}
|
|
});
|