367 lines
17 KiB
JavaScript
367 lines
17 KiB
JavaScript
import fs from 'node:fs/promises';
|
||
import { createReadStream, createWriteStream } from 'node:fs';
|
||
import path from 'node:path';
|
||
import { createHash } from 'node:crypto';
|
||
import { Readable, Transform } from 'node:stream';
|
||
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 lockfile from 'proper-lockfile';
|
||
import { nativeKnowledgeFetch } from './native-knowledge-http.mjs';
|
||
import { knowledgeAuthorizationMessage, knowledgeTiming, networkFailure, transientStatus } from './knowledge-network.mjs';
|
||
import origins from './enterprise-knowledge-origins.json' with { type: 'json' };
|
||
|
||
const delays = [200, 500];
|
||
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||
|
||
function fileAt(root, relative) {
|
||
if (typeof relative !== 'string' || !relative || relative.split('/').some(part =>
|
||
!part || part === '.' || part === '..' || /[:\\\x00]/u.test(part))) {
|
||
throw Error('小壹知识包路径无效');
|
||
}
|
||
return path.join(root, ...relative.split('/'));
|
||
}
|
||
|
||
async function hasSize(file, item) {
|
||
const stat = await fs.stat(file).catch(error => {
|
||
if (error.code !== 'ENOENT') throw error;
|
||
});
|
||
return stat?.isFile() && stat.size === item.size;
|
||
}
|
||
|
||
async function matches(file, item) {
|
||
if (!await hasSize(file, item)) return false;
|
||
const digest = createHash('sha256');
|
||
for await (const bytes of createReadStream(file)) digest.update(bytes);
|
||
return digest.digest('hex') === item.sha256;
|
||
}
|
||
|
||
async function httpError(response) {
|
||
const body = await response.json().catch(error => {
|
||
if (error instanceof SyntaxError) return {};
|
||
throw error;
|
||
});
|
||
const messages = {
|
||
401: '小壹知识库连接已失效,请重新登录素材库后检测连接',
|
||
403: '当前连接无权读取小壹知识,请联系知识库管理员',
|
||
410: '此小壹知识版本已撤回。已完整校验的本地工程可继续使用原版本',
|
||
};
|
||
const message = knowledgeAuthorizationMessage(body.code) ?? (body.code === 'not_published' ? '此模板还没有发布小壹版本'
|
||
: response.status === 404 && !body.code ? '当前知识库地址没有提供小壹制作通道,请联系知识库管理员'
|
||
: messages[response.status] ?? (response.status >= 500 ? '小壹知识库服务暂不可用,请稍后重试' : body.error ?? '小壹知识库请求失败'));
|
||
const retry = response.headers.get('retry-after');
|
||
const retryMs = retry === null ? Number(body.retryAfterSeconds) * 1000
|
||
: /^\d+$/.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now();
|
||
return Object.assign(Error(message), {
|
||
status: response.status, code: body.code,
|
||
retryable: response.status === 429 || transientStatus(response.status, body.code) && body.retryable !== false,
|
||
retryMs: Number.isFinite(retryMs) ? Math.max(0, retryMs) : undefined,
|
||
});
|
||
}
|
||
|
||
async function readJsonCache(filePath) {
|
||
try {
|
||
return JSON.parse(await fs.readFile(filePath, 'utf8'));
|
||
} catch (error) {
|
||
if (error?.code === 'ENOENT') return undefined;
|
||
if (error instanceof SyntaxError) {
|
||
await fs.rm(filePath, {force:true}).catch(()=>{});
|
||
return undefined;
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
export async function acquireXiaoyiRelease(options) {
|
||
const { templateId, directory, cache, signal, pinnedKnowledgeVersion, sleep = wait, _healedRetry = false } = options;
|
||
const template = '/api/xiaoyi/v1/templates/' + encodeURIComponent(templateId);
|
||
const lock = path.join(directory, 'manifest.json');
|
||
let saved = await readJsonCache(lock);
|
||
await fs.mkdir(directory, {recursive:true});
|
||
async function retry(operation) {
|
||
for (let attempt = 0;; attempt++) {
|
||
signal?.throwIfAborted();
|
||
try {
|
||
return await operation();
|
||
} catch (cause) {
|
||
const error = networkFailure(cause, signal);
|
||
if (attempt >= delays.length || error.retryExhausted || !(error.network || error.retryable)) throw error;
|
||
await sleep(error.retryMs ?? delays[attempt] + Math.random() * 100, undefined, {signal});
|
||
}
|
||
}
|
||
}
|
||
|
||
async function request(route, headers) {
|
||
try {
|
||
return await options.fetch(route, {method:'GET', headers, signal});
|
||
} catch (error) {
|
||
if (error.category === 'credential') throw Error('小壹知识库未连接,请在小壹设置中检测连接', {cause:error});
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async function bytes(route, verify) {
|
||
return retry(async () => {
|
||
const response = await request(route);
|
||
if (!response.ok) throw await httpError(response);
|
||
const raw = Buffer.from(await response.arrayBuffer());
|
||
verify?.(raw,response.headers);
|
||
return raw;
|
||
});
|
||
}
|
||
|
||
async function download(route, file, item) {
|
||
if (await matches(file, item)) return;
|
||
await fs.mkdir(path.dirname(file), {recursive:true});
|
||
const partial = file + '.part';
|
||
await retry(async () => {
|
||
const stat = await fs.stat(partial).catch(error => {
|
||
if (error.code !== 'ENOENT') throw error;
|
||
});
|
||
let offset = stat?.size ?? 0;
|
||
if (offset >= item.size) offset = 0;
|
||
const response = await request(route, offset ? {
|
||
range: 'bytes=' + offset + '-', 'if-range': '"' + item.sha256 + '"',
|
||
} : undefined);
|
||
if ([412, 416].includes(response.status)) {
|
||
await response.body?.cancel();
|
||
await fs.rm(partial, {force:true});
|
||
throw Object.assign(Error('小壹知识包需要重新下载'), {retryable:true,retryMs:0});
|
||
}
|
||
if (!response.ok) throw await httpError(response);
|
||
const append = response.status === 206;
|
||
if (append && (!offset || response.headers.get('content-range') !==
|
||
`bytes ${offset}-${item.size - 1}/${item.size}`)) {
|
||
await response.body?.cancel();
|
||
await fs.rm(partial, {force:true});
|
||
throw Object.assign(Error('小壹知识包续传范围无效'), {retryable:true,retryMs:0});
|
||
}
|
||
let received = append ? offset : 0;
|
||
let reported = performance.now();
|
||
const progress = new Transform({transform(chunk, _encoding, done) {
|
||
received += chunk.length;
|
||
const now = performance.now();
|
||
if (now - reported >= 2000) {
|
||
options.onProgress?.({phase:'download',bytes:received,totalBytes:item.size});
|
||
reported = now;
|
||
}
|
||
done(null,chunk);
|
||
}});
|
||
await pipeline(Readable.fromWeb(response.body), progress, createWriteStream(partial, {flags:append?'a':'w'}), {signal});
|
||
if (!await matches(partial, item)) {
|
||
const length = (await fs.stat(partial)).size;
|
||
if (length < item.size) throw Object.assign(Error('小壹知识包下载中断'), {network:true});
|
||
await fs.rm(partial, {force:true});
|
||
throw Error('小壹知识包 SHA-256 或大小校验失败');
|
||
}
|
||
await fs.rename(partial, file);
|
||
});
|
||
}
|
||
|
||
try {
|
||
let manifest = saved;
|
||
if (!manifest) {
|
||
const prefix = templateId + '@';
|
||
if (pinnedKnowledgeVersion && !pinnedKnowledgeVersion.startsWith(prefix)) {
|
||
throw Error('本地记录的知识版本与项目模板不一致');
|
||
}
|
||
const current = pinnedKnowledgeVersion ? {version:pinnedKnowledgeVersion.slice(prefix.length)}
|
||
: JSON.parse(await bytes(template + '/current'));
|
||
const raw = await bytes(template + '/releases/' + encodeURIComponent(current.version) + '/manifest',
|
||
(body,headers) => {
|
||
const sha256 = current.manifestSha256 ?? headers.get('etag')?.match(/^"([a-f0-9]{64})"$/u)?.[1];
|
||
if (hash(body) !== sha256) throw Error('小壹清单 SHA-256 校验失败');
|
||
});
|
||
manifest = JSON.parse(raw);
|
||
if (manifest.version !== current.version) throw Error('小壹清单版本不一致');
|
||
}
|
||
if (pinnedKnowledgeVersion && manifest.knowledgeVersion !== pinnedKnowledgeVersion) {
|
||
throw Error('小壹清单与本轮锁定版本不一致');
|
||
}
|
||
if (manifest.schemaVersion !== 1) throw Error('不支持的小壹知识清单版本');
|
||
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;
|
||
try {
|
||
contents = unzipSync(await fs.readFile(bundle));
|
||
} catch (unzipError) {
|
||
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});
|
||
}
|
||
}
|
||
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 assets = options.metadataOnly ? [] : manifest.assets;
|
||
if (assets.length) {
|
||
await fs.mkdir(cache, {recursive:true});
|
||
let confirmAssetReleasePromise;
|
||
const confirmAssetRelease = () => {
|
||
confirmAssetReleasePromise ??= bytes(release + '/manifest');
|
||
return confirmAssetReleasePromise;
|
||
};
|
||
let nextAssetIndex = 0;
|
||
const workerCount = Math.min(4, assets.length);
|
||
await Promise.all(Array.from({length: workerCount}, async () => {
|
||
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});
|
||
try {
|
||
if (!await matches(cached, item)) {
|
||
if (saved) {
|
||
// A blob can be referenced by multiple releases. Check the pinned release
|
||
// before repairing files so a retired release cannot borrow another one's access.
|
||
await confirmAssetRelease();
|
||
}
|
||
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);
|
||
}
|
||
}));
|
||
}
|
||
const packaged = new Set(manifest.files.map(item => item.path));
|
||
if (![manifest.entrypoint,manifest.supplement,manifest.productionConfig].every(entry => packaged.has(entry))) {
|
||
throw Error('小壹知识清单缺少制作指引、补充说明或制作配置');
|
||
}
|
||
const configFile = fileAt(root, manifest.productionConfig);
|
||
let config;
|
||
try {
|
||
config = JSON.parse(await fs.readFile(configFile, 'utf8'));
|
||
} catch (configError) {
|
||
if (configError instanceof SyntaxError || configError?.code === 'ENOENT') {
|
||
await fs.rm(configFile, {force:true}).catch(()=>{});
|
||
await fs.rm(lock, {force:true}).catch(()=>{});
|
||
if (!_healedRetry && typeof options.fetch === 'function') {
|
||
return acquireXiaoyiRelease({...options, _healedRetry:true});
|
||
}
|
||
throw Error('小壹制作配置缓存已损坏,已清理损坏缓存,请检查网络连接后重试', {cause:configError});
|
||
}
|
||
throw configError;
|
||
}
|
||
if (!config.productionProfiles || typeof config.productionProfiles !== 'object') throw Error('小壹制作配置缺失');
|
||
if (!saved) await atomic(lock, manifest);
|
||
return {manifest, root, productionProfiles:config.productionProfiles};
|
||
} catch (error) {
|
||
signal?.throwIfAborted();
|
||
if (saved) throw error;
|
||
throw Object.assign(Error('无法开工:' + error.message, {cause:error}), {status:error.status,code:error.code});
|
||
}
|
||
}
|
||
|
||
|
||
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});
|
||
const unlock = await lockfile.lock(directory);
|
||
try {
|
||
const roundFile = path.join(directory, 'round.json');
|
||
if (finishedGoal) {
|
||
const prior = await readJsonCache(roundFile);
|
||
if (prior !== finishedGoal) {
|
||
await fs.rm(path.join(directory, 'manifest.json'), {force:true});
|
||
await atomic(roundFile, finishedGoal);
|
||
}
|
||
}
|
||
let origin = origins[0];
|
||
if (process.env.PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE) {
|
||
origin = await fs.readFile(process.env.PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE, 'utf8')
|
||
.then(JSON.parse, error => {
|
||
if (error.code !== 'ENOENT') throw error;
|
||
return origins[0];
|
||
});
|
||
}
|
||
const {manifest, root, productionProfiles} = await acquireXiaoyiRelease({
|
||
templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), 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 entry = fileAt(root, manifest.entrypoint);
|
||
const resource = loadSkills({cwd:store.dir, agentDir:store.dir, skillPaths:[entry], includeDefaults:false});
|
||
if (!resource.skills.length) throw Error('无法开工:小壹知识包缺少可用制作指引');
|
||
const documents = new Map([...manifest.files,...manifest.assets].map(item => [
|
||
fileAt(root, item.path), {
|
||
fileId:item.sha256, sha256:item.sha256, revision:manifest.knowledgeVersion, path:item.path, kind:item.type,
|
||
},
|
||
]));
|
||
const entryDir = path.posix.dirname(manifest.entrypoint);
|
||
const entryPrefix = entryDir === '.' ? '' : entryDir + '/';
|
||
const docPaths = manifest.files
|
||
.map(item => item.path)
|
||
.filter(filePath => filePath.endsWith('.md') && filePath !== manifest.entrypoint && filePath !== manifest.supplement)
|
||
.sort();
|
||
const packageDocs = entryPrefix
|
||
? docPaths.filter(filePath => filePath.startsWith(entryPrefix))
|
||
: docPaths.filter(filePath => !filePath.includes('/'));
|
||
const fontManifests = Object.fromEntries(
|
||
Object.entries(manifest.bindings ?? {})
|
||
.filter(([, binding]) => typeof binding?.fontManifest === 'string' && binding.fontManifest.trim())
|
||
.map(([component, binding]) => [component, binding.fontManifest]),
|
||
);
|
||
const localAssets = manifest.assets.map(item => ({...item,localPath:fileAt(root,item.path)}));
|
||
const componentFonts = Object.fromEntries(
|
||
Object.keys(manifest.bindings ?? {}).map(component => [
|
||
component,
|
||
localAssets.filter(item => item.type === 'font' && (!item.component || item.component === component || item.component === 'shared')),
|
||
]),
|
||
);
|
||
const execution = {
|
||
knowledgeVersion:manifest.knowledgeVersion, entrypoint:manifest.entrypoint,
|
||
supplement:manifest.supplement, overrides:manifest.overrides,
|
||
...(packageDocs.length ? {packageDocs} : {}),
|
||
...(docPaths.length ? {docPaths} : {}),
|
||
instruction:'按锁定的知识库根相对路径读取资料(packageDocs/docPaths 为已索引文档路径,按需用 read 读取)。共享章节有覆盖声明时,以对应补充章节为准,其余共享内容继续适用。',
|
||
};
|
||
const sources = [...documents.values()];
|
||
return {
|
||
knowledgeVersion:manifest.knowledgeVersion, execution, productionProfiles, snapshot:{manifest,root},
|
||
productionBinding:{templateId, knowledgeVersion:manifest.knowledgeVersion, productionProfiles,
|
||
...(Object.keys(fontManifests).length ? {fontManifests} : {}),
|
||
...(Object.values(componentFonts).some(list => list.length) ? {componentFonts} : {}),
|
||
assets:localAssets},
|
||
filesRoot:root, resource, documents, sources,
|
||
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)};
|
||
}),
|
||
};
|
||
} finally { await unlock(); }
|
||
}
|