/** * ============================================================ * src/utils/resourcePaths.ts —— 资源目录双源解析 * ------------------------------------------------------------ * 问题:skills/ 和 plugins/ 这类"资源目录"需要在两种场景下都能找到: * - 用户在 minimal-agent 源码仓库里跑(dev):cwd === packageRoot * - 用户全局 npm install 后在自己项目里跑:cwd ≠ packageRoot * 此时既要看 npm 包自带的资源,也要看用户在自己项目里新加的资源。 * * 方案:返回 [cwd/, packageRoot/],cwd 优先。 * - 用 existsSync 过滤不存在的目录(保留静默降级) * - cwd 与 packageRoot 重合时去重(dev 场景) * * 消费者(commandRouter / skillList / 各插件 loader)按顺序扫描,先扫到的 * 同名条目胜出 —— 让用户能在自己项目里覆盖或扩展全局自带资源。 * * ResourceName 故意是开放 string:插件可以自由声明自己的资源名(如 * workflow-runner 的 'workflows'),框架不预设资源名清单。 * ============================================================ */ import { existsSync } from 'node:fs'; import { isAbsolute, join, resolve } from 'node:path'; import { getWorkingDir } from '../bootstrap/workingDir.js'; import { execSiblingDir } from './greenRoot.js'; import { findPackageRoot } from './packageRoot.js'; /** 资源目录名(也作为子目录名)。开放字符串,框架不锁定取值。 */ export type ResourceName = string; /** Compiled Desktop places resources beside the app, not beside its sidecar. * Its launcher supplies the absolute data root; the portable CLI uses its * executable's own directory instead. Neither location is the user's cwd. */ export function compiledResourceRoots(): string[] { const desktopRoot = process.env.KAKADEAI_AGENT_ROOT; const sibling = execSiblingDir(); return process.env.KAKADEAI_COMPILED === '1' && desktopRoot && isAbsolute(desktopRoot) ? [...new Set([resolve(desktopRoot), sibling])] : [sibling]; } /** * 返回资源目录的搜索顺序数组(cwd 优先 + packageRoot fallback)。 * * @param name 资源类别名(也作为子目录名) * @param metaUrl 调用方 import.meta.url(用于定位 packageRoot) * @returns 存在的搜索路径数组;都不存在则返回空数组 */ export function getResourceSearchPaths( name: ResourceName, metaUrl: string, workingDir = getWorkingDir(), ): string[] { const paths: string[] = []; const cwdPath = resolve(join(workingDir, name)); if (existsSync(cwdPath)) { paths.push(cwdPath); } for (const root of compiledResourceRoots()) { const bundledPath = resolve(root, name); if (!paths.includes(bundledPath) && existsSync(bundledPath)) paths.push(bundledPath); } let pkgPath: string; try { pkgPath = resolve(join(findPackageRoot(metaUrl), name)); } catch { return paths; } if (!paths.includes(pkgPath) && existsSync(pkgPath)) { paths.push(pkgPath); } return paths; }