Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(companions): preserve import intent and repaired skill settings
zqchris699477b63a20
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.tsindex 5734cec123..ab975ba5a6 100644--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts@@ -979,3 +979,69 @@ it.each([false, true])('publishes completion after deferred setup without duplicexpect(rows.size).toBe(2);expect(h.pause).toHaveBeenCalledTimes(1);});++it.each([false, true])('keeps the original deferred setup choice across retries and checkpoints (legacy receipt: %s)', async legacy => {+ const { continueCompanionImport } = await import('../host.js');+ const [source] = await listCompanionImportSources('fixture');+ const preview = await previewCompanionImport(source!.id, 'fixture');+ const selection = { requestId: 'fixture-identity-setup', previewId: preview.id, name: 'Ada', entryIds: ['task'], takeover: true, deferSetup: true };+ await startCompanionImport(selection, 'fixture');+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('needs-attention'));+ const result = (await getCompanionImportResult(selection.requestId))!;+ const receiptFile = path.join(h.root, 'companion-imports', `${selection.requestId}.json`);+ if (legacy) {+ const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8'));+ delete receipt.deferSetup;+ receipt.selectionHash = fingerprint([selection.name, undefined, selection.entryIds, selection.takeover, h.snapshot.source.kind, h.snapshot.source.agentId, h.snapshot.source.root]);+ receipt.result.checks = [];+ await fs.writeFile(receiptFile, JSON.stringify(receipt));+ }+ const saved = await fs.readFile(receiptFile, 'utf8');+ h.verified = true;+ await expect(startCompanionImport({ ...selection, deferSetup: false }, 'fixture')).rejects.toThrow('REQUEST_ALREADY_USED');+ expect(await fs.readFile(receiptFile, 'utf8')).toBe(saved);+ expect(h.pause).not.toHaveBeenCalled();+ // A reconnected controller uses the checkpoint even after losing preview access.+ await expect(startCompanionImport({ ...selection, deferSetup: false }, 'reconnected')).rejects.toThrow('REQUEST_ALREADY_USED');+ await continueCompanionImport(result.botId, h.root, () => {});+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('complete'));+ expect(h.pause).toHaveBeenCalledOnce();+ expect(JSON.parse(await fs.readFile(receiptFile, 'utf8')).deferSetup).toBe(true);+});++it.each(['hermes', 'openclaw'] as const)('restores disabled %s skill metadata and private settings after an unreadable manifest is repaired', async kind => {+ const actual = await vi.importActual<typeof import('../sources.js')>('../sources.js');+ vi.mocked(createImportSourceReader).mockImplementation(actual.createImportSourceReader);+ h.snapshot.source.kind = kind;+ const secret = 'fixture-repaired-skill-secret';+ const config = { skills: { disabled: ['report'], entries: { 'report-auth': { enabled: false, apiKey: secret, env: { REPORT_REGION: 'fixture' } } } } };+ await fs.writeFile(h.snapshot.source.configFile, JSON.stringify(config));+ const directory = path.join(h.root, 'skills', 'folder-name');+ await fs.mkdir(directory, { recursive: true });+ const manifest = path.join(directory, 'SKILL.md');+ await fs.writeFile(manifest, '');+ await fs.truncate(manifest, 16 * 1024 * 1024 + 1);+ const { discoverImportSkills } = await import('../skills.js');+ const { createImportBudget } = await import('../files.js');+ h.snapshot.items = await discoverImportSkills(h.snapshot.source, config, h.root, {}, createImportBudget());+ expect(h.snapshot.items[0]?.captureIssue).toBe('SOURCE_FILE_TOO_LARGE');+ const entryId = h.snapshot.items[0]!.view.id;+ const [source] = await listCompanionImportSources('fixture');+ const preview = await previewCompanionImport(source!.id, 'fixture');+ const selection = { requestId: 'fixture-repair-manifest', previewId: preview.id, name: 'Ada', entryIds: [entryId], takeover: false, deferSetup: true };+ await startCompanionImport(selection, 'fixture');+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('needs-attention'));+ const first = (await getCompanionImportResult(selection.requestId))!;+ await fs.writeFile(manifest, `---\nname: report\ndescription: Recovered report\nmetadata:\n openclaw:\n skillKey: report-auth\n primaryEnv: REPORT_TOKEN\n---\n# Report\nPrivate value ${secret}`);+ await startCompanionImport(selection, 'reconnected');+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('complete'));+ const result = (await getCompanionImportResult(selection.requestId))!;+ expect(result).toMatchObject({ botId: first.botId, savedEntryIds: [entryId] });+ const environment = (await h.store.read(h.root, first.botId, () => {}))!;+ expect(environment.env).toMatchObject({ REPORT_TOKEN: secret, REPORT_REGION: 'fixture' });+ const readable = await fs.readFile(path.join(h.root, 'bots', first.botId, 'disabled-skills', 'report', 'SKILL.md'), 'utf8');+ expect(readable).toContain('name: report');+ expect(readable).not.toContain(secret);+ await expect(fs.stat(path.join(h.root, 'bots', first.botId, 'skills', 'report'))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(JSON.stringify(result)).not.toContain(secret);+});diff --git a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts b/apps/desktop/src/main/bot-import/__tests__/sources.test.tsindex b08750de0b..fb7a68048b 100644--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts@@ -55,11 +55,11 @@ it('retains an over-budget skill for retry without dropping healthy siblings', aconst jobs = (skills: string[]) => JSON.stringify([{ id: 'read', skills, prompt: 'Read resources', schedule: { kind: 'interval', minutes: 5 } }]);await write('.hermes/cron/jobs.json', jobs(['first']));const reader = deps(); const [source] = await discoverImportSources(reader);- const snapshot = await inspectImportSource(source!, reader, createImportBudget(4500));+ const snapshot = await inspectImportSource(source!, reader, createImportBudget(6000));expect(snapshot.items.find(item => item.view.name === 'first')?.files?.find(file => file.name === 'data.txt')?.bytes.length).toBe(2048);expect(snapshot.items.find(item => item.view.name === 'second')?.files).toHaveLength(1);await write('.hermes/cron/jobs.json', jobs(['first', 'second']));- const partial = await inspectImportSource(source!, reader, createImportBudget(4500));+ const partial = await inspectImportSource(source!, reader, createImportBudget(6000));expect(partial.items.find(item => item.view.name === 'second')?.captureIssue).toBe('SOURCE_SNAPSHOT_TOO_LARGE');expect(partial.items.find(item => item.view.name === 'first')?.files).toHaveLength(2);});@@ -505,3 +505,32 @@ it('preserves native manifest file symlinks while charging their contents', asynexpect((await discoverImportSkills(source, config, home, {}, createImportBudget())).map(item => item.view.name)).toEqual(['report']);await expect(discoverImportSkills(source, config, home, {}, createImportBudget(10))).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');});++it.each(['workspace', 'extraDirs', 'plugin', 'hermes'])('bounds empty %s directories during enumeration and closes the stream on budget failure', async location => {+ const root = path.join(home, location === 'hermes' ? '.hermes' : '.openclaw');+ const workspace = path.join(root, 'workspace');+ const directory = location === 'workspace' ? path.join(workspace, 'skills') : location === 'plugin' ? path.join(root, 'extensions') : location === 'extraDirs' ? path.join(home, 'extras') : path.join(root, 'skills');+ for (let index = 0; index < 40; index++) await fs.mkdir(path.join(directory, `empty-${index}`), { recursive: true });+ const source = { kind: location === 'hermes' ? 'hermes' as const : 'openclaw' as const, agentId: 'main', name: 'Ada', root, workspace, configFile: path.join(root, 'config.json') };+ const budget = createImportBudget(1500);+ const reserve = vi.spyOn(budget, 'reserve');+ const open = vi.spyOn(fs, 'opendir');+ const readdir = vi.spyOn(fs, 'readdir');+ await expect(discoverImportSkills(source, location === 'extraDirs' ? { skills: { load: { extraDirs: [directory] } } } : {}, home, {}, budget)).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');+ expect(readdir).not.toHaveBeenCalled();+ expect(reserve.mock.calls.length).toBeLessThan(40);+ const opened = open.mock.results.filter((_, index) => String(open.mock.calls[index]![0]) === directory);+ expect(opened).toHaveLength(1);+ const handle = await opened[0]!.value;+ await expect(handle.read()).rejects.toMatchObject({ code: 'ERR_DIR_CLOSED' });+});++it('preserves sorted skill-name precedence after streaming directory entries', async () => {+ await write('.hermes/skills/z-last/SKILL.md', '---\nname: report\n---\nLast');+ await write('.hermes/skills/a-first/SKILL.md', '---\nname: report\n---\nFirst');+ const root = path.join(home, '.hermes');+ const items = await discoverImportSkills({ kind: 'hermes', agentId: 'main', name: 'Ada', root, workspace: root, configFile: path.join(root, 'config.yaml') }, {}, home, {}, createImportBudget());+ expect(items).toHaveLength(1);+ expect(items[0]!.sourceAlias).toBe('a-first');+ expect(items[0]!.files![0]!.bytes.toString()).toContain('First');+});diff --git a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts b/apps/desktop/src/main/bot-import/__tests__/transfer.test.tsindex 9426ff23e8..135f091327 100644--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts@@ -284,6 +284,47 @@ it('finishes saving before any login or read probe, then resumes takeover from cexpect(deps.pauseSource).toHaveBeenCalledOnce();});+it.each([false, true])('rejects changing the original deferSetup=%s without writes or takeover', async deferSetup => {+ const { deps, receipt } = harness();+ vi.mocked(deps.verifyAutomation).mockResolvedValue({ verified: false });+ await transferCompanion(snapshot, { ...selection, deferSetup }, deps);+ const saved = structuredClone(receipt());+ vi.clearAllMocks();+ await expect(transferCompanion(snapshot, { ...selection, deferSetup: !deferSetup }, deps)).rejects.toThrow('REQUEST_ALREADY_USED');+ expect(receipt()).toEqual(saved);+ expect(deps.createCompanion).not.toHaveBeenCalled();+ expect(deps.verifyAutomation).not.toHaveBeenCalled();+ expect(deps.pauseSource).not.toHaveBeenCalled();+});++it('treats absent deferSetup as false and persists the choice before saving the checkpoint', async () => {+ const { deps, receipt } = harness();+ vi.mocked(deps.saveCheckpoint).mockImplementationOnce(async () => {+ expect(receipt()?.deferSetup).toBe(false);+ throw new Error('interrupted checkpoint');+ });+ await expect(transferCompanion(snapshot, selection, deps)).rejects.toThrow('interrupted checkpoint');+ await expect(transferCompanion(snapshot, { ...selection, deferSetup: true }, deps)).rejects.toThrow('REQUEST_ALREADY_USED');+ expect((await transferCompanion(snapshot, { ...selection, deferSetup: false }, deps)).status).toBe('complete');+});++it('upgrades a legacy deferred receipt from its saved choice, including a checkpoint interrupted before checks', async () => {+ const { deps, receipt } = harness();+ await transferCompanion(snapshot, { ...selection, deferSetup: true }, deps);+ const legacy = structuredClone(receipt()!);+ delete legacy.deferSetup;+ legacy.selectionHash = fingerprint([selection.name, undefined, selection.entryIds.toSorted(), selection.takeover, snapshot.source.kind, snapshot.source.agentId, snapshot.source.root]);+ legacy.result.checks = [];+ await deps.saveReceipt(legacy);+ deps.readLegacyDeferSetup = async () => true;+ await expect(transferCompanion(snapshot, selection, deps)).rejects.toThrow('REQUEST_ALREADY_USED');+ expect(receipt()).toEqual(legacy);+ expect((await transferCompanion(snapshot, { ...selection, deferSetup: true }, deps, false, true)).status).toBe('complete');+ expect(receipt()?.deferSetup).toBe(true);+ expect(receipt()?.selectionHash).not.toBe(legacy.selectionHash);+ expect(deps.pauseSource).toHaveBeenCalledOnce();+});+it('restores compact selections from a selected-only checkpoint without changing their meaning', async () => {const { deps } = harness();const indexed = { ...snapshot, items: snapshot.items.map((item, sourceIndex) => ({ ...item, sourceIndex })) };@@ -311,3 +352,17 @@ it('saves healthy content and a conversation when a single routine cannot be creexpect(result.checks).toContainEqual({ entryId: 'task', status: 'needs-attention', message: 'IMPORT_ITEM_FAILED' });expect(deps.pauseSource).not.toHaveBeenCalled();});++it('returns a completed legacy deferred receipt even after its checkpoint was removed', async () => {+ const { deps, receipt } = harness();+ const input = { ...selection, deferSetup: true };+ await transferCompanion(snapshot, input, deps, false, true);+ const legacy = structuredClone(receipt()!);+ delete legacy.deferSetup;+ legacy.selectionHash = fingerprint([selection.name, undefined, selection.entryIds.toSorted(), selection.takeover, snapshot.source.kind, snapshot.source.agentId, snapshot.source.root]);+ await deps.saveReceipt(legacy);+ vi.clearAllMocks();+ await expect(transferCompanion(snapshot, input, deps)).resolves.toEqual(legacy.result);+ expect(deps.createCompanion).not.toHaveBeenCalled();+ expect(deps.pauseSource).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.tsindex d6cbc73ca0..f103f9ebdc 100644--- a/apps/desktop/src/main/bot-import/host.ts+++ b/apps/desktop/src/main/bot-import/host.ts@@ -24,7 +24,7 @@ import { createImportSourceReader, discoverImportSources, inspectImportSource, timport { readOpenClawCronDatabase } from './openclawCron.js';import { companionEnvironmentStore, recoverCompanionEnvironmentRemovals } from './runtime.js';import { deserializeImportSnapshotAsync, fingerprint, serializeImportSnapshotAsync, reserveSnapshotItems, MAX_SNAPSHOT_BYTES } from './files.js';-import { transferCompanion, validateImportSelection, type ImportReceipt, type TransferDeps } from './transfer.js';+import { transferCompanion, validateImportSelection, validateImportRequestIdentity, type ImportReceipt, type TransferDeps } from './transfer.js';import { CompanionImportError, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';import { changeSourceAutomationState } from './takeover.js';import { verifyImportedAutomation } from './verification.js';@@ -357,8 +357,10 @@ export async function startCompanionImport(selection: CompanionImportSelection,if (!(error instanceof CompanionImportError) || error.code !== 'PREVIEW_EXPIRED') throw error;const receipt = await readReceipt(scope.root, selection.requestId); scope.assert();const pending = receipt ? (await companionEnvironmentStore.read(scope.root, receipt.result.botId, scope.assert))?.pendingImport : undefined;- const intentKey = (value: CompanionImportSelection) => fingerprint({ ...value, entryIds: [...value.entryIds].sort() });- if (!pending || !Array.isArray(selection.entryIds) || intentKey(pending.selection) !== intentKey(selection)) throw error;+ const intentKey = (value: CompanionImportSelection) => fingerprint([value.requestId, value.previewId, value.name, value.avatarImageBase64,+ [...value.entryIds].sort(), value.entryRanges, value.takeover, value.deferSetup === true]);+ if (!pending || !Array.isArray(selection.entryIds)) throw error;+ if (intentKey(pending.selection) !== intentKey(selection)) throw new CompanionImportError('REQUEST_ALREADY_USED');snapshot = await deserializeImportSnapshotAsync(pending.snapshotJson, scope.assert);}const selected = validateImportSelection(selection, snapshot);@@ -392,6 +394,11 @@ export async function startCompanionImport(selection: CompanionImportSelection,};const prior = await readReceipt(scope.root, selection.requestId); scope.assert();if (prior?.cancelled) return prior.result;+ const readLegacyDeferSetup = async (botId: string) => {+ const pending = (await companionEnvironmentStore.read(scope.root, botId, scope.assert))?.pendingImport;+ return pending ? pending.selection.deferSetup === true : undefined;+ };+ await validateImportRequestIdentity(snapshot, selection, prior, readLegacyDeferSetup); scope.assert();if (!prior) {const profiles = await listBotRemoteResourceSources(); scope.assert();if (profiles.some(profile => profile.status !== 'archived' && normalizeBotName(profile.name) === normalizeBotName(selection.name))) throw new CompanionImportError('IMPORT_NAME_EXISTS');@@ -399,9 +406,16 @@ export async function startCompanionImport(selection: CompanionImportSelection,const jobKey = `${scope.scope}:${selection.requestId}`;const running = jobs.get(jobKey);if (running) return accepted(running, scope.root, selection.requestId);+ let skillConfigReader: { budget: Parameters<NonNullable<TransferDeps['readSkillConfig']>>[1]; reader: ReturnType<typeof createImportSourceReader> } | undefined;const transferDeps: TransferDeps = {assertOwner: scope.assert,validateItems(items) {+ // Repaired manifests can reveal credentials that were unavailable at preview time.+ for (const value of Object.values(selectedImportRedactions(items))) {+ if (knownValues.has(value)) continue;+ while (`content_retry_${nextMask}` in contentSecrets) nextMask++;+ contentSecrets[`content_retry_${nextMask++}`] = value; knownValues.add(value);+ }// Capturing lazily selected resources may grow even a rejected selection.const cached = previews.get(selection.previewId);if (cached?.value === snapshot) retainPreview(selection.previewId, cached);@@ -413,6 +427,11 @@ export async function startCompanionImport(selection: CompanionImportSelection,}},readReceipt: requestId => readReceipt(scope.root, requestId),+ readLegacyDeferSetup,+ readSkillConfig(source, budget) {+ if (skillConfigReader?.budget !== budget) skillConfigReader = { budget, reader: createImportSourceReader(readers(), budget) };+ return skillConfigReader.reader.readConfig(path.dirname(source.configFile), source.configFile);+ },saveReceipt: receipt => saveReceipt(scope.root, receipt),async createCompanion(botId, input) {try {@@ -446,6 +465,9 @@ export async function startCompanionImport(selection: CompanionImportSelection,}}if (prior?.environmentSaved) await companionEnvironmentStore.update(scope.root, botId, scope.assert, environment => {+ // A formerly unreadable manifest may only now supply its own settings.+ if (item.env) environment.env = { ...environment.env, ...item.env };+ if (item.credential) environment.credentials = [...environment.credentials.filter(value => value.id !== item.view.id), { id: item.view.id, ...item.credential }];for (const [id, text] of documentEntries(item)) { environment.documents ??= {}; environment.documents[id] = text; }if (item.view.category === 'skills') {const slug = skillSlug(item);@@ -597,6 +619,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,}})().catch(async error => {scope.assert();+ if (error instanceof CompanionImportError && error.code === 'REQUEST_ALREADY_USED') throw error;return withBotProfileLocks([`import_${fingerprint(selection.requestId).slice(0, 24)}`], async () => {const receipt = await readReceipt(scope.root, selection.requestId);scope.assert();diff --git a/apps/desktop/src/main/bot-import/skills.ts b/apps/desktop/src/main/bot-import/skills.tsindex a57667bf30..22c3b7239b 100644--- a/apps/desktop/src/main/bot-import/skills.ts+++ b/apps/desktop/src/main/bot-import/skills.ts@@ -1,4 +1,4 @@-import { promises as fs } from 'node:fs';+import { promises as fs, type Dirent } from 'node:fs';import path from 'node:path';import yaml from 'js-yaml';import { fingerprint, inside, readImportFile, readImportTree, type ImportReadBudget } from './files.js';@@ -8,6 +8,17 @@ import { CompanionImportError, object, string, type ImportItem, type ImportSourcinterface SkillRoot { directory: string; links: 'any' | string[]; bundled?: boolean }const ignored = new Set(['.git', '.github', '.hub', '.archive', '_archive', '.venv', 'venv', 'node_modules', 'site-packages', '__pycache__', '.tox', '.nox', '.pytest_cache', '.mypy_cache', '.ruff_cache']);const strings = (value: unknown): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && !!v.trim()) : [];+const disabledSkills = (config: Record<string, unknown>) => new Set([...strings(config.disabled), ...strings(object(config.platform_disabled).cli)]);++/** Charge entries before retaining them; sorting preserves native name precedence. */+async function directoryEntries(directory: string, budget: ImportReadBudget): Promise<Dirent[]> {+ const entries: Dirent[] = [];+ for await (const entry of await fs.opendir(directory)) {+ budget.reserve(128 + Buffer.byteLength(path.join(directory, entry.name)));+ if (entry.isDirectory() || entry.isSymbolicLink()) entries.push(entry);+ }+ return entries.sort((a, b) => a.name.localeCompare(b.name));+}/** Resolve only path configuration; never expand credentials into public names. */function sourcePath(value: string, base: string, home: string, env: NodeJS.ProcessEnv) {@@ -61,7 +72,7 @@ async function rootsFor(source: ImportSource, values: Record<string, unknown>, hconst locations = [...strings(object(plugins.load).paths).map(resolve),...Object.values(object(plugins.installs)).flatMap(value => string(object(value).installPath) ? [resolve(string(object(value).installPath))] : [])];for (const parent of [path.join(source.root, 'extensions'), ...(install ? [path.join(install, 'extensions')] : [])]) {- try { for (const entry of await fs.readdir(parent, { withFileTypes: true })) if (entry.isDirectory()) locations.push(path.join(parent, entry.name)); }+ try { for (const entry of await directoryEntries(parent, budget)) if (entry.isDirectory()) locations.push(path.join(parent, entry.name)); }catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }}for (const location of new Set(locations)) {@@ -78,15 +89,35 @@ async function rootsFor(source: ImportSource, values: Record<string, unknown>, hreturn roots;}+/** Discovery and repaired manifests must apply exactly the same native settings. */+export function normalizeImportSkill(kind: ImportSource['kind'], alias: string, text: string, config: Record<string, unknown>, disabled = disabledSkills(config)): Pick<ImportItem, 'view' | 'sourceAlias' | 'env' | 'credential'> {+ const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);+ let info: Record<string, unknown> = {};+ try { if (front) info = object(yaml.load(front[1]!)); } catch { /* Keep the original file for native loader diagnostics. */ }+ const name = string(info.name) || alias;+ const metadata = object(object(info.metadata).openclaw ?? object(info.metadata).clawdbot ?? object(info.metadata).hermes);+ const settings = object(object(config.entries)[string(metadata.skillKey) || name]);+ const enabled = kind === 'hermes' ? !disabled.has(name) : settings.enabled !== false;+ const item: Pick<ImportItem, 'view' | 'sourceAlias' | 'env' | 'credential'> = { view: { id: `skill-${fingerprint(name).slice(0, 20)}`, category: 'skills', name,+ description: string(info.description).slice(0, 280), selected: true, enabled },+ sourceAlias: alias };+ item.env = Object.fromEntries(Object.entries(object(settings.env)).filter(([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === 'string')) as Record<string, string>;+ const primary = string(metadata.primaryEnv);+ if (typeof settings.apiKey === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(primary)) item.env[primary] = settings.apiKey;+ else if (settings.apiKey) {+ item.view.issues = ['MISSING_ENVIRONMENT_REFERENCE'];+ item.credential = { format: 'source-skill-auth', value: { apiKey: settings.apiKey } };+ }+ return item;+}+/** Follow native precedence by declared name; grouped layouts stop at a skill entrypoint. */export async function discoverImportSkills(source: ImportSource, values: Record<string, unknown>, home: string, env: NodeJS.ProcessEnv, budget: ImportReadBudget, used = new Set<string>()): Promise<ImportItem[]> {const items: ImportItem[] = [];const names = new Set<string>();const visited = new Set<string>();const config = object(values.skills);- const disabled = new Set(strings(config.disabled));- const platformDisabled = object(config.platform_disabled);- for (const name of strings(platformDisabled.cli)) disabled.add(name);+ const disabled = disabledSkills(config);for (const root of await rootsFor(source, values, home, env, budget)) {let realRoot: string;try { realRoot = await fs.realpath(root.directory); }@@ -95,6 +126,7 @@ export async function discoverImportSkills(source: ImportSource, values: Record<const real = await fs.realpath(directory);if (visited.has(real)) return;if (root.links !== 'any' && !inside(realRoot, real) && !root.links.some(allowed => inside(allowed, real))) return;+ budget.reserve(128 + Buffer.byteLength(real));visited.add(real);let manifest;try { manifest = await readImportFile(real, path.join(real, 'SKILL.md'), budget); }@@ -107,28 +139,12 @@ export async function discoverImportSkills(source: ImportSource, values: Record<}}if (manifest?.bytes.toString('utf8').trim()) {- const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(manifest.bytes.toString('utf8'));- let info: Record<string, unknown> = {};- try { if (front) info = object(yaml.load(front[1]!)); } catch { /* Keep the original file for native loader diagnostics. */ }- const name = string(info.name) || path.basename(directory);+ const metadata = normalizeImportSkill(source.kind, path.basename(directory), manifest.bytes.toString('utf8'), config, disabled);+ const name = metadata.view.name;if (names.has(name)) return;if (root.bundled && Array.isArray(config.allowBundled) && !strings(config.allowBundled).includes(name)) return;names.add(name);- const metadata = object(object(info.metadata).openclaw ?? object(info.metadata).clawdbot ?? object(info.metadata).hermes);- const settings = object(object(config.entries)[string(metadata.skillKey) || name]);- const enabled = source.kind === 'hermes' ? !disabled.has(name) : settings.enabled !== false;- const item: ImportItem = { view: { id: `skill-${fingerprint(name).slice(0, 20)}`, category: 'skills', name,- description: string(info.description).slice(0, 280), selected: true, enabled },- sourceDirectory: real, sourceAlias: path.basename(directory), files: [manifest], filesComplete: false };- {- item.env = Object.fromEntries(Object.entries(object(settings.env)).filter(([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === 'string')) as Record<string, string>;- const primary = string(metadata.primaryEnv);- if (typeof settings.apiKey === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(primary)) item.env[primary] = settings.apiKey;- else if (settings.apiKey) {- item.view.issues = ['MISSING_ENVIRONMENT_REFERENCE'];- item.credential = { format: 'source-skill-auth', value: { apiKey: settings.apiKey } };- }- }+ const item: ImportItem = { ...metadata, sourceDirectory: real, files: [manifest], filesComplete: false };if (used.has(name) || used.has(path.basename(directory))) {try {item.files = [manifest, ...await readImportTree(real, name => name !== 'SKILL.md', budget)];@@ -138,7 +154,7 @@ export async function discoverImportSkills(source: ImportSource, values: Record<items.push(item); return;}if (source.kind === 'openclaw' && depth >= 6) return;- for (const entry of (await fs.readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {+ for (const entry of await directoryEntries(directory, budget)) {if (ignored.has(entry.name) || entry.name.startsWith('.')) continue;const child = path.join(directory, entry.name);if (entry.isDirectory()) await visit(child, depth + 1);diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.tsindex b52923305a..af7edd9a09 100644--- a/apps/desktop/src/main/bot-import/transfer.ts+++ b/apps/desktop/src/main/bot-import/transfer.ts@@ -1,12 +1,15 @@import { promises as fs } from 'node:fs';import type { CompanionImportResult, CompanionImportSelection } from '@cindy/maker-shared/companion-import';import type { RoutineInput } from '@cindy/maker-scheduler';-import { createImportBudget, fingerprint, readImportFile, readImportTree, reserveSnapshotItems } from './files.js';-import { CompanionImportError, type ImportItem, type ImportSnapshot } from './types.js';+import { createImportBudget, fingerprint, readImportFile, readImportTree, reserveSnapshotItems, type ImportReadBudget } from './files.js';+import { CompanionImportError, object, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';+import { normalizeImportSkill } from './skills.js';import { resolveImportEnvironmentDependencies, selectedImportEnvironment } from './environmentSelection.js';export interface ImportReceipt {selectionHash: string;+ /** Present on receipts whose identity includes the original setup choice. */+ deferSetup?: boolean;result: CompanionImportResult;copied: string[];environmentSaved?: boolean;@@ -24,6 +27,8 @@ export interface ImportReceipt {export interface TransferDeps {assertOwner(): void;readReceipt(requestId: string): Promise<ImportReceipt | undefined>;+ readLegacyDeferSetup?(botId: string): Promise<boolean | undefined>;+ readSkillConfig?(source: ImportSource, budget: ImportReadBudget): Promise<Record<string, unknown>>;saveReceipt(receipt: ImportReceipt): Promise<void>;createCompanion(botId: string, selection: CompanionImportSelection): Promise<void>;validateItems?(items: ImportItem[]): void;@@ -62,21 +67,45 @@ export function validateImportSelection(value: CompanionImportSelection, snapshoreturn resolveImportEnvironmentDependencies(items);}+/** Old hashes predate deferSetup; the durable checkpoint retains its original value. */+export async function validateImportRequestIdentity(snapshot: ImportSnapshot, selection: CompanionImportSelection, existing: ImportReceipt | undefined,+ readLegacyDeferSetup?: TransferDeps['readLegacyDeferSetup']): Promise<string> {+ const items = validateImportSelection(selection, snapshot);+ const identity = [selection.name, selection.avatarImageBase64, items.map(item => item.view.id).toSorted(), selection.takeover, snapshot.source.kind, snapshot.source.agentId, snapshot.source.root];+ const deferSetup = selection.deferSetup === true;+ const selectionHash = fingerprint([...identity, deferSetup]);+ if (!existing) return selectionHash;+ if (existing.deferSetup !== undefined) {+ if (existing.selectionHash !== selectionHash || existing.deferSetup !== deferSetup) throw new CompanionImportError('REQUEST_ALREADY_USED');+ } else {+ if (existing.selectionHash !== fingerprint(identity)) throw new CompanionImportError('REQUEST_ALREADY_USED');+ // Terminal legacy receipts may have already discarded their checkpoint.+ // Returning them cannot start setup or change any takeover side effects.+ if (!existing.cancelled && existing.result.status !== 'complete') {+ const original = await readLegacyDeferSetup?.(existing.result.botId)+ ?? existing.result.checks.some(check => check.message === 'IMPORT_SETUP_DEFERRED');+ if (original !== deferSetup) throw new CompanionImportError('REQUEST_ALREADY_USED');+ }+ }+ return selectionHash;+}+/** One receipt is shared by GUI, remote actions and command callers. Writes are serialized by the host. */export async function transferCompanion(snapshot: ImportSnapshot, selection: CompanionImportSelection, deps: TransferDeps, reconcileOnly = false, resumeSetup = false): Promise<CompanionImportResult> {const items = validateImportSelection(selection, snapshot);deps.assertOwner();const selectedIds = items.map(item => item.view.id);- const selectionHash = fingerprint([selection.name, selection.avatarImageBase64, selectedIds.toSorted(), selection.takeover, snapshot.source.kind, snapshot.source.agentId, snapshot.source.root]);const existing = await deps.readReceipt(selection.requestId);+ const selectionHash = await validateImportRequestIdentity(snapshot, selection, existing, deps.readLegacyDeferSetup);deps.assertOwner();- if (existing && existing.selectionHash !== selectionHash) throw new CompanionImportError('REQUEST_ALREADY_USED');if (existing?.creationRejected) throw new CompanionImportError(existing.creationRejected);if (existing?.cancelled) return existing.result;if (existing?.result.status === 'complete') return existing.result;const receipt: ImportReceipt = existing ?? { selectionHash, handoverMarkers: true, copied: [], routines: {}, result: {requestId: selection.requestId, botId: `import_${fingerprint(selection.requestId).slice(0, 24)}`, status: 'running', checks: [],} };+ receipt.selectionHash = selectionHash;+ receipt.deferSetup = selection.deferSetup === true;const botId = receipt.result.botId;const save = async () => { deps.assertOwner(); await deps.saveReceipt(receipt); deps.assertOwner(); };const check = (entryId: string, status: CompanionImportResult['checks'][number]['status'], message?: string) => {@@ -111,10 +140,25 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comdeps.assertOwner();}if (item.sourceDirectory && !item.filesComplete) {+ // Failed discovery uses a directory-based ID. Older successful imports+ // also lack sourceAlias, so absence alone must not reinterpret them.+ const metadataPending = item.view.category === 'skills' && !!item.captureIssue && !item.sourceAlias+ && item.view.id === `skill-${fingerprint(item.sourceDirectory).slice(0, 20)}`;const captured = item.files ?? [];const names = new Set(captured.map(file => file.name));try {item.files = [...captured, ...await readImportTree(item.sourceDirectory, name => !names.has(name), budget)];+ if (metadataPending) {+ const manifest = item.files.find(file => file.name === 'SKILL.md')?.bytes.toString('utf8');+ if (!manifest?.trim() || !deps.readSkillConfig) throw new CompanionImportError('SOURCE_CONFIG_INVALID');+ const config = await deps.readSkillConfig(snapshot.source, budget);+ deps.assertOwner();+ const metadata = normalizeImportSkill(snapshot.source.kind, item.view.name, manifest, object(config.skills));+ const restored = { ...item, ...metadata, view: { ...item.view, ...metadata.view, id: item.view.id } };+ // A newly readable credential must not silently choose a conflicting account.+ selectedImportEnvironment(items.map(candidate => candidate === item ? restored : candidate));+ Object.assign(item, restored);+ }item.filesComplete = true;delete item.captureIssue;} catch (error) {diff --git a/apps/mobile/src/session/CompanionImportSheet.tsx b/apps/mobile/src/session/CompanionImportSheet.tsxindex 55cb49c995..0f5fe5bd72 100644--- a/apps/mobile/src/session/CompanionImportSheet.tsx+++ b/apps/mobile/src/session/CompanionImportSheet.tsx@@ -139,5 +139,5 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({label: { fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium, color: colors.textPrimary },note: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: colors.textSecondary },count: { fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: colors.textTertiary },- input: { minHeight: 44, borderWidth: 1, borderColor: colors.border, borderRadius: radius.container, paddingHorizontal: spacing.md, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.regular, color: colors.textPrimary, backgroundColor: colors.surfaceElevated },+ input: { minHeight: 44, borderWidth: 1, borderColor: colors.border, borderRadius: radius.container, paddingHorizontal: spacing.md, fontSize: typeScale.body, fontWeight: fontWeight.regular, color: colors.textPrimary, backgroundColor: colors.surfaceElevated },});