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。

fix(companions): cache skill catalogs and mask structured URLs

Chris904433ac1fc7
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 511ddd399b..a2a4baed91 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -96,6 +96,11 @@ omitting it retains normal companion defaults, and a rejected request can be cor
`list_teammate_skills` searches full original metadata and pages by count and
response bytes. Relative resources remain rooted at the original Skill folder;
later saves, deletion and disabling refresh the discovery index on the next turn.
+ Repeated runtime hydrations reuse the small per-owner/bot projection and saved
+ catalog. Typed writes invalidate it synchronously; filesystem observation plus
+ directory identity checks cover hand edits, moves and replacement. Watcher
+ errors fall back to rebuilding, and missing generated catalogs are recreated.
+ The cache retains at most 32 roots, not a maximum number of stored Skills.
- Skill discovery follows grouped Hermes directories, configured external roots,
native directory links and disabled lists. OpenClaw discovery covers workspace,
workspace `.agents`, personal/managed/workshop, installed bundled, extra and
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
index 9b17460da2..0be81732a7 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -414,8 +414,11 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
it.each([false, true])('publishes structured command env credentials safely (command selected: %s)', async selected => {
const secret = 'fixture-command-json-token';
const nested = 'fixture-command-json-nested';
- const config = JSON.stringify({ token: secret, credentials: [{ key: nested }], unused: { password: 'fixture-unused-command-secret' }, city: 'Paris', count: 7 });
- const text = `Keep Paris and 7. ${secret} ${nested}`;
+ const urlSecrets = ['fixture-hook-token', 'fixture-fragment token', 'fixture-fragment%20token'];
+ const config = JSON.stringify({ token: secret, credentials: [{ key: nested }],
+ services: [{ endpoint: 'https://host/hooks/fixture-hook-token#access_token=fixture-fragment%20token' }],
+ unused: { password: 'fixture-unused-command-secret' }, city: 'Paris', count: 7 });
+ const text = `Keep Paris and 7. ${secret} ${nested} ${urlSecrets.join(' ')}`;
const skill = `---\nname: report\ndescription: ${text}\n---\n${text}\n`;
const original = { enabled: false, payload: { kind: 'command', argv: ['node', '-e', ''], env: { CONFIG: config } } };
h.sourceEnabled = false;
@@ -428,7 +431,7 @@ it.each([false, true])('publishes structured command env credentials safely (com
];
const [source] = await listCompanionImportSources('fixture');
const remote = await readRemoteCompanionImport(`preview:${source!.id}`, 'fixture', false);
- for (const value of [secret, nested]) expect(JSON.stringify(remote)).not.toContain(value);
+ for (const value of [secret, nested, ...urlSecrets]) expect(JSON.stringify(remote)).not.toContain(value);
const preview = await previewCompanionImport(source!.id, 'fixture');
const requestId = 'fixture-json-command-publication';
const result = await startCompanionImport({ requestId, previewId: preview.id, name: 'Ada',
@@ -436,7 +439,7 @@ it.each([false, true])('publishes structured command env credentials safely (com
await vi.waitFor(async () => expect((await getCompanionImportResult(requestId))?.saved).toBe(true));
const published = await fs.readFile(path.join(h.root, 'bots', result.botId, 'skills/report/SKILL.md'), 'utf8');
const output = JSON.stringify([published, h.importDocument.mock.calls, h.routines]);
- for (const value of [secret, nested]) expect(output).not.toContain(value);
+ for (const value of [secret, nested, ...urlSecrets]) expect(output).not.toContain(value);
expect(published).toContain('Keep Paris and 7.');
const stored = (await h.store.read(h.root, result.botId, () => {}))!;
expect(stored.documents?.memory).toBe(text);
diff --git a/apps/desktop/src/main/bot-import/connectionCatalog.ts b/apps/desktop/src/main/bot-import/connectionCatalog.ts
index bfbf913361..2f34226e4d 100644
--- a/apps/desktop/src/main/bot-import/connectionCatalog.ts
+++ b/apps/desktop/src/main/bot-import/connectionCatalog.ts
@@ -74,6 +74,9 @@ export function importedContentRedactions(environment: Pick<CompanionEnvironment
const collect = (value: unknown, credentialValue = false): void => {
if (typeof value === 'string') {
if (credentialValue) values.push(value);
+ // Structured command env may put capability URLs under ordinary names
+ // such as endpoint. Apply the same URL policy as command output masks.
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) values.push(...urlCredentialValues(value, true));
return;
}
if (!value || typeof value !== 'object') return;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeCache.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeCache.test.ts
new file mode 100644
index 0000000000..74f7996884
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeCache.test.ts
@@ -0,0 +1,48 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { cachedBotSkillRuntime, invalidateBotSkillRuntime } from '../botSkillRuntimeCache';
+
+let root: string;
+beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-cache-')); });
+afterEach(async () => { await fs.rm(root, { recursive: true, force: true }); });
+const projection = (name: string) => ({ pluginRoot: root,
+ skills: [{ name, description: name, path: root, filePath: path.join(root, 'SKILL.md') }] });
+
+it('shares concurrent hydration work and reconciles mutations during the read', async () => {
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ let version = 'old';
+ const build = vi.fn(async () => {
+ const captured = version;
+ if (captured === 'old') await held;
+ return projection(captured);
+ });
+ const first = cachedBotSkillRuntime(root, build);
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(1));
+ const second = cachedBotSkillRuntime(root, build);
+ const third = cachedBotSkillRuntime(root, build);
+ version = 'new';
+ invalidateBotSkillRuntime(root);
+ release();
+ const results = await Promise.all([first, second, third]);
+ expect(results.map(item => item.skills[0].name)).toEqual(['new', 'new', 'new']);
+ expect(build).toHaveBeenCalledTimes(2);
+ results[0].skills[0].name = 'caller edit';
+ expect(results[1].skills[0].name).toBe('new');
+ expect((await cachedBotSkillRuntime(root, build)).skills[0].name).toBe('new');
+ expect(build).toHaveBeenCalledTimes(2);
+});
+
+it('retries failed catalog builds and never caches an unwatchable source', async () => {
+ const build = vi.fn().mockRejectedValueOnce(new Error('fixture write failure')).mockResolvedValue(projection('retry'));
+ await expect(cachedBotSkillRuntime(root, build)).rejects.toThrow('fixture write failure');
+ expect((await cachedBotSkillRuntime(root, build)).skills[0].name).toBe('retry');
+ expect(build).toHaveBeenCalledTimes(2);
+ const missing = path.join(root, 'missing');
+ const uncached = vi.fn(async () => ({ pluginRoot: missing, skills: [] }));
+ await cachedBotSkillRuntime(missing, uncached);
+ await cachedBotSkillRuntime(missing, uncached);
+ expect(uncached).toHaveBeenCalledTimes(2);
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts
index 367dd3f2aa..21f5fc8317 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts
@@ -1,10 +1,10 @@
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { collectBotOwnSkillMounts, listBotSkillsForSession } from '../botSkillService';
import { BOT_SKILL_RUNTIME_INDEX_BYTES } from '../botSkillRuntimeProjection';
-import { botSkillRootDir, parseBotSkillFile } from '../botSkillStore';
+import { botSkillRootDir, parseBotSkillFile, saveBotSkill, seedBotSkillIfMissing, importBotSkillFiles, deleteBotSkill } from '../botSkillStore';
import { buildBotSkillIndex } from '../botSystemPrompt';
import { applyPiBotSkillPolicy } from '../../../../../../packages/maker-core/src/agents/pi/bot-skill-policy';
import { buildCodexBotSkillConfigOverrides } from '../../../../../../packages/maker-core/src/agents/codex/capability-routing';
@@ -12,7 +12,7 @@ import { buildCodexBotSkillConfigOverrides } from '../../../../../../packages/ma
let userDataDir: string;
const botId = 'imported-bot';
beforeEach(async () => { userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-projection-')); });
-afterEach(async () => { await fs.rm(userDataDir, { recursive: true, force: true }); });
+afterEach(async () => { vi.restoreAllMocks(); await fs.rm(userDataDir, { recursive: true, force: true }); });
const deps = () => ({ userDataDir, resolveBotId: async () => ({ ok: true as const, botId }) });
async function writeSkill(slug: string, source: string, disabled = false) {
@@ -93,6 +93,15 @@ describe('complete personal Skills with bounded startup projection', () => {
const last = catalog.at(-1);
expect(last.slug).toBe('skill-02047');
expect(await fs.readFile(last.filePath, 'utf8')).toContain('Instructions for skill-02047');
+ const reads = vi.spyOn(fs, 'readFile');
+ const opens = vi.spyOn(fs, 'open');
+ const catalogTime = (await fs.stat(path.join(mounts.pluginRoot, 'catalog.jsonl'))).mtimeMs;
+ for (let turn = 0; turn < 5; turn++) expect((await collectBotOwnSkillMounts(botId, deps())).skills).toEqual(mounts.skills);
+ const sourcePrefix = path.join(botSkillRootDir(userDataDir, botId), 'skills') + path.sep;
+ expect(reads.mock.calls.filter(([file]) => String(file).startsWith(sourcePrefix))).toHaveLength(0);
+ expect(opens.mock.calls.filter(([file]) => String(file).includes('catalog.jsonl'))).toHaveLength(0);
+ expect((await fs.stat(path.join(mounts.pluginRoot, 'catalog.jsonl'))).mtimeMs).toBe(catalogTime);
+ reads.mockRestore(); opens.mockRestore();
const firstPage = await listBotSkillsForSession({ callerSessionId: 'session', query: 'workflow' }, deps());
expect(firstPage).toMatchObject({ ok: true, total: count, nextOffset: 20 });
const lastPage = await listBotSkillsForSession({ callerSessionId: 'session', query: 'workflow', offset: count - 1 }, deps());
@@ -103,9 +112,37 @@ describe('complete personal Skills with bounded startup projection', () => {
catalog = (await fs.readFile(path.join(mounts.pluginRoot, 'catalog.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line));
expect(catalog).toHaveLength(count + 1);
expect(catalog.at(-1).slug).toBe('z-new');
+ await fs.unlink(path.join(mounts.pluginRoot, 'catalog.jsonl'));
+ await collectBotOwnSkillMounts(botId, deps());
+ expect((await fs.readFile(path.join(mounts.pluginRoot, 'catalog.jsonl'), 'utf8')).trim().split('\n')).toHaveLength(count + 1);
expect(await fs.readdir(path.join(mounts.pluginRoot))).not.toEqual(expect.arrayContaining([expect.stringMatching(/\.tmp$/)]));
}, 30_000);
+ it('refreshes after typed mutations, hand edits, disabling and directory replacement without mixing owners', async () => {
+ const input = { name: 'report', description: 'Original', body: 'Steps' };
+ await seedBotSkillIfMissing(userDataDir, botId, input);
+ const collect = () => collectBotOwnSkillMounts(botId, deps());
+ expect((await collect()).skills[0].description).toBe('Original');
+ await saveBotSkill(userDataDir, botId, { ...input, description: 'Saved update' });
+ expect((await collect()).skills[0].description).toBe('Saved update');
+ await importBotSkillFiles(userDataDir, botId, 'imported', [{ name: 'SKILL.md',
+ bytes: Buffer.from('---\nname: imported\ndescription: Imported\n---\nSteps'), executable: false }], () => {});
+ expect((await collect()).skills.map(item => item.name)).toEqual(['imported', 'report']);
+ await writeSkill('report', '---\nname: report\ndescription: Hand edited\n---\nSteps');
+ await vi.waitFor(async () => expect((await collect()).skills.find(item => item.name === 'report')?.description).toBe('Hand edited'));
+ await deleteBotSkill(userDataDir, botId, 'imported');
+ expect((await collect()).skills.map(item => item.name)).toEqual(['report']);
+ const root = botSkillRootDir(userDataDir, botId);
+ await fs.rename(path.join(root, 'skills'), path.join(root, 'disabled-skills'));
+ expect((await collect()).skills).toEqual([]);
+ await writeSkill('replacement', '---\nname: replacement\ndescription: New directory\n---\nSteps');
+ expect((await collect()).skills.map(item => item.name)).toEqual(['replacement']);
+ const other = path.join(userDataDir, 'other-owner');
+ await seedBotSkillIfMissing(other, botId, { ...input, name: 'private-other-owner' });
+ expect((await collectBotOwnSkillMounts(botId, { userDataDir: other })).skills.map(item => item.name)).toEqual(['private-other-owner']);
+ expect((await collect()).skills.map(item => item.name)).toEqual(['replacement']);
+ });
+
it('paginates by response bytes as well as page size without losing the remainder', async () => {
for (let index = 0; index < 35; index++) {
const slug = `wide-${String(index).padStart(2, '0')}`;
diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.ts
new file mode 100644
index 0000000000..e07fbb3e9d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.ts
@@ -0,0 +1,118 @@
+import { promises as fs, watch, type FSWatcher } from 'node:fs';
+import path from 'node:path';
+
+type Projection = {
+ pluginRoot: string;
+ skills: { name: string; description: string; path: string; filePath: string }[];
+};
+type Entry = {
+ revision: number;
+ loadedRevision: number;
+ stamp: string;
+ watchers: FSWatcher[];
+ value?: Projection;
+ loading?: Promise<Projection>;
+};
+// Only small runtime projections are retained, never the complete source list.
+// This bounds idle watcher handles across owners/bots without limiting Skills.
+const entries = new Map<string, Entry>();
+const MAX_CACHED_ROOTS = 32;
+
+export function invalidateBotSkillRuntime(root: string): void {
+ const entry = entries.get(path.resolve(root));
+ if (entry) entry.revision++;
+}
+
+function discard(root: string, entry: Entry) {
+ if (entries.get(root) === entry) entries.delete(root);
+ for (const watcher of entry.watchers) watcher.close();
+ entry.watchers = [];
+ entry.revision++;
+}
+
+/** Constant-size directory identity checks also detect delete/recreate and moves. */
+async function sourceStamp(root: string): Promise<string> {
+ const [parent, skills] = await Promise.all([
+ fs.stat(root).catch(() => null), fs.stat(path.join(root, 'skills')).catch(() => null),
+ ]);
+ return `${parent?.dev}:${parent?.ino}/${skills?.dev}:${skills?.ino}:${skills?.mtimeMs}:${skills?.ctimeMs}`;
+}
+
+/** Rebuild once per mutation, share concurrent hydrations, observe external edits. */
+export async function cachedBotSkillRuntime(root: string, build: () => Promise<Projection>): Promise<Projection> {
+ root = path.resolve(root);
+ const stamp = await sourceStamp(root);
+ let entry = entries.get(root);
+ if (!entry) {
+ entry = { revision: 0, loadedRevision: -1, stamp: '', watchers: [] };
+ entries.set(root, entry);
+ }
+ if (entry.stamp !== stamp || !entry.watchers.length) {
+ // Reattach on directory replacement without forking an in-flight build.
+ // Its revision loop incorporates mutations before publishing the result.
+ entry.stamp = stamp;
+ entry.revision++;
+ for (const watcher of entry.watchers) watcher.close();
+ entry.watchers = [];
+ const observed = entry;
+ try {
+ // Do not watch the whole profile/workdir or generated catalog. The parent
+ // watcher covers a missing/replaced skills directory; recursive watching
+ // catches SKILL.md edits that do not change the directory timestamps.
+ observed.watchers.push(watch(root, { persistent: false }, (_event, filename) => {
+ if (!filename || filename.toString() === 'skills') observed.revision++;
+ }));
+ try {
+ observed.watchers.push(watch(path.join(root, 'skills'), { recursive: true, persistent: false }, (_event, filename) => {
+ // Script outputs/venv caches do not alter the Skill metadata index.
+ if (!filename || /^[^/\\]+(?:[/\\]skill\.md)?$/i.test(filename.toString())) observed.revision++;
+ }));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ for (const watcher of observed.watchers) watcher.on('error', () => {
+ for (const handle of observed.watchers) handle.close();
+ observed.watchers = [];
+ observed.revision++;
+ });
+ } catch {
+ // Unwatchable roots/platforms must stay fresh, never silently cache forever.
+ for (const watcher of observed.watchers) watcher.close();
+ observed.watchers = [];
+ }
+ }
+ // LRU eviction closes native handles; it does not remove any saved catalog.
+ entries.delete(root);
+ entries.set(root, entry);
+ while (entries.size > MAX_CACHED_ROOTS) {
+ const [oldRoot, oldEntry] = entries.entries().next().value!;
+ discard(oldRoot, oldEntry);
+ }
+ const current = entry;
+ if (current.loading) return structuredClone(await current.loading);
+ if (current.watchers.length && current.value && current.loadedRevision === current.revision) {
+ // Generated files are disposable: deleting them must rebuild the catalog.
+ const present = current.value.pluginRoot === root || await Promise.all([
+ fs.access(path.join(current.value.pluginRoot, 'catalog.jsonl')),
+ fs.access(current.value.skills[0].filePath),
+ ]).then(() => true, () => false);
+ if (present && current.loadedRevision === current.revision) return structuredClone(current.value);
+ if (!present) current.revision++;
+ }
+ // Another hydration may have started rebuilding during the artifact check.
+ if (current.loading) return structuredClone(await current.loading);
+ current.loading = (async () => {
+ let value: Projection;
+ let revision: number;
+ do {
+ revision = current.revision;
+ value = await build();
+ } while (revision !== current.revision && entries.get(root) === current);
+ current.value = value;
+ current.loadedRevision = revision;
+ return structuredClone(value);
+ })();
+ try { return await current.loading; }
+ catch (error) { discard(root, current); throw error; }
+ finally { current.loading = undefined; }
+}
diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.ts
index af871c1c74..fe30b3271f 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts
@@ -10,6 +10,7 @@
import { app } from 'electron';
import { collectTeammateGuideMount } from './teammateGuideStore.js';
import { BOT_SKILL_RUNTIME_INDEX_BYTES, botSkillRuntimeSummary, projectBotSkillMounts } from './botSkillRuntimeProjection.js';
+import { cachedBotSkillRuntime } from './botSkillRuntimeCache.js';
import { requestBotRuntimeEpochRefresh } from './botRuntimeEpochRefreshSignal.js';
import { and, eq } from 'drizzle-orm';
@@ -311,9 +312,10 @@ export async function collectBotOwnSkillMounts(
}> {
const boundary = captureOwnerBoundary(deps);
const userDataDir = await skillHomeOf(deps, botId, boundary);
- const skills = await listBotSkills(userDataDir, botId, false);
const baseline = await collectTeammateGuideMount(userDataDir);
- const projected = await projectBotSkillMounts(botSkillRootDir(userDataDir, botId), skills);
+ const root = botSkillRootDir(userDataDir, botId);
+ const projected = await cachedBotSkillRuntime(root, async () =>
+ projectBotSkillMounts(root, await listBotSkills(userDataDir, botId, false)));
assertOwnerBoundary(deps, boundary);
return { ...projected, baseline };
}
diff --git a/apps/desktop/src/main/maker-ipc/botSkillStore.ts b/apps/desktop/src/main/maker-ipc/botSkillStore.ts
index 9332956da1..f20a89605a 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillStore.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillStore.ts
@@ -33,6 +33,7 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
+import { invalidateBotSkillRuntime } from './botSkillRuntimeCache.js';
/** 一个技能在磁盘上的完整形态。 */
export interface BotSkillRecord {
@@ -247,6 +248,7 @@ async function readCompatibleBotSkillSource(filePath: string, slug: string): Pro
body: parsed.body,
});
await fs.writeFile(filePath, migrated, 'utf8');
+ invalidateBotSkillRuntime(path.dirname(path.dirname(path.dirname(filePath))));
return migrated;
}
@@ -440,6 +442,7 @@ export async function seedBotSkillIfMissing(
const filePath = path.join(skillDir, 'SKILL.md');
try {
await fs.writeFile(filePath, renderBotSkillFile(normalized), { encoding: 'utf8', flag: 'wx' });
+ invalidateBotSkillRuntime(botSkillRootDir(userDataDir, botId));
} catch (cause) {
if ((cause as NodeJS.ErrnoException)?.code !== 'EEXIST') throw cause;
const raced = await readBotSkill(userDataDir, botId, normalized.slug);
@@ -486,6 +489,7 @@ export async function saveBotSkill(
renderBotSkillFile({ slug, name, description, updatedAt, body }),
'utf8',
);
+ invalidateBotSkillRuntime(botSkillRootDir(userDataDir, botId));
return {
record: { slug, name, description, updatedAt, body, dirPath: skillDir, filePath, ...(previous?.enabled === false ? { enabled: false } : {}) },
created,
@@ -535,7 +539,10 @@ export async function importBotSkillFiles(userDataDir: string, botId: string, sl
else await fs.writeFile(output, file.bytes, { flag: 'wx', mode: file.executable ? 0o700 : 0o600 });
}
assertOwner();
- try { await fs.rename(temporary, target); }
+ try {
+ await fs.rename(temporary, target);
+ invalidateBotSkillRuntime(botSkillRootDir(userDataDir, botId));
+ }
catch (error) {
if (!['EEXIST', 'ENOTEMPTY', 'EPERM'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
// Resume after a committed rename, without overwriting a later user edit.
@@ -572,6 +579,7 @@ export async function deleteBotSkill(
try { if (!(await fs.stat(skillDir)).isDirectory()) continue; }
catch { continue; }
await fs.rm(skillDir, { recursive: true, force: true });
+ invalidateBotSkillRuntime(botSkillRootDir(userDataDir, botId));
return true;
}
return false;