fix(detail-agent-pi): keep xiaoyi knowledge docs in memory and redact persisted session reads
This commit is contained in:
parent
7e9707edf6
commit
684d35f106
@ -1110,12 +1110,12 @@ export class DetailPiAgent {
|
||||
const template = workflow?.template;
|
||||
if (!workflow?.available || !template?.enterprise) return null;
|
||||
if (template.knowledgeVersion) {
|
||||
const {execution,snapshot,sources} = await openXiaoyiSkills(
|
||||
const {execution,snapshot,sources,memoryFiles} = await openXiaoyiSkills(
|
||||
this.store,template.id,undefined,undefined,undefined,template.knowledgeVersion,true,
|
||||
);
|
||||
const rules = await Promise.all([execution.entrypoint,execution.supplement].map(async rulePath => ({
|
||||
path:rulePath,
|
||||
text:await fs.readFile(path.join(snapshot.root,rulePath),'utf8'),
|
||||
text:memoryFiles?.get(rulePath)?.toString('utf8') ?? await fs.readFile(path.join(snapshot.root,rulePath),'utf8'),
|
||||
})));
|
||||
return {execution,sources,rules};
|
||||
}
|
||||
|
||||
@ -14,6 +14,53 @@ export function redact(value) {
|
||||
.map(([key, item]) => [key, redact(item)]));
|
||||
}
|
||||
|
||||
const knowledgePlaceholder = '[企业知识内容已隐藏,仅运行时内存可用]';
|
||||
|
||||
function summarizeKnowledgeText(text, knowledgePath) {
|
||||
const clean = typeof text === 'string' ? text.trimStart() : '';
|
||||
const preview = clean.slice(0, 80).replace(/\r?\n/g, ' ');
|
||||
const prefix = knowledgePath ? `[${knowledgePath}] ` : '';
|
||||
return `${prefix}${preview ? preview + '…\n' : ''}${knowledgePlaceholder}`;
|
||||
}
|
||||
|
||||
function sanitizeKnowledgeEntryForDisk(entry) {
|
||||
if (entry?.type !== 'message') return entry;
|
||||
const message = entry.message;
|
||||
if (message?.role !== 'toolResult' || !message.details?.enterpriseKnowledge) return entry;
|
||||
const knowledgePath = message.details.knowledgePath;
|
||||
const summarize = text => summarizeKnowledgeText(text, knowledgePath);
|
||||
const safeContent = Array.isArray(message.content)
|
||||
? message.content.map(block => {
|
||||
if (!block || typeof block !== 'object') return block;
|
||||
const { textSignature, thinkingSignature, thoughtSignature, signature, ...fields } = block;
|
||||
const next = fields.type === 'text' ? { ...fields, text: summarize(fields.text) } : fields;
|
||||
return {
|
||||
...next,
|
||||
...(textSignature === undefined ? {} : { textSignature }),
|
||||
...(thinkingSignature === undefined ? {} : { thinkingSignature }),
|
||||
...(thoughtSignature === undefined ? {} : { thoughtSignature }),
|
||||
...(signature === undefined ? {} : { signature }),
|
||||
};
|
||||
})
|
||||
: typeof message.content === 'string' ? summarize(message.content) : message.content;
|
||||
const { truncation, ...restDetails } = message.details;
|
||||
const safeDetails = truncation
|
||||
? { ...restDetails, truncation: { ...truncation, content: knowledgePlaceholder } }
|
||||
: message.details;
|
||||
const safeStructured = message.structuredContent?.type === 'text_page'
|
||||
? { ...message.structuredContent, text: summarize(message.structuredContent.text) }
|
||||
: message.structuredContent;
|
||||
return {
|
||||
...entry,
|
||||
message: {
|
||||
...message,
|
||||
content: safeContent,
|
||||
details: safeDetails,
|
||||
...(message.structuredContent === undefined ? {} : { structuredContent: safeStructured }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function protectSession(manager) {
|
||||
const appendMessage = manager.appendMessage.bind(manager);
|
||||
manager.appendMessage = message => {
|
||||
@ -31,5 +78,33 @@ export function protectSession(manager) {
|
||||
}) : redact(content);
|
||||
return appendMessage({...redact(metadata), content:safeContent});
|
||||
};
|
||||
if (typeof manager._persist === 'function') {
|
||||
const persist = manager._persist.bind(manager);
|
||||
manager._persist = entry => {
|
||||
const original = manager.fileEntries;
|
||||
if (!manager.flushed && Array.isArray(original)) {
|
||||
manager.fileEntries = original.map(sanitizeKnowledgeEntryForDisk);
|
||||
}
|
||||
try {
|
||||
return persist(sanitizeKnowledgeEntryForDisk(entry));
|
||||
} finally {
|
||||
if (original !== undefined) manager.fileEntries = original;
|
||||
}
|
||||
};
|
||||
}
|
||||
if (typeof manager._rewriteFile === 'function') {
|
||||
const rewriteFile = manager._rewriteFile.bind(manager);
|
||||
manager._rewriteFile = () => {
|
||||
const original = manager.fileEntries;
|
||||
if (Array.isArray(original)) {
|
||||
manager.fileEntries = original.map(sanitizeKnowledgeEntryForDisk);
|
||||
}
|
||||
try {
|
||||
return rewriteFile();
|
||||
} finally {
|
||||
if (original !== undefined) manager.fileEntries = original;
|
||||
}
|
||||
};
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
|
||||
@ -497,7 +497,10 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
|
||||
if (item?.type !== type) throw Error('小壹组件绑定缺少' + type + ':' + relative);
|
||||
return item;
|
||||
};
|
||||
const jsonAt = async item => JSON.parse(await fs.readFile(path.join(root,item.path),'utf8'));
|
||||
const jsonAt = async item => {
|
||||
const mem = skills.memoryFiles?.get(item.path);
|
||||
return JSON.parse(mem ? mem.toString('utf8') : await fs.readFile(path.join(root, item.path), 'utf8'));
|
||||
};
|
||||
const packs = {};
|
||||
const allWarnings = [...skills.warnings];
|
||||
for (const [component,binding] of Object.entries(manifest.bindings)) {
|
||||
|
||||
@ -40,11 +40,12 @@ export function projectShell(root, store, skillFiles = () => []) {
|
||||
const files = await skillFiles(operation);
|
||||
if (files.length) {
|
||||
stagedSkills = await fs.mkdtemp(path.join(store.dir, 'skill-shell-'));
|
||||
for (const { file, source } of files) {
|
||||
for (const { file, bytes, source } of files) {
|
||||
operation.throwIfAborted();
|
||||
const target = path.join(stagedSkills, ...source.path.split('/'));
|
||||
await fs.mkdir(path.dirname(target), { recursive: true });
|
||||
await fs.copyFile(file, target);
|
||||
if (bytes) await fs.writeFile(target, bytes);
|
||||
else await fs.copyFile(file, target);
|
||||
}
|
||||
}
|
||||
operation.throwIfAborted();
|
||||
|
||||
@ -107,16 +107,23 @@ export async function projectTools(host) {
|
||||
detectImageMimeType:async file=>worker ? undefined : exportMimeType(file),
|
||||
access:async file=>{
|
||||
const normalized=path.normalize(file);
|
||||
const skills=workerSkills??host.productionSkills;
|
||||
if(workerSkills){
|
||||
if(!await workerSkills.resolveFile(normalized))throw new UnlockedEnterpriseFile(normalized);
|
||||
} else if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checkedRead(file);
|
||||
const resource=skills?.documents.get(normalized);
|
||||
if(resource){
|
||||
if(!skills.memoryFiles?.has(resource.path)) await fs.access(resource.localPath??file);
|
||||
return;
|
||||
}
|
||||
await fs.access(file);
|
||||
},
|
||||
readFile:async file=>{
|
||||
const normalized=path.normalize(file);
|
||||
const resource=(workerSkills??host.productionSkills)?.documents.get(normalized);
|
||||
const skills=workerSkills??host.productionSkills;
|
||||
const resource=skills?.documents.get(normalized);
|
||||
if(!resource) return fs.readFile(host.localSkillFiles?.has(normalized)?file:await checkedRead(file));
|
||||
const bytes=await fs.readFile(file);
|
||||
const bytes=skills.memoryFiles?.get(resource.path)??await fs.readFile(resource.localPath??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;
|
||||
@ -178,8 +185,11 @@ export async function projectTools(host) {
|
||||
const readFile=async (input,resolvedPath)=>{
|
||||
const result=await tool.execute(id,input,signal,onUpdate);
|
||||
const page=readTextPage(result,input);
|
||||
const doc=skills?.documents.get(path.normalize(input.path));
|
||||
return {...result,...(page?{structuredContent:page}:null),
|
||||
...(resolvedPath?{details:{...result.details,path:resolvedPath}}:null)};
|
||||
...((resolvedPath||doc)?{details:{...result.details,
|
||||
...(resolvedPath?{path:resolvedPath}:null),
|
||||
...(doc?{enterpriseKnowledge:true,knowledgePath:doc.path}:null)}}:null)};
|
||||
};
|
||||
try {
|
||||
return await readFile(resolved?{...params,path:resolved.file}:params,resolved?.path);
|
||||
|
||||
@ -7,7 +7,7 @@ import { pipeline } from 'node:stream/promises';
|
||||
import { setTimeout as wait } from 'node:timers/promises';
|
||||
import { unzipSync } from 'fflate';
|
||||
import { atomic, digest } from './store.mjs';
|
||||
import { loadSkills } from '@earendil-works/pi-coding-agent';
|
||||
import { parseFrontmatter } from '@earendil-works/pi-coding-agent';
|
||||
import lockfile from 'proper-lockfile';
|
||||
import { nativeKnowledgeFetch } from './native-knowledge-http.mjs';
|
||||
import { knowledgeAuthorizationMessage, knowledgeTiming, networkFailure, transientStatus } from './knowledge-network.mjs';
|
||||
@ -189,40 +189,41 @@ export async function acquireXiaoyiRelease(options) {
|
||||
if (manifest.templateId !== templateId) throw Error('小壹清单模板不一致');
|
||||
const root = fileAt(path.join(directory, 'files'), manifest.version);
|
||||
const release = template + '/releases/' + encodeURIComponent(manifest.version);
|
||||
const missing = [];
|
||||
for (const item of manifest.files) {
|
||||
if (!await matches(fileAt(root, item.path), item)) missing.push(item);
|
||||
}
|
||||
if (missing.length) {
|
||||
if (!/^[a-f0-9]{64}$/.test(manifest.bundle.sha256)) throw Error('小壹知识包摘要无效');
|
||||
const bundle = path.join(directory, manifest.bundle.sha256 + '.zip');
|
||||
await download(release + '/bundle', bundle, manifest.bundle);
|
||||
let contents;
|
||||
if (!/^[a-f0-9]{64}$/.test(manifest.bundle.sha256)) throw Error('小壹知识包摘要无效');
|
||||
const bundle = cache ? path.join(cache, manifest.bundle.sha256) : path.join(directory, manifest.bundle.sha256 + '.zip');
|
||||
const loadBundle = async () => {
|
||||
if (cache) await fs.mkdir(cache, {recursive:true});
|
||||
const unlockBundle = cache ? await lockfile.lock(bundle, {realpath:false, retries:30}) : null;
|
||||
try {
|
||||
contents = unzipSync(await fs.readFile(bundle));
|
||||
} catch (unzipError) {
|
||||
await download(release + '/bundle', bundle, manifest.bundle);
|
||||
return unzipSync(await fs.readFile(bundle));
|
||||
} finally {
|
||||
await unlockBundle?.();
|
||||
}
|
||||
};
|
||||
let contents;
|
||||
try {
|
||||
contents = await loadBundle();
|
||||
} catch (unzipError) {
|
||||
await fs.rm(bundle, {force:true}).catch(()=>{});
|
||||
if (typeof options.fetch !== 'function') {
|
||||
throw Error('小壹知识包缓存已损坏,已清理损坏缓存,请检查网络连接后重试', {cause:unzipError});
|
||||
}
|
||||
try {
|
||||
contents = await loadBundle();
|
||||
} catch (retryError) {
|
||||
await fs.rm(bundle, {force:true}).catch(()=>{});
|
||||
if (typeof options.fetch !== 'function') {
|
||||
throw Error('小壹知识包缓存已损坏,已清理损坏缓存,请检查网络连接后重试', {cause:unzipError});
|
||||
}
|
||||
try {
|
||||
await download(release + '/bundle', bundle, manifest.bundle);
|
||||
contents = unzipSync(await fs.readFile(bundle));
|
||||
} catch (retryError) {
|
||||
await fs.rm(bundle, {force:true}).catch(()=>{});
|
||||
throw Error('小壹知识包缓存已损坏,已清理损坏缓存,请检查网络连接后重试', {cause:retryError});
|
||||
}
|
||||
throw Error('小壹知识包缓存已损坏,已清理损坏缓存,请检查网络连接后重试', {cause:retryError});
|
||||
}
|
||||
for (const item of missing) {
|
||||
const content = Object.hasOwn(contents, item.path) && contents[item.path];
|
||||
if (!content || content.byteLength !== item.size || hash(content) !== item.sha256) {
|
||||
await fs.rm(bundle, {force:true}).catch(()=>{});
|
||||
throw Error('小壹知识文件校验失败:' + item.path);
|
||||
}
|
||||
const file = fileAt(root, item.path);
|
||||
await fs.mkdir(path.dirname(file), {recursive:true});
|
||||
await fs.writeFile(file, content);
|
||||
}
|
||||
const memoryFiles = new Map();
|
||||
for (const item of manifest.files) {
|
||||
const content = Object.hasOwn(contents, item.path) && contents[item.path];
|
||||
if (!content || content.byteLength !== item.size || hash(content) !== item.sha256) {
|
||||
await fs.rm(bundle, {force:true}).catch(()=>{});
|
||||
throw Error('小壹知识文件校验失败:' + item.path);
|
||||
}
|
||||
memoryFiles.set(item.path, Buffer.from(content));
|
||||
}
|
||||
const assets = options.metadataOnly ? [] : (manifest.assets ?? []);
|
||||
if (assets.length) {
|
||||
@ -238,8 +239,6 @@ export async function acquireXiaoyiRelease(options) {
|
||||
while (nextAssetIndex < assets.length) {
|
||||
signal?.throwIfAborted();
|
||||
const item = assets[nextAssetIndex++];
|
||||
const file = fileAt(root, item.path);
|
||||
if (await matches(file, item)) continue;
|
||||
if (!/^[a-f0-9]{64}$/.test(item.sha256)) throw Error('小壹资产摘要无效');
|
||||
const cached = path.join(cache, item.sha256);
|
||||
const unlock = await lockfile.lock(cached, {realpath:false, retries:30});
|
||||
@ -253,9 +252,6 @@ export async function acquireXiaoyiRelease(options) {
|
||||
await download('/api/xiaoyi/v1/blobs/' + item.sha256, cached, item);
|
||||
}
|
||||
} finally { await unlock(); }
|
||||
await fs.mkdir(path.dirname(file), {recursive:true});
|
||||
await fs.rm(file, {force:true});
|
||||
await fs.link(cached, file);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@ -267,10 +263,10 @@ export async function acquireXiaoyiRelease(options) {
|
||||
let productionProfiles;
|
||||
if (packaged.has(manifest.productionConfig)) {
|
||||
try {
|
||||
const config = JSON.parse(await fs.readFile(fileAt(root, manifest.productionConfig), 'utf8'));
|
||||
const config = JSON.parse(memoryFiles.get(manifest.productionConfig).toString('utf8'));
|
||||
productionProfiles = config?.productionProfiles;
|
||||
} catch (error) {
|
||||
if (!(error instanceof SyntaxError) && error.code !== 'ENOENT') throw error;
|
||||
if (!(error instanceof SyntaxError)) throw error;
|
||||
}
|
||||
}
|
||||
if (!productionProfiles || typeof productionProfiles !== 'object' || Array.isArray(productionProfiles)) {
|
||||
@ -278,7 +274,7 @@ export async function acquireXiaoyiRelease(options) {
|
||||
productionProfiles = {};
|
||||
}
|
||||
if (!saved) await atomic(lock, manifest);
|
||||
return {manifest, root, entrypoint, supplement, productionProfiles, warnings};
|
||||
return {manifest, root, cache, memoryFiles, entrypoint, supplement, productionProfiles, warnings};
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (saved) throw error;
|
||||
@ -287,6 +283,34 @@ export async function acquireXiaoyiRelease(options) {
|
||||
}
|
||||
|
||||
|
||||
function loadSkillFromMemory(filePath, rawContent) {
|
||||
const diagnostics = [];
|
||||
let frontmatter;
|
||||
try {
|
||||
({ frontmatter } = parseFrontmatter(rawContent));
|
||||
} catch (error) {
|
||||
diagnostics.push({ type: 'warning', message: error instanceof Error ? error.message : 'failed to parse skill file', path: filePath });
|
||||
return { skills: [], diagnostics };
|
||||
}
|
||||
const description = frontmatter.description;
|
||||
if (typeof description !== 'string' || !description.trim()) {
|
||||
return { skills: [], diagnostics };
|
||||
}
|
||||
const skillDir = path.dirname(filePath);
|
||||
const name = (typeof frontmatter.name === 'string' && frontmatter.name) || path.basename(skillDir);
|
||||
return {
|
||||
skills: [{
|
||||
name,
|
||||
description,
|
||||
filePath,
|
||||
baseDir: skillDir,
|
||||
sourceInfo: { path: filePath, source: 'path', scope: 'temporary', origin: 'top-level', baseDir: skillDir },
|
||||
disableModelInvocation: frontmatter['disable-model-invocation'] === true,
|
||||
}],
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
export async function openXiaoyiSkills(store, templateId, signal, finishedGoal, fetch = nativeKnowledgeFetch, pinnedKnowledgeVersion, metadataOnly = false) {
|
||||
const directory = path.join(store.dir, 'xiaoyi-release', digest(templateId).slice(0, 24));
|
||||
await fs.mkdir(directory, {recursive:true});
|
||||
@ -308,21 +332,31 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
|
||||
return origins[0];
|
||||
});
|
||||
}
|
||||
const {manifest, root, entrypoint, supplement, productionProfiles, warnings} = await acquireXiaoyiRelease({
|
||||
templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion, metadataOnly, onProgress:store.xiaoyiProgress,
|
||||
const cache = store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs');
|
||||
const {manifest, root, memoryFiles, entrypoint, supplement, productionProfiles, warnings} = await acquireXiaoyiRelease({
|
||||
templateId, directory, cache, signal, pinnedKnowledgeVersion, metadataOnly, onProgress:store.xiaoyiProgress,
|
||||
fetch:(route, init) => fetch(new URL(route, origin), {
|
||||
...init, redirect:'manual', ...knowledgeTiming(fetch, signal, /\/bundle$|\/blobs\//.test(route) ? 240_000 : 45_000),
|
||||
}),
|
||||
});
|
||||
const skillPaths = entrypoint ? [fileAt(root, entrypoint)] : [];
|
||||
const resource = loadSkills({cwd:store.dir, agentDir:store.dir, skillPaths, includeDefaults:false});
|
||||
const resource = entrypoint
|
||||
? loadSkillFromMemory(fileAt(root, entrypoint), memoryFiles.get(entrypoint).toString('utf8'))
|
||||
: {skills:[], diagnostics:[]};
|
||||
if (entrypoint && !resource.skills.length) warnings.push('模板制作指引无法加载');
|
||||
const assets = manifest.assets ?? [];
|
||||
const documents = new Map([...manifest.files,...assets].map(item => [
|
||||
fileAt(root, item.path), {
|
||||
fileId:item.sha256, sha256:item.sha256, revision:manifest.knowledgeVersion, path:item.path, kind:item.type,
|
||||
},
|
||||
]));
|
||||
const documents = new Map([
|
||||
...manifest.files.map(item => [
|
||||
fileAt(root, item.path), {
|
||||
fileId:item.sha256, sha256:item.sha256, revision:manifest.knowledgeVersion, path:item.path, kind:item.type,
|
||||
},
|
||||
]),
|
||||
...assets.map(item => [
|
||||
fileAt(root, item.path), {
|
||||
fileId:item.sha256, sha256:item.sha256, revision:manifest.knowledgeVersion, path:item.path, kind:item.type,
|
||||
localPath:path.join(cache, item.sha256),
|
||||
},
|
||||
]),
|
||||
]);
|
||||
const entryDir = entrypoint ? path.posix.dirname(entrypoint) : '.';
|
||||
const entryPrefix = entryDir === '.' ? '' : entryDir + '/';
|
||||
const docPaths = manifest.files
|
||||
@ -337,7 +371,7 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
|
||||
.filter(([, binding]) => typeof binding?.fontManifest === 'string' && binding.fontManifest.trim())
|
||||
.map(([component, binding]) => [component, binding.fontManifest]),
|
||||
);
|
||||
const localAssets = assets.map(item => ({...item,localPath:fileAt(root,item.path)}));
|
||||
const localAssets = assets.map(item => ({...item,localPath:path.join(cache, item.sha256)}));
|
||||
const componentFonts = Object.fromEntries(
|
||||
Object.keys(manifest.bindings ?? {}).map(component => [
|
||||
component,
|
||||
@ -358,12 +392,12 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
|
||||
...(Object.keys(fontManifests).length ? {fontManifests} : {}),
|
||||
...(Object.values(componentFonts).some(list => list.length) ? {componentFonts} : {}),
|
||||
assets:localAssets},
|
||||
filesRoot:root, resource, documents, sources,
|
||||
filesRoot:root, resource, documents, sources, memoryFiles,
|
||||
files:[...documents].map(([file, source]) => ({...source,path:file})),
|
||||
resolveFile:async file => documents.has(file),
|
||||
shellFiles:async () => manifest.files.map(item => {
|
||||
const file = fileAt(root,item.path);
|
||||
return {file,source:documents.get(file)};
|
||||
return {file,bytes:memoryFiles.get(item.path),source:documents.get(file)};
|
||||
}),
|
||||
};
|
||||
} finally { await unlock(); }
|
||||
|
||||
@ -85,7 +85,8 @@ test('an oversized appendix is held in the bundle and read on demand', async t =
|
||||
'规则/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);
|
||||
assert.equal(bound.memoryFiles.get('规则/appendix.md').toString('utf8'),body);
|
||||
await assert.rejects(fs.access(path.join(bound.filesRoot,'规则','appendix.md')),{code:'ENOENT'});
|
||||
});
|
||||
|
||||
test('knowledge tools keep server rules, quota and policy in events and out of both model result channels', async () => {
|
||||
@ -149,7 +150,7 @@ test('锁定快照保留规则链接使用的图片、PDF 和 JSON 附件原始
|
||||
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));
|
||||
assert.deepEqual(locked.memoryFiles.get(relative),Buffer.from(body));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
160
apps/detail-agent-pi/test/kb-antileak.test.mjs
Normal file
160
apps/detail-agent-pi/test/kb-antileak.test.mjs
Normal file
@ -0,0 +1,160 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
||||
import { protectSession } from '../src/credentials.mjs';
|
||||
import { projectTools } from '../src/project-tools.mjs';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { openXiaoyiSkills } from '../src/xiaoyi-release.mjs';
|
||||
import { xiaoyiFixture } from './xiaoyi-fixture.mjs';
|
||||
|
||||
async function listFilesRecursive(dir) {
|
||||
const results = [];
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true }).catch(error => {
|
||||
if (error.code === 'ENOENT') return [];
|
||||
throw error;
|
||||
});
|
||||
for (const entry of entries) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) results.push(...await listFilesRecursive(full));
|
||||
else results.push(full);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
test('knowledge docs stay in memory without plaintext .md on disk and share blobs across projects', async t => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-antileak-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
const cache = path.join(root, 'xiaoyi-blobs');
|
||||
const projectA = path.join(root, 'project-a');
|
||||
const projectB = path.join(root, 'project-b');
|
||||
const entry = '规则/SKILL.md';
|
||||
const brandGuide = '规则/品牌规范.md';
|
||||
const secretRule = '核心机密品牌规范正文:严禁外泄的视觉规范与卖点话术。';
|
||||
const fetch = xiaoyiFixture('SOFA', 'v1', entry, {
|
||||
[entry]: '---\nname: sofa\ndescription: Sofa guide.\n---\n入口指引',
|
||||
[brandGuide]: secretRule,
|
||||
});
|
||||
|
||||
const id = project => ({ scope: 'a'.repeat(64), project });
|
||||
const binding = { brandId: 'b', shopId: 's', categoryId: 'c', platform: 'p', version: '1', source: 'fixture', rules: [] };
|
||||
const storeA = await ProjectStore.open(projectA, id(randomUUID()), binding);
|
||||
storeA.xiaoyiCache = cache;
|
||||
const skillsA = await openXiaoyiSkills(storeA, 'SOFA', undefined, undefined, fetch);
|
||||
assert.equal(skillsA.resource.skills.length, 1);
|
||||
assert.equal(skillsA.resource.skills[0].name, 'sofa');
|
||||
|
||||
const storeB = await ProjectStore.open(projectB, id(randomUUID()), binding);
|
||||
storeB.xiaoyiCache = cache;
|
||||
let networkCalls = 0;
|
||||
const skillsB = await openXiaoyiSkills(storeB, 'SOFA', undefined, undefined, async (...args) => {
|
||||
networkCalls++;
|
||||
return fetch(...args);
|
||||
});
|
||||
// Project B still fetches current/manifest once (first lock), but reuses bundle blob from shared cache.
|
||||
assert.ok(networkCalls <= 2);
|
||||
|
||||
// No plaintext .md files anywhere in project dirs or shared cache.
|
||||
const allDiskFiles = [
|
||||
...await listFilesRecursive(projectA),
|
||||
...await listFilesRecursive(projectB),
|
||||
...await listFilesRecursive(cache),
|
||||
];
|
||||
assert.equal(allDiskFiles.some(file => file.endsWith('.md')), false);
|
||||
for (const file of allDiskFiles) {
|
||||
const content = await fs.readFile(file, 'utf8').catch(() => '');
|
||||
assert.equal(content.includes(secretRule), false, `secret text leaked to disk file: ${file}`);
|
||||
}
|
||||
|
||||
// Per-project xiaoyi-release dir only keeps lightweight index files (manifest.json).
|
||||
const releaseFilesA = await listFilesRecursive(path.join(storeA.dir, 'xiaoyi-release'));
|
||||
assert.deepEqual(releaseFilesA.map(file => path.basename(file)), ['manifest.json']);
|
||||
|
||||
// read tool (main, worker, /skills/..., unique basename) still returns full content from memory.
|
||||
const { read } = await projectTools({ store: storeA, productionSkills: skillsA });
|
||||
for (const agent of ['main', 'worker']) {
|
||||
const direct = await read(agent).execute('r1', { path: brandGuide });
|
||||
assert.equal(direct.content[0].text, secretRule);
|
||||
assert.equal(direct.details.enterpriseKnowledge, true);
|
||||
assert.equal(direct.details.knowledgePath, brandGuide);
|
||||
|
||||
const mounted = await read(agent).execute('r2', { path: '/skills/' + brandGuide });
|
||||
assert.equal(mounted.content[0].text, secretRule);
|
||||
|
||||
const byUniqueName = await read(agent).execute('r3', { path: 'other/品牌规范.md' });
|
||||
assert.equal(byUniqueName.content[0].text, secretRule);
|
||||
assert.equal(byUniqueName.details.path, brandGuide);
|
||||
assert.equal(byUniqueName.details.enterpriseKnowledge, true);
|
||||
}
|
||||
assert.equal((await read('main').execute('r4', { path: brandGuide })).content[0].text, skillsB.memoryFiles.get(brandGuide).toString('utf8'));
|
||||
});
|
||||
|
||||
test('protectSession redacts knowledge read toolResult on disk while preserving in-memory context and signatures', async t => {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-session-antileak-'));
|
||||
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
||||
const manager = protectSession(SessionManager.create(dir, path.join(dir, 'sessions')));
|
||||
const fullKnowledge = '第一行标题:核心机密规则。' + 'A'.repeat(100) + 'TAIL_SECRET_MARKER_NEVER_ON_DISK';
|
||||
const normalWorkspaceText = '普通工作区文件正文 NORMAL_WORKSPACE_MARKER';
|
||||
|
||||
manager.appendMessage({ role: 'user', timestamp: 1, content: '开始制作' });
|
||||
manager.appendMessage({
|
||||
role: 'assistant',
|
||||
timestamp: 2,
|
||||
content: [
|
||||
{ type: 'thinking', thinking: '思考过程', thinkingSignature: 'sig-thinking-1', thoughtSignature: 'sig-thought-2' },
|
||||
{ type: 'text', text: '正在读取规则', textSignature: 'sig-text-3', signature: 'sig-generic-4' },
|
||||
{ type: 'toolCall', id: 'call-kb', name: 'read', arguments: { path: '规则/品牌规范.md' } },
|
||||
],
|
||||
});
|
||||
manager.appendMessage({
|
||||
role: 'toolResult',
|
||||
toolCallId: 'call-kb',
|
||||
toolName: 'read',
|
||||
timestamp: 3,
|
||||
isError: false,
|
||||
content: [{ type: 'text', text: fullKnowledge }],
|
||||
structuredContent: { type: 'text_page', text: fullKnowledge, nextOffset: 2 },
|
||||
details: {
|
||||
enterpriseKnowledge: true,
|
||||
knowledgePath: '规则/品牌规范.md',
|
||||
truncation: { truncated: true, content: fullKnowledge, outputLines: 1, maxBytes: 100 },
|
||||
},
|
||||
});
|
||||
manager.appendMessage({
|
||||
role: 'toolResult',
|
||||
toolCallId: 'call-ws',
|
||||
toolName: 'read',
|
||||
timestamp: 4,
|
||||
isError: false,
|
||||
content: [{ type: 'text', text: normalWorkspaceText }],
|
||||
details: {},
|
||||
});
|
||||
|
||||
// In-memory context retains the complete knowledge text for the running model.
|
||||
const inMemory = manager.buildSessionContext().messages;
|
||||
const kbInMemory = inMemory.find(m => m.role === 'toolResult' && m.toolCallId === 'call-kb');
|
||||
assert.equal(kbInMemory.content[0].text, fullKnowledge);
|
||||
assert.equal(kbInMemory.structuredContent.text, fullKnowledge);
|
||||
assert.equal(kbInMemory.details.truncation.content, fullKnowledge);
|
||||
|
||||
// On-disk sessions/*.jsonl hides the knowledge body while keeping signatures & normal workspace reads.
|
||||
const disk = await fs.readFile(manager.getSessionFile(), 'utf8');
|
||||
assert.doesNotMatch(disk, /TAIL_SECRET_MARKER_NEVER_ON_DISK/);
|
||||
assert.match(disk, /\[企业知识内容已隐藏,仅运行时内存可用\]/);
|
||||
assert.match(disk, /规则\/品牌规范\.md/);
|
||||
assert.match(disk, /NORMAL_WORKSPACE_MARKER/);
|
||||
assert.match(disk, /sig-thinking-1/);
|
||||
assert.match(disk, /sig-thought-2/);
|
||||
assert.match(disk, /sig-text-3/);
|
||||
assert.match(disk, /sig-generic-4/);
|
||||
|
||||
// Reopening from disk sees the redacted copy, not the secret tail.
|
||||
const reopened = SessionManager.open(manager.getSessionFile()).buildSessionContext().messages;
|
||||
const kbOnDisk = reopened.find(m => m.role === 'toolResult' && m.toolCallId === 'call-kb');
|
||||
assert.doesNotMatch(kbOnDisk.content[0].text, /TAIL_SECRET_MARKER_NEVER_ON_DISK/);
|
||||
assert.match(kbOnDisk.content[0].text, /\[企业知识内容已隐藏,仅运行时内存可用\]/);
|
||||
assert.doesNotMatch(kbOnDisk.details.truncation.content, /TAIL_SECRET_MARKER_NEVER_ON_DISK/);
|
||||
});
|
||||
@ -223,7 +223,7 @@ test('acquireXiaoyiRelease downloads missing blobs with 4-way bounded concurrenc
|
||||
assert.equal(result.manifest.version, '1.0.0');
|
||||
assert.ok(maxInFlightBlobs > 1 && maxInFlightBlobs <= 4, `expected 2..4 concurrent blobs, got ${maxInFlightBlobs}`);
|
||||
for (const asset of assets) {
|
||||
const content = await fs.readFile(path.join(result.root, asset.path));
|
||||
const content = await fs.readFile(path.join(result.cache, asset.sha256));
|
||||
assert.equal(sha256(content), asset.sha256);
|
||||
}
|
||||
});
|
||||
|
||||
@ -54,7 +54,8 @@ test('离线重开保留相同的锁定入口与所有可按需读取的正文',
|
||||
()=>assert.fail('locked prefixes must not use network'));
|
||||
assert.deepEqual(first.execution,second.execution);
|
||||
for (const [file,body] of Object.entries(guides)) {
|
||||
assert.equal(await fs.readFile(path.join(second.filesRoot,file),'utf8'),body);
|
||||
assert.equal(second.memoryFiles.get(file).toString('utf8'),body);
|
||||
await assert.rejects(fs.access(path.join(second.filesRoot,file)),{code:'ENOENT'});
|
||||
}
|
||||
assert.ok(await first.resolveFile(path.join(first.filesRoot,'附录.md')));
|
||||
});
|
||||
|
||||
@ -255,9 +255,8 @@ test('locks a verified release, resumes offline and repairs from the same bundle
|
||||
const noNetwork = {...options,fetch:() => assert.fail('attempted network')};
|
||||
const original = await acquireXiaoyiRelease(noNetwork);
|
||||
assert.equal(original.manifest.version,'v1');
|
||||
await fs.rm(path.join(first.root,'规则','SKILL.md'));
|
||||
await acquireXiaoyiRelease(noNetwork);
|
||||
assert.equal(await fs.readFile(path.join(first.root,'规则','SKILL.md'),'utf8'),'guide');
|
||||
assert.equal(original.memoryFiles.get('规则/SKILL.md').toString('utf8'),'guide');
|
||||
await assert.rejects(fs.access(path.join(first.root,'规则','SKILL.md')),{code:'ENOENT'});
|
||||
});
|
||||
|
||||
test('an unknown manifest schema and malformed optional production config still open with warnings', async t => {
|
||||
@ -272,13 +271,14 @@ test('an unknown manifest schema and malformed optional production config still
|
||||
});
|
||||
|
||||
test('same-size tampering fails SHA-256 validation while the locked release stays available for repair', async t => {
|
||||
const {options,manifest,blob}=await fixture(t);
|
||||
const {root}=await acquireXiaoyiRelease(options);
|
||||
const guide=path.join(root,'规则','SKILL.md');
|
||||
await fs.writeFile(guide,'evil');
|
||||
await acquireXiaoyiRelease({...options,fetch:()=>assert.fail('verified bundle should repair the guide offline')});
|
||||
assert.equal(await fs.readFile(guide,'utf8'),'guide');
|
||||
const original=path.join(root,'模板','original.psd');
|
||||
const {options,manifest,bundle,blob}=await fixture(t);
|
||||
await acquireXiaoyiRelease(options);
|
||||
const cachedBundle=path.join(options.cache,manifest.bundle.sha256);
|
||||
await fs.writeFile(cachedBundle,Buffer.alloc(bundle.length,120));
|
||||
await assert.rejects(acquireXiaoyiRelease({...options,fetch:()=>{throw Error('fixture offline');}}),error => error.message.includes('缓存已损坏') && error.cause?.message === 'fixture offline');
|
||||
const repairedBundle = await acquireXiaoyiRelease(options);
|
||||
assert.equal(repairedBundle.memoryFiles.get('规则/SKILL.md').toString('utf8'),'guide');
|
||||
const original=path.join(options.cache,sha(blob));
|
||||
await fs.writeFile(original,Buffer.alloc(blob.length,120));
|
||||
await assert.rejects(acquireXiaoyiRelease({...options,fetch:()=>{throw Error('fixture offline');}}),/fixture offline/);
|
||||
assert.equal(JSON.parse(await fs.readFile(path.join(options.directory,'manifest.json'),'utf8')).knowledgeVersion,manifest.knowledgeVersion);
|
||||
@ -290,7 +290,7 @@ test('continues bundle and blob partials with matching If-Range', async t => {
|
||||
const {options,requests,bundle,blob,manifest} = await fixture(t);
|
||||
await fs.mkdir(options.directory);
|
||||
await fs.mkdir(options.cache);
|
||||
await fs.writeFile(path.join(options.directory,manifest.bundle.sha256+'.zip.part'),bundle.subarray(0,5));
|
||||
await fs.writeFile(path.join(options.cache,manifest.bundle.sha256+'.part'),bundle.subarray(0,5));
|
||||
await fs.writeFile(path.join(options.cache,sha(blob)+'.part'),blob.subarray(0,3));
|
||||
await acquireXiaoyiRelease(options);
|
||||
assert.deepEqual(requests.filter(([,headers])=>headers).map(([,headers])=>headers.range), ['bytes=5-','bytes=3-']);
|
||||
@ -382,7 +382,8 @@ test('catalog retries a timeout and a 500, then preserves cached fields and the
|
||||
test('a rejected range restarts the same bundle without a range header', async t => {
|
||||
const {options,requests,manifest,bundle} = await fixture(t);
|
||||
await fs.mkdir(options.directory);
|
||||
await fs.writeFile(path.join(options.directory,manifest.bundle.sha256+'.zip.part'),bundle.subarray(0,5));
|
||||
await fs.mkdir(options.cache);
|
||||
await fs.writeFile(path.join(options.cache,manifest.bundle.sha256+'.part'),bundle.subarray(0,5));
|
||||
const fetch = options.fetch;
|
||||
let rejected = false;
|
||||
options.fetch = (route,init) => {
|
||||
@ -433,8 +434,7 @@ test('a switched HTTP current is ignored on continuation and picked up by the ne
|
||||
|
||||
test('repair of a missing uncached asset checks the pinned release and stops on retirement', async t => {
|
||||
const {options,blob} = await fixture(t);
|
||||
const locked = await acquireXiaoyiRelease(options);
|
||||
await fs.rm(path.join(locked.root,'模板','original.psd'));
|
||||
await acquireXiaoyiRelease(options);
|
||||
await fs.rm(path.join(options.cache,sha(blob)));
|
||||
const requested = [];
|
||||
options.fetch = route => {
|
||||
@ -452,10 +452,9 @@ test('a second template reuses an already verified blob by digest', async t => {
|
||||
const second = await acquireXiaoyiRelease({...next.options,cache:first.options.cache});
|
||||
assert.equal(second.manifest.templateId,'TABLE');
|
||||
assert.equal(next.requests.some(([route])=>route.includes('/blobs/')),false);
|
||||
const asset = await fs.stat(path.join(second.root,'模板','original.psd'),{bigint:true});
|
||||
await assert.rejects(fs.access(path.join(second.root,'模板','original.psd')),{code:'ENOENT'});
|
||||
const cached = await fs.stat(path.join(first.options.cache,sha(next.blob)),{bigint:true});
|
||||
assert.equal(asset.ino,cached.ino);
|
||||
assert.equal(cached.nlink,3n);
|
||||
assert.equal(cached.nlink,1n);
|
||||
});
|
||||
|
||||
test('a resumed project with a missing manifest uses its recorded version', async t => {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user