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): bound skill discovery and protect import previews

Chris020f711e8fcc
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index c011e12e24..511ddd399b 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -88,6 +88,14 @@ omitting it retains normal companion defaults, and a rejected request can be cor
in-memory snapshot byte bounds remain; this is not an unlimited-byte importer.
Skills disabled at the source are saved outside the active native skills folder
and stay disabled when read or edited.
+ Runtime discovery is separately bounded: small shelves mount directly; headers
+ or catalogs exceeding the startup metadata/path byte budget use one native
+ discovery Skill for Pi, Codex and Claude Code. A streamed, complete JSONL index
+ points to original files and body line offsets; names/descriptions are previews
+ within the existing 64/280-character limits, never rewrites of source files.
+ `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.
- 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 dd3560d5e1..9b17460da2 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -411,6 +411,47 @@ 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 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;
+ h.snapshot.items = [
+ { view: { id: 'task', name: text, category: 'automations', selected, enabled: false }, automation: { sourceId: 'task', fingerprint: 'fixture', original,
+ input: { name: text, prompt: text, enabled: false, triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }] } } },
+ { view: { id: 'memory', name: text, category: 'memory', selected: true }, text },
+ { view: { id: 'skill', name: 'report', description: text, category: 'skills', selected: true }, filesComplete: true,
+ files: [{ name: 'SKILL.md', bytes: Buffer.from(skill), executable: false }] },
+ ];
+ 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);
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const requestId = 'fixture-json-command-publication';
+ const result = await startCompanionImport({ requestId, previewId: preview.id, name: 'Ada',
+ entryIds: ['memory', 'skill', ...(selected ? ['task'] : [])], takeover: false }, 'fixture');
+ 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);
+ expect(published).toContain('Keep Paris and 7.');
+ const stored = (await h.store.read(h.root, result.botId, () => {}))!;
+ expect(stored.documents?.memory).toBe(text);
+ const savedSkill = stored.skillFiles?.report?.find(file => file.name === 'SKILL.md');
+ expect(Buffer.from(savedSkill!.bytes, 'base64').toString()).toBe(skill);
+ if (selected) {
+ expect(stored.sourceAutomations?.[0]?.original).toEqual(original);
+ expect(h.routines).toHaveLength(1);
+ expect(h.routines[0]?.enabled).toBe(false);
+ } else {
+ expect(h.routines).toHaveLength(0);
+ expect(JSON.stringify(stored)).not.toContain('fixture-unused-command-secret');
+ }
+});
+
it('persists redacted routine fields and retains identical publication masks across a handover retry after restart', async () => {
const selectedSecret = 'fake-active-query-token'; const excludedSecret = 'fake-excluded-note-token';
const input = h.snapshot.items[0]!.automation!.input!;
diff --git a/apps/desktop/src/main/bot-import/environmentSelection.ts b/apps/desktop/src/main/bot-import/environmentSelection.ts
index 763452fe0f..5af43ef464 100644
--- a/apps/desktop/src/main/bot-import/environmentSelection.ts
+++ b/apps/desktop/src/main/bot-import/environmentSelection.ts
@@ -75,12 +75,24 @@ function importRedactions(items: ImportItem[], env: Record<string, string>): Rec
// Missing variables do not supply a known credential. Actual connection imports
// still require every selected dependency and use strict reference resolution.
const resolve = (value: unknown) => resolveImportReferences(value, env, true);
+ const commandEnvironments = items.map(item => Object.fromEntries(
+ Object.entries(object(object(item.automation?.original.payload).env))
+ .filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
+ ));
+ // Command env JSON can also occur in readable Skill/memory/routine copies.
+ // Reuse the credential-field classifier before preview and publication, not
+ // just after command execution. Ordinary JSON scalar settings stay unchanged.
+ const structured = commandEnvironments.flatMap(environment => Object.values(environment)).flatMap((value, index) => {
+ try {
+ const parsed: unknown = JSON.parse(String(resolve(value)));
+ return parsed && typeof parsed === 'object' ? [{ id: `command_${index}`, format: 'command-env', value: parsed }] : [];
+ } catch { return []; }
+ });
return importedContentRedactions({ env,
- contentRedactions: Object.fromEntries(items.flatMap(item => Object.entries(environmentRedactions(
- Object.fromEntries(Object.entries(object(object(item.automation?.original.payload).env)).filter((entry): entry is [string, string] => typeof entry[1] === 'string')),
- ))).map(([name, value], index) => [`command_${index}_${name}`, value])),
+ contentRedactions: Object.fromEntries(commandEnvironments.flatMap(environment => Object.entries(environmentRedactions(environment)))
+ .map(([name, value], index) => [`command_${index}_${name}`, value])),
mcp: items.flatMap(item => item.mcp ? [resolve(item.mcp) as NonNullable<typeof item.mcp>] : []),
- credentials: items.flatMap(item => item.credential ? [{ id: item.view.id, ...item.credential, value: resolve(item.credential.value) }] : []),
+ credentials: [...items.flatMap(item => item.credential ? [{ id: item.view.id, ...item.credential, value: resolve(item.credential.value) }] : []), ...structured],
});
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts
new file mode 100644
index 0000000000..367dd3f2aa
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts
@@ -0,0 +1,130 @@
+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 { collectBotOwnSkillMounts, listBotSkillsForSession } from '../botSkillService';
+import { BOT_SKILL_RUNTIME_INDEX_BYTES } from '../botSkillRuntimeProjection';
+import { botSkillRootDir, parseBotSkillFile } 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';
+
+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 }); });
+const deps = () => ({ userDataDir, resolveBotId: async () => ({ ok: true as const, botId }) });
+
+async function writeSkill(slug: string, source: string, disabled = false) {
+ const directory = path.join(botSkillRootDir(userDataDir, botId), disabled ? 'disabled-skills' : 'skills', slug);
+ await fs.mkdir(directory, { recursive: true });
+ const filePath = path.join(directory, 'SKILL.md');
+ await fs.writeFile(filePath, source);
+ return filePath;
+}
+
+async function assertBoundedNativeMounts() {
+ const mounts = await collectBotOwnSkillMounts(botId, deps());
+ expect(mounts.skills).toHaveLength(1);
+ expect(Buffer.byteLength(buildBotSkillIndex(mounts.skills))).toBeLessThan(BOT_SKILL_RUNTIME_INDEX_BYTES);
+ const policy = { mode: 'allowlist' as const, configured: [], catalog: [], ownSkills: mounts.skills };
+ const pi = applyPiBotSkillPolicy(policy, {
+ skillPaths: [], launchSkillPaths: [], launchSkillDigests: [], launchSkillSourceFingerprints: [],
+ } as unknown as Parameters<typeof applyPiBotSkillPolicy>[1]);
+ expect(pi.explicitSkillPaths).toEqual([mounts.skills[0].path]);
+ expect(Buffer.byteLength(JSON.stringify(pi.explicitSkillPaths))).toBeLessThan(4096);
+ expect(buildCodexBotSkillConfigOverrides(policy)['skills.config']).toEqual([
+ { path: mounts.skills[0].filePath, enabled: true },
+ ]);
+ // Claude Code sees only the discovery Skill, never the original large shelf.
+ expect(await fs.readdir(path.join(mounts.pluginRoot, 'skills'))).toEqual(['personal-skill-library']);
+ expect(JSON.parse(await fs.readFile(path.join(mounts.pluginRoot, '.claude-plugin/plugin.json'), 'utf8')).name)
+ .toBe('personal-skill-library');
+ const mountedSource = await fs.readFile(mounts.skills[0].filePath, 'utf8');
+ const metadata = parseBotSkillFile(mountedSource);
+ expect(metadata.name.length).toBeLessThanOrEqual(64);
+ expect(metadata.description.length).toBeLessThanOrEqual(280);
+ expect(Buffer.byteLength(mountedSource)).toBeLessThan(4096);
+ return mounts;
+}
+
+describe('complete personal Skills with bounded startup projection', () => {
+ it('preserves a near-16 MiB original header and loads only bounded runtime metadata', async () => {
+ const source = `---\r\nname: ${'n'.repeat(7 * 1024 * 1024)}\r\ndescription: ${'d'.repeat(8 * 1024 * 1024)} tail-query\r\n---\r\nRun scripts/report.py\r\n`;
+ const original = await writeSkill('oversized', source);
+ await fs.mkdir(path.join(path.dirname(original), 'scripts'));
+ await fs.writeFile(path.join(path.dirname(original), 'scripts/report.py'), '# original resource');
+ const mounts = await assertBoundedNativeMounts();
+ const rows = (await fs.readFile(path.join(mounts.pluginRoot, 'catalog.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line));
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ slug: 'oversized', filePath: original, bodyStartLine: 5 });
+ expect(rows[0].name).toHaveLength(64);
+ expect(rows[0].description).toHaveLength(280);
+ expect(await fs.readFile(original, 'utf8')).toBe(source);
+ expect(source.split('\n').slice(rows[0].bodyStartLine - 1).join('\n')).toContain('Run scripts/report.py');
+ expect(await fs.readFile(path.join(path.dirname(rows[0].filePath), 'scripts/report.py'), 'utf8')).toBe('# original resource');
+ // Search sees even metadata beyond the runtime preview and returns a short page.
+ const page = await listBotSkillsForSession({ callerSessionId: 'session', query: 'tail-query' }, deps());
+ expect(page).toMatchObject({ ok: true, total: 1, skills: [{ slug: 'oversized' }] });
+ expect(Buffer.byteLength(JSON.stringify(page))).toBeLessThan(BOT_SKILL_RUNTIME_INDEX_BYTES);
+ // Disabling the only Skill also clears its previously mounted catalog.
+ const disabled = path.join(botSkillRootDir(userDataDir, botId), 'disabled-skills');
+ await fs.mkdir(disabled);
+ await fs.rename(path.dirname(original), path.join(disabled, 'oversized'));
+ expect((await collectBotOwnSkillMounts(botId, deps())).skills).toEqual([]);
+ expect(await fs.readFile(path.join(mounts.pluginRoot, 'catalog.jsonl'), 'utf8')).toBe('');
+ expect(await fs.readFile(path.join(disabled, 'oversized', 'SKILL.md'), 'utf8')).toBe(source);
+ });
+
+ it('keeps every Skill in a large shelf discoverable, including the final page and later additions', async () => {
+ const count = 2048;
+ // Bounded filesystem concurrency; these are real files consumed by the store.
+ for (let start = 0; start < count; start += 32) {
+ await Promise.all(Array.from({ length: 32 }, (_, offset) => {
+ const slug = `skill-${String(start + offset).padStart(5, '0')}`;
+ return writeSkill(slug, `---\nname: ${slug}\ndescription: Workflow ${slug}\n---\nInstructions for ${slug}\n`);
+ }));
+ }
+ await writeSkill('disabled', '---\nname: disabled\ndescription: Leave disabled\n---\nDo not run\n', true);
+ const mounts = await assertBoundedNativeMounts();
+ let catalog = (await fs.readFile(path.join(mounts.pluginRoot, 'catalog.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line));
+ expect(catalog).toHaveLength(count);
+ expect(new Set(catalog.map(item => item.slug)).size).toBe(count);
+ const last = catalog.at(-1);
+ expect(last.slug).toBe('skill-02047');
+ expect(await fs.readFile(last.filePath, 'utf8')).toContain('Instructions for skill-02047');
+ 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());
+ expect(lastPage).toMatchObject({ ok: true, skills: [{ slug: 'skill-02047' }] });
+ expect(lastPage).not.toHaveProperty('nextOffset');
+ await writeSkill('z-new', '---\nname: z-new\ndescription: Newly learned\n---\nNew steps\n');
+ await collectBotOwnSkillMounts(botId, deps());
+ 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');
+ expect(await fs.readdir(path.join(mounts.pluginRoot))).not.toEqual(expect.arrayContaining([expect.stringMatching(/\.tmp$/)]));
+ }, 30_000);
+
+ 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')}`;
+ await writeSkill(slug, `---\nname: ${slug}\ndescription: ${'说明'.repeat(140)}\n---\nSteps\n`);
+ }
+ const found: string[] = [];
+ let offset = 0;
+ do {
+ const result = await listBotSkillsForSession({ callerSessionId: 'session', limit: 50, offset }, deps());
+ expect(result.ok).toBe(true);
+ if (!result.ok) throw new Error(result.errorCode);
+ expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(BOT_SKILL_RUNTIME_INDEX_BYTES + 256);
+ found.push(...result.skills.map(item => item.slug));
+ if (result.nextOffset === undefined) break;
+ expect(result.nextOffset).toBeGreaterThan(offset);
+ offset = result.nextOffset;
+ } while (offset < 35);
+ expect(found).toHaveLength(35);
+ expect(new Set(found).size).toBe(35);
+ expect(offset).toBeGreaterThan(0);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts
new file mode 100644
index 0000000000..62414cbef2
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts
@@ -0,0 +1,104 @@
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import {
+ BOT_SKILL_MAX_DESCRIPTION_CHARS,
+ BOT_SKILL_MAX_NAME_CHARS,
+ type BotSkillSummary,
+} from './botSkillStore.js';
+
+/** A startup/output byte budget, never a limit on stored or discoverable Skills. */
+export const BOT_SKILL_RUNTIME_INDEX_BYTES = 16 * 1024;
+
+export function botSkillRuntimeSummary(item: BotSkillSummary) {
+ return {
+ slug: item.slug,
+ name: item.name.slice(0, BOT_SKILL_MAX_NAME_CHARS),
+ description: item.description.slice(0, BOT_SKILL_MAX_DESCRIPTION_CHARS),
+ updatedAt: item.updatedAt.slice(0, 64),
+ filePath: item.filePath,
+ bodyStartLine: item.bodyStartLine,
+ ...(item.enabled === false ? { enabled: false } : {}),
+ };
+}
+
+async function writeSkillCatalog(catalogPath: string, skills: BotSkillSummary[]) {
+ // Stream a complete index in bounded chunks; no second full-catalog string or
+ // per-entry synchronous rewrite. Atomic replacement also supports live updates.
+ const temporary = `${catalogPath}.${randomUUID()}.tmp`;
+ try {
+ const handle = await fs.open(temporary, 'wx', 0o600);
+ try {
+ let chunk = '';
+ for (const item of skills) {
+ chunk += `${JSON.stringify(botSkillRuntimeSummary(item))}\n`;
+ if (Buffer.byteLength(chunk) >= 64 * 1024) {
+ await handle.writeFile(chunk);
+ chunk = '';
+ }
+ }
+ if (chunk) await handle.writeFile(chunk);
+ } finally { await handle.close(); }
+ await fs.rename(temporary, catalogPath);
+ } finally { await fs.rm(temporary, { force: true }); }
+}
+
+/**
+ * All three harnesses consume this same projection. Small shelves retain native
+ * mounts. Large shelves (or headers) mount one discovery Skill instead of passing
+ * every path on argv / injecting every raw YAML description into the prompt.
+ * Originals and relative resources stay in place; nothing is truncated on disk.
+ */
+export async function projectBotSkillMounts(root: string, skills: BotSkillSummary[]) {
+ const pluginRoot = path.join(root, '.runtime-skills');
+ const catalogPath = path.join(pluginRoot, 'catalog.jsonl');
+ let bytes = 0;
+ const direct = skills.every(item => {
+ bytes += item.frontmatterBytes + Buffer.byteLength(JSON.stringify(botSkillRuntimeSummary(item)));
+ return bytes <= BOT_SKILL_RUNTIME_INDEX_BYTES
+ && item.name.length <= BOT_SKILL_MAX_NAME_CHARS
+ && item.description.length <= BOT_SKILL_MAX_DESCRIPTION_CHARS;
+ });
+ if (direct) {
+ // A previous large shelf may still be open in an active harness. Remove
+ // deleted/disabled entries from its discovery surface even after shrinking.
+ if (await fs.stat(catalogPath).catch(() => null)) await writeSkillCatalog(catalogPath, skills);
+ return {
+ pluginRoot: root,
+ skills: skills.map(item => ({ name: item.name, description: item.description,
+ path: item.dirPath, filePath: item.filePath })),
+ };
+ }
+
+ const name = 'personal-skill-library';
+ const description = 'Search your complete personal Skill library before choosing how to do a task. Read the matching original Skill and use its resources on demand; the library includes all enabled personal Skills.';
+ const skillPath = path.join(pluginRoot, 'skills', name);
+ const filePath = path.join(skillPath, 'SKILL.md');
+ const source = [
+ '---', `name: ${name}`, `description: ${JSON.stringify(description)}`, '---', '',
+ 'Your complete enabled personal Skill library is available here; it is not a missing or disabled capability.',
+ `Catalog: ${JSON.stringify(catalogPath)} (JSON Lines, one Skill per line).`,
+ 'Before doing a task, search this catalog for relevant names/descriptions with your native file/search tools. Read only matching lines or a small page, never the entire catalog.',
+ 'If available, list_teammate_skills(query=keywords) also searches full original metadata. Follow nextOffset to continue a page; an empty first page is not the complete library.',
+ 'For a match, read its original filePath starting at bodyStartLine, in bounded chunks, then follow that Skill. Resolve all relative resource/script paths against the directory containing that original file, not this discovery Skill directory.',
+ 'Catalog names/descriptions are short previews. Full original metadata, instructions and resources remain at filePath; search original Skill files if the preview is insufficient. Load only the Skill(s) needed for the current work.',
+ 'Disabled Skills are excluded from this catalog. Do not enable or execute them through discovery.', '',
+ ].join('\n');
+ const manifestPath = path.join(pluginRoot, '.claude-plugin', 'plugin.json');
+ await fs.mkdir(skillPath, { recursive: true });
+ await fs.mkdir(path.dirname(manifestPath), { recursive: true });
+
+ await writeSkillCatalog(catalogPath, skills);
+ for (const [target, content] of [
+ [filePath, source],
+ [manifestPath, JSON.stringify({ name, version: '1.0.0', description })],
+ ]) {
+ if (await fs.readFile(target, 'utf8').catch(() => null) === content) continue;
+ const staging = `${target}.${randomUUID()}.tmp`;
+ try {
+ await fs.writeFile(staging, content, { encoding: 'utf8', mode: 0o600 });
+ await fs.rename(staging, target);
+ } finally { await fs.rm(staging, { force: true }); }
+ }
+ return { pluginRoot, skills: [{ name, description, path: skillPath, filePath }] };
+}
diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.ts
index d7d95ab6e9..af871c1c74 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts
@@ -9,6 +9,7 @@
import { app } from 'electron';
import { collectTeammateGuideMount } from './teammateGuideStore.js';
+import { BOT_SKILL_RUNTIME_INDEX_BYTES, botSkillRuntimeSummary, projectBotSkillMounts } from './botSkillRuntimeProjection.js';
import { requestBotRuntimeEpochRefresh } from './botRuntimeEpochRefreshSignal.js';
import { and, eq } from 'drizzle-orm';
@@ -217,17 +218,35 @@ export async function saveBotSkillForSession(
/** 列出这个伙伴已经学会的技能,供模型避免重复学 / 决定该更新哪一条。 */
export async function listBotSkillsForSession(
- params: { callerSessionId: string },
+ params: { callerSessionId: string; query?: string; offset?: number; limit?: number },
deps: BotSkillServiceDeps = {},
-): Promise<BotSkillResult<{ skills: BotSkillWireSummary[] }>> {
+): Promise<BotSkillResult<{ skills: ReturnType<typeof botSkillRuntimeSummary>[]; total: number; nextOffset?: number }>> {
try {
const boundary = captureOwnerBoundary(deps);
const owner = await (deps.resolveBotId ?? defaultResolveBotId)(params.callerSessionId);
if (!owner.ok) return owner;
assertOwnerBoundary(deps, boundary);
- const skills = await listBotSkills(await skillHomeOf(deps, owner.botId, boundary), owner.botId);
+ const all = await listBotSkills(await skillHomeOf(deps, owner.botId, boundary), owner.botId);
assertOwnerBoundary(deps, boundary);
- return { ok: true, skills: skills.map(toWire) };
+ const terms = (params.query ?? '').toLocaleLowerCase().split(/\s+/).filter(Boolean);
+ const matches = terms.length ? all.filter(item => {
+ const text = `${item.slug}\n${item.name}\n${item.description}`.toLocaleLowerCase();
+ return terms.every(term => text.includes(term));
+ }) : all;
+ const offset = Math.max(0, Math.floor(params.offset ?? 0));
+ const limit = Math.max(1, Math.min(50, Math.floor(params.limit ?? 20)));
+ const skills: ReturnType<typeof botSkillRuntimeSummary>[] = [];
+ let bytes = 0;
+ for (let index = offset; index < matches.length && skills.length < limit; index++) {
+ const summary = botSkillRuntimeSummary(matches[index]);
+ const size = Buffer.byteLength(JSON.stringify(summary));
+ if (skills.length && bytes + size > BOT_SKILL_RUNTIME_INDEX_BYTES) break;
+ skills.push(summary);
+ bytes += size;
+ }
+ const next = offset + skills.length;
+ return { ok: true, skills, total: matches.length,
+ ...(next < matches.length ? { nextOffset: next } : {}) };
} catch (cause) {
return storeError(cause);
}
@@ -277,7 +296,7 @@ export async function deleteBotSkillForBot(
}
/**
- * 会话启动时要挂载的东西:每个技能的目录 + Claude Code 用的 plugin 根。
+ * 会话启动时的有界挂载:小目录直接挂载,大目录按需检索完整原文件。
*
* 一份磁盘事实两种消费方式 —— pi 拿 `dirPath` 走 `--skill`,Claude Code 拿
* `pluginRoot` 走本地 plugin。没有技能时返回空,调用方据此完全不注入。
@@ -294,15 +313,7 @@ export async function collectBotOwnSkillMounts(
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);
assertOwnerBoundary(deps, boundary);
- return {
- pluginRoot: botSkillRootDir(userDataDir, botId),
- baseline,
- skills: skills.map((item) => ({
- name: item.name,
- description: item.description,
- path: item.dirPath,
- filePath: item.filePath,
- })),
- };
+ return { ...projected, baseline };
}
diff --git a/apps/desktop/src/main/maker-ipc/botSkillStore.ts b/apps/desktop/src/main/maker-ipc/botSkillStore.ts
index 705daff1b4..9332956da1 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillStore.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillStore.ts
@@ -55,7 +55,12 @@ export interface BotSkillRecord {
}
/** list 只需要元信息时用的轻量形态(不读正文,省 IO)。 */
-export type BotSkillSummary = Omit<BotSkillRecord, 'body'>;
+export type BotSkillSummary = Omit<BotSkillRecord, 'body'> & {
+ /** Charge the native loader's entire header, including YAML fields we do not interpret. */
+ frontmatterBytes: number;
+ /** One-based line at which a bounded read can skip even a very large header. */
+ bodyStartLine: number;
+};
export const BOT_SKILL_MAX_NAME_CHARS = 64;
export const BOT_SKILL_MAX_DESCRIPTION_CHARS = 280;
@@ -314,8 +319,15 @@ export async function listBotSkills(
const filePath = await readSkillFilePath(skillDir);
if (!filePath) continue;
let parsed: ReturnType<typeof parseBotSkillFile>;
+ let frontmatterBytes: number;
+ let bodyStartLine: number;
try {
- parsed = parseBotSkillFile(await readCompatibleBotSkillSource(filePath, slug));
+ const source = await readCompatibleBotSkillSource(filePath, slug);
+ parsed = parseBotSkillFile(source);
+ const header = /^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.exec(source)?.[0] ?? '';
+ // A nonstandard header is not safe to hand to a different native parser.
+ frontmatterBytes = Buffer.byteLength(header || source);
+ bodyStartLine = header ? header.split('\n').length : 1;
} catch {
continue;
}
@@ -326,6 +338,8 @@ export async function listBotSkills(
updatedAt: parsed.updatedAt,
dirPath: skillDir,
filePath,
+ frontmatterBytes,
+ bodyStartLine,
...(enabled ? {} : { enabled: false }),
});
}
diff --git a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
index 1078c59edf..c90961fc48 100644
--- a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
+++ b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
@@ -11,8 +11,7 @@
* 有记忆才讲怎么记。伙伴不需要先去「发现」自己会什么 —— 开局就写在
* 提示词里。判定信号用 runtime 已解析的 toolset id(等价于 Hermes 的
* valid_tool_names)。
- * 3. **技能索引整份进提示词**:每个技能的名字与一句话描述都可见,不靠
- * 模型自己翻目录。
+ * 3. **技能入口进提示词**:小目录直接可见,大目录提供完整检索入口,正文按需读。
*
* 为什么必须这么做(2026-08-21 真机实证):伙伴会话里 cindy_docs 明明挂载成功
* (日志 instance_resolved),但 make_pptx / list_tools 的调用次数是 0 —— 模型
@@ -48,7 +47,7 @@ export interface BotSystemPromptInput {
/** SOUL:身份正本。空则由调用方兜底。 */
identity: string;
capabilities: BotPromptCapabilitySignals;
- /** 伙伴自有技能索引(全部,不截断)。 */
+ /** 宿主投影的技能入口;原文件与完整目录由存储层保留。 */
skillIndex: readonly BotPromptSkillIndexEntry[];
/** 队友名册(见 buildBotTeammateRoster)。没有队友时不传。 */
teammates?: readonly { id: string; name: string; description?: string | null }[];
@@ -247,10 +246,8 @@ export function buildBotStableTier(input: BotSystemPromptInput): string {
}
/**
- * 技能索引:全部技能的名字 + 一句话描述。
- *
- * 照搬 Hermes 的口径 —— 索引里**不省略任何技能名**。模型看得见名字才知道
- * 自己有这份本事;正文按需再读。
+ * 技能索引:宿主提供的有界运行时目录。大目录由原生检索 Skill 引导按需
+ * 读取完整目录与原文件;此处不再次展开整个存储目录。
*/
export function buildBotSkillIndex(entries: readonly BotPromptSkillIndexEntry[]): string {
const rows = entries
diff --git a/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts b/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts
index cd09c96e05..3073de0f55 100644
--- a/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts
@@ -87,6 +87,15 @@ describe('Bot skill tools', () => {
expect(parse(result)).toMatchObject({ ok: true, skills: [SKILL] });
});
+ it('forwards search and pagination to the owner and preserves the next page and source location', async () => {
+ const list = vi.fn(async () => ({ ok: true as const, skills: [{ ...SKILL, filePath: '/bot/skills/weekly-report/SKILL.md', bodyStartLine: 5 }], total: 3000, nextOffset: 41 }));
+ const reg = registry({ callbacks: { save: vi.fn(), list } });
+ const result = await reg.call('list_teammate_skills', { query: 'weekly report', offset: 40, limit: 1 });
+ expect(list).toHaveBeenCalledWith({ callerSessionId: 'bot-session', query: 'weekly report', offset: 40, limit: 1 });
+ expect(parse(result)).toMatchObject({ total: 3000, nextOffset: 41,
+ skills: [{ filePath: '/bot/skills/weekly-report/SKILL.md', bodyStartLine: 5 }] });
+ });
+
it('fails closed without a bound Session', async () => {
const reg = new XdtHelperToolRegistry();
registerBotSkillTools(reg, {
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_skills.ts b/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
index 7164b3159b..3e71f20571 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
@@ -20,6 +20,9 @@ export interface BotSkillSummaryWire {
name: string;
description: string;
updatedAt: string;
+ filePath?: string;
+ bodyStartLine?: number;
+ enabled?: boolean;
}
export interface BotSkillCallbacks {
@@ -37,7 +40,10 @@ export interface BotSkillCallbacks {
>;
list(params: {
callerSessionId: string;
- }): Promise<ControlResult<{ skills: BotSkillSummaryWire[] }, string>>;
+ query?: string;
+ offset?: number;
+ limit?: number;
+ }): Promise<ControlResult<{ skills: BotSkillSummaryWire[]; total?: number; nextOffset?: number }, string>>;
}
export interface BotSkillToolDeps {
@@ -106,15 +112,28 @@ export function registerBotSkillTools(
category: 'bots',
description:
'列出当前伙伴已经学会的技能(名称 / 说明 / 更新时间,不含正文)。'
+ + '按 query 搜索完整名称和说明;返回短预览和原文件路径。大目录分页返回,使用 nextOffset 继续,不能把第一页当成全部。'
+ + '需要使用时从 filePath 的 bodyStartLine 开始分段读正文,资源相对路径以原文件目录为准;enabled=false 的技能保留但未启用。'
+ '需要当前运行位置支持伙伴自有 Skill 存储;远端未挂载时返回不可用,不把本机技能表冒充远端可用技能。'
+ '打算沉淀新技能前先看一眼:已经有的就用同名更新,不要重复学一遍。',
- inputShape: {},
- handler: async () => {
+ inputShape: {
+ query: z.string().max(1024).optional().describe('名称或说明中的关键词,空白分隔的词均须匹配'),
+ offset: z.number().int().min(0).optional().describe('上一页返回的 nextOffset'),
+ limit: z.number().int().min(1).max(50).optional().describe('每页最多条数,默认 20;宿主同时限制响应大小'),
+ },
+ handler: async ({ query, offset, limit }) => {
const sessionId = callerSessionId(deps);
if (!sessionId) return missingSession();
- const result = await deps.callbacks.list({ callerSessionId: sessionId });
+ const result = await deps.callbacks.list({ callerSessionId: sessionId,
+ ...(query !== undefined ? { query } : {}),
+ ...(offset !== undefined ? { offset } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
return result.ok
- ? okPayload({ skills: result.skills })
+ ? okPayload({ skills: result.skills,
+ ...(result.total !== undefined ? { total: result.total } : {}),
+ ...(result.nextOffset !== undefined ? { nextOffset: result.nextOffset } : {}),
+ })
: errorPayload(result.errorCode, result.message);
},
});