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): retain imported script execute permissions

Chris7e74ecec0494
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index b2ea9d0486..7b5fa29b4d 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -99,6 +99,9 @@ omitting it retains normal companion defaults, and a rejected request can be cor
name; referenced skill scripts contribute their environment dependencies.
Hermes entry and monitor scripts select their entire directory subtrees,
preserving sibling modules and resource paths in the encrypted snapshot.
+ Script assets retain their captured executable flags through the encrypted
+ archive and execution tree, so direct sibling helper calls keep working.
+ Legacy archives without those flags retain their non-executable default.
These files remain individually deselectable; deselecting a subtree dependency
prevents that automation's takeover, leaving its source running. Helper code
contributes environment dependencies and bounded verification planning text.
diff --git a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts
index 739a9954e7..581c8771e4 100644
--- a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts
@@ -28,26 +28,31 @@ it.skipIf(process.platform === 'win32')('executes the default imported script an
const files = {
'config.yaml': 'name: Ada\n',
'cron/jobs.json': JSON.stringify([{ id: 'report', script: 'reports/report.sh', monitor_script: 'monitor/check.sh', no_agent: true, schedule: { kind: 'interval', minutes: 5 } }]),
- 'scripts/reports/report.sh': 'test ! -e "$HERMES_HOME/memory/image.png" || exit 91\ntest -f "$HERMES_HOME/scripts/unrelated/unused.sh" || exit 92\n. ./helper.sh\nreport\n',
- 'scripts/reports/helper.sh': 'report() { cat data/report.txt; }\n',
+ 'scripts/reports/report.sh': 'test ! -x data/report.txt || exit 90\ntest ! -e "$HERMES_HOME/memory/image.png" || exit 91\ntest -f "$HERMES_HOME/scripts/unrelated/unused.sh" || exit 92\n./helper.sh\n',
+ 'scripts/reports/helper.sh': '#!/bin/sh\ncat data/report.txt\n',
'scripts/reports/data/report.txt': 'copied report resource',
- 'scripts/monitor/check.sh': '. ./helper.sh\nmonitor\n',
- 'scripts/monitor/helper.sh': 'monitor() { cat data/state.txt; }\n',
+ 'scripts/monitor/check.sh': './helper.sh\n',
+ 'scripts/monitor/helper.sh': '#!/bin/sh\ncat data/state.txt\n',
'scripts/monitor/data/state.txt': 'copied monitor resource',
'scripts/unrelated/unused.sh': 'exit 99',
};
for (const [name, text] of Object.entries(files)) { const file = path.join(sourceRoot, name); await fs.mkdir(path.dirname(file), { recursive: true }); await fs.writeFile(file, text); }
+ for (const name of ['reports/helper.sh', 'monitor/helper.sh']) await fs.chmod(path.join(sourceRoot, 'scripts', name), 0o700);
const reader = { home: root, env: {}, readCronDatabase: vi.fn(async () => []) };
const [source] = await discoverImportSources(reader);
const snapshot = await inspectImportSource(source!, reader);
const selected = validateImportSelection({ requestId: 'script-subtree-fixture', previewId: 'preview', name: 'Ada', takeover: true, entryIds: snapshot.items.filter(item => item.view.selected).map(item => item.view.id) }, snapshot);
const task = selected.find(item => item.automation)!;
const assets = Object.fromEntries(selected.flatMap(item => item.asset ? [[item.asset.name, item.asset.bytes.toString('base64')]] : []));
+ const fileExecutables = Object.fromEntries(selected.flatMap(item => item.asset ? [[item.asset.name, item.asset.executable === true]] : []));
+ expect(fileExecutables['scripts/reports/helper.sh']).toBe(true);
+ expect(fileExecutables['scripts/monitor/helper.sh']).toBe(true);
+ expect(fileExecutables['scripts/reports/data/report.txt']).toBe(false);
expect(Object.keys(assets)).toHaveLength(7);
expect(assets['scripts/unrelated/unused.sh']).toBe(Buffer.from('exit 99').toString('base64'));
expect(task.view.dependsOn).not.toContain(snapshot.items.find(item => item.asset?.name === 'scripts/unrelated/unused.sh')!.view.id);
assets['memory/image.png'] = Buffer.from('legacy-private-image').toString('base64');
- await shared.store.write(root, 'bot', { version: 1, env: {}, mcp: [], credentials: [], files: assets, automations: {
+ await shared.store.write(root, 'bot', { version: 1, env: {}, mcp: [], credentials: [], files: assets, fileExecutables, automations: {
routine: { kind: 'hermes', handover: 'ready', original: task.automation!.original, sourceRoot, deliveries: [] },
} }, () => {});
await fs.rm(sourceRoot, { recursive: true, force: true });
@@ -61,7 +66,7 @@ it.skipIf(process.platform === 'win32')('executes the default imported script an
it('does not materialize legacy media or archived memory for a native command', async () => {
const routine = { id: 'routine', botId: 'bot', prompt: 'Fixture command' } as Routine;
const directory = path.join(root, 'bots', 'bot', 'import-executions');
- const code = 'const fs=require("node:fs"),path=require("node:path");const dirs=fs.readdirSync(process.argv[1]);console.log(dirs.every(name=>!fs.existsSync(path.join(process.argv[1],name,"memory"))&&fs.existsSync(path.join(process.argv[1],name,"scripts/unused.py")))?"clean":"incorrect assets");';
+ const code = 'const fs=require("node:fs"),path=require("node:path");const dirs=fs.readdirSync(process.argv[1]);console.log(dirs.every(name=>!fs.existsSync(path.join(process.argv[1],name,"memory"))&&fs.existsSync(path.join(process.argv[1],name,"scripts/unused.py"))&&(process.platform==="win32"||(fs.statSync(path.join(process.argv[1],name,"scripts/unused.py")).mode&0o111)===0))?"clean":"incorrect assets");';
const original = { payload: { kind: 'command', argv: [process.execPath, '-e', code, directory], cwd: root } };
const legacyFiles = { 'memory/image.png': Buffer.from('legacy-media-bytes').toString('base64'), 'scripts/unused.py': Buffer.from('unused').toString('base64') };
await shared.store.write(root, 'bot', { version: 1, env: {}, mcp: [], credentials: [], files: legacyFiles,
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 a248963278..e7a2bad407 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -1550,6 +1550,40 @@ it('retains managed media by ledger reference without copying its bytes into exe
expect(JSON.stringify(environment)).not.toContain(image.toString('base64'));
});
+it.each([false, true])('preserves script executable flags in the archive and checkpoint (retry: %s)', async retry => {
+ h.snapshot.items = [
+ { view: { id: 'helper', name: 'helper', category: 'connections', selected: true },
+ asset: { name: 'scripts/helper', bytes: Buffer.from('#!/bin/sh\nprintf fixture'), executable: true } },
+ { view: { id: 'data', name: 'data.txt', category: 'connections', selected: true },
+ asset: { name: 'scripts/data.txt', bytes: Buffer.from('data'), executable: false } },
+ { view: { id: 'legacy', name: 'legacy.py', category: 'connections', selected: true },
+ asset: { name: 'scripts/legacy.py', bytes: Buffer.from('print("fixture")') } },
+ { view: { id: 'memory', name: 'note', category: 'memory', selected: true }, text: 'Original note' },
+ ];
+ if (retry) h.importDocument.mockRejectedValueOnce(Object.assign(new Error('full'), { code: 'ENOSPC' }));
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: `script-executable-${retry}`, previewId: preview.id, name: 'Ada',
+ entryIds: ['helper', 'data', 'legacy', 'memory'], takeover: false, deferSetup: true };
+ const accepted = await startCompanionImport(selection, 'fixture');
+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ const expected = { 'scripts/helper': true, 'scripts/data.txt': false, 'scripts/legacy.py': false };
+ let stored = (await h.store.read(h.root, accepted.botId, () => {}))!;
+ expect(stored.fileExecutables).toEqual(expected);
+ const bytes = stored.files;
+ if (retry) {
+ const checkpoint = await deserializeImportSnapshotAsync(stored.pendingImport!.snapshotJson, () => {});
+ expect(checkpoint.items.find(item => item.view.id === 'helper')?.asset?.executable).toBe(true);
+ await startCompanionImport(selection, 'after-restart');
+ const completed = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(completed?.status).toBe('complete');
+ stored = (await h.store.read(h.root, accepted.botId, () => {}))!;
+ expect(stored.fileExecutables).toEqual(expected);
+ expect(stored.files).toEqual(bytes);
+ }
+ expect(stored.pendingImport).toBeUndefined();
+});
+
it('cleans a completed checkpoint after a crash without replaying import work', async () => {
h.snapshot.items = [{ view: { id: 'memory', name: 'note', category: 'memory', selected: true }, text: 'Original' }];
const [source] = await listCompanionImportSources('fixture'); const preview = await previewCompanionImport(source!.id, 'fixture');
diff --git a/apps/desktop/src/main/bot-import/automationRuntime.ts b/apps/desktop/src/main/bot-import/automationRuntime.ts
index 287146fc2c..1636281bc4 100644
--- a/apps/desktop/src/main/bot-import/automationRuntime.ts
+++ b/apps/desktop/src/main/bot-import/automationRuntime.ts
@@ -86,7 +86,7 @@ export async function prepareImportedAutomation(root: string, routine: Routine,
// Old environments mixed memory attachments into files. The source script
// namespace retains all helpers/resources, including cross-directory imports.
await writeImportFiles(directory, Object.entries(environment.files ?? {}).filter(([name]) => name.startsWith('scripts/'))
- .map(([name, bytes]) => ({ name, bytes: Buffer.from(bytes, 'base64'), executable: false })));
+ .map(([name, bytes]) => ({ name, bytes: Buffer.from(bytes, 'base64'), executable: environment.fileExecutables?.[name] === true })));
let prompt = redact(routine.prompt); let direct: string | undefined; let skipped = false;
let monitorOutput: string | undefined;
if (command) {
diff --git a/apps/desktop/src/main/bot-import/environment.ts b/apps/desktop/src/main/bot-import/environment.ts
index c2287cd7d0..a76682edb5 100644
--- a/apps/desktop/src/main/bot-import/environment.ts
+++ b/apps/desktop/src/main/bot-import/environment.ts
@@ -15,6 +15,8 @@ export interface CompanionEnvironment {
credentials: Array<{ id: string; format: string; value: unknown }>;
/** Source script assets. Legacy imports may also contain memory attachments; execution filters by the scripts/ namespace. */
files?: Record<string, string>;
+ /** Captured script execute bits, keyed like files; absent legacy flags remain non-executable. */
+ fileExecutables?: Record<string, boolean>;
/** Non-media memory originals (including empty markers); never execution assets. Media originals live in the media ledger. */
memoryFiles?: Record<string, string>;
/** Originals behind redacted skill projections; only materialized for authorized host commands. */
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index 85b40256f0..ae4c425227 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -711,9 +711,15 @@ export async function startCompanionImport(selection: CompanionImportSelection,
// A successful retry may upgrade an earlier mixed execution archive.
// Remove only the exact copy whose original has just been preserved.
for (const file of [...(item.asset ? [item.asset] : []), ...item.files ?? []]) {
- if (environment.files?.[file.name] === file.bytes.toString('base64')) delete environment.files[file.name];
+ if (environment.files?.[file.name] === file.bytes.toString('base64')) {
+ delete environment.files[file.name];
+ delete environment.fileExecutables?.[file.name];
+ }
}
- } else if (item.asset) environment.files = { ...environment.files, [item.asset.name]: item.asset.bytes.toString('base64') };
+ } else if (item.asset) {
+ environment.files = { ...environment.files, [item.asset.name]: item.asset.bytes.toString('base64') };
+ environment.fileExecutables = { ...environment.fileExecutables, [item.asset.name]: item.asset.executable === true };
+ }
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(persistedItem)) { environment.documents ??= {}; environment.documents[id] = text; }
if (item.view.category === 'skills') {
@@ -761,6 +767,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}),
credentials: items.flatMap(item => item.credential && !item.view.dependsOn?.some(id => !chosen.has(id)) && (!item.view.issues?.length || item.credential.format !== 'telegram') ? [{ id: item.view.id, ...item.credential, ...(item.credential.format === 'telegram' ? { value: resolveReferences(item.credential.value) } : {}) }] : []),
files: Object.fromEntries(items.flatMap(item => item.asset && !isMemoryItem(item) ? [[item.asset.name, item.asset.bytes.toString('base64')]] : [])),
+ fileExecutables: Object.fromEntries(items.flatMap(item => item.asset && !isMemoryItem(item) ? [[item.asset.name, item.asset.executable === true]] : [])),
memoryFiles: Object.fromEntries(items.flatMap(memoryFileEntries)),
skillFiles,
documents,
diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.ts
index b757a1a738..b318ca5d00 100644
--- a/apps/desktop/src/main/bot-import/sources.ts
+++ b/apps/desktop/src/main/bot-import/sources.ts
@@ -330,7 +330,7 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead
}
await connections(items, source, values, deps, budget);
if (source.kind === 'hermes' && (await directories(source.root)).includes('scripts')) {
- for (const file of await readImportTree(path.join(source.root, 'scripts'), undefined, budget)) items.push({ view: { id: entryId('script', file.name), category: 'connections', name: `scripts/${file.name}`, selected: true }, asset: { name: `scripts/${file.name}`, bytes: file.bytes } });
+ for (const file of await readImportTree(path.join(source.root, 'scripts'), undefined, budget)) items.push({ view: { id: entryId('script', file.name), category: 'connections', name: `scripts/${file.name}`, selected: true }, asset: { name: `scripts/${file.name}`, bytes: file.bytes, executable: file.executable } });
}
const row = source.kind === 'openclaw' ? agentRows(values).find(row => row.id === source.agentId) ?? {} : values;
sourceConfiguration(items, source, values);
diff --git a/apps/desktop/src/main/bot-import/types.ts b/apps/desktop/src/main/bot-import/types.ts
index 898665c4a5..83eacd9bb1 100644
--- a/apps/desktop/src/main/bot-import/types.ts
+++ b/apps/desktop/src/main/bot-import/types.ts
@@ -60,7 +60,7 @@ export interface ImportItem {
envDependencies?: { names: string[]; entries: string[] };
mcp?: ImportedMcpServer;
credential?: { format: string; value: unknown };
- asset?: { name: string; bytes: Buffer };
+ asset?: { name: string; bytes: Buffer; executable?: boolean };
automation?: {
sourceId: string;
input?: RoutineInput;