Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(plugins): 支持跟随宿主语言的插件本地化 (#338)

nanaco13e8d6d77bdf
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 365b17b610..4c740b9a13 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -550,6 +550,7 @@ import { registerLayoutIpc } from './layout/index.js';
import {
getGhostManager,
isGhostAvailableForActiveSession,
+ refreshGhostLocalization,
registerGhostIpc,
setGhostsChangedObserver,
suspendAllGhosts,
@@ -1498,6 +1499,7 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>
);
setSelectionContextMenuLocale(currentApplicationMenuLocale);
setMainLocale(currentApplicationMenuLocale);
+ refreshGhostLocalization();
const mainWindow = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef : null;
if (mainWindow) {
installApplicationMenu(mainWindow, currentApplicationMenuLocale);
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index cee206ee5e..5973f11c54 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -6,10 +6,16 @@ import JSZip from 'jszip';
import {
GHOST_MANIFEST_FILE,
+ GHOST_LOCALE_MAX_BYTES,
+ ghostLocalePathFor,
ghostIconMimeType,
isValidGhostId,
+ resolveGhostManifestLocale,
validateGhostManifest,
+ validateGhostManifestLocaleResource,
+ withGhostResolvedLocale,
type GhostManifest,
+ type GhostManifestLocaleResource,
type GhostTrustInfo,
type InstalledGhost,
} from '../../shared/ghost.js';
@@ -17,6 +23,7 @@ import {
verifyGhostZipSignatures,
type GhostTrustRegistry,
} from './ghostSignature.js';
+import { isPathInsideDir } from './dirDeposit.js';
/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */
const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;
@@ -49,6 +56,8 @@ export interface GhostManagerOptions {
getRootDir: () => string;
/** 装/卸成功后通知(index.ts 用它广播 ghosts:changed 到所有窗口)。 */
onChanged?: (ghosts: InstalledGhost[]) => void;
+ /** 当前宿主语言;插件未提供时由 shared 契约固定回退英文。 */
+ getLocale?: () => string;
/** Cindy 维护的发布者/审核公钥表;缺省为空,签名仍验完整性但不抬身份等级。 */
trustRegistry?: GhostTrustRegistry;
log?: GhostManagerLogger;
@@ -125,9 +134,10 @@ export class GhostManager {
}
// icon 读失败只降级为无图标(warn),不影响意识本体可用。
const iconDataUrl = this.readInstalledIconDataUrl(dir, v.manifest);
+ const localizedManifest = this.readInstalledLocalizedManifest(dir, v.manifest);
const trust = this.readInstalledTrust(dir);
result.push({
- manifest: v.manifest,
+ manifest: localizedManifest,
dir,
enabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),
...(trust ? { trust } : {}),
@@ -138,6 +148,48 @@ export class GhostManager {
return result;
}
+ /**
+ * 读取当前宿主语言对应的 locale 文件。已安装目录被用户手工改坏时不让
+ * 整个插件消失:记录告警并回退原 manifest;正常安装路径已在 parse 阶段严验。
+ */
+ private readInstalledLocalizedManifest(dir: string, manifest: GhostManifest): GhostManifest {
+ const requestedLocale = this.options.getLocale?.();
+ const runtimeManifest = withGhostResolvedLocale(manifest, requestedLocale);
+ const localePath = ghostLocalePathFor(manifest, requestedLocale);
+ if (!localePath) return runtimeManifest;
+ const fallbackPath = manifest.locales?.en;
+ const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];
+ for (const candidatePath of candidates) {
+ try {
+ const absPath = path.join(dir, ...candidatePath.split('/'));
+ const stat = fs.lstatSync(absPath);
+ if (!stat.isFile() || stat.size > GHOST_LOCALE_MAX_BYTES) {
+ throw new Error(`locale 文件缺失或超过 ${GHOST_LOCALE_MAX_BYTES} 字节`);
+ }
+ const realDir = fs.realpathSync.native(dir);
+ const realLocalePath = fs.realpathSync.native(absPath);
+ if (!isPathInsideDir(realDir, realLocalePath)) {
+ throw new Error('locale 文件经软链解析后位于插件目录之外');
+ }
+ const raw = JSON.parse(fs.readFileSync(realLocalePath, 'utf8'));
+ const validated = validateGhostManifestLocaleResource(raw, manifest);
+ if (!validated.ok) throw new Error(validated.reason);
+ return resolveGhostManifestLocale(runtimeManifest, validated.resource);
+ } catch (err) {
+ this.options.log?.warn('ghost locale candidate invalid', {
+ id: manifest.id,
+ localePath: candidatePath,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ this.options.log?.warn('ghost locale fallback to base manifest', {
+ id: manifest.id,
+ localePath,
+ });
+ return runtimeManifest;
+ }
+
/**
* 启用 / 停用一张意识。停用不删任何东西,只在安装目录里放一个 `.disabled`
* 标记文件(目录即事实:打开文件夹一眼可见);启用即删掉标记。幂等。
@@ -291,6 +343,26 @@ export class GhostManager {
}
const prefix = detectSingleTopFolderPrefix(allEntries.map((e) => e.name));
+ // ZIP 条目名在检查阶段区分大小写,但 Windows / 默认 macOS 解压落盘不区分。
+ // 折叠后撞同一路径会让后写条目覆盖先写条目(包括 ghost.json),必须在
+ // 读取清单前整体拒绝。
+ const seenEntryPaths = new Set<string>();
+ const aliasedEntry = allEntries.find((entry) => {
+ const rel = entry.name.slice(prefix.length).replace(/\/$/, '');
+ if (rel.length === 0) return false;
+ const folded = rel.toLowerCase();
+ if (seenEntryPaths.has(folded)) return true;
+ seenEntryPaths.add(folded);
+ return false;
+ });
+ if (aliasedEntry) {
+ return {
+ rejection: {
+ code: 'file-invalid',
+ reason: `压缩包含大小写折叠后重复的路径:${aliasedEntry.name.slice(prefix.length)}`,
+ },
+ };
+ }
// 这两个点文件只属于主机:包若能自带它们,就可伪造停用状态或覆盖
// 签名信任快照。大小写也折叠检查,避免在 Windows/macOS 上撞同一文件。
const reservedHostFile = allEntries.find((entry) => {
@@ -350,6 +422,52 @@ export class GhostManager {
},
};
}
+ let localizedManifest = withGhostResolvedLocale(v.manifest, this.options.getLocale?.());
+ if (v.manifest.locales !== undefined) {
+ const resources = new Map<string, GhostManifestLocaleResource>();
+ for (const localePath of Object.values(v.manifest.locales)) {
+ if (!localePath) continue;
+ const localeEntry = zip.file(`${prefix}${localePath}`);
+ if (!localeEntry) {
+ return {
+ rejection: {
+ code: 'file-invalid',
+ reason: `清单声明了 locale,但压缩包内缺少 ${localePath}`,
+ },
+ };
+ }
+ let localeRaw: unknown;
+ try {
+ localeRaw = JSON.parse(
+ (await readZipEntryBufferWithLimit(
+ localeEntry,
+ GHOST_LOCALE_MAX_BYTES,
+ `locale ${localePath}`,
+ )).toString('utf8'),
+ );
+ } catch {
+ return {
+ rejection: {
+ code: 'file-invalid',
+ reason: `locale 文件不是合法 JSON 或超过 ${GHOST_LOCALE_MAX_BYTES} 字节:${localePath}`,
+ },
+ };
+ }
+ const validated = validateGhostManifestLocaleResource(localeRaw, v.manifest);
+ if (!validated.ok) {
+ return {
+ rejection: {
+ code: 'file-invalid',
+ reason: `locale 文件不合格(${localePath}):${validated.reason}`,
+ },
+ };
+ }
+ resources.set(localePath, validated.resource);
+ }
+ const localePath = ghostLocalePathFor(v.manifest, this.options.getLocale?.());
+ const resource = localePath ? resources.get(localePath) : undefined;
+ if (resource) localizedManifest = resolveGhostManifestLocale(localizedManifest, resource);
+ }
const maxUncompressedBytes = v.manifest.node
? MAX_NODE_UNCOMPRESSED_BYTES
: MAX_BASIC_UNCOMPRESSED_BYTES;
@@ -407,7 +525,7 @@ export class GhostManager {
}
return {
- manifest: v.manifest,
+ manifest: localizedManifest,
trust: signature.trust,
packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 3593319d1d..c5e6ae326d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -13,12 +13,18 @@ let workDir: string;
let rootDir: string;
let onChanged: ReturnType<typeof vi.fn>;
let manager: GhostManager;
+let hostLocale: string;
beforeEach(async () => {
workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ghost-test-'));
rootDir = path.join(workDir, 'ghosts');
onChanged = vi.fn();
- manager = new GhostManager({ getRootDir: () => rootDir, onChanged });
+ hostLocale = 'zh-CN';
+ manager = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
});
afterEach(async () => {
@@ -78,6 +84,122 @@ async function expectRejection(
}
describe('GhostManager · install', () => {
+ it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
+ const manifest = {
+ ...goodManifest(),
+ name: 'Base name',
+ description: 'Base description',
+ locales: {
+ en: 'locales/en.json',
+ 'zh-CN': 'locales/zh-CN.json',
+ },
+ };
+ const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({
+ name,
+ description,
+ tools: { do_thing: { description: toolDescription } },
+ });
+ const cindy = await makeCindy('localized.cindy', manifest, {
+ 'locales/en.json': locale('English name', 'English description', 'English tool'),
+ 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),
+ });
+ const result = await manager.install(cindy);
+ expect(result).toMatchObject({
+ ghost: {
+ manifest: {
+ name: '中文名称',
+ description: '中文说明',
+ resolvedLocale: 'zh-CN',
+ tools: [{ name: 'do_thing', description: '中文工具' }],
+ },
+ },
+ });
+
+ hostLocale = 'ja';
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'English name',
+ description: 'English description',
+ resolvedLocale: 'ja',
+ tools: [{ name: 'do_thing', description: 'English tool' }],
+ });
+ hostLocale = 'fr-FR';
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'English name',
+ resolvedLocale: 'en',
+ });
+ });
+
+ it('已安装 locale 或其父目录被替换为目录外软链时拒绝读取并回退基础清单', async () => {
+ hostLocale = 'en';
+ const manifest = {
+ ...goodManifest(),
+ name: 'Base name',
+ locales: { en: 'locales/en.json' },
+ };
+ const locale = (name: string) => JSON.stringify({
+ name,
+ tools: { do_thing: { description: 'Localized tool' } },
+ });
+ const cindy = await makeCindy('localized-symlink.cindy', manifest, {
+ 'locales/en.json': locale('Packaged name'),
+ });
+ await manager.install(cindy);
+ const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');
+ const outsidePath = path.join(workDir, 'outside-locale.json');
+ await fs.promises.writeFile(outsidePath, locale('Outside name'));
+ await fs.promises.rm(localePath);
+ try {
+ await fs.promises.symlink(outsidePath, localePath, 'file');
+ } catch {
+ return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。
+ }
+
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'Base name',
+ resolvedLocale: 'en',
+ tools: [{ name: 'do_thing', description: '做点事' }],
+ });
+
+ const localesDir = path.dirname(localePath);
+ const outsideLocalesDir = path.join(workDir, 'outside-locales');
+ await fs.promises.rm(localesDir, { recursive: true, force: true });
+ await fs.promises.mkdir(outsideLocalesDir);
+ await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));
+ await fs.promises.symlink(
+ outsideLocalesDir,
+ localesDir,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'Base name',
+ resolvedLocale: 'en',
+ });
+ });
+
+ it('locale 文件缺失、非法 JSON 或缺少工具翻译时 inspect/install 都拒绝', async () => {
+ const manifest = {
+ ...goodManifest(),
+ locales: { en: 'locales/en.json' },
+ };
+ const missing = await makeCindy('locale-missing.cindy', manifest);
+ await expectRejection(await manager.install(missing), 'file-invalid');
+
+ const invalid = await makeCindy('locale-invalid.cindy', manifest, {
+ 'locales/en.json': '{ nope',
+ });
+ await expectRejection(await manager.install(invalid), 'file-invalid');
+
+ const incomplete = await makeCindy('locale-incomplete.cindy', manifest, {
+ 'locales/en.json': JSON.stringify({ name: 'English', tools: {} }),
+ });
+ await expectRejection(await manager.install(incomplete), 'file-invalid');
+
+ const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {
+ 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),
+ });
+ await expectRejection(await manager.install(aliasedManifest), 'file-invalid');
+ });
+
it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {
const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });
const result = await manager.install(cindy);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
new file mode 100644
index 0000000000..6ece321a1c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
@@ -0,0 +1,67 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { provisionBuiltinGhosts } from '../builtinGhostProvisioner.js';
+
+const tempDirs: string[] = [];
+
+async function makeTempDir(): Promise<string> {
+ const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-builtin-locale-'));
+ tempDirs.push(dir);
+ return dir;
+}
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs.splice(0).map((dir) => fs.promises.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+describe('builtinGhostProvisioner locale validation', () => {
+ it('locale 资源不完整时跳过官方种子,不把损坏翻译播种给用户', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ const seedDir = path.join(seedRoot, 'localized-seed');
+ await fs.promises.mkdir(path.join(seedDir, 'locales'), { recursive: true });
+ await fs.promises.writeFile(path.join(seedDir, 'main.js'), '// brain');
+ await fs.promises.writeFile(
+ path.join(seedDir, 'ghost.json'),
+ JSON.stringify({
+ schemaVersion: 2,
+ id: 'localized-seed',
+ name: 'Base',
+ version: '1.0.0',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'run', description: 'Base tool' }],
+ locales: { en: 'locales/en.json' },
+ }),
+ );
+ await fs.promises.writeFile(
+ path.join(seedDir, 'locales', 'en.json'),
+ JSON.stringify({ name: 'English', tools: {} }),
+ );
+ const warn = vi.fn();
+
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ log: { info: vi.fn(), warn },
+ });
+
+ expect(outcome).toMatchObject({
+ installed: [],
+ updated: [],
+ skipped: ['localized-seed'],
+ });
+ expect(fs.existsSync(path.join(repoRoot, 'localized-seed'))).toBe(false);
+ expect(warn).toHaveBeenCalledWith(
+ 'builtin seed skipped: invalid locale resources',
+ expect.objectContaining({ reason: expect.stringContaining('locale.tools 缺少') }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 25091bcbde..7d6ad6a747 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -107,6 +107,89 @@ describe('packGhostDir', () => {
});
});
+ it('打包期校验 locale 文件存在、合法且完整,产物可按宿主语言 inspect', async () => {
+ const manifest = {
+ ...GOOD_MANIFEST,
+ description: 'Base description',
+ locales: {
+ en: 'locales/en.json',
+ ja: 'locales/ja.json',
+ },
+ };
+ const locale = (name: string, description: string, tool: string) => JSON.stringify({
+ name,
+ description,
+ tools: { do_thing: { description: tool } },
+ });
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// brain',
+ 'locales/en.json': locale('Demo', 'English description', 'English tool'),
+ 'locales/ja.json': locale('デモ', '日本語の説明', '日本語のツール'),
+ });
+ const packed = await packGhostDir(dir);
+ expect(packed.ok, JSON.stringify(packed)).toBe(true);
+ if (!packed.ok) return;
+ const manager = new GhostManager({
+ getRootDir: () => path.join(workDir, 'ghosts'),
+ getLocale: () => 'ja',
+ });
+ expect(await manager.inspect(packed.cindyPath)).toMatchObject({
+ manifest: {
+ name: 'デモ',
+ description: '日本語の説明',
+ resolvedLocale: 'ja',
+ tools: [{ name: 'do_thing', description: '日本語のツール' }],
+ },
+ });
+ });
+
+ it('Forge 在 locale 缺文件、坏 JSON 或缺译时直接拒绝', async () => {
+ const manifest = {
+ ...GOOD_MANIFEST,
+ locales: { en: 'locales/en.json' },
+ };
+ const missing = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// brain',
+ });
+ expect(await packGhostDir(missing)).toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ });
+
+ await fs.promises.mkdir(path.join(missing, 'locales'), { recursive: true });
+ await fs.promises.writeFile(path.join(missing, 'locales', 'en.json'), '{ nope');
+ expect(await packGhostDir(missing)).toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ });
+
+ await fs.promises.writeFile(
+ path.join(missing, 'locales', 'en.json'),
+ JSON.stringify({ name: 'Demo', tools: {} }),
+ );
+ expect(await packGhostDir(missing)).toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ });
+
+ await fs.promises.rm(path.join(missing, 'locales'), { recursive: true, force: true });
+ await fs.promises.mkdir(path.join(missing, 'Locales'), { recursive: true });
+ await fs.promises.writeFile(
+ path.join(missing, 'Locales', 'EN.json'),
+ JSON.stringify({
+ name: 'Demo',
+ tools: { do_thing: { description: 'English tool' } },
+ }),
+ );
+ expect(await packGhostDir(missing)).toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: expect.stringContaining('大小写不一致'),
+ });
+ });
+
it('目录不存在 / 清单坏 / 声明的入口文件缺失 → 结构化拒绝', async () => {
expect((await packGhostDir(path.join(workDir, 'nope'))).ok).toBe(false);
@@ -303,6 +386,10 @@ describe('FORGE_GUIDE', () => {
'data-ghost-link',
'cindy.request',
'app-context',
+ 'navigator.language',
+ 'host-context-changed',
+ 'locales/en.json',
+ '固定使用英文',
'clientIdAlternatives',
'cindy.fetch',
'network 槽',
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index b54f260604..951abbe40f 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -8,6 +8,7 @@ import {
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
+import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
/**
* builtinGhostProvisioner — 内置意识的启动播种(第一方可信通道)。
@@ -547,6 +548,14 @@ function readSeedManifest(seedDir: string, id: string, log?: BuiltinProvisionerL
log?.warn('builtin seed skipped: dir name != manifest id', { seedDir, manifestId: v.manifest.id });
return null;
}
+ const localeValidation = validateGhostLocaleResourcesInDirectory(seedDir, v.manifest);
+ if (!localeValidation.ok) {
+ log?.warn('builtin seed skipped: invalid locale resources', {
+ seedDir,
+ reason: localeValidation.reason,
+ });
+ return null;
+ }
return v.manifest;
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index b964f52adf..b72fb73b34 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -23,6 +23,7 @@ import {
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
+import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */
const MAX_BASIC_FILES = 256;
@@ -553,7 +554,18 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {
}
const manifest = v.manifest;
- // 2) 清单声明的入口文件必须真实在场(打包期拦,别等装入后沙箱 404)。
+ // 2) locale 资源必须真实、可解析且完整覆盖已声明字段。与装入侧使用
+ // 同一 validator,避免 Forge 能打包、安装却被拒的契约漂移。
+ const localeValidation = validateGhostLocaleResourcesInDirectory(dir, manifest);
+ if (!localeValidation.ok) {
+ return {
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: localeValidation.reason,
+ };
+ }
+
+ // 3) 清单声明的入口文件必须真实在场(打包期拦,别等装入后沙箱 404)。
const mustExist: string[] = [];
if (manifest.entry) mustExist.push(manifest.entry);
if (manifest.node?.entry) mustExist.push(manifest.node.entry);
@@ -568,17 +580,27 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {
}
}
- // 3) 收集文件(递归,跳过开发残留),数量/体积设限。
+ // 4) 收集文件(递归,跳过开发残留),数量/体积设限。
const files: Array<{ rel: string; abs: string }> = [];
let totalBytes = 0;
const maxFiles = manifest.node ? MAX_NODE_FILES : MAX_BASIC_FILES;
const maxTotalBytes = manifest.node ? MAX_NODE_TOTAL_BYTES : MAX_BASIC_TOTAL_BYTES;
+ const seenPackPaths = new Set<string>();
const walk = async (cur: string, relBase: string): Promise<ForgePackResult | null> => {
const entries = await fs.promises.readdir(cur, { withFileTypes: true });
for (const e of entries) {
if (shouldSkip(e.name)) continue;
const abs = path.join(cur, e.name);
const rel = relBase ? `${relBase}/${e.name}` : e.name;
+ const foldedRel = rel.toLowerCase();
+ if (seenPackPaths.has(foldedRel)) {
+ return {
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: `源码目录含大小写折叠后重复的路径:${rel}`,
+ };
+ }
+ seenPackPaths.add(foldedRel);
if (e.isDirectory()) {
const bad = await walk(abs, rel);
if (bad) return bad;
@@ -602,7 +624,7 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {
const tooLarge = await walk(dir, '');
if (tooLarge) return tooLarge;
- // 4) 打包到源码目录自身(2026-07 Lizi 定案:产物跟源码住一起,拿取直观)。
+ // 5) 打包到源码目录自身(2026-07 Lizi 定案:产物跟源码住一起,拿取直观)。
// 文件收集在写盘之前完成 + shouldSkip 跳过 *.cindy,自身产物不会进包;
// 同名覆盖:同 id 同版本重打包语义上就是同一个包。
const zip = new JSZip();
@@ -651,6 +673,11 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册
my-ghost/
├── ghost.json ← 身份卡(必须,zip 根部)
├── main.js ← 电子脑:后台逻辑入口(声明了 tools/cindy 时必须)
+├── locales/ ← 可选:宿主驱动的清单文案翻译(声明 locales 时英文必须存在)
+│ ├── en.json
+│ ├── zh-CN.json
+│ ├── ja.json
+│ └── ko.json
├── node/
│ └── worker.cjs ← 可选:随包 Node/stdio MCP 入口(声明 node 槽时必须,见 §4.12)
├── panel.html ← 面板界面(声明了 panel.html 时必须)
@@ -668,6 +695,12 @@ my-ghost/
"name": "我的意识", // 展示名
"description": "一句话说清这段意识是干嘛的(给人看:装入确认框/详情页)", // 1–300 字
"whenToUse": "需要生成图片、插画、配图、修图、P 图、改图时找我", // 1–300 字,给模型看:进 agent 会话的意识花名册,是"用户不点名时 AI 能不能想起你"的关键。写成场景枚举,可反复调优;缺省时花名册回落用 description
+ "locales": { // 可选:插件只跟随宿主语言;不支持/缺失语言固定回退 en
+ "en": "locales/en.json",
+ "zh-CN": "locales/zh-CN.json",
+ "ja": "locales/ja.json",
+ "ko": "locales/ko.json"
+ },
"version": "1.0.0",
"entry": "main.js", // 电子脑入口(kind 字段已无需填写:意识只有芯片一种形态,缺省即 chip;写了也只认 "chip")
"launch": "on-demand", // 可选:电子脑启动模式。on-demand(缺省)=被需要才拉起;resident=唤醒即常驻(确认框会如实标注"常驻运行",绝大多数意识不需要,仅订阅型/需秒响应的场景用)
@@ -693,6 +726,63 @@ my-ghost/
}
\`\`\`
+### 2.1 本地化资源(locales)
+
+插件语言**只跟随 Cindy 宿主当前语言**。不要读取 \`navigator.language\`、操作系统语言或
+浏览器偏好,也不要在插件内保存另一份语言选择。宿主当前支持
+\`zh-CN / en / ja / ko\`;插件没提供宿主当前语言时固定使用英文,因此只要声明
+\`locales\` 就必须提供 \`en\`。
+
+每个 locale JSON 完整覆盖清单中已有的可本地化字段;工具按稳定的 tool name 对齐,
+协议键、工具名和参数名不翻译:
+
+\`\`\`json
+{
+ "name": "My Plugin",
+ "description": "What this plugin does.",
+ "whenToUse": "Use it when ...",
+ "tools": {
+ "do_thing": {
+ "description": "Do the task and return the result.",
+ "parameters": {
+ "/properties/query": {
+ "title": "Query",
+ "description": "Describe what to search for."
+ }
+ }
+ }
+ },
+ "panel": { "title": "Plugin panel" },
+ "network": {
+ "secrets": {
+ "api_key": { "label": "API key", "hint": "Create one in account settings." }
+ },
+ "connections": {
+ "instance": { "label": "Service instance", "hint": "Enter the instance URL and token." }
+ }
+ },
+ "node": {
+ "secretBindings": {
+ "worker_key": { "label": "Worker key", "hint": "Used only by the local worker." }
+ }
+ },
+ "setup": {
+ "kv": {
+ "default_repo": { "label": "Default repository" }
+ }
+ }
+}
+\`\`\`
+
+若原清单声明了 \`description\`、\`whenToUse\`、\`tools\`、\`panel.title\`、
+\`network.secrets / connections\`、\`node.secretBindings\` 或 \`setup\` 的 kv 标签,
+每个 locale 文件都必须完整提供对应文案;凭证、连接、Node 凭证和 kv 项按稳定 key 对齐。
+工具参数 schema 中已有的 \`title / description\` 用 JSON Pointer 对齐(如
+\`/properties/query\`;根节点用空字符串 \`""\`),参数名、类型、枚举和协议结构不翻译。
+缺译、未知 key、多余字段、文件缺失、路径大小写与磁盘不一致、无效 JSON 或单文件超过
+64KB 都会在 Forge 打包期、内置播种期与安装期拒绝。清单列表、详情页、Panel 标题、
+安装/配置提示和 Agent 工具目录都消费同一份本地化结果。
+
十三个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图)、\`agent\`(让
当前 Agent 开始一个普通用户回合,见 §4.11)、\`panel\`(常驻
面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话
@@ -997,12 +1087,13 @@ const r = await cindy.send({ type: 'cindy-request', kind: 'gen_image', prompt: '
## 4.1 宿主公开上下文(request,无需卡槽)
-电子脑需要按宿主构建身份选择公开配置时,走只读 request。当前只暴露
-\`region: 'cn' | 'global'\`,不含登录态、路径、设备信息或凭证:
+电子脑需要按宿主构建身份或当前语言选择公开配置/界面文案时,走只读 request。当前只暴露
+\`region: 'cn' | 'global'\` 与 \`locale: 'zh-CN' | 'en' | 'ja' | 'ko'\`,
+不含登录态、路径、设备信息或凭证:
\`\`\`js
const r = await cindy.request({ kind: 'app-context' });
-// → { ok:true, context:{ region:'cn'|'global' } }
+// → { ok:true, context:{ region:'cn'|'global', locale:'zh-CN'|'en'|'ja'|'ko' } }
\`\`\`
\`settingsHtml\` / panel 没有 preload 桥,读取同一份上下文走同源只读端点:
@@ -1010,6 +1101,7 @@ const r = await cindy.request({ kind: 'app-context' });
\`\`\`js
const r = await (await fetch('/app-context')).json();
const region = r.context.region;
+const locale = r.context.locale;
\`\`\`
region 只适合选择**已在 manifest 声明过**的公开配置。例如 broker OAuth
@@ -1017,6 +1109,13 @@ region 只适合选择**已在 manifest 声明过**的公开配置。例如 brok
\`clientId\` 放进 \`/oauth/<key>/connect\` body;主机会做清单白名单复验。
不要用 region 推断用户位置、语言或数据归属。
+\`locale\` 是插件语言的唯一事实来源。设置页、panel 和电子脑都只使用它;
+不要读取 \`navigator.language\`。宿主切换语言时,运行中的电子脑会收到
+\`{ type:'host-context-changed', ok:true, context:{ region, locale } }\`,可用
+\`BroadcastChannel\` 通知同插件的设置页/panel 重新读取 \`/app-context\` 并换文案。
+未运行的插件会在下次启动或页面重新装载时直接读到新语言。插件自身不支持该 locale 时
+必须选英文资源。
+
## 4.5 聊天卡片(card 槽,海报模式)
声明 \`"slots": [..., "card"]\` 即可,无配套清单字段。作用:你的工具调用在聊天流里
diff --git a/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
new file mode 100644
index 0000000000..736210c6b6
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
@@ -0,0 +1,75 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ GHOST_LOCALE_MAX_BYTES,
+ validateGhostManifestLocaleResource,
+ type GhostManifest,
+} from '../../shared/ghost.js';
+
+export type GhostLocaleDirectoryValidation = { ok: true } | { ok: false; reason: string };
+
+/**
+ * Resolve a manifest path one segment at a time so case-insensitive filesystems
+ * cannot hide a casing mismatch that would later produce a different ZIP entry.
+ */
+function resolveExactFile(rootDir: string, relativePath: string): string {
+ const segments = relativePath.split('/');
+ let current = rootDir;
+ for (let index = 0; index < segments.length; index += 1) {
+ const segment = segments[index];
+ const entries = fs.readdirSync(current, { withFileTypes: true });
+ const exact = entries.find((entry) => entry.name === segment);
+ if (!exact) {
+ const caseInsensitive = entries.find(
+ (entry) => entry.name.toLowerCase() === segment.toLowerCase(),
+ );
+ if (caseInsensitive) {
+ throw new Error(
+ `路径大小写不一致:manifest 声明 ${JSON.stringify(segment)},磁盘实际为 ${JSON.stringify(caseInsensitive.name)}`,
+ );
+ }
+ throw new Error(`路径不存在:${relativePath}`);
+ }
+ const isLast = index === segments.length - 1;
+ if (isLast ? !exact.isFile() : !exact.isDirectory()) {
+ throw new Error(`路径不是${isLast ? '文件' : '目录'}:${relativePath}`);
+ }
+ current = path.join(current, exact.name);
+ }
+ return current;
+}
+
+/** Forge 与内置播种共用的目录 locale 校验。 */
+export function validateGhostLocaleResourcesInDirectory(
+ rootDir: string,
+ manifest: GhostManifest,
+): GhostLocaleDirectoryValidation {
+ if (!manifest.locales) return { ok: true };
+ for (const [locale, relativePath] of Object.entries(manifest.locales)) {
+ try {
+ const absolutePath = resolveExactFile(rootDir, relativePath);
+ const stat = fs.statSync(absolutePath);
+ if (stat.size > GHOST_LOCALE_MAX_BYTES) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 超过 ${GHOST_LOCALE_MAX_BYTES} 字节上限(${relativePath})`,
+ };
+ }
+ const raw = JSON.parse(fs.readFileSync(absolutePath, 'utf8')) as unknown;
+ const localized = validateGhostManifestLocaleResource(raw, manifest);
+ if (!localized.ok) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 不合格(${relativePath}):${localized.reason}`,
+ };
+ }
+ } catch (error) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 不可用(${relativePath}):${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+ }
+ return { ok: true };
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 4e22f51aa9..2c8c8296b5 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -70,7 +70,7 @@ import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoin
import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccounts.js';
import { reclaimLoopbackPort } from './portReclaim.js';
import { GhostConnectionManager } from './ghostConnections.js';
-import { t } from '../i18n.js';
+import { getResolvedMainLocale, t } from '../i18n.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import {
FILO_GOOGLE_GHOST_ID,
@@ -189,14 +189,17 @@ import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';
const log = createLogger('brain');
/**
- * 电子脑管子与 settingsHtml `/app-context` 共用,避免两条 region 口径漂移。
+ * 电子脑管子与 settingsHtml `/app-context` 共用,避免 region / locale 两条口径漂移。
* dev 区域(第三系统身份,2026-07-20)对意识映射为 'cn':意识契约
* GhostAppRegion 维持 cn|global 两值(FORGE_GUIDE §4.1 不变),dev 的行为
* 语义本就归 cn 系,意识按区域选公开配置时应与 cn 同待遇。
*/
function currentGhostAppContext() {
const region: GhostAppRegion = CURRENT_CINDY_REGION === 'global' ? 'global' : 'cn';
- return { ok: true as const, context: { region } };
+ return {
+ ok: true as const,
+ context: { region, locale: getResolvedMainLocale() },
+ };
}
let managerSingleton: GhostManager | null = null;
@@ -507,6 +510,7 @@ export function getGhostManager(): GhostManager {
managerSingleton = new GhostManager({
getRootDir: brainRootDir,
onChanged: broadcastGhostsChanged,
+ getLocale: getResolvedMainLocale,
trustRegistry: loadGhostTrustRegistry(),
log,
});
@@ -3141,6 +3145,24 @@ export function setGhostsChangedObserver(
ghostsChangedObserver = observer;
}
+/**
+ * 宿主语言切换后的插件刷新入口:重新按当前语言解析 manifest 并广播;
+ * 已运行的逻辑页收到同一份 app-context 变化,可经自身 BroadcastChannel
+ * 通知设置页/面板。未运行插件下次启动时直接读取最新语言。
+ */
+export function refreshGhostLocalization(): void {
+ if (!managerSingleton) return;
+ const ghosts = managerSingleton.list();
+ broadcastGhostsChanged(ghosts);
+ const context = currentGhostAppContext();
+ for (const ghost of ghosts) {
+ sendToGhostLogic(ghost.manifest.id, {
+ type: 'host-context-changed',
+ ...context,
+ });
+ }
+}
+
/** Plugin 顶部快捷行的 host-owned MRU 快照,多窗口同步。 */
function broadcastGhostRecentUsageChanged(ids: string[]): void {
BrowserWindow.getAllWindows().forEach((window) => {
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
index 23d9a83fcb..ecbeef30fd 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
@@ -386,7 +386,15 @@ function SettingsWebviewBody({
webview.remove();
};
// version 入依赖:原位更新换版后 webview 重挂载,设置区立刻跑新代码。
- }, [crashed, generation, manifest.id, manifest.version, settingsHtml, fixedHeight]);
+ }, [
+ crashed,
+ generation,
+ manifest.id,
+ manifest.version,
+ manifest.resolvedLocale,
+ settingsHtml,
+ fixedHeight,
+ ]);
if (crashed) {
return (
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
index 8677108c95..ce8c4622c7 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
@@ -247,7 +247,14 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
};
// version 入依赖:原位更新换版后 webview 重挂载,面板立刻跑新代码
// (供片协议直读安装目录,不重挂会一直渲染旧版缓存的页面)。
- }, [crashed, generation, manifest.id, manifest.version, panelHtml]);
+ }, [
+ crashed,
+ generation,
+ manifest.id,
+ manifest.version,
+ manifest.resolvedLocale,
+ panelHtml,
+ ]);
if (crashed) {
return (
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 4cfb499498..f6ca288473 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -6,6 +6,7 @@ import {
diffGhostPermissionItems,
ghostContentKeys,
ghostExternalLinkUrls,
+ ghostLocalePathFor,
ghostNetworkHostMatches,
ghostPanelKind,
ghostPreviewUrlAllowed,
@@ -19,7 +20,10 @@ import {
isValidGhostNetworkHostPattern,
layoutWithGhostPanel,
parseGhostPartition,
+ resolveGhostManifestLocale,
validateGhostManifest,
+ validateGhostManifestLocaleResource,
+ withGhostResolvedLocale,
type GhostManifest,
} from '../ghost';
import { createDefaultLayout, type SplitNode } from '../layoutTree';
@@ -239,6 +243,251 @@ describe('ghost · 清单校验', () => {
expect(validateGhostManifest({ ...goodManifest(), author: 42 }).ok).toBe(false);
});
+ it('locales 只接受宿主四种语言、安全 JSON 路径且必须提供英文', () => {
+ const valid = validateGhostManifest({
+ ...goodManifest(),
+ locales: {
+ en: 'locales/en.json',
+ 'zh-CN': 'locales/zh-CN.json',
+ ja: 'locales/ja.json',
+ ko: 'locales/ko.json',
+ },
+ });
+ expect(valid.ok).toBe(true);
+ expect(valid.ok && valid.manifest.locales?.en).toBe('locales/en.json');
+
+ expect(validateGhostManifest({
+ ...goodManifest(),
+ locales: { 'zh-CN': 'locales/zh-CN.json' },
+ }).ok).toBe(false);
+ expect(validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: '../en.json' },
+ }).ok).toBe(false);
+ expect(validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: 'locales/en.json', fr: 'locales/fr.json' },
+ }).ok).toBe(false);
+ expect(validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: 'locales/en.json', ja: 'locales/en.json' },
+ }).ok).toBe(false);
+ expect(validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: 'locales/en.json', ja: 'Locales/EN.json' },
+ }).ok).toBe(false);
+ expect(validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: 'GHOST.JSON' },
+ }).ok).toBe(false);
+ });
+
+ it('locale 选择完全跟随宿主,插件不支持或宿主值未知时固定回退英文', () => {
+ const parsed = validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: 'locales/en.json', ja: 'locales/ja.json' },
+ });
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ expect(ghostLocalePathFor(parsed.manifest, 'ja')).toBe('locales/ja.json');
+ expect(ghostLocalePathFor(parsed.manifest, 'zh-CN')).toBe('locales/en.json');
+ expect(ghostLocalePathFor(parsed.manifest, 'fr-FR')).toBe('locales/en.json');
+ expect(withGhostResolvedLocale(parsed.manifest, 'ko').resolvedLocale).toBe('ko');
+ expect(withGhostResolvedLocale(parsed.manifest, 'fr-FR').resolvedLocale).toBe('en');
+ });
+
+ it('locale 资源完整覆盖清单文案和全部工具,并按稳定 tool name 合并', () => {
+ const parsed = validateGhostManifest({
+ schemaVersion: 2,
+ id: 'localized',
+ name: 'Base',
+ description: 'Base description',
+ whenToUse: 'Base routing',
+ version: '1.0.0',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [
+ {
+ name: 'alpha',
+ description: 'Base alpha',
+ parameters: {
+ type: 'object',
+ title: 'Base arguments',
+ properties: {
+ query: {
+ type: 'string',
+ title: 'Base query',
+ description: 'Base query description',
+ },
+ mode: {
+ oneOf: [
+ { const: 'fast', title: 'Base fast mode' },
+ { const: 'safe', title: 'Base safe mode' },
+ ],
+ },
+ },
+ },
+ },
+ { name: 'beta', description: 'Base beta' },
+ ],
+ });
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ const resource = validateGhostManifestLocaleResource({
+ name: 'Localized',
+ description: 'Localized description',
+ whenToUse: 'Localized routing',
+ tools: {
+ beta: { description: 'Localized beta' },
+ alpha: {
+ description: 'Localized alpha',
+ parameters: {
+ '': { title: 'Localized arguments' },
+ '/properties/query': {
+ title: 'Localized query',
+ description: 'Localized query description',
+ },
+ '/properties/mode/oneOf/0': { title: 'Localized fast mode' },
+ '/properties/mode/oneOf/1': { title: 'Localized safe mode' },
+ },
+ },
+ },
+ }, parsed.manifest);
+ expect(resource.ok).toBe(true);
+ if (!resource.ok) return;
+ expect(resolveGhostManifestLocale(parsed.manifest, resource.resource)).toMatchObject({
+ name: 'Localized',
+ description: 'Localized description',
+ whenToUse: 'Localized routing',
+ tools: [
+ {
+ name: 'alpha',
+ description: 'Localized alpha',
+ parameters: {
+ title: 'Localized arguments',
+ properties: {
+ query: {
+ title: 'Localized query',
+ description: 'Localized query description',
+ },
+ mode: {
+ oneOf: [
+ { title: 'Localized fast mode' },
+ { title: 'Localized safe mode' },
+ ],
+ },
+ },
+ },
+ },
+ { name: 'beta', description: 'Localized beta' },
+ ],
+ });
+ expect(validateGhostManifestLocaleResource({
+ name: 'Incomplete',
+ description: 'Localized description',
+ whenToUse: 'Localized routing',
+ tools: { alpha: { description: 'Only one' } },
+ }, parsed.manifest).ok).toBe(false);
+ });
+
+ it('locale 资源完整覆盖宿主持有的面板、凭证、连接与 setup 标签', () => {
+ const parsed = validateGhostManifest({
+ schemaVersion: 2,
+ id: 'localized-labels',
+ name: 'Base',
+ version: '1.0.0',
+ entry: 'main.js',
+ settingsHtml: 'settings.html',
+ slots: ['panel', 'network', 'node'],
+ panel: { title: 'Base panel', html: 'panel.html' },
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [{
+ key: 'api_key',
+ label: 'Base API key',
+ hint: 'Base secret hint',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ }],
+ connections: [{
+ key: 'instance',
+ label: 'Base instance',
+ hint: 'Base connection hint',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ }],
+ },
+ node: {
+ entry: 'node/worker.cjs',
+ protocol: 'json-rpc-stdio',
+ secretBindings: [{
+ key: 'worker_key',
+ label: 'Base worker key',
+ hint: 'Base worker hint',
+ methods: ['run'],
+ }],
+ },
+ setup: {
+ requires: [{ anyOf: [{ kv: 'default_repo', label: 'Base repository' }] }],
+ },
+ });
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ const resource = validateGhostManifestLocaleResource({
+ name: 'Localized',
+ panel: { title: 'Localized panel' },
+ network: {
+ secrets: {
+ api_key: { label: 'Localized API key', hint: 'Localized secret hint' },
+ },
+ connections: {
+ instance: { label: 'Localized instance', hint: 'Localized connection hint' },
+ },
+ },
+ node: {
+ secretBindings: {
+ worker_key: { label: 'Localized worker key', hint: 'Localized worker hint' },
+ },
+ },
+ setup: {
+ kv: {
+ default_repo: { label: 'Localized repository' },
+ },
+ },
+ }, parsed.manifest);
+ expect(resource.ok).toBe(true);
+ if (!resource.ok) return;
+ expect(resolveGhostManifestLocale(parsed.manifest, resource.resource)).toMatchObject({
+ panel: { title: 'Localized panel' },
+ network: {
+ secrets: [{
+ key: 'api_key',
+ label: 'Localized API key',
+ hint: 'Localized secret hint',
+ }],
+ connections: [{
+ key: 'instance',
+ label: 'Localized instance',
+ hint: 'Localized connection hint',
+ }],
+ },
+ node: {
+ secretBindings: [{
+ key: 'worker_key',
+ label: 'Localized worker key',
+ hint: 'Localized worker hint',
+ }],
+ },
+ setup: {
+ requires: [{
+ anyOf: [{ kind: 'kv', key: 'default_repo', label: 'Localized repository' }],
+ }],
+ },
+ });
+ expect(validateGhostManifestLocaleResource({
+ name: 'Incomplete',
+ panel: { title: 'Localized panel' },
+ }, parsed.manifest).ok).toBe(false);
+ });
+
it('icon:可选包内相对路径,扩展名白名单;非法路径/扩展名 → 拒', () => {
const base = validateGhostManifest({ ...goodManifest(), icon: 'assets/icon.png' });
expect(base.ok && (base as { ok: true; manifest: GhostManifest }).manifest.icon).toBe('assets/icon.png');
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index a895a66c7a..4d8378d4eb 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1,4 +1,5 @@
import { findSplitChildByPanelKind, insertRootSplitPane, type Layout } from './layoutTree';
+import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './locale';
/**
* 意识(Ghost,.cindy 文件)的清单数据模型与校验 —— main / renderer 共用。
@@ -879,6 +880,16 @@ export interface GhostManifest {
version: string;
/** 作者展示名(仅展示用)。 */
author?: string;
+ /**
+ * 本地化资源路径。声明后必须至少提供英文;宿主按当前应用语言读取,
+ * 当前语言未提供时固定回退英文。路径均位于插件安装目录内。
+ */
+ locales?: Partial<Record<SupportedLocale, string>> & { en: string };
+ /**
+ * 宿主解析清单后附加的当前语言,只用于运行时视图与 webview 刷新。
+ * 不属于 ghost.json 作者字段;validateGhostManifest 会忽略包内同名输入。
+ */
+ resolvedLocale?: SupportedLocale;
/**
* 意识自我介绍(1–300 字,仅展示用):这段意识是干嘛
* 的、给谁用。装入确认框与详情页展示;与 tools[].description(给 AI 看的
@@ -977,6 +988,35 @@ export interface GhostManifest {
panel?: GhostPanelDecl;
}
+/**
+ * 单个插件 locale 文件的 manifest 文案。协议键、工具名和参数名不翻译;
+ * tools 以稳定 tool name 对齐,避免数组顺序变化导致翻译错位。
+ */
+export interface GhostManifestLocaleResource {
+ name: string;
+ description?: string;
+ whenToUse?: string;
+ tools?: Record<string, {
+ description: string;
+ /** JSON Pointer → 该参数 schema 节点已有的 title / description 翻译。 */
+ parameters?: Record<string, { title?: string; description?: string }>;
+ }>;
+ panel?: { title: string };
+ network?: {
+ secrets?: Record<string, { label: string; hint?: string }>;
+ connections?: Record<string, { label: string; hint?: string }>;
+ };
+ node?: {
+ secretBindings?: Record<string, { label: string; hint?: string }>;
+ };
+ setup?: {
+ kv?: Record<string, { label: string }>;
+ };
+}
+
+/** 单个插件 locale JSON 的字节上限。Forge 与装入侧共用,避免两端契约漂移。 */
+export const GHOST_LOCALE_MAX_BYTES = 64 * 1024;
+
/** 已装入主机的意识(清单 + 安装位置 + 启用态)。 */
export interface InstalledGhost {
manifest: GhostManifest;
@@ -1493,6 +1533,514 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
+/** 当前宿主语言在插件未提供时固定回退英文。 */
+export function ghostLocalePathFor(
+ manifest: GhostManifest,
+ locale: string | undefined | null,
+): string | null {
+ if (!manifest.locales) return null;
+ const supported = (SUPPORTED_LOCALES as readonly string[]).includes(locale ?? '')
+ ? locale as SupportedLocale
+ : DEFAULT_LOCALE;
+ return manifest.locales[supported] ?? manifest.locales[DEFAULT_LOCALE] ?? null;
+}
+
+/** 把当前宿主语言附到运行时清单视图;不支持的输入固定归一到英文。 */
+export function withGhostResolvedLocale(
+ manifest: GhostManifest,
+ locale: string | undefined | null,
+): GhostManifest {
+ const resolvedLocale = (SUPPORTED_LOCALES as readonly string[]).includes(locale ?? '')
+ ? locale as SupportedLocale
+ : DEFAULT_LOCALE;
+ return { ...manifest, resolvedLocale };
+}
+
+type GhostSchemaLocaleText = { title?: string; description?: string };
+type GhostSchemaLocaleShape = { title: boolean; description: boolean };
+
+const GHOST_SCHEMA_MAP_KEYWORDS = [
+ 'properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas',
+] as const;
+const GHOST_SCHEMA_SINGLE_KEYWORDS = [
+ 'additionalProperties', 'unevaluatedProperties', 'propertyNames', 'items',
+ 'contains', 'not', 'if', 'then', 'else',
+] as const;
+const GHOST_SCHEMA_ARRAY_KEYWORDS = ['allOf', 'anyOf', 'oneOf', 'prefixItems'] as const;
+
+function ghostJsonPointerChild(pointer: string, segment: string | number): string {
+ const escaped = String(segment).replace(/~/g, '~0').replace(/\//g, '~1');
+ return `${pointer}/${escaped}`;
+}
+
+/** 收集 JSON Schema 节点中已有的 title / description,以 JSON Pointer 稳定寻址。 */
+function collectGhostSchemaLocaleShape(
+ schema: unknown,
+ pointer = '',
+ result: Record<string, GhostSchemaLocaleShape> = {},
+): Record<string, GhostSchemaLocaleShape> {
+ if (!isPlainObject(schema)) return result;
+ const title = typeof schema.title === 'string';
+ const description = typeof schema.description === 'string';
+ if (title || description) result[pointer] = { title, description };
+ for (const keyword of GHOST_SCHEMA_MAP_KEYWORDS) {
+ const children = schema[keyword];
+ if (!isPlainObject(children)) continue;
+ for (const [key, child] of Object.entries(children)) {
+ collectGhostSchemaLocaleShape(child, ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), key), result);
+ }
+ }
+ for (const keyword of GHOST_SCHEMA_SINGLE_KEYWORDS) {
+ collectGhostSchemaLocaleShape(schema[keyword], ghostJsonPointerChild(pointer, keyword), result);
+ }
+ for (const keyword of GHOST_SCHEMA_ARRAY_KEYWORDS) {
+ const children = schema[keyword];
+ if (!Array.isArray(children)) continue;
+ children.forEach((child, index) => {
+ collectGhostSchemaLocaleShape(child, ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), index), result);
+ });
+ }
+ return result;
+}
+
+function resolveGhostSchemaLocale(
+ schema: Record<string, unknown>,
+ localized: Record<string, GhostSchemaLocaleText>,
+ pointer = '',
+): Record<string, unknown> {
+ const result: Record<string, unknown> = { ...schema };
+ const text = localized[pointer];
+ if (text?.title !== undefined) result.title = text.title;
+ if (text?.description !== undefined) result.description = text.description;
+ for (const keyword of GHOST_SCHEMA_MAP_KEYWORDS) {
+ const children = schema[keyword];
+ if (!isPlainObject(children)) continue;
+ result[keyword] = Object.fromEntries(
+ Object.entries(children).map(([key, child]) => [
+ key,
+ isPlainObject(child)
+ ? resolveGhostSchemaLocale(
+ child,
+ localized,
+ ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), key),
+ )
+ : child,
+ ]),
+ );
+ }
+ for (const keyword of GHOST_SCHEMA_SINGLE_KEYWORDS) {
+ const child = schema[keyword];
+ if (!isPlainObject(child)) continue;
+ result[keyword] = resolveGhostSchemaLocale(child, localized, ghostJsonPointerChild(pointer, keyword));
+ }
+ for (const keyword of GHOST_SCHEMA_ARRAY_KEYWORDS) {
+ const children = schema[keyword];
+ if (!Array.isArray(children)) continue;
+ result[keyword] = children.map((child, index) => (
+ isPlainObject(child)
+ ? resolveGhostSchemaLocale(
+ child,
+ localized,
+ ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), index),
+ )
+ : child
+ ));
+ }
+ return result;
+}
+
+/**
+ * 校验 locale 文件,并要求它完整覆盖原 manifest 已声明的可本地化字段。
+ * 缺译拒装,避免支持语言中静默混入另一种语言。
+ */
+export function validateGhostManifestLocaleResource(
+ raw: unknown,
+ manifest: GhostManifest,
+): { ok: true; resource: GhostManifestLocaleResource } | { ok: false; reason: string } {
+ if (!isPlainObject(raw)) return { ok: false, reason: 'locale 文件必须是对象' };
+ const allowedTopLevelFields = new Set([
+ 'name', 'description', 'whenToUse', 'tools', 'panel', 'network', 'node', 'setup',
+ ]);
+ const unknownTopLevelField = Object.keys(raw).find((field) => !allowedTopLevelFields.has(field));
+ if (unknownTopLevelField) {
+ return { ok: false, reason: `locale 含未知字段 ${JSON.stringify(unknownTopLevelField)}` };
+ }
+ if (typeof raw.name !== 'string' || raw.name.trim().length === 0 || raw.name.length > 64) {
+ return { ok: false, reason: 'locale.name 必须是 1–64 字符的非空字符串' };
+ }
+ const optionalText = (
+ field: 'description' | 'whenToUse',
+ max: number,
+ ): string | undefined | { error: string } => {
+ const expected = manifest[field] !== undefined;
+ const value = raw[field];
+ if (!expected) {
+ if (value !== undefined) return { error: `locale.${field} 不应存在:原 manifest 未声明该字段` };
+ return undefined;
+ }
+ if (typeof value !== 'string' || value.trim().length === 0 || value.length > max) {
+ return { error: `locale.${field} 必须是 1–${max} 字符的非空字符串` };
+ }
+ return value;
+ };
+ const description = optionalText('description', 300);
+ if (isPlainObject(description) && typeof description.error === 'string') {
+ return { ok: false, reason: description.error };
+ }
+ const whenToUse = optionalText('whenToUse', 300);
+ if (isPlainObject(whenToUse) && typeof whenToUse.error === 'string') {
+ return { ok: false, reason: whenToUse.error };
+ }
+
+ let tools: GhostManifestLocaleResource['tools'];
+ if (manifest.tools !== undefined) {
+ if (!isPlainObject(raw.tools)) {
+ return { ok: false, reason: 'locale.tools 必须按 tool name 提供完整对象' };
+ }
+ const expectedNames = new Set(manifest.tools.map((tool) => tool.name));
+ const actualNames = Object.keys(raw.tools);
+ const unknown = actualNames.find((name) => !expectedNames.has(name));
+ if (unknown) return { ok: false, reason: `locale.tools 含未知工具 ${JSON.stringify(unknown)}` };
+ tools = {};
+ for (const tool of manifest.tools) {
+ const localized = raw.tools[tool.name];
+ if (!isPlainObject(localized)) {
+ return { ok: false, reason: `locale.tools 缺少 ${JSON.stringify(tool.name)}` };
+ }
+ const unknownToolField = Object.keys(localized).find(
+ (field) => field !== 'description' && field !== 'parameters',
+ );
+ if (unknownToolField) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}] 含未知字段 ${JSON.stringify(unknownToolField)}`,
+ };
+ }
+ if (
+ typeof localized.description !== 'string' ||
+ localized.description.trim().length === 0 ||
+ localized.description.length > 1024
+ ) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].description 必须是 1–1024 字符的非空字符串`,
+ };
+ }
+ const parameterShape = collectGhostSchemaLocaleShape(tool.parameters);
+ const parameterPointers = Object.keys(parameterShape);
+ let parameters: Record<string, GhostSchemaLocaleText> | undefined;
+ if (parameterPointers.length > 0) {
+ if (!isPlainObject(localized.parameters)) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters 必须按 JSON Pointer 完整提供参数文案`,
+ };
+ }
+ const expectedPointers = new Set(parameterPointers);
+ const unknownPointer = Object.keys(localized.parameters).find((pointer) => !expectedPointers.has(pointer));
+ if (unknownPointer) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters 含未知路径 ${JSON.stringify(unknownPointer)}`,
+ };
+ }
+ parameters = {};
+ for (const pointer of parameterPointers) {
+ const shape = parameterShape[pointer];
+ const localizedText = localized.parameters[pointer];
+ if (!isPlainObject(localizedText)) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters 缺少 ${JSON.stringify(pointer)}`,
+ };
+ }
+ const allowedFields = new Set([
+ ...(shape.title ? ['title'] : []),
+ ...(shape.description ? ['description'] : []),
+ ]);
+ const unknownField = Object.keys(localizedText).find((field) => !allowedFields.has(field));
+ if (unknownField) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters[${JSON.stringify(pointer)}] 含未知字段 ${JSON.stringify(unknownField)}`,
+ };
+ }
+ if (
+ shape.title &&
+ (typeof localizedText.title !== 'string' || localizedText.title.trim().length === 0 || localizedText.title.length > 256)
+ ) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters[${JSON.stringify(pointer)}].title 必须是 1–256 字符的非空字符串`,
+ };
+ }
+ if (
+ shape.description &&
+ (
+ typeof localizedText.description !== 'string' ||
+ localizedText.description.trim().length === 0 ||
+ localizedText.description.length > 1024
+ )
+ ) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters[${JSON.stringify(pointer)}].description 必须是 1–1024 字符的非空字符串`,
+ };
+ }
+ parameters[pointer] = {
+ ...(typeof localizedText.title === 'string' ? { title: localizedText.title } : {}),
+ ...(typeof localizedText.description === 'string' ? { description: localizedText.description } : {}),
+ };
+ }
+ } else if (localized.parameters !== undefined) {
+ return {
+ ok: false,
+ reason: `locale.tools[${JSON.stringify(tool.name)}].parameters 不应存在:原参数 schema 没有 title / description`,
+ };
+ }
+ tools[tool.name] = {
+ description: localized.description,
+ ...(parameters !== undefined ? { parameters } : {}),
+ };
+ }
+ } else if (raw.tools !== undefined) {
+ return { ok: false, reason: 'locale.tools 不应存在:原 manifest 未声明工具' };
+ }
+
+ let panel: GhostManifestLocaleResource['panel'];
+ if (manifest.panel?.title !== undefined) {
+ if (!isPlainObject(raw.panel)) {
+ return { ok: false, reason: 'locale.panel 必须提供 panel.title' };
+ }
+ const unknownPanelField = Object.keys(raw.panel).find((field) => field !== 'title');
+ if (unknownPanelField) {
+ return { ok: false, reason: `locale.panel 含未知字段 ${JSON.stringify(unknownPanelField)}` };
+ }
+ if (typeof raw.panel.title !== 'string' || raw.panel.title.trim().length === 0 || raw.panel.title.length > 64) {
+ return { ok: false, reason: 'locale.panel.title 必须是 1–64 字符的非空字符串' };
+ }
+ panel = { title: raw.panel.title };
+ } else if (raw.panel !== undefined) {
+ return { ok: false, reason: 'locale.panel 不应存在:原 manifest 未声明 panel.title' };
+ }
+
+ const validateLocalizedLabels = (
+ rawValue: unknown,
+ fieldPath: string,
+ declarations: ReadonlyArray<{ key: string; hint?: string }>,
+ ): { ok: true; labels?: Record<string, { label: string; hint?: string }> } | { ok: false; reason: string } => {
+ if (declarations.length === 0) {
+ if (rawValue !== undefined) {
+ return { ok: false, reason: `${fieldPath} 不应存在:原 manifest 未声明对应项目` };
+ }
+ return { ok: true };
+ }
+ if (!isPlainObject(rawValue)) {
+ return { ok: false, reason: `${fieldPath} 必须按稳定 key 提供完整对象` };
+ }
+ const expectedKeys = new Set(declarations.map((declaration) => declaration.key));
+ const unknownKey = Object.keys(rawValue).find((key) => !expectedKeys.has(key));
+ if (unknownKey) {
+ return { ok: false, reason: `${fieldPath} 含未知 key ${JSON.stringify(unknownKey)}` };
+ }
+ const labels: Record<string, { label: string; hint?: string }> = {};
+ for (const declaration of declarations) {
+ const localized = rawValue[declaration.key];
+ if (!isPlainObject(localized)) {
+ return { ok: false, reason: `${fieldPath} 缺少 ${JSON.stringify(declaration.key)}` };
+ }
+ const allowedFields = declaration.hint !== undefined ? new Set(['label', 'hint']) : new Set(['label']);
+ const unknownField = Object.keys(localized).find((field) => !allowedFields.has(field));
+ if (unknownField) {
+ return {
+ ok: false,
+ reason: `${fieldPath}[${JSON.stringify(declaration.key)}] 含未知字段 ${JSON.stringify(unknownField)}`,
+ };
+ }
+ if (typeof localized.label !== 'string' || localized.label.trim().length === 0 || localized.label.length > 64) {
+ return {
+ ok: false,
+ reason: `${fieldPath}[${JSON.stringify(declaration.key)}].label 必须是 1–64 字符的非空字符串`,
+ };
+ }
+ if (
+ declaration.hint !== undefined &&
+ (typeof localized.hint !== 'string' || localized.hint.trim().length === 0 || localized.hint.length > 200)
+ ) {
+ return {
+ ok: false,
+ reason: `${fieldPath}[${JSON.stringify(declaration.key)}].hint 必须是 1–200 字符的非空字符串`,
+ };
+ }
+ labels[declaration.key] = {
+ label: localized.label,
+ ...(typeof localized.hint === 'string' ? { hint: localized.hint } : {}),
+ };
+ }
+ return { ok: true, labels };
+ };
+
+ const secretDecls = manifest.network?.secrets ?? [];
+ const connectionDecls = manifest.network?.connections ?? [];
+ let network: GhostManifestLocaleResource['network'];
+ if (secretDecls.length > 0 || connectionDecls.length > 0) {
+ if (!isPlainObject(raw.network)) {
+ return { ok: false, reason: 'locale.network 必须完整覆盖凭证与连接展示文案' };
+ }
+ const unknownNetworkField = Object.keys(raw.network).find(
+ (field) => field !== 'secrets' && field !== 'connections',
+ );
+ if (unknownNetworkField) {
+ return { ok: false, reason: `locale.network 含未知字段 ${JSON.stringify(unknownNetworkField)}` };
+ }
+ const secrets = validateLocalizedLabels(raw.network.secrets, 'locale.network.secrets', secretDecls);
+ if (!secrets.ok) return secrets;
+ const connections = validateLocalizedLabels(raw.network.connections, 'locale.network.connections', connectionDecls);
+ if (!connections.ok) return connections;
+ network = {
+ ...(secrets.labels !== undefined ? { secrets: secrets.labels } : {}),
+ ...(connections.labels !== undefined ? { connections: connections.labels } : {}),
+ };
+ } else if (raw.network !== undefined) {
+ return { ok: false, reason: 'locale.network 不应存在:原 manifest 未声明凭证或连接' };
+ }
+
+ const nodeSecretDecls = manifest.node?.secretBindings ?? [];
+ let node: GhostManifestLocaleResource['node'];
+ if (nodeSecretDecls.length > 0) {
+ if (!isPlainObject(raw.node)) {
+ return { ok: false, reason: 'locale.node 必须完整覆盖 Node 凭证展示文案' };
+ }
+ const unknownNodeField = Object.keys(raw.node).find((field) => field !== 'secretBindings');
+ if (unknownNodeField) {
+ return { ok: false, reason: `locale.node 含未知字段 ${JSON.stringify(unknownNodeField)}` };
+ }
+ const secretBindings = validateLocalizedLabels(
+ raw.node.secretBindings,
+ 'locale.node.secretBindings',
+ nodeSecretDecls,
+ );
+ if (!secretBindings.ok) return secretBindings;
+ node = { secretBindings: secretBindings.labels! };
+ } else if (raw.node !== undefined) {
+ return { ok: false, reason: 'locale.node 不应存在:原 manifest 未声明 node.secretBindings' };
+ }
+
+ const setupKvDecls = new Map<string, { key: string }>();
+ for (const group of manifest.setup?.requires ?? []) {
+ for (const requirement of group.anyOf) {
+ if (requirement.kind === 'kv') setupKvDecls.set(requirement.key, { key: requirement.key });
+ }
+ }
+ let setup: GhostManifestLocaleResource['setup'];
+ if (setupKvDecls.size > 0) {
+ if (!isPlainObject(raw.setup)) {
+ return { ok: false, reason: 'locale.setup 必须完整覆盖 setup kv 展示文案' };
+ }
+ const unknownSetupField = Object.keys(raw.setup).find((field) => field !== 'kv');
+ if (unknownSetupField) {
+ return { ok: false, reason: `locale.setup 含未知字段 ${JSON.stringify(unknownSetupField)}` };
+ }
+ const kv = validateLocalizedLabels(raw.setup.kv, 'locale.setup.kv', [...setupKvDecls.values()]);
+ if (!kv.ok) return kv;
+ setup = {
+ kv: Object.fromEntries(
+ Object.entries(kv.labels!).map(([key, localized]) => [key, { label: localized.label }]),
+ ),
+ };
+ } else if (raw.setup !== undefined) {
+ return { ok: false, reason: 'locale.setup 不应存在:原 manifest 未声明 setup kv 项' };
+ }
+
+ return {
+ ok: true,
+ resource: {
+ name: raw.name,
+ ...(typeof description === 'string' ? { description } : {}),
+ ...(typeof whenToUse === 'string' ? { whenToUse } : {}),
+ ...(tools !== undefined ? { tools } : {}),
+ ...(panel !== undefined ? { panel } : {}),
+ ...(network !== undefined ? { network } : {}),
+ ...(node !== undefined ? { node } : {}),
+ ...(setup !== undefined ? { setup } : {}),
+ },
+ };
+}
+
+/** 用已校验的 locale 资源生成宿主与 Agent 消费的本地化 manifest 视图。 */
+export function resolveGhostManifestLocale(
+ manifest: GhostManifest,
+ resource: GhostManifestLocaleResource,
+): GhostManifest {
+ return {
+ ...manifest,
+ name: resource.name,
+ ...(resource.description !== undefined ? { description: resource.description } : {}),
+ ...(resource.whenToUse !== undefined ? { whenToUse: resource.whenToUse } : {}),
+ ...(manifest.tools !== undefined && resource.tools !== undefined
+ ? {
+ tools: manifest.tools.map((tool) => ({
+ ...tool,
+ description: resource.tools![tool.name].description,
+ ...(tool.parameters !== undefined && resource.tools![tool.name].parameters !== undefined
+ ? { parameters: resolveGhostSchemaLocale(tool.parameters, resource.tools![tool.name].parameters!) }
+ : {}),
+ })),
+ }
+ : {}),
+ ...(manifest.panel !== undefined && resource.panel !== undefined
+ ? { panel: { ...manifest.panel, title: resource.panel.title } }
+ : {}),
+ ...(manifest.network !== undefined && resource.network !== undefined
+ ? {
+ network: {
+ ...manifest.network,
+ ...(manifest.network.secrets !== undefined && resource.network.secrets !== undefined
+ ? {
+ secrets: manifest.network.secrets.map((secret) => ({
+ ...secret,
+ ...resource.network!.secrets![secret.key],
+ })),
+ }
+ : {}),
+ ...(manifest.network.connections !== undefined && resource.network.connections !== undefined
+ ? {
+ connections: manifest.network.connections.map((connection) => ({
+ ...connection,
+ ...resource.network!.connections![connection.key],
+ })),
+ }
+ : {}),
+ },
+ }
+ : {}),
+ ...(manifest.node !== undefined && resource.node?.secretBindings !== undefined
+ ? {
+ node: {
+ ...manifest.node,
+ secretBindings: manifest.node.secretBindings?.map((binding) => ({
+ ...binding,
+ ...resource.node!.secretBindings![binding.key],
+ })),
+ },
+ }
+ : {}),
+ ...(manifest.setup !== undefined && resource.setup?.kv !== undefined
+ ? {
+ setup: {
+ requires: manifest.setup.requires.map((group) => ({
+ anyOf: group.anyOf.map((requirement) => (
+ requirement.kind === 'kv'
+ ? { ...requirement, label: resource.setup!.kv![requirement.key].label }
+ : requirement
+ )),
+ })),
+ },
+ }
+ : {}),
+ };
+}
+
/**
* 校验一份解析后的 ghost.json。宽进严出:忽略未知字段(向前兼容),
* 已知字段全部严格检查;任何不合格都给出人类可读 reason。
@@ -1523,6 +2071,60 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
) {
return { ok: false, reason: 'author 必须是 1–64 字符的非空字符串' };
}
+ let locales: GhostManifest['locales'];
+ if (raw.locales !== undefined) {
+ if (!isPlainObject(raw.locales)) {
+ return { ok: false, reason: 'locales 必须是语言到 locale JSON 路径的对象' };
+ }
+ const unknownLocale = Object.keys(raw.locales).find(
+ (locale) => !(SUPPORTED_LOCALES as readonly string[]).includes(locale),
+ );
+ if (unknownLocale) {
+ return {
+ ok: false,
+ reason: `locales 含宿主不支持的语言 ${JSON.stringify(unknownLocale)}(可用:${SUPPORTED_LOCALES.join(' / ')})`,
+ };
+ }
+ if (raw.locales.en === undefined) {
+ return { ok: false, reason: 'locales 必须提供 en,作为所有不支持语言的固定回退' };
+ }
+ const normalized: Partial<Record<SupportedLocale, string>> = {};
+ const seenPaths = new Set<string>();
+ const nonLocalePaths = [
+ GHOST_MANIFEST_FILE,
+ raw.entry,
+ raw.icon,
+ raw.settingsHtml,
+ isPlainObject(raw.panel) ? raw.panel.html : undefined,
+ isPlainObject(raw.node) ? raw.node.entry : undefined,
+ ...(isPlainObject(raw.node) && Array.isArray(raw.node.entries) ? raw.node.entries : []),
+ ].filter((value): value is string => typeof value === 'string');
+ const nonLocalePathFolds = new Set(nonLocalePaths.map((value) => value.toLowerCase()));
+ for (const locale of SUPPORTED_LOCALES) {
+ const localePath = raw.locales[locale];
+ if (localePath === undefined) continue;
+ if (
+ typeof localePath !== 'string' ||
+ !isSafeGhostRelativePath(localePath) ||
+ !localePath.toLowerCase().endsWith('.json')
+ ) {
+ return { ok: false, reason: `locales.${locale} 必须是安装目录内以 .json 结尾的安全相对路径` };
+ }
+ const normalizedLocalePath = localePath.toLowerCase();
+ if (nonLocalePathFolds.has(normalizedLocalePath)) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 路径 ${JSON.stringify(localePath)} 与插件其他声明文件大小写折叠后冲突`,
+ };
+ }
+ if (seenPaths.has(normalizedLocalePath)) {
+ return { ok: false, reason: `locales 含重复路径 ${JSON.stringify(localePath)}` };
+ }
+ seenPaths.add(normalizedLocalePath);
+ normalized[locale] = localePath;
+ }
+ locales = normalized as GhostManifest['locales'];
+ }
if (
raw.description !== undefined &&
(typeof raw.description !== 'string' || raw.description.trim().length === 0 || raw.description.length > 300)
@@ -2984,6 +3586,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
version: raw.version,
kind: 'chip',
...(raw.author !== undefined ? { author: raw.author as string } : {}),
+ ...(locales !== undefined ? { locales } : {}),
...(raw.description !== undefined ? { description: raw.description as string } : {}),
...(raw.whenToUse !== undefined ? { whenToUse: raw.whenToUse as string } : {}),
...(raw.icon !== undefined ? { icon: raw.icon as string } : {}),
@@ -3017,7 +3620,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
*
* 上行(电子脑 → 主机,cindy.send(payload) = ipcRenderer.invoke):
* - tool-result:交卷。
- * - host-request:读取宿主公开上下文。目前只支持 app-context(region),
+ * - host-request:读取宿主公开上下文。目前只支持 app-context(region + locale),
* 无需声明卡槽、无用户数据与凭证内容。
* - cindy-request(旧名 model-request 兼容):cindy 槽代办(意识请 Cindy 本体干活;invoke 的返回值即结果,
* 无需另配对)。gen_image / edit_image;须声明 'cindy' 卡槽与能力详单。
@@ -3306,6 +3909,8 @@ export interface GhostAppContextResult {
ok: true;
context: {
region: GhostAppRegion;
+ /** 当前宿主应用语言;插件只使用本值,不读取 navigator.language。 */
+ locale: SupportedLocale;
};
}