@evolinkai/cli 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/skills.mjs CHANGED
@@ -2,36 +2,173 @@ import * as fs from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { randomUUID } from 'node:crypto';
6
- import { requireThat } from './errors.mjs';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { CliError, requireThat } from './errors.mjs';
7
+ import { State } from './state.mjs';
8
+ import { CLI_VERSION } from './version.mjs';
7
9
 
8
10
  const AGENT_DIRS = {
9
11
  codex: '.agents', 'claude-code': '.claude', cursor: '.agents',
10
12
  gemini: '.agents', opencode: '.agents', copilot: '.agents',
11
13
  openclaw: '.openclaw', hermes: '.hermes',
12
14
  };
15
+ const MANIFEST = '.evolink-cli.json';
16
+ const LEGACY_HASHES = new Set([
17
+ '680faa81bab65b6324933fa24bed34f2680c88df0bbf843423b53e3d3c9b6de5', // Published 0.5.0.
18
+ 'bed3f5dcba1d5d07e98f21f6ab45180eaa5983b610851d2aed25274114b64982', // Published 0.5.1.
19
+ ]);
20
+ const digest = content => createHash('sha256').update(content).digest('hex');
21
+ const owned = content => content?.startsWith('---\nname: evolink-cli\n') && content.includes('<!-- evolink-media-cli-owned -->');
22
+ const source = fileURLToPath(new URL('../skills/evolink-cli/', import.meta.url));
13
23
 
14
- export async function installSkill({ home = os.homedir(), agent = 'all' } = {}) {
15
- requireThat(agent === 'all' || Object.hasOwn(AGENT_DIRS, agent), 'invalid_agent', 'Choose all, codex, claude-code, cursor, gemini, opencode, copilot, openclaw or hermes.');
16
- const source = fileURLToPath(new URL('../skills/evolink-cli/SKILL.md', import.meta.url));
17
- const content = await fs.readFile(source, 'utf8');
24
+ export function validateAgent(agent = 'all') {
25
+ requireThat(agent === 'all' || Object.hasOwn(AGENT_DIRS, agent), 'invalid_agent',
26
+ 'Choose all, codex, claude-code, cursor, gemini, opencode, copilot, openclaw or hermes.');
27
+ return agent;
28
+ }
29
+ function targets(home, agent) {
30
+ validateAgent(agent);
18
31
  const dirs = agent === 'all' ? [...new Set(Object.values(AGENT_DIRS))] : [AGENT_DIRS[agent]];
19
- const files = [];
20
- // Check all destinations before updating any of them.
21
- for (const dir of dirs) {
22
- const target = path.join(home, dir, 'skills', 'evolink-cli', 'SKILL.md');
23
- let previous;
24
- try { previous = await fs.readFile(target, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
25
- requireThat(!previous || previous.startsWith('---\nname: evolink-cli\n') && previous.includes('<!-- evolink-media-cli-owned -->'),
26
- 'skill_conflict', 'A different evolink-cli skill already exists. Choose how to replace it before installing.');
27
- files.push({ path: target, updated: !!previous });
32
+ return dirs.map(dir => path.join(home, dir, 'skills', 'evolink-cli'));
33
+ }
34
+ async function readOptional(file) {
35
+ try { return await fs.readFile(file, 'utf8'); }
36
+ catch (e) { if (e.code === 'ENOENT') return undefined; throw e; }
37
+ }
38
+ async function bundle() {
39
+ const files = {};
40
+ async function visit(dir, prefix = '') {
41
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
42
+ const relative = prefix + entry.name;
43
+ requireThat(!entry.isSymbolicLink(), 'invalid_skill_bundle', 'The bundled skill cannot contain symbolic links.');
44
+ if (entry.isDirectory()) await visit(path.join(dir, entry.name), `${relative}/`);
45
+ else if (entry.isFile()) files[relative] = await fs.readFile(path.join(dir, entry.name));
46
+ }
47
+ }
48
+ await visit(source);
49
+ return files;
50
+ }
51
+ async function noSymlinks(home, dir, files) {
52
+ for (const file of ['', MANIFEST, ...Object.keys(files)]) {
53
+ const relative = path.relative(home, path.join(dir, file));
54
+ let current = home;
55
+ for (const part of relative.split(path.sep)) {
56
+ current = path.join(current, part);
57
+ try {
58
+ requireThat(!(await fs.lstat(current)).isSymbolicLink(), 'skill_conflict',
59
+ 'A skill destination is a symbolic link. Choose a regular skill directory before installing.', { path: current });
60
+ } catch (e) { if (e.code !== 'ENOENT') throw e; break; }
61
+ }
28
62
  }
29
- for (const file of files) {
30
- await fs.mkdir(path.dirname(file.path), { recursive: true, mode: 0o700 });
31
- const temp = `${file.path}.${randomUUID()}.tmp`;
32
- try { await fs.writeFile(temp, content, { flag: 'wx', mode: 0o600 }); await fs.rename(temp, file.path); }
33
- finally { await fs.unlink(temp).catch(() => {}); }
63
+ }
64
+ async function inspect(home, dir, files) {
65
+ await noSymlinks(home, dir, files);
66
+ const previous = await readOptional(path.join(dir, 'SKILL.md'));
67
+ const raw = await readOptional(path.join(dir, MANIFEST));
68
+ let manifest;
69
+ try { manifest = raw ? JSON.parse(raw) : undefined; } catch { /* Treat damaged metadata as a conflict. */ }
70
+ const valid = manifest?.schema_version === 1 && typeof manifest.cli_version === 'string' &&
71
+ manifest.files && typeof manifest.files === 'object' && !Array.isArray(manifest.files) &&
72
+ Object.entries(manifest.files).every(([name, sha]) => /^[a-zA-Z0-9_.\/-]+$/.test(name) &&
73
+ !name.startsWith('/') && name.split('/').every(p => p && p !== '.' && p !== '..') && /^[a-f0-9]{64}$/.test(sha));
74
+ const changes = [];
75
+ const liveHashes = {};
76
+ let matches = true;
77
+ for (const [relative, content] of Object.entries(files)) {
78
+ const live = await readOptional(path.join(dir, relative));
79
+ liveHashes[relative] = live === undefined ? null : digest(live);
80
+ if (live === undefined || digest(live) !== digest(content)) matches = false;
81
+ // Existing untracked resources are user content and must not be overwritten.
82
+ if (live !== undefined && valid && (!manifest.files[relative] || digest(live) !== manifest.files[relative])) changes.push(relative);
83
+ if (live !== undefined && !raw && relative !== 'SKILL.md' && digest(live) !== digest(content)) changes.push(relative);
84
+ }
85
+ if (valid) {
86
+ await noSymlinks(home, dir, manifest.files);
87
+ for (const [relative, sha] of Object.entries(manifest.files)) {
88
+ const live = await readOptional(path.join(dir, relative));
89
+ liveHashes[relative] = live === undefined ? null : digest(live);
90
+ if (live === undefined || digest(live) !== sha) changes.push(relative);
91
+ }
34
92
  }
35
- return { skill: 'evolink-cli', path: files[0].path, updated: files.some(f => f.updated), installations: files,
36
- next_step: 'Verify that your assistant discovers evolink-cli. If it does not refresh skills, open a new conversation.' };
93
+ if (previous && !valid && !matches && !LEGACY_HASHES.has(digest(previous))) changes.push('SKILL.md');
94
+ let status;
95
+ if (previous === undefined && raw === undefined && !changes.length) status = 'missing';
96
+ else if (!owned(previous) || raw && !valid) status = 'conflict';
97
+ else if (changes.length || !valid && !matches && !LEGACY_HASHES.has(digest(previous))) status = 'modified';
98
+ else if (!valid) status = LEGACY_HASHES.has(digest(previous)) ? 'legacy' : 'unmanaged';
99
+ else status = matches && manifest.cli_version === CLI_VERSION ? 'current' : 'outdated';
100
+ return { path: path.join(dir, 'SKILL.md'), directory: dir, status,
101
+ installed_cli_version: valid ? manifest.cli_version : null, changed_files: [...new Set(changes)],
102
+ _fingerprint: digest(JSON.stringify({ previous, raw, liveHashes })) };
103
+ }
104
+ function lock(home, fn) {
105
+ // Skills are shared across state directories and agents: use one per-home lock.
106
+ return new State(path.join(home, '.evolink-media')).lock('skills-install', fn);
107
+ }
108
+ function publicInstallation({ _fingerprint, ...view }) { return view; }
109
+ export async function skillStatus({ home = os.homedir(), agent = 'all' } = {}) {
110
+ const dirs = targets(home, agent);
111
+ return lock(home, async () => {
112
+ const files = await bundle();
113
+ const installations = await Promise.all(dirs.map(dir => inspect(home, dir, files)));
114
+ return { skill: 'evolink-cli', cli_version: CLI_VERSION, agent, current: installations.every(f => f.status === 'current'),
115
+ installations: installations.map(publicInstallation), assistant_discovery: 'not_checked',
116
+ next_step: 'Run evolink skills install for missing or outdated files. Ask your assistant to confirm discovery; only reopen the conversation if needed.' };
117
+ });
118
+ }
119
+ export async function installSkill({ home = os.homedir(), agent = 'all', replaceModified = false } = {}) {
120
+ const dirs = targets(home, agent);
121
+ return lock(home, async () => {
122
+ const files = await bundle();
123
+ const plans = await Promise.all(dirs.map(dir => inspect(home, dir, files)));
124
+ // Validate every destination before writing to any agent's skill directory.
125
+ const conflict = plans.find(plan => plan.status === 'conflict');
126
+ requireThat(!conflict, 'skill_conflict', 'A different skill or invalid installation metadata already exists. Resolve it before installing.', { path: conflict?.path });
127
+ const modified = plans.find(plan => plan.status === 'modified');
128
+ requireThat(!modified || replaceModified, 'skill_modified',
129
+ 'The installed skill has local changes. Keep them, or explicitly use --replace-modified to back up and replace it.', { path: modified?.path, changed_files: modified?.changed_files });
130
+ const swaps = [];
131
+ const staged = [];
132
+ try {
133
+ for (const plan of plans.filter(p => p.status !== 'current')) {
134
+ const temp = path.join(path.dirname(plan.directory), `.evolink-cli-staging-${randomUUID()}`);
135
+ const backup = path.join(home, '.evolink-media', 'skill-backups', randomUUID());
136
+ await fs.mkdir(path.dirname(plan.directory), { recursive: true, mode: 0o700 });
137
+ await fs.mkdir(temp, { mode: 0o700 });
138
+ staged.push(temp);
139
+ let existed = false;
140
+ try { await fs.cp(plan.directory, temp, { recursive: true, dereference: false }); existed = true; }
141
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
142
+ for (const [relative, content] of Object.entries(files)) {
143
+ const file = path.join(temp, relative);
144
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
145
+ await fs.writeFile(file, content, { mode: 0o600 });
146
+ }
147
+ await fs.writeFile(path.join(temp, MANIFEST), JSON.stringify({ schema_version: 1, cli_version: CLI_VERSION,
148
+ files: Object.fromEntries(Object.entries(files).map(([relative, content]) => [relative, digest(content)])) }, null, 2) + '\n', { mode: 0o600 });
149
+ const now = await inspect(home, plan.directory, files);
150
+ requireThat(now._fingerprint === plan._fingerprint, 'skill_changed', 'The skill changed during installation. Retry after the other editor finishes.', { path: plan.path });
151
+ const swap = { plan, temp, backup: existed ? backup : null, backedUp: false, installed: false };
152
+ swaps.push(swap);
153
+ if (existed) {
154
+ await fs.mkdir(path.dirname(backup), { recursive: true, mode: 0o700 });
155
+ await fs.rename(plan.directory, backup);
156
+ swap.backedUp = true;
157
+ }
158
+ await fs.rename(temp, plan.directory);
159
+ swap.installed = true;
160
+ }
161
+ } catch (e) {
162
+ for (const swap of swaps.reverse()) {
163
+ if (swap.installed) await fs.rename(swap.plan.directory, swap.temp);
164
+ if (swap.backedUp) await fs.rename(swap.backup, swap.plan.directory);
165
+ }
166
+ throw e;
167
+ } finally { for (const temp of staged) await fs.rm(temp, { recursive: true, force: true }); }
168
+ const installations = plans.map(plan => ({ path: plan.path, status: 'current', updated: plan.status !== 'current',
169
+ previous_status: plan.status, backup: swaps.find(s => s.plan === plan)?.backup || null }));
170
+ return { skill: 'evolink-cli', cli_version: CLI_VERSION, path: installations[0].path,
171
+ updated: installations.some(f => f.updated), installations, assistant_discovery: 'not_checked',
172
+ next_step: 'Ask your assistant to confirm it discovers evolink-cli. If it does not refresh skills, open a new conversation.' };
173
+ });
37
174
  }
package/src/state.mjs CHANGED
@@ -15,6 +15,41 @@ export function canonical(value) {
15
15
  export const hash = value => createHash('sha256').update(canonical(value)).digest('hex');
16
16
  export const validID = id => typeof id === 'string' && /^[a-zA-Z0-9._-]{1,96}$/.test(id) && !id.includes('..');
17
17
 
18
+ const hostID = createHash('sha256').update(os.hostname()).digest('hex').slice(0, 16);
19
+ const pause = () => new Promise(resolve => setTimeout(resolve, 100));
20
+ // Windows can briefly deny directory deletion while another waiter reads it.
21
+ const removeLock = dir => fs.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
22
+ function dead(pid) {
23
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
24
+ try { process.kill(pid, 0); return false; }
25
+ catch (error) { return error.code === 'ESRCH'; }
26
+ }
27
+ async function ownerOf(dir) {
28
+ try { return JSON.parse(await fs.readFile(path.join(dir, 'owner.json'), 'utf8')); }
29
+ catch { return undefined; }
30
+ }
31
+ async function staleOwner(dir) {
32
+ const owner = await ownerOf(dir);
33
+ if (owner) return owner.hostname === os.hostname() && dead(owner.pid);
34
+ try { return Date.now() - (await fs.stat(dir)).mtimeMs > 30_000; }
35
+ catch (error) { if (error.code !== 'ENOENT') throw error; return false; }
36
+ }
37
+ async function recovering(dir) {
38
+ let entries;
39
+ try { entries = await fs.readdir(dir); }
40
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
41
+ let active = false;
42
+ for (const name of entries) {
43
+ const match = /^([a-f0-9]{16})\.([1-9][0-9]*)\.([a-f0-9-]{36})$/.exec(name);
44
+ // Old releases left an empty recovery directory, not an owned ticket.
45
+ if (!match) continue;
46
+ if (match[1] === hostID && dead(Number(match[2]))) {
47
+ await fs.unlink(path.join(dir, name)).catch(error => { if (error.code !== 'ENOENT') throw error; });
48
+ } else active = true;
49
+ }
50
+ return active;
51
+ }
52
+
18
53
  export class State {
19
54
  // Retain the original storage location so renaming the command preserves sessions and request IDs.
20
55
  constructor(home = process.env.EVOLINK_CLI_HOME || process.env.EVOLINK_MEDIA_HOME || path.join(os.homedir(), '.evolink-media')) {
@@ -48,36 +83,40 @@ export class State {
48
83
  const dir = path.join(this.home, 'locks', id);
49
84
  await fs.mkdir(path.dirname(dir), { recursive: true, mode: 0o700 });
50
85
  const deadline = Date.now() + 10_000;
86
+ const recovery = `${dir}.recovery`;
87
+ const token = randomUUID();
88
+ const busy = () => {
89
+ if (Date.now() > deadline) throw new CliError('operation_busy', 'Another command is using this state. Wait for it to finish.');
90
+ };
51
91
  for (;;) {
52
- try { await fs.mkdir(dir, { mode: 0o700 }); break; }
92
+ let acquired = false;
93
+ try { await fs.mkdir(dir, { mode: 0o700 }); acquired = true; }
53
94
  catch (e) {
54
95
  if (e.code !== 'EEXIST') throw e;
55
- // Serialize stale-owner recovery so two contenders cannot remove a new lock.
56
- const recovery = `${dir}.recovery`;
57
- let recovering = false;
96
+ // Each recovery has a unique, process-owned ticket. New owners wait for
97
+ // all tickets before entering; a crash cannot leave an unowned guard.
98
+ await fs.mkdir(recovery, { recursive: true, mode: 0o700 });
99
+ const ticket = path.join(recovery, `${hostID}.${process.pid}.${randomUUID()}`);
100
+ await fs.writeFile(ticket, '', { flag: 'wx', mode: 0o600 });
58
101
  try {
59
- await fs.mkdir(recovery, { mode: 0o700 });
60
- recovering = true;
61
- let stale = false;
62
- try {
63
- const owner = JSON.parse(await fs.readFile(path.join(dir, 'owner.json'), 'utf8'));
64
- if (owner.hostname === os.hostname()) {
65
- try { process.kill(owner.pid, 0); } catch (probe) { stale = probe.code === 'ESRCH'; }
66
- }
67
- } catch {
68
- try { stale = Date.now() - (await fs.stat(dir)).mtimeMs > 30_000; }
69
- catch (statError) { if (statError.code !== 'ENOENT') throw statError; }
70
- }
71
- if (stale) await fs.rm(dir, { recursive: true, force: true });
72
- } catch (recoveryError) { if (recoveryError.code !== 'EEXIST') throw recoveryError; }
73
- finally { if (recovering) await fs.rmdir(recovery); }
74
- if (Date.now() > deadline) throw new CliError('operation_busy', 'Another command is using this state. Wait for it to finish.');
75
- await new Promise(resolve => setTimeout(resolve, 100));
102
+ if (await staleOwner(dir)) await removeLock(dir);
103
+ } finally { await fs.unlink(ticket); }
76
104
  }
105
+ if (!acquired) { busy(); await pause(); continue; }
106
+ let entered = false;
107
+ try {
108
+ await fs.writeFile(path.join(dir, 'owner.json'), JSON.stringify({ pid: process.pid, hostname: os.hostname(), token }), { mode: 0o600 });
109
+ while (await recovering(recovery)) { busy(); await pause(); }
110
+ // Another recovery may have removed this not-yet-entered owner.
111
+ if ((await ownerOf(dir))?.token !== token) { busy(); continue; }
112
+ entered = true;
113
+ return await fn();
114
+ } catch (error) {
115
+ if (entered || error.code !== 'ENOENT') throw error;
116
+ } finally {
117
+ if ((await ownerOf(dir))?.token === token) await removeLock(dir);
118
+ }
119
+ busy();
77
120
  }
78
- try {
79
- await fs.writeFile(path.join(dir, 'owner.json'), JSON.stringify({ pid: process.pid, hostname: os.hostname() }), { mode: 0o600 });
80
- return await fn();
81
- } finally { await fs.rm(dir, { recursive: true, force: true }); }
82
121
  }
83
122
  }
@@ -0,0 +1,3 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ export const CLI_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;