修复小壹子代理企业指引路径与读取回执

This commit is contained in:
WuYongJie 2026-11-28 18:28:04 +08:00
parent b0bab65aba
commit fbd1fcfae0
6 changed files with 110 additions and 26 deletions

View File

@ -570,9 +570,12 @@ export class DetailPiAgent {
activeSignal?.throwIfAborted();
const scoped = broker?.forDetailSlot?.(requestScope);
if (!scoped&&!transport?.stream) throw Error('详情页模型连接未就绪');
const enterpriseSkills = host.productionSkills?.resource.skills;
if (enterpriseSkills?.length) {
systemPrompt += formatSkillsForPrompt(enterpriseSkills);
const enterpriseSkills = host.productionSkills;
if (enterpriseSkills?.resource.skills.length) {
systemPrompt += formatSkillsForPrompt(enterpriseSkills.resource.skills.map(skill=>({
...skill,filePath:enterpriseSkills.documents.get(skill.filePath).path,
}))).replace("Resolve relative paths against the skill's directory (parent of SKILL.md). Use absolute paths in tool calls.",
'调用 read 时填写相对于锁定资料根目录的路径。SKILL.md 内的相对链接先按该文件所在目录拼接。');
tools = [...tools,files.read('worker',requestScope)];
}
const resourceLoader = await (workerResources ??= loadWorkerResources());

View File

@ -23,7 +23,8 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
const references = new Map();
const inFlight = new Map();
const download = saved ? null : {fileCount:0,bytes:0};
const filePath = relative => path.join(directory, 'files', ...relative.split('/'));
const filesRoot = path.join(directory, 'files');
const filePath = relative => path.join(filesRoot, ...relative.split('/'));
const validPath = relative => typeof relative === 'string' && relative && relative !== '.' &&
relative !== '..' && !relative.startsWith('../') && !path.posix.isAbsolute(relative) &&
!/[:\\\0]/u.test(relative) && path.posix.normalize(relative) === relative;
@ -147,6 +148,21 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
return true;
}
function missingFileMessage(file, requestedPath) {
const relativePath = target=>path.relative(filesRoot,target).split(path.sep).join('/');
const relative = relativePath(file);
const outside = path.isAbsolute(relative) || relative === '..' || relative.startsWith('../');
const displayed = outside ? requestedPath : relative || '.';
const entries = skillPaths.map(entry=>documents.get(entry).path);
const name = path.basename(file);
const namesakes = [...new Set([...documents.keys(),...scriptSources.keys(),...references.keys()])]
.filter(target=>path.basename(target)===name).map(relativePath);
return [`「${displayed}」不在当前项目锁定的企业资料中。`,
'锁定资料入口:',...entries,
...(namesakes.length ? ['同名文件:',...namesakes] : []),
].join('\n');
}
async function shellFiles(signal) {
for (const file of [...scriptSources.keys(), ...knowledge.rules.map(item => filePath(item.path))]) {
signal.throwIfAborted();
@ -187,6 +203,6 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
return [...sources.values()].map(source=>({...source,path:filePath(source.path)}));
},
resource, documents, resolveFile, shellFiles,
filesRoot, resource, documents, resolveFile, missingFileMessage, shellFiles,
};
}

View File

@ -685,7 +685,13 @@ export async function openProductionOperations(host,{target=host.productionGoal,
if(status.drawLimitReached)return drawLimit(live,status);
const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined,useTemplateReference,
prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange,
...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)});
...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)}).catch(async error=>{
if(error.message!=='同款原图编号无效')throw error;
const {referenceCount}=await readImages(slot.id,{includeTemplateReference:false});
const range=referenceCount ? `可用编号 0–${referenceCount-1}` : '当前没有同款原图';
error.message+=`,${range}`;
throw error;
});
return {...receipt,operationId:receipt.requestId};
};
const preparedRequest=async(requestId,slot)=>{

View File

@ -3,6 +3,13 @@ import path from 'node:path';
import {createReadTool,createWriteTool,createEditTool,createLsTool,createFindTool,createGrepTool,createBashTool} from '@earendil-works/pi-coding-agent';
import {projectShell} from './project-shell.mjs';
class UnlockedEnterpriseFile extends Error {
constructor(file){
super();
this.file=file;
}
}
export async function projectTools(host) {
const projectRoot = await fs.realpath(host.store.dir);
const cwd = path.join(projectRoot,'workspace');
@ -29,23 +36,36 @@ export async function projectTools(host) {
try {await fs.access(file);return true;}
catch(error) {if(error.code==='ENOENT')return false;throw error;}
};
const read=(agent,requestScope)=>createReadTool(cwd,{operations:{
access:async file=>{
const normalized=path.normalize(file);
if(agent==='worker'){
if(!await host.productionSkills.resolveFile(normalized))throw Error('制作助手只能读取当前项目锁定的企业资料');
} else if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checked(file);
await fs.access(file);
},
readFile:async file=>{
const resource=host.productionSkills?.documents.get(path.normalize(file));
if(!resource) return fs.readFile(host.localSkillFiles?.has(path.normalize(file))?file:await checked(file));
const bytes=await fs.readFile(file);
await host.store.appendEvent({type:'enterprise_skill_resource_read',agent,requestScope,
fileId:resource.fileId,revision:resource.revision,kind:resource.kind,path:resource.path});
return bytes;
},
}});
const read=(agent,requestScope)=>{
const worker=agent==='worker';
const workerSkills=worker?host.productionSkills:undefined;
const tool=createReadTool(worker?workerSkills.filesRoot:cwd,{operations:{
access:async file=>{
const normalized=path.normalize(file);
if(workerSkills){
if(!await workerSkills.resolveFile(normalized))throw new UnlockedEnterpriseFile(normalized);
} else if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checked(file);
await fs.access(file);
},
readFile:async file=>{
const normalized=path.normalize(file);
const resource=(workerSkills??host.productionSkills)?.documents.get(normalized);
if(!resource) return fs.readFile(host.localSkillFiles?.has(normalized)?file:await checked(file));
const bytes=await fs.readFile(file);
await host.store.appendEvent({type:'enterprise_skill_resource_read',agent,requestScope,
fileId:resource.fileId,revision:resource.revision,kind:resource.kind,path:resource.path});
return bytes;
},
}});
if(!workerSkills)return tool;
return {...tool,async execute(id,params,signal,onUpdate){
try {return await tool.execute(id,params,signal,onUpdate);}
catch(error){
if(!(error instanceof UnlockedEnterpriseFile))throw error;
throw Error(workerSkills.missingFileMessage(error.file,params.path));
}
}};
};
const writeFile=async (file,content)=>fs.writeFile(await checked(file),content);
const stat=async file=>fs.stat(await checked(file));
const bash=createBashTool(cwd,{

View File

@ -98,16 +98,23 @@ test('Pi production and its worker read the same locked Skill and its relative r
let main=0,worker=0,serial=0;
const reads=new Map();
const skillLists=new Map();
const missing='「Skills/lighting/finish.md」不在当前项目锁定的企业资料中。\n'+
'锁定资料入口:\nSkills/lighting/SKILL.md\n同名文件:\nSkills/lighting/references/finish.md';
const transport={info:info(id.scope),stream(_model,context){
const system=getCurrentSystemPrompt(context.messages);
assert.match(system,/<name>lighting<\/name>/);
assert.doesNotMatch(system,/PINNED_FINISH|Use the \[fixture notes\]/);
const location=system.match(/<name>lighting<\/name>[\s\S]*?<location>([^<]*SKILL\.md)<\/location>/u)[1];
const child=system.includes('完成主代理委托的图位');
if(child){
assert.equal(location,'Skills/lighting/SKILL.md');
assert.match(system,/调用 read 时填写相对于锁定资料根目录的路径。/u);
}else assert.equal(path.isAbsolute(location),true);
const skillList=system.match(/<available_skills>[\s\S]*?<\/available_skills>/u)[0];
skillLists.set(child?'worker':'main',[...skillList.matchAll(/<name>([^<]+)<\/name>/gu)].map(match=>match[1]).sort());
const steps=child?[
['read',{path:location}],
['read',{path:'Skills/lighting/finish.md'}],
['read',{path:path.join(path.dirname(location),'references','finish.md')}],
]:[
['read',{path:location}],
@ -117,8 +124,11 @@ test('Pi production and its worker read the same locked Skill and its relative r
['finish_production',{revision:1}],
];
for(const result of context.messages.filter(message=>message.role==='toolResult'&&message.toolName==='read')){
assert.notEqual(result.isError,true,JSON.stringify(result.content));
reads.set(result.toolCallId,result.content.map(item=>item.text).join('\n'));
const body=result.content.map(item=>item.text).join('\n');
if(result.isError){
assert.equal(child,true);
assert.equal(body,missing);
}else reads.set(result.toolCallId,body);
}
const step=steps[child?worker++:main++];
return step?stream([{type:'toolCall',name:step[0],id:'skill-'+(++serial),arguments:step[1]}]):
@ -175,6 +185,7 @@ test('Pi production and its worker read the same locked Skill and its relative r
assert.equal(mainBinding.resource.skills[0].filePath,second.resource.skills[0].filePath);
assert.equal(await mainBinding.resolveFile(path.join(path.dirname(mainBinding.resource.skills[0].filePath),'references','finish.md')),true);
const events=(await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
assert.deepEqual(events.filter(e=>e.type==='tool_execution_end'&&e.toolName==='read'&&e.isError).map(e=>e.error),[missing]);
assert.deepEqual(events.filter(e=>e.type==='enterprise_skill_resource_read').map(e=>[e.agent,e.fileId,e.revision]),
[['main','root','r4'],['worker','root','r4'],['worker','finish','r7'],['main','finish','r7']]);
} finally {await host.dispose();}
@ -186,7 +197,8 @@ test('native read reports an unavailable linked document and can read it once pu
const store=await ProjectStore.open(dir,id,binding('finish'));
const selection={outputId:'detail'};
const knowledge={skillDirectory:'Skills',skills:[{fileId:'root',revision:'r4',kind:'skill',path:'Skills/lights/SKILL.md',
text:'---\nname: lights\ndescription: Lamp production.\n---\n[Finish](references/missing.md)'}],rules:[]};
text:'---\nname: lights\ndescription: Lamp production.\n---\n[Finish](references/missing.md)'}],
rules:[{fileId:'other',revision:'r1',kind:'rule',path:'Skills/other/missing.md',text:'Other locked rule.'}]};
const target='Skills/lights/references/missing.md';
let published=false, searchCalls=0, reads=0;
const client=new EnterpriseContext(store,{
@ -212,11 +224,22 @@ test('native read reports an unavailable linked document and can read it once pu
const skill=host.productionSkills.resource.skills[0].filePath;
const readMain=read('main'), readWorker=read('worker');
const file=path.join(path.dirname(skill),'references','missing.md');
await fs.writeFile(path.join(store.dir,'workspace','outside.md'),'Only the main agent can read this.');
const outside='.././../../workspace/outside.md';
await assert.rejects(readWorker.execute('outside',{path:outside}),{
message:`「${outside}」不在当前项目锁定的企业资料中。\n锁定资料入口:\nSkills/lights/SKILL.md`,
});
await assert.rejects(readWorker.execute('wrong-directory',{path:path.join(path.dirname(skill),'missing.md')}),{
message:'「Skills/lights/missing.md」不在当前项目锁定的企业资料中。\n锁定资料入口:\nSkills/lights/SKILL.md\n'+
'同名文件:\nSkills/other/missing.md\nSkills/lights/references/missing.md',
});
assert.equal((await readMain.execute('workspace',{path:'outside.md'})).content[0].text,'Only the main agent can read this.');
await assert.rejects(readMain.execute('absent',{path:file}),/Skills\/lights\/SKILL\.md.*Skills\/lights\/references\/missing\.md/u);
await assert.rejects(fs.access(file),{code:'ENOENT'});
await assert.rejects(readMain.execute('unrelated',{path:path.join(path.dirname(file),'unrelated.md')}),/本项目工作目录之外/u);
assert.equal(searchCalls,1);
assert.match((await readMain.execute('entry',{path:skill})).content[0].text,/Lamp production/u);
assert.match((await readWorker.execute('absolute-entry',{path:skill})).content[0].text,/Lamp production/u);
published=true;
for(const reply of await Promise.all([readMain.execute('present',{path:file}),readWorker.execute('same',{path:file})])){
assert.equal(reply.content[0].text,'The exact published reference.');

View File

@ -436,14 +436,23 @@ test('closeup preparation forwards only the requested reference and resolution o
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'detail',productVariantId:'oak',
template:{contentHash:'studio'},totalSlots:1,slots:[{id:'slot',fieldId:'P06',productionRule:{focus:'卷边接缝特写'}}]}),
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
async detailImages(slotId,candidateId,options){
assert.equal(slotId,'slot');
assert.equal(candidateId,undefined);
assert.equal(options.includeTemplateReference,false);
referenceReads++;
return {referenceCount:3};
},
async imageRequest(action,args){
assert.equal(action,'prepare');
forwarded.push(args);
if(args.referenceIndexes[0]===7)throw Error('同款原图编号无效');
return {requestId:randomUUID(),revision:1,requestSpecHash:'mock',outputId:'detail',variantId:'oak',slotId:'slot',
spec:{prompt:args.instructions}};
},
}};
const forwarded=[];
let referenceReads=0;
const actions=await openProductionOperations(host);
const args={slotId:'P06',prompt:'侧光下看缝线间距',referenceIndexes:[0,2]};
for(const options of [{},{useTemplateReference:true,useSceneComposite:true,prefer2k:false},
@ -453,6 +462,13 @@ test('closeup preparation forwards only the requested reference and resolution o
assert.deepEqual({useTemplateReference,useSceneComposite,prefer2k,referenceIndexes},
{useTemplateReference:undefined,useSceneComposite:undefined,prefer2k:undefined,referenceIndexes:[0,2],...options});
}
await t.test('同款原图编号无效时返回该图位的可用编号',async()=>{
assert.equal(referenceReads,0);
await assert.rejects(actions.prepare_image_request({...args,referenceIndexes:[7]}),{
message:'同款原图编号无效,可用编号 0–2',
});
assert.equal(referenceReads,1);
});
await actions.close();
});
async function generateAndWait(actions, {source,...request}) {