@evolinkai/cli 0.5.1 → 0.7.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/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;