Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(companions): stream initial skill indexes without truncating imports
Chris7b529c3c71c2
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.mdindex a2a4baed91..76e71ffda5 100644--- a/apps/desktop/src/main/bot-import/README.md+++ b/apps/desktop/src/main/bot-import/README.md@@ -101,6 +101,14 @@ omitting it retains normal companion defaults, and a rejected request can be cordirectory identity checks cover hand edits, moves and replacement. Watchererrors fall back to rebuilding, and missing generated catalogs are recreated.The cache retains at most 32 roots, not a maximum number of stored Skills.+ Initial hydration uses `opendir` and bounded header reads, writing JSONL chunks+ as entries arrive. Only the native-mount byte budget is retained/sorted; a large+ shelf is never collected into a runtime array. Giant metadata lines keep short+ previews while the scanner finds the original body offset; ordinary Skill+ bodies are not loaded/parsed in full for indexing. Existing legacy migration+ remains for small authored files; oversized legacy files retain their original+ bytes and use discovery. Full-text query/authoring APIs still read the originals.+ Failed directory scans leave the last complete catalog intact for retry.- 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 anddiff --git a/apps/desktop/src/main/bot-import/__tests__/process.test.ts b/apps/desktop/src/main/bot-import/__tests__/process.test.tsindex 2ba3bd041a..c44f44d503 100644--- a/apps/desktop/src/main/bot-import/__tests__/process.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/process.test.ts@@ -3,6 +3,15 @@ import { importedProcessEnvironment, redactEnvironmentData, redactEnvironmentValimport { previewImportRedactions } from '../environmentSelection.js';import { connectionRedactions, importedContentRedactions, redactImportedResult } from '../connectionCatalog.js';+it.each(['json', 'command-env'])('limits structured URL decomposition to command env, preserving provider paths (%s)', format => {+ const masks = importedContentRedactions({ env: {}, mcp: [], credentials: [{ id: 'fixture', format,+ value: { base_url: 'https://model.example/codex', api_key: 'fixture-private-key' } }] });+ const output = redactEnvironmentValues('Use codex with fixture-private-key', masks);+ expect(output).not.toContain('fixture-private-key');+ if (format === 'json') expect(output).toContain('Use codex with');+ else expect(output).not.toContain('codex');+});+it('preserves native boolean switches, local bind addresses and transport/policy enums without exempting credentials', () => {const env = { BLUEBUBBLES_SEND_READ_RECEIPTS: 'false', BLUEBUBBLES_WEBHOOK_HOST: '192.168.10.100', AWS_BEDROCK_FORCE_HTTP1: '1', BROWSERBASE_PROXIES: 'true', BROWSERBASE_ADVANCED_STEALTH: 'false',TELEGRAM_REQUIRE_MENTION: 'true', TELEGRAM_OBSERVE_UNMENTIONED_GROUP_MESSAGES: 'true', FEISHU_ALLOW_ALL_USERS: 'false',diff --git a/apps/desktop/src/main/bot-import/connectionCatalog.ts b/apps/desktop/src/main/bot-import/connectionCatalog.tsindex 2f34226e4d..bf387e1fd6 100644--- a/apps/desktop/src/main/bot-import/connectionCatalog.ts+++ b/apps/desktop/src/main/bot-import/connectionCatalog.ts@@ -71,12 +71,13 @@ export function importedContentRedactions(environment: Pick<CompanionEnvironment...Object.values(environment.contentRedactions ?? {}),...environment.mcp.flatMap(server => Object.values(connectionRedactions(server, environment.env))),...monitorUrls.flatMap(url => urlCredentialValues(url, true))];- const collect = (value: unknown, credentialValue = false): void => {+ const collect = (value: unknown, credentialValue = false, commandEnv = 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));+ // such as endpoint. Ordinary provider config/base URLs are not capability+ // grants; their public path names must not become global content masks.+ if (commandEnv && /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) values.push(...urlCredentialValues(value, true));return;}if (!value || typeof value !== 'object') return;@@ -87,10 +88,10 @@ export function importedContentRedactions(environment: Pick<CompanionEnvironmentif (/^token[_-]?type$/i.test(key) && typeof child === 'string' && /^(?:Bearer|DPoP)$/i.test(child)) continue;// Credential-bearing containers remain private through array indices and// nested objects; unrelated sibling fields keep their own classification.- collect(child, credentialValue || CREDENTIAL_FIELD.test(key));+ collect(child, credentialValue || CREDENTIAL_FIELD.test(key), commandEnv);}};- for (const credential of environment.credentials) collect(credential.value);+ for (const credential of environment.credentials) collect(credential.value, false, credential.format === 'command-env');const named = environmentRedactions(environment.env);const namedValues = new Set(Object.values(named));let index = 0;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.tsindex 21f5fc8317..17d127e228 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts@@ -3,7 +3,7 @@ import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { collectBotOwnSkillMounts, listBotSkillsForSession } from '../botSkillService';-import { BOT_SKILL_RUNTIME_INDEX_BYTES } from '../botSkillRuntimeProjection';+import { BOT_SKILL_RUNTIME_INDEX_BYTES, projectBotSkillMounts } from '../botSkillRuntimeProjection';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';@@ -90,8 +90,8 @@ describe('complete personal Skills with bounded startup projection', () => {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');+ const last = catalog.find(item => item.slug === 'skill-02047');+ expect(last).toBeDefined();expect(await fs.readFile(last.filePath, 'utf8')).toContain('Instructions for skill-02047');const reads = vi.spyOn(fs, 'readFile');const opens = vi.spyOn(fs, 'open');@@ -111,13 +111,43 @@ describe('complete personal Skills with bounded startup projection', () => {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(catalog.some(item => item.slug === 'z-new')).toBe(true);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('writes a 100,000-entry stream before enumeration finishes, with atomic failure recovery', async () => {+ const root = botSkillRootDir(userDataDir, botId);+ const catalogRoot = path.join(root, '.runtime-skills');+ async function* items() {+ for (let index = 0; index < 100_000; index++) {+ if (index === 2000) {+ const staging = (await fs.readdir(catalogRoot)).find(file => file.endsWith('.tmp'))!;+ expect((await fs.stat(path.join(catalogRoot, staging))).size).toBeGreaterThan(0);+ await expect(fs.stat(path.join(catalogRoot, 'catalog.jsonl'))).rejects.toMatchObject({ code: 'ENOENT' });+ }+ yield { slug: `s-${index}`, name: `Skill ${index}`, description: 'Fixture', updatedAt: '',+ dirPath: `/fixture/s-${index}`, filePath: `/fixture/s-${index}/SKILL.md`, frontmatterBytes: 60, bodyStartLine: 5 };+ }+ }+ const mounts = await projectBotSkillMounts(root, items());+ expect(mounts.skills).toHaveLength(1);+ const catalogPath = path.join(catalogRoot, 'catalog.jsonl');+ const original = await fs.readFile(catalogPath, 'utf8');+ expect(original.trim().split('\n')).toHaveLength(100_000);+ expect(original).toContain('"slug":"s-99999"');+ async function* failed() {+ yield { slug: 'partial', name: 'Partial', description: '', updatedAt: '',+ dirPath: '/fixture/partial', filePath: '/fixture/partial/SKILL.md', frontmatterBytes: 60, bodyStartLine: 5 };+ throw new Error('fixture enumeration failure');+ }+ await expect(projectBotSkillMounts(root, failed())).rejects.toThrow('fixture enumeration failure');+ expect(await fs.readFile(catalogPath, 'utf8')).toBe(original);+ expect((await fs.readdir(catalogRoot)).some(file => file.endsWith('.tmp'))).toBe(false);+ }, 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);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeSource.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeSource.test.tsnew file mode 100644index 0000000000..188b70b52f--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeSource.test.ts@@ -0,0 +1,93 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { iterateBotSkillRuntimeSummaries } from '../botSkillRuntimeSource';+import { botSkillsDir } from '../botSkillStore';++let home: string;+beforeEach(async () => { home = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-stream-')); });+afterEach(async () => { vi.restoreAllMocks(); await fs.rm(home, { recursive: true, force: true }); });+async function source(slug: string, text: string) {+ const dir = path.join(botSkillsDir(home, 'bot'), slug);+ await fs.mkdir(dir, { recursive: true });+ const file = path.join(dir, 'SKILL.md');+ await fs.writeFile(file, text);+ return file;+}+async function read() {+ const items = [];+ for await (const item of iterateBotSkillRuntimeSummaries(home, 'bot')) items.push(item);+ return items;+}++it('uses directory streaming and header-only reads for a large Skill body', async () => {+ const file = await source('large-body', `---\nname: fixture\ndescription: Preview\n---\n${'Body '.repeat(2 * 1024 * 1024)}`);+ const readdir = vi.spyOn(fs, 'readdir').mockRejectedValue(new Error('unbounded enumeration'));+ const readFile = vi.spyOn(fs, 'readFile').mockRejectedValue(new Error('full file read'));+ const originalOpen = fs.open.bind(fs);+ let bytesRead = 0;+ const open = vi.spyOn(fs, 'open').mockImplementation(async (...args) => {+ const handle = await originalOpen(...args);+ const originalRead = handle.read.bind(handle);+ vi.spyOn(handle, 'read').mockImplementation(async (...readArgs: any[]) => {+ const result = await (originalRead as any)(...readArgs);+ bytesRead += result.bytesRead;+ return result;+ });+ return handle;+ });+ expect(await read()).toMatchObject([{ name: 'fixture', description: 'Preview', filePath: file, bodyStartLine: 5 }]);+ expect(bytesRead).toBeLessThanOrEqual(8192);+ expect(readdir).not.toHaveBeenCalled(); expect(readFile).not.toHaveBeenCalled();+ open.mockRestore();+});++it('bounds giant scalar previews, scans later metadata, and counts CRLF/EOF body offsets', async () => {+ const text = `---\r\nunknown: ${'x'.repeat(4 * 1024 * 1024)}\r\nname: "${'名'.repeat(2 * 1024 * 1024)}"\r\ndescription: "Quoted \\"value\\""\r\n---`;+ const file = await source('wide-header', text);+ const [item] = await read();+ expect(Buffer.byteLength(JSON.stringify(item))).toBeLessThan(8192);+ expect(item.name).toMatch(/^名/);+ expect(item.description).toBe('Quoted "value"');+ expect(item.bodyStartLine).toBe(5);+ expect(item.frontmatterBytes).toBe(Buffer.byteLength(text));+ expect(await fs.readFile(file, 'utf8')).toBe(text);+});++it('preserves bounded legacy migration and routes oversized legacy bodies to original-file discovery', async () => {+ const header = '---\nname: "旧技能"\ndescription: "Preview"\nupdatedAt: "2026-09-29"\n---\n';+ const small = await source('old-small', header + 'Original steps');+ const bigText = header + 'Large original body\n'.repeat(8192);+ const large = await source('old-large', bigText);+ const items = await read();+ expect(items.find(item => item.slug === 'old-small')).toMatchObject({ name: '旧技能', bodyStartLine: 8 });+ expect(await fs.readFile(small, 'utf8')).toContain('displayName: "旧技能"');+ expect(items.find(item => item.slug === 'old-large')).toMatchObject({ name: '旧技能', requiresDiscovery: true, bodyStartLine: 6 });+ expect(await fs.readFile(large, 'utf8')).toBe(bigText);+});++it('handles absent or unfinished frontmatter and excludes disabled/hidden/non-directory entries', async () => {+ await source('raw', 'Just a body');+ await source('unfinished', '---\nname: ignored\nNo closing header');+ await source('.hidden', '---\nname: hidden\n---\n');+ await fs.writeFile(path.join(botSkillsDir(home, 'bot'), 'not-a-directory'), 'Not a Skill');+ const disabled = path.join(home, 'bots/bot/disabled-skills/disabled');+ await fs.mkdir(disabled, { recursive: true });+ await fs.writeFile(path.join(disabled, 'SKILL.md'), '---\nname: disabled\n---\n');+ const items = await read();+ expect(items.map(item => item.slug).sort()).toEqual(['raw', 'unfinished']);+ expect(items.every(item => item.name === item.slug && item.description === '' && item.bodyStartLine === 1)).toBe(true);+});++it('keeps healthy siblings when one existing Skill cannot be read', async () => {+ const broken = await source('unreadable', '---\nname: unreadable\n---\n');+ await source('healthy', '---\nname: healthy\n---\n');+ const originalOpen = fs.open.bind(fs);+ vi.spyOn(fs, 'open').mockImplementation(async (...args) => {+ if (args[0] === broken) throw Object.assign(new Error('fixture permission'), { code: 'EACCES' });+ return originalOpen(...args);+ });+ expect((await read()).map(item => item.slug)).toEqual(['healthy']);+ expect(await fs.readFile(broken, 'utf8')).toContain('name: unreadable');+});diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.tsindex 62414cbef2..e6f696cf1c 100644--- a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts@@ -22,53 +22,66 @@ export function botSkillRuntimeSummary(item: BotSkillSummary) {};}-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[]) {+export async function projectBotSkillMounts(root: string, skills: Iterable<BotSkillSummary> | AsyncIterable<BotSkillSummary>) {const pluginRoot = path.join(root, '.runtime-skills');const catalogPath = path.join(pluginRoot, 'catalog.jsonl');+ const hadCatalog = !!await fs.stat(catalogPath).catch(() => null);+ const temporary = `${catalogPath}.${randomUUID()}.tmp`;+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;+ let chunk = '';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 })),- };+ let direct = true;+ let small: BotSkillSummary[] = [];+ const write = async (item: BotSkillSummary) => {+ if (!handle) {+ await fs.mkdir(pluginRoot, { recursive: true });+ handle = await fs.open(temporary, 'wx', 0o600);+ }+ chunk += `${JSON.stringify(botSkillRuntimeSummary(item))}\n`;+ if (Buffer.byteLength(chunk) >= 64 * 1024) {+ await handle.writeFile(chunk);+ chunk = '';+ }+ };+ try {+ // Refresh even an empty catalog when a formerly large shelf shrinks.+ if (hadCatalog) handle = await fs.open(temporary, 'wx', 0o600);+ for await (const item of skills) {+ if (direct) {+ bytes += item.frontmatterBytes + Buffer.byteLength(JSON.stringify(botSkillRuntimeSummary(item)));+ direct = bytes <= BOT_SKILL_RUNTIME_INDEX_BYTES && !item.requiresDiscovery+ && item.name.length <= BOT_SKILL_MAX_NAME_CHARS+ && item.description.length <= BOT_SKILL_MAX_DESCRIPTION_CHARS;+ if (direct) small.push(item);+ else {+ if (!hadCatalog) for (const previous of small) await write(previous);+ small = [];+ }+ }+ if (!direct || hadCatalog) await write(item);+ }+ if (handle) {+ if (chunk) await handle.writeFile(chunk);+ await handle.close(); handle = undefined;+ await fs.rename(temporary, catalogPath);+ }+ } finally {+ try { await handle?.close(); }+ finally { await fs.rm(temporary, { force: true }); }}+ if (direct) return {+ pluginRoot: root,+ // Only the byte-bounded native prefix is sorted/retained in memory.+ skills: small.sort((a, b) => a.name.localeCompare(b.name)).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.';@@ -88,7 +101,6 @@ export async function projectBotSkillMounts(root: string, skills: BotSkillSummarawait 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 })],diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeSource.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeSource.tsnew file mode 100644index 0000000000..b44fdae6a2--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeSource.ts@@ -0,0 +1,117 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';+import {+ BOT_SKILL_MAX_BODY_BYTES, botSkillsDir, readCompatibleBotSkillSource,+ unescapeFrontmatterValue, type BotSkillSummary,+} from './botSkillStore.js';++// Retain only a preview of any single YAML line, even a multi-MiB scalar.+const LINE_PREVIEW_BYTES = 4096;+const READ_BYTES = 8192;++async function readRuntimeHeader(filePath: string, slug: string, migrate = true): Promise<BotSkillSummary> {+ const handle = await fs.open(filePath, 'r');+ const fields = new Map<string, string>();+ let frontmatterBytes = 0;+ let bodyStartLine = 1;+ let legacy = true;+ const legacyKeys: string[] = [];+ let complete = false;+ let size = 0;+ try {+ size = (await handle.stat()).size;+ const buffer = Buffer.alloc(READ_BYTES);+ let line = Buffer.alloc(0);+ let lineBytes = 0;+ let lineNumber = 0;+ let done = false;+ const finishLine = (newline: boolean) => {+ lineNumber++;+ const text = line.toString('utf8').replace(/\r$/, '');+ const entire = lineBytes === line.length;+ frontmatterBytes += lineBytes + (newline ? 1 : 0);+ if (lineNumber === 1) {+ if (!entire || text !== '---' || !newline) done = true;+ } else if (entire && text === '---') {+ complete = true;+ bodyStartLine = lineNumber + (newline ? 1 : 0);+ done = true;+ } else {+ const separator = text.indexOf(':');+ const key = text.slice(0, separator).trim();+ if (!entire || /^\s/.test(text) || separator <= 0 || legacyKeys.length >= 3+ || !['name', 'description', 'updatedAt'].includes(key)) legacy = false;+ if (legacy) legacyKeys.push(key);+ if (separator > 0 && ['name', 'displayName', 'description', 'updatedAt'].includes(key)) {+ let value = text.slice(separator + 1).trim();+ // Close only the preview's quote. The original scalar stays untouched.+ if (!entire && /^["']/.test(value) && !value.endsWith(value[0])) value += value[0];+ fields.set(key, unescapeFrontmatterValue(value));+ }+ }+ line = Buffer.alloc(0);+ lineBytes = 0;+ };+ while (!done) {+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);+ if (!bytesRead) {+ if (lineBytes) finishLine(false);+ break;+ }+ let offset = 0;+ while (offset < bytesRead && !done) {+ const found = buffer.indexOf(10, offset);+ const end = found >= 0 && found < bytesRead ? found : bytesRead;+ const segment = buffer.subarray(offset, end);+ lineBytes += segment.length;+ if (line.length < LINE_PREVIEW_BYTES) line = Buffer.concat([line, segment.subarray(0, LINE_PREVIEW_BYTES - line.length)]);+ if (end < bytesRead) finishLine(true);+ offset = end + 1;+ }+ }+ } finally { await handle.close(); }+ legacy = complete && legacy && ['name', 'description', 'updatedAt'].every(key => legacyKeys.includes(key));+ // Keep the existing compatibility migration for bounded, historically authored+ // files. Huge hand-written legacy files remain intact and use body discovery.+ if (migrate && legacy && size <= BOT_SKILL_MAX_BODY_BYTES + 16 * 1024) {+ await readCompatibleBotSkillSource(filePath, slug);+ return readRuntimeHeader(filePath, slug, false);+ }+ return {+ slug,+ name: complete ? (fields.get('displayName') ?? fields.get('name')) || slug : slug,+ description: complete ? fields.get('description') ?? '' : '',+ updatedAt: complete ? fields.get('updatedAt') ?? '' : '',+ dirPath: path.dirname(filePath), filePath,+ frontmatterBytes: complete ? frontmatterBytes : size,+ bodyStartLine: complete ? bodyStartLine : 1,+ ...(legacy ? { requiresDiscovery: true } : {}),+ };+}++/** Runtime-only streaming view; full authoring/query APIs retain original text. */+export async function* iterateBotSkillRuntimeSummaries(userDataDir: string, botId: string): AsyncGenerator<BotSkillSummary> {+ const root = botSkillsDir(userDataDir, botId);+ let directory;+ try { directory = await fs.opendir(root, { bufferSize: 32 }); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;+ throw error;+ }+ for await (const entry of directory) {+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;+ for (const name of ['SKILL.md', 'skill.md']) {+ const filePath = path.join(root, entry.name, name);+ try {+ if (!(await fs.stat(filePath)).isFile()) continue;+ yield await readRuntimeHeader(filePath, entry.name);+ break;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ // Match the full-list API: an unreadable Skill must not suppress its+ // healthy siblings. Its source remains in place for repair/retry.+ break;+ }+ }+ }+}diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.tsindex fe30b3271f..34e130931f 100644--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts@@ -11,6 +11,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 { iterateBotSkillRuntimeSummaries } from './botSkillRuntimeSource.js';import { requestBotRuntimeEpochRefresh } from './botRuntimeEpochRefreshSignal.js';import { and, eq } from 'drizzle-orm';@@ -315,7 +316,7 @@ export async function collectBotOwnSkillMounts(const baseline = await collectTeammateGuideMount(userDataDir);const root = botSkillRootDir(userDataDir, botId);const projected = await cachedBotSkillRuntime(root, async () =>- projectBotSkillMounts(root, await listBotSkills(userDataDir, botId, false)));+ projectBotSkillMounts(root, iterateBotSkillRuntimeSummaries(userDataDir, botId)));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.tsindex f20a89605a..7ee9fcf1aa 100644--- a/apps/desktop/src/main/maker-ipc/botSkillStore.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillStore.ts@@ -61,6 +61,8 @@ export type BotSkillSummary = Omit<BotSkillRecord, 'body'> & {frontmatterBytes: number;/** One-based line at which a bounded read can skip even a very large header. */bodyStartLine: number;+ /** Legacy headers that cannot safely be handed to a native Skill parser. */+ requiresDiscovery?: boolean;};export const BOT_SKILL_MAX_NAME_CHARS = 64;@@ -166,7 +168,7 @@ function escapeFrontmatterValue(value: string): string {.replace(/[\r\n]+/g, ' ')}"`;}-function unescapeFrontmatterValue(raw: string): string {+export function unescapeFrontmatterValue(raw: string): string {const trimmed = raw.trim();if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {return trimmed.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');@@ -225,7 +227,7 @@ export function parseBotSkillFile(source: string): {* frontmatter。只迁移这一个可精确识别的三字段旧格式,正文与用户编辑全部保留;* 含有任何其它字段的手写 Skill 不动。*/-async function readCompatibleBotSkillSource(filePath: string, slug: string): Promise<string> {+export async function readCompatibleBotSkillSource(filePath: string, slug: string): Promise<string> {const source = await fs.readFile(filePath, 'utf8');const normalized = source.replace(/\r\n/g, '\n');const match = /^---\n([\s\S]*?)\n---\n?/.exec(normalized);