174 lines
9.7 KiB
JavaScript
174 lines
9.7 KiB
JavaScript
import {openXiaoyiSkills} from '../src/xiaoyi-release.mjs';
|
|
import {xiaoyiFixture} from './xiaoyi-fixture.mjs';
|
|
import {projectTools} from '../src/project-tools.mjs';
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import {createHash} from 'node:crypto';
|
|
import {EnterpriseContext} from '../src/enterprise-context.mjs';
|
|
import {EnterpriseKnowledge,enterpriseToolResult} from '../src/enterprise-knowledge.mjs';
|
|
|
|
test('selected resource guides are read completely with their own versions',async t=>{
|
|
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-guides-'));
|
|
t.after(()=>fs.rm(root,{recursive:true}));
|
|
const calls=[],documents=[];
|
|
const display=['SKILL.md','SKILL.md','验图全文.md'];
|
|
const assets=display.map((name,index)=>({id:'guide-'+index,role:'guide',required:true,status:'available',
|
|
file:{name,path:'Skills/'+index+'/'+name,fileId:'file-'+index,revision:'revision-'+index}}));
|
|
assets.push({id:'optional',role:'guide',required:false,status:'available',
|
|
file:{name:'附录.md',path:'Skills/2/附录.md',fileId:'file-3',revision:'revision-3'}});
|
|
const client={
|
|
call:async(name,params)=>{
|
|
calls.push([name,params]);
|
|
if(name==='list_libraries')return {result:{navigation:[{name:'Skills',path:'Skills'}]}};
|
|
return {result:{revision:'view',resourceSet:{brand:'顾家',category:'电脑桌'},components:[{id:'visual_guides',status:'available',assets}]}};
|
|
},
|
|
readDocument:async (id,revision)=>{
|
|
documents.push([id,revision]);
|
|
return {result:{text:'第一页\n第二页',pages:2,revision}};
|
|
},
|
|
};
|
|
const ctx=new EnterpriseContext({root,appendEvent:async()=>{}},client);
|
|
const result=await ctx.load({task:'image',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected'});
|
|
assert.deepEqual(calls.map(([name])=>name),['list_libraries','get_resource_set']);
|
|
assert.equal(calls[1][1].resourceSetId,'selected');
|
|
assert.deepEqual(documents,assets.slice(0,3).map(a=>[a.file.fileId,a.file.revision]));
|
|
assert.equal(result.skills.length,2);
|
|
assert.equal(result.rules[0].text,'第一页\n第二页');
|
|
assert.equal(result.rules[0].pages,2);
|
|
const production=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'});
|
|
assert.deepEqual(production.skills,result.skills);
|
|
assert.deepEqual(production.rules.map(rule=>rule.text),['第一页\n第二页','第一页\n第二页']);
|
|
assert.deepEqual(documents.slice(3),assets.map(a=>[a.file.fileId,a.file.revision]));
|
|
assert.deepEqual(calls.slice(2).map(([name])=>name),['list_libraries','get_resource_set']);
|
|
assets[0].file.revision='updated-after-first-load';
|
|
const current=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'});
|
|
assert.equal(current.skills[0].revision,'updated-after-first-load');
|
|
const attachment={name:'references.zip',path:'Skills/2/references.zip',fileId:'attachment',revision:'pinned'};
|
|
assets.push({id:'references',role:'attachment',status:'available',file:attachment});
|
|
const localPath=path.join(root,attachment.name);
|
|
await fs.writeFile(localPath,'fixture attachment');
|
|
client.download=async args=>{
|
|
assert.deepEqual(args,{fileId:'attachment',revision:'pinned'});
|
|
return {result:{localPath}};
|
|
};
|
|
const withAttachment=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected'});
|
|
assert.equal(withAttachment.rules.at(-1).kind,'attachment');
|
|
assert.equal(Buffer.from(withAttachment.rules.at(-1).bytes,'base64').toString(),'fixture attachment');
|
|
});
|
|
|
|
test('all referenced guides lock with their original relative paths', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-guides-'));
|
|
t.after(() => fs.rm(dir,{recursive:true}));
|
|
const store = {dir,appendEvent:async()=>{}};
|
|
const entry = '规则/SKILL.md';
|
|
const documents = Object.fromEntries(Array.from({length:18},(_,n)=>['规则/rule-'+n+'.md','规则 '+n]));
|
|
documents[entry] = '---\nname: lighting\ndescription: Lighting instructions.\n---\n[Review](rule-0.md)';
|
|
const open = openXiaoyiSkills(store,'light',undefined,undefined,xiaoyiFixture('light','v1',entry,documents));
|
|
const bound = await open;
|
|
assert.equal(bound.resource.skills[0].name,'lighting');
|
|
assert.equal(bound.files.length,20);
|
|
const {read} = await projectTools({store,productionSkills:bound});
|
|
assert.equal((await read('main').execute('',{path:'规则/rule-0.md'})).content[0].text,'规则 0');
|
|
});
|
|
|
|
test('an oversized appendix is held in the bundle and read on demand', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-appendix-'));
|
|
t.after(() => fs.rm(dir,{recursive:true}));
|
|
const store = {dir,appendEvent:async()=>{}};
|
|
const entry = '规则/SKILL.md';
|
|
const body = '规则'.repeat(40000);
|
|
const fetch = xiaoyiFixture('light','v1',entry,{
|
|
[entry]:'---\nname: lighting\ndescription: Lighting instructions.\n---\n[附录](appendix.md)',
|
|
'规则/appendix.md':body,
|
|
});
|
|
const bound = await openXiaoyiSkills(store,'light',undefined,undefined,fetch);
|
|
assert.equal(await fs.readFile(path.join(bound.filesRoot,'规则','appendix.md'),'utf8'),body);
|
|
});
|
|
|
|
test('knowledge tools keep server rules, quota and policy in events and out of both model result channels', async () => {
|
|
const payload = {revision:'view',resourceSet:{resourceSetId:'selected'},components:[]};
|
|
const taskRules = {task:'production',required:true};
|
|
const usage={remaining:100}, policy={maxResponseCharacters:24000}, events=[];
|
|
const knowledge = new EnterpriseKnowledge({
|
|
store:{appendEvent:async event=>events.push(event)},
|
|
endpoints:['https://knowledge.test'],
|
|
fetchImpl:async (_url,options)=>{
|
|
if(!options.body) return Response.json({status:'ok',service:'enterprise-knowledge-base'});
|
|
const {id,method} = JSON.parse(options.body);
|
|
if(method!=='initialize') {
|
|
assert.equal(options.headers['Mcp-Session-Id'],'offline-session');
|
|
assert.equal(options.headers['MCP-Protocol-Version'],'2025-06-18');
|
|
}
|
|
if(method==='notifications/initialized') return new Response(null,{status:202});
|
|
const result={
|
|
initialize:{protocolVersion:'2025-06-18'},
|
|
'tools/list':{tools:[{name:'get_resource_set',inputSchema:{type:'object',
|
|
properties:{resourceSetId:{type:'string'},revision:{type:'string'}},
|
|
required:['resourceSetId'],additionalProperties:false}}]},
|
|
'tools/call':{content:[payload,{taskRules,usage,policy}].map(value=>({type:'text',text:JSON.stringify(value)}))},
|
|
}[method];
|
|
const envelope={jsonrpc:'2.0',id,result};
|
|
return new Response('event: message\ndata: '+JSON.stringify(envelope)+'\n\n',
|
|
{headers:{'content-type':'text/event-stream',...(method==='initialize'?{'mcp-session-id':'offline-session'}:{})}});
|
|
},
|
|
});
|
|
|
|
const reply=await knowledge.call('get_resource_set',{resourceSetId:'selected',revision:'view'});
|
|
const shown=enterpriseToolResult(reply);
|
|
assert.deepEqual(shown.details.result,payload);
|
|
assert.deepEqual(JSON.parse(shown.content[0].text).result,payload);
|
|
assert.deepEqual(events,[{type:'enterprise_knowledge_operational',tool:'get_resource_set',taskRules,usage,policy}]);
|
|
await assert.rejects(knowledge.call('get_resource_set',{resourceSetId:'selected',revision:'stale'}),{status:409});
|
|
});
|
|
|
|
test('a document with a mismatched normalized-text hash cannot be locked', async () => {
|
|
const knowledge=new EnterpriseKnowledge();
|
|
const text='版本锁定的正文';
|
|
const textSha256=createHash('sha256').update(text).digest('hex');
|
|
let body=text;
|
|
knowledge.call=async()=>({result:{revision:'one',text:body,textSha256,isLastPage:true,nextOffset:null}});
|
|
assert.equal((await knowledge.readDocument('guide','one')).result.text,text);
|
|
body+='另一个版本';
|
|
await assert.rejects(knowledge.readDocument('guide','one'),/全文校验失败/u);
|
|
});
|
|
|
|
|
|
test('锁定快照保留规则链接使用的图片、PDF 和 JSON 附件原始字节', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-attachments-'));
|
|
t.after(() => fs.rm(dir,{recursive:true}));
|
|
const store = {dir};
|
|
const entry = '规则/SKILL.md';
|
|
const attachments = {'规则/photo.png':Buffer.from([0,255,7]),'规则/spec.pdf':'%PDF-1.7','规则/preset.json':'{"a":1}'};
|
|
const fetch = xiaoyiFixture('light','v1',entry,{
|
|
[entry]:'---\nname: lighting\ndescription: Lighting instructions.\n---\n[预览](photo.png)',
|
|
...attachments,
|
|
});
|
|
await openXiaoyiSkills(store,'light',undefined,undefined,fetch);
|
|
const locked = await openXiaoyiSkills(store,'light',undefined,undefined,()=>assert.fail('再次访问服务端'));
|
|
for (const [relative,body] of Object.entries(attachments)) {
|
|
assert.deepEqual(await fs.readFile(path.join(locked.filesRoot,relative)),Buffer.from(body));
|
|
}
|
|
});
|
|
|
|
test('续做时只读本地锁定版本,服务端撤回不会触发请求', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-retired-'));
|
|
t.after(() => fs.rm(dir,{recursive:true}));
|
|
const store = {dir};
|
|
const entry = '规则/SKILL.md';
|
|
const fetch = xiaoyiFixture('light','v1',entry,{
|
|
[entry]:'---\nname: lighting\ndescription: Lighting instructions.\n---\n正文',
|
|
});
|
|
await openXiaoyiSkills(store,'light',undefined,undefined,fetch);
|
|
let requests = 0;
|
|
const retired = () => {
|
|
requests++;
|
|
return Response.json({status:410,code:'version_retired',retryable:false},{status:410});
|
|
};
|
|
assert.equal((await openXiaoyiSkills(store,'light',undefined,undefined,retired)).knowledgeVersion,'light@v1');
|
|
assert.equal(requests,0);
|
|
await assert.rejects(openXiaoyiSkills(store,'light',undefined,'prior-finished',retired),{status:410});
|
|
});
|