clavarium-docket 0.1.1 → 0.1.2-next.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium-docket",
3
- "version": "0.1.1",
3
+ "version": "0.1.2-next.3",
4
4
  "description": "Clavarium Docket: events an AI agent or a script sees and acknowledges, and reminders it sets itself (a command and an MCP server, and a library for the application). No dependency.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/clavarium/clavarium-docket#readme",
package/server/docket.mjs CHANGED
@@ -18,14 +18,14 @@
18
18
  * plans.jsonl the worker's: the reminders it set, and took back
19
19
  * plans-off.jsonl the application's: the reminders the person took back
20
20
  */
21
- import { appendFileSync, readFileSync, mkdirSync, statSync, lstatSync, realpathSync } from 'node:fs';
21
+ import { appendFileSync, readFileSync, mkdirSync, statSync, lstatSync, realpathSync, openSync, readSync, closeSync, constants } from 'node:fs';
22
22
  import { dirname, join, resolve } from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
24
  import { randomUUID, createHash } from 'node:crypto';
25
25
  import { createInterface } from 'node:readline';
26
26
  import { zoneOf, isZone, parseWhen, parseIn, parseCron, nextCron, lastCron, wall } from './time.mjs';
27
27
 
28
- export const VERSION = '0.1.1';
28
+ export const VERSION = '0.1.2-next.3';
29
29
  export const FOLDER = '.docket';
30
30
  export const TEXT_MAX = 500;
31
31
  export const NOTE_MAX = 1000;
@@ -41,8 +41,37 @@ const NOT_SHOWN = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F​-‏‪-‮⁠-⁤
41
41
  export const oneLine = (text, max) => String(text ?? '').replace(/\r/g, '').replace(NOT_SHOWN, '').replace(/\s+/g, ' ').trim().slice(0, max);
42
42
  const parsed = (line) => { try { const j = JSON.parse(line); return j && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; } };
43
43
  /* The lines of one file of the folder: never through a link; one that does not parse is skipped. */
44
+ /* READ ONCE, THEN ONLY WHAT WAS ADDED (18-11: the server read every awake conversation's events and acks whole
45
+ every 5 s; they only grow): per file, where it was read up to; grown, only its new bytes; replaced or shrunk,
46
+ read again whole. The list given is the one kept: read it, never change it. */
47
+ export const LINES_KEPT = 512;
48
+ const kept = new Map();
44
49
  export function lines(file) {
45
- try { if (lstatSync(file).isSymbolicLink()) return []; return readFileSync(file, 'utf8').split('\n').filter(Boolean).map(parsed).filter(Boolean); } catch { return []; }
50
+ let info;
51
+ try { info = lstatSync(file); } catch { kept.delete(file); return []; }
52
+ if (info.isSymbolicLink() || !info.isFile()) { kept.delete(file); return []; }
53
+ let k = kept.get(file);
54
+ if (k && (k.ino !== info.ino || k.dev !== info.dev || info.size < k.offset)) k = undefined;
55
+ if (k && info.size === k.size && info.mtimeMs === k.mtimeMs) return k.rows;
56
+ if (!k) k = { ino: info.ino, dev: info.dev, offset: 0, rows: [], size: 0, mtimeMs: 0 };
57
+ try {
58
+ const fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
59
+ try {
60
+ const want = info.size - k.offset;
61
+ const buf = Buffer.alloc(Math.max(0, want));
62
+ let got = 0;
63
+ while (got < want) { const n = readSync(fd, buf, got, want - got, k.offset + got); if (n <= 0) break; got += n; }
64
+ const end = buf.subarray(0, got).lastIndexOf(0x0a);
65
+ if (end >= 0) {
66
+ for (const line of buf.subarray(0, end).toString('utf8').split('\n')) { if (!line) continue; const j = parsed(line); if (j) k.rows.push(j); }
67
+ k.offset += end + 1;
68
+ }
69
+ k.size = k.offset + (end >= 0 ? got - end - 1 : got); k.mtimeMs = info.mtimeMs;
70
+ } finally { closeSync(fd); }
71
+ } catch { kept.delete(file); return []; }
72
+ kept.delete(file); kept.set(file, k);
73
+ if (kept.size > LINES_KEPT) kept.delete(kept.keys().next().value);
74
+ return k.rows;
46
75
  }
47
76
  const isFolder = (path) => { try { return statSync(path).isDirectory(); } catch { return false; } };
48
77
 
@@ -233,5 +262,8 @@ if (main) {
233
262
  const at = process.argv.indexOf('--dir');
234
263
  const dir = findFolder({ dir: at >= 0 ? process.argv[at + 1] : undefined });
235
264
  if (!dir) { process.stderr.write(`No ${FOLDER} folder: give --dir FOLDER.\n`); process.exit(2); }
236
- serve(dir);
265
+ /* Under a relay (02-11): a new version installed is taken up between two requests, the session never
266
+ restarted. --child: the server itself, as the relay starts it. */
267
+ if (process.argv.includes('--child') || process.env.DOCKET_NO_RELAY === '1' || process.env.MCP_RELAYED === '1') serve(dir);
268
+ else void import('./relay.mjs').then(({ relay }) => relay({ args: [HERE, ...process.argv.slice(2), '--child'], packageJson: join(dirname(HERE), '..', 'package.json') })).catch(() => serve(dir));
237
269
  }
@@ -0,0 +1,71 @@
1
+ /* TAKEN UP WITHOUT A RESTART (02-11). An MCP server lives as long as the session that started it: a new
2
+ * version installed under it was not seen until the session itself was restarted ("on ne peut pas mettre à
3
+ * jour un composant sans redémarrer la session ?"). So the server runs as a child of this relay; between two
4
+ * requests, when the version installed on disk is no longer the child's, the relay starts the new one, says
5
+ * hello to it as the session did, and tells the session its tools may have changed. Nothing is lost: a
6
+ * request in flight is answered by the child it went to, the next goes to the new one. */
7
+ import { spawn } from 'node:child_process';
8
+ import { readFileSync } from 'node:fs';
9
+ import { createInterface } from 'node:readline';
10
+
11
+ /* -> the version installed now, read from package.json (null if unreadable: keep the child). */
12
+ export const installedVersion = (packageJson) => { try { return String(JSON.parse(readFileSync(packageJson, 'utf8')).version ?? '') || null; } catch { return null; } };
13
+
14
+ export function relay({ command = process.execPath, args, packageJson, input = process.stdin, output = process.stdout, spawner = spawn, version = installedVersion, log = () => {} }) {
15
+ let child = null; let running = null; let hello = null; let helloDone = false;
16
+ const pending = new Set(); const queue = [];
17
+ const send = (m) => output.write(`${JSON.stringify(m)}\n`);
18
+ const start = () => {
19
+ running = version(packageJson);
20
+ const c = spawner(command, args, { stdio: ['pipe', 'pipe', 'inherit'] });
21
+ child = c;
22
+ createInterface({ input: c.stdout }).on('line', (line) => {
23
+ let m; try { m = JSON.parse(line); } catch { return; }
24
+ if (m && typeof m.id === 'string' && m.id.startsWith('relay:')) return; /* its answer to our own hello */
25
+ if (m && m.id !== undefined) pending.delete(m.id);
26
+ output.write(`${line}\n`);
27
+ if (pending.size === 0) flush();
28
+ });
29
+ c.on('exit', () => {
30
+ if (child !== c) return;
31
+ child = null;
32
+ /* It stopped under a request: answered, never left waiting; the next one starts it again. */
33
+ for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: 'The tool stopped; try again.' } });
34
+ pending.clear(); flush();
35
+ });
36
+ return c;
37
+ };
38
+ const greet = (c) => {
39
+ if (!hello) return;
40
+ c.stdin.write(`${JSON.stringify({ ...hello, id: `relay:${Date.now()}` })}\n`);
41
+ c.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`);
42
+ };
43
+ /* Between requests: the new version if there is one (once nothing is in flight), then what waited. */
44
+ const needsNew = () => { if (!child) return true; if (!helloDone) return false; const now = version(packageJson); return Boolean(now && now !== running); };
45
+ const flush = () => {
46
+ while (queue.length) {
47
+ if (needsNew()) {
48
+ if (pending.size > 0) return;
49
+ const old = child; const was = running;
50
+ const c = start(); greet(c);
51
+ log(`relay: ${was} -> ${running}`);
52
+ try { old?.stdin.end(); old?.kill(); } catch { /* gone already */ }
53
+ if (helloDone) send({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' });
54
+ }
55
+ const m = queue.shift();
56
+ if (m.id !== undefined) pending.add(m.id);
57
+ child.stdin.write(`${JSON.stringify(m)}\n`);
58
+ }
59
+ };
60
+ start();
61
+ createInterface({ input }).on('line', (line) => {
62
+ let m; try { m = JSON.parse(line); } catch { return; }
63
+ if (!m || typeof m !== 'object') return;
64
+ if (m.method === 'initialize') { hello = m; }
65
+ if (m.method === 'notifications/initialized') helloDone = true;
66
+ queue.push(m);
67
+ flush();
68
+ });
69
+ input.on('end', () => { try { child?.stdin.end(); } catch { /* gone */ } });
70
+ return { get child() { return child; }, get version() { return running; } };
71
+ }