clavarium 0.2.20 → 0.2.21-next.1

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.
@@ -26,6 +26,13 @@ if [ -f "$chat/server.mjs" ] && ! grep -q "\"$chat/server.mjs\"" "$HOME/.claude.
26
26
  claude mcp add --scope user parley -- node "$chat/server.mjs" --dir "$chat" >/dev/null 2>&1 \
27
27
  || echo "launch: Parley was not given to Claude Code as tools: the command parley still works" >&2
28
28
  fi
29
+ # ITS DOCKET AS ITS OWN TOOLS (MCP), with its chat: what woke it, to say done or failed; the
30
+ # reminders it sets itself. The same as the command "docket", installed in every machine.
31
+ docket="/work/.docket"
32
+ if [ -f "$chat/server.mjs" ] && command -v docket-mcp >/dev/null 2>&1 && ! grep -q "\"$docket\"" "$HOME/.claude.json" 2>/dev/null; then
33
+ claude mcp add --scope user docket -- docket-mcp --dir "$docket" >/dev/null 2>&1 \
34
+ || echo "launch: Docket was not given to Claude Code as tools: the command docket still works" >&2
35
+ fi
29
36
  # ITS PULSE: Claude Code's own hooks say to the chat that it acts, and when its turn ends, so that
30
37
  # the person sees "Working..." while it works without a word (parley pulse; nothing posted).
31
38
  if [ -f "$chat/server.mjs" ]; then
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- /* PARLEY'S ARCHIVE FOR THE MACHINES, fetched from the registry at the exact
3
- * version and integrity npm recorded in the lock file (server/parley.mjs),
4
- * into <app>/toolbox/. The server offers it to machines only if it still has
2
+ /* THE ARCHIVES OF THE MACHINES' TOOLS (Parley, Docket: MACHINE_TOOLS in
3
+ * server/parley.mjs), fetched from the registry at the exact version and
4
+ * integrity npm recorded in the lock file, into <app>/toolbox/. The server offers it to machines only if it still has
5
5
  * that integrity (server/toolbox.mjs). Machines never reach npm.
6
6
  *
7
7
  * node deploy/parley-archive.mjs [--app DIR] [--registry URL]
@@ -12,26 +12,37 @@
12
12
  import { mkdirSync, writeFileSync, renameSync, readFileSync, readdirSync, rmSync, existsSync } from 'node:fs';
13
13
  import { join } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
- import { APP, ARCHIVES, PARLEY, archiveName, locked } from '../server/parley.mjs';
15
+ import { APP, ARCHIVES, PARLEY, MACHINE_TOOLS, archiveName, locked } from '../server/parley.mjs';
16
16
  import { integrityOf } from '../server/toolbox.mjs';
17
17
 
18
18
  export const REGISTRY = 'https://registry.npmjs.org';
19
19
 
20
20
  /* `registry`: where the archive is asked for; the lock file's address is kept
21
21
  for the path only, so a stand-in registry can serve it in tests. */
22
- export async function fetchParleyArchive({ app = APP, registry = REGISTRY, fetcher = fetch } = {}) {
23
- const lock = locked(PARLEY, app);
24
- if (!lock?.resolved) throw new Error(`the lock file of ${app} does not record ${PARLEY}`);
25
- const to = join(app, ARCHIVES, archiveName(lock.version));
22
+ export async function fetchParleyArchive(options = {}) { return fetchArchive(PARLEY, options); }
23
+
24
+ /* Each tool's, in turn; then only those versions are kept there. Resolves with what each gave. */
25
+ export async function fetchToolArchives({ app = APP, ...options } = {}) {
26
+ const done = [];
27
+ for (const tool of MACHINE_TOOLS) done.push(await fetchArchive(tool.pkg, { app, ...options, keep: false }));
28
+ const wanted = new Set(done.map((d) => d.file.split('/').pop()));
29
+ for (const name of readdirSync(join(app, ARCHIVES))) if (!wanted.has(name)) rmSync(join(app, ARCHIVES, name), { force: true });
30
+ return done;
31
+ }
32
+
33
+ export async function fetchArchive(pkg, { app = APP, registry = REGISTRY, fetcher = fetch, keep = true } = {}) {
34
+ const lock = locked(pkg, app);
35
+ if (!lock?.resolved) throw new Error(`the lock file of ${app} does not record ${pkg}`);
36
+ const to = join(app, ARCHIVES, archiveName(lock.version, pkg));
26
37
  if (existsSync(to) && integrityOf(readFileSync(to)) === lock.integrity) return { file: to, version: lock.version, fetched: false };
27
38
  const url = new URL(new URL(lock.resolved).pathname, registry.endsWith('/') ? registry : `${registry}/`);
28
39
  const answer = await fetcher(url, { signal: AbortSignal.timeout(120_000) });
29
40
  if (!answer.ok) throw new Error(`the registry answered ${answer.status} for ${url}`);
30
41
  const bytes = Buffer.from(await answer.arrayBuffer());
31
- if (integrityOf(bytes) !== lock.integrity) throw new Error(`${PARLEY} ${lock.version} from the registry does not have the integrity of the lock file`);
42
+ if (integrityOf(bytes) !== lock.integrity) throw new Error(`${pkg} ${lock.version} from the registry does not have the integrity of the lock file`);
32
43
  mkdirSync(join(app, ARCHIVES), { recursive: true });
33
- /* Only this version is kept there. */
34
- for (const name of readdirSync(join(app, ARCHIVES))) if (name !== archiveName(lock.version)) rmSync(join(app, ARCHIVES, name), { force: true });
44
+ /* Only this version of it is kept there (fetchToolArchives keeps each tool's). */
45
+ if (keep) for (const name of readdirSync(join(app, ARCHIVES))) if (name.startsWith(`${pkg}-`) && name !== archiveName(lock.version, pkg)) rmSync(join(app, ARCHIVES, name), { force: true });
35
46
  writeFileSync(`${to}.new`, bytes);
36
47
  renameSync(`${to}.new`, to);
37
48
  return { file: to, version: lock.version, fetched: true };
@@ -41,7 +52,6 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
41
52
  const argv = process.argv.slice(2);
42
53
  const value = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; };
43
54
  try {
44
- const done = await fetchParleyArchive({ app: value('--app') ?? APP, registry: value('--registry') ?? REGISTRY });
45
- console.log(`parley: ${done.file}${done.fetched ? '' : ' (already there)'}`);
55
+ for (const done of await fetchToolArchives({ app: value('--app') ?? APP, registry: value('--registry') ?? REGISTRY })) console.log(`archive: ${done.file}${done.fetched ? '' : ' (already there)'}`);
46
56
  } catch (error) { console.error(`parley-archive: ${error.message}`); process.exitCode = 1; }
47
57
  }
@@ -26,12 +26,12 @@
26
26
  * A RELEASE IS MADE (prepare) in a folder of its own, beside the one that runs:
27
27
  * 1. npm installs clavarium@<version> with no script run, from the registry;
28
28
  * 2. checked: the integrity npm recorded is the registry's; Clavarium and
29
- * Parley each carry a provenance statement whose subject is that very
29
+ * Parley and Docket each carry a provenance statement whose subject is that very
30
30
  * archive and whose source is their repository on GitHub (REPOS); and
31
31
  * `npm audit signatures` checks the registry's signatures and those
32
32
  * statements' own signatures, for every package installed;
33
33
  * 3. only then the build scripts run (npm rebuild: node-pty is compiled),
34
- * Parley's archive for the machines is fetched and checked
34
+ * the archives of the machines' tools are fetched and checked
35
35
  * (parley-archive.mjs), and the server's own smoke test runs
36
36
  * (server/smoke.mjs). Anything wrong: the folder goes, nothing changed.
37
37
  *
@@ -53,7 +53,7 @@ import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync
53
53
  import { dirname, join, basename } from 'node:path';
54
54
  import { tmpdir } from 'node:os';
55
55
  import { fileURLToPath } from 'node:url';
56
- import { fetchParleyArchive, REGISTRY } from './parley-archive.mjs';
56
+ import { fetchToolArchives, REGISTRY } from './parley-archive.mjs';
57
57
  import { ensureTunnel, tunnelUnit, relayOfUnit, TUNNEL_UNIT, TUNNEL_PROGRAM } from './tunnel.mjs';
58
58
  /* The updater's run keeps the tunnel up to date: the same functions, from here too. */
59
59
  export { ensureTunnel, tunnelUnit, relayOfUnit, TUNNEL_UNIT, TUNNEL_PROGRAM };
@@ -61,7 +61,7 @@ export { ensureTunnel, tunnelUnit, relayOfUnit, TUNNEL_UNIT, TUNNEL_PROGRAM };
61
61
  export const PATHS = { code: '/opt/clavarium', conf: '/etc/clavarium/update.conf', stateDir: '/var/lib/clavarium/update', data: '/home/clavarium', host: '/usr/local/sbin/clavarium-host', gitRead: '/usr/lib/clavarium/git-read', tunnel: '/usr/local/sbin/clavarium-tunnel' };
62
62
  export const NAME = 'clavarium';
63
63
  /* Where each package checked here must have been built: its provenance says so. */
64
- export const REPOS = { clavarium: 'https://github.com/clavarium/clavarium', 'clavarium-parley': 'https://github.com/clavarium/clavarium-parley' };
64
+ export const REPOS = { clavarium: 'https://github.com/clavarium/clavarium', 'clavarium-parley': 'https://github.com/clavarium/clavarium-parley', 'clavarium-docket': 'https://github.com/clavarium/clavarium-docket' };
65
65
  export const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9A-Za-z.-]{1,40})?$/;
66
66
  export const LOCAL = /^local-\d{8}-\d{6}$/;
67
67
  export const MODES = ['auto', 'asap', 'ask', 'off'];
@@ -411,7 +411,7 @@ export class Updater {
411
411
  /* The build scripts run now, checked first: node-pty is compiled for this release's Node.js. */
412
412
  const built = await this.#npm(['rebuild', '--no-audit', '--no-fund'], { cwd: version ? tmp : app, nodeDir });
413
413
  if (built.code !== 0) throw new Error(`the build failed (npm rebuild): ${lastLine(built)}`);
414
- await fetchParleyArchive({ app, registry: this.#o.registry, fetcher: this.#fetch });
414
+ await fetchToolArchives({ app, registry: this.#o.registry, fetcher: this.#fetch });
415
415
  if (version) symlinkSync(join('node_modules', NAME), join(tmp, 'app'));
416
416
  this.#step(action, id, 'Testing');
417
417
  const smoke = await this.#run([join(nodeDir, 'bin', 'node'), join(app, 'server', 'smoke.mjs')], { cwd: app, env: this.#npmEnv(nodeDir), timeoutMs: 120_000 });
@@ -1,17 +1,18 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.20",
3
+ "version": "0.2.21-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.20",
9
+ "version": "0.2.21-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
- "clavarium-parley": "0.13.1",
14
+ "clavarium-docket": "0.1.0-next.2",
15
+ "clavarium-parley": "0.13.2-next.1",
15
16
  "mermaid": "11.17.2",
16
17
  "node-pty": "^1.1.0",
17
18
  "pdfjs-dist": "6.4.299",
@@ -685,10 +686,23 @@
685
686
  "node": ">=6"
686
687
  }
687
688
  },
689
+ "node_modules/clavarium-docket": {
690
+ "version": "0.1.0-next.2",
691
+ "resolved": "https://registry.npmjs.org/clavarium-docket/-/clavarium-docket-0.1.0-next.2.tgz",
692
+ "integrity": "sha512-g3j0kvessJcdXUPkagSXYetDUIqJvPzTt9RT345rn0xu3bC5HKYpNgUkOhQAPQ2iU0BBfcf5SQlwfE1f3NhXTA==",
693
+ "license": "MIT",
694
+ "bin": {
695
+ "docket": "bin/docket.mjs",
696
+ "docket-mcp": "server/docket.mjs"
697
+ },
698
+ "engines": {
699
+ "node": ">=22"
700
+ }
701
+ },
688
702
  "node_modules/clavarium-parley": {
689
- "version": "0.13.1",
690
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.13.1.tgz",
691
- "integrity": "sha512-E7oWXndo/wWDjmQfNXXjAu7GNOoxzEqVFhPZMvn8jf+xmpKafYowu59FSIYmKSgOiNFgn1hLuRBkEx20yFganw==",
703
+ "version": "0.13.2-next.1",
704
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.13.2-next.1.tgz",
705
+ "integrity": "sha512-+jnrnnKWJeIOlfNZoWQVkl7qydmoE+j4M6YuhjiYjVP0EgrEm7mmcqlGfzaiOcLNMKU47ZLXif1Z4C2vHCeaNg==",
692
706
  "license": "MIT",
693
707
  "bin": {
694
708
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.20",
3
+ "version": "0.2.21-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -44,7 +44,8 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-parley": "0.13.1",
47
+ "clavarium-docket": "0.1.0-next.2",
48
+ "clavarium-parley": "0.13.2-next.1",
48
49
  "mermaid": "11.17.2",
49
50
  "node-pty": "^1.1.0",
50
51
  "pdfjs-dist": "6.4.299",
package/server/api.mjs CHANGED
@@ -299,6 +299,9 @@ export async function handleApi(request, response, conversations, headers, resou
299
299
  if (guided && guide) return send(200, guide.about(decodeURIComponent(guided[1]))), true;
300
300
  const talked = /^\/api\/conversations\/([^/]+)\/talk$/.exec(pathname);
301
301
  if (talked && talk) return send(200, talk.of(decodeURIComponent(talked[1]))), true;
302
+ /* Its docket: the reminders its tool set, the newest events (dockets.mjs). */
303
+ const docketRead = /^\/api\/conversations\/([^/]+)\/docket$/.exec(pathname);
304
+ if (docketRead && wakeups) return send(200, wakeups.docketOf(decodeURIComponent(docketRead[1]))), true;
302
305
  const answered = /^\/api\/conversations\/([^/]+)\/answerer\/log$/.exec(pathname);
303
306
  if (answered && answerer) return send(200, answerer.log(decodeURIComponent(answered[1]))), true;
304
307
  /* A repository: where its commits go, and what would go now. */
@@ -436,6 +439,11 @@ export async function handleApi(request, response, conversations, headers, resou
436
439
  if (typeof body.on === 'boolean') { const now = await talk.set(conversation, body.on); retell(conversation); return send(200, now), true; }
437
440
  return send(201, await talk.say(conversation, body.text, body.answers, body.files, body.via)), true;
438
441
  }
442
+ const docketed = /^\/api\/conversations\/([^/]+)\/docket(\/cancel)?$/.exec(pathname);
443
+ if (docketed && wakeups) {
444
+ const conversation = decodeURIComponent(docketed[1]);
445
+ if (docketed[2]) return send(200, wakeups.cancelReminder(conversation, body.plan)), true;
446
+ }
439
447
  const woken = /^\/api\/conversations\/([^/]+)\/wakeups(?:\/([0-9a-f-]{36})(\/remove)?)?$/.exec(pathname);
440
448
  if (woken && wakeups) {
441
449
  const conversation = decodeURIComponent(woken[1]);
@@ -0,0 +1,149 @@
1
+ /* DOCKET, AS CLAVARIUM USES IT (clavarium-docket, a project of its own, an npm
2
+ * dependency installed in every machine as Parley is: toolbox.mjs).
3
+ *
4
+ * WHAT WAKES A TOOL IS AN EVENT IT ACKNOWLEDGES, where its chat is on: a
5
+ * wake-up (wakeups.mjs) posts one to its docket instead of typing its line,
6
+ * and one line is typed instead -- WAKE, 'You have something to handle: run
7
+ * "docket".' The tool lists what waits, does it, and says done or failed.
8
+ * Where the chat is off, a wake-up types its line as before.
9
+ *
10
+ * NOTHING IS LOST: an event not acknowledged is told again, when the tool is
11
+ * idle (its pulse, Parley's, says it is not in a turn), every AGAIN_MS, at
12
+ * most TOLD_MAX times; then its chat says it was not handled.
13
+ *
14
+ * THE TOOL'S OWN REMINDERS (docket remind --at/--in/--cron) are turned into
15
+ * events here (tick), and told the same way. Its owner sees them in the
16
+ * conversation's settings, and may take one back.
17
+ *
18
+ * ITS CHAT SAYS what was handled, what failed (and why: the owner is alerted)
19
+ * and what was never handled; a reminder the tool set is a trace.
20
+ *
21
+ * The folder is the work folder's .docket, beside .parley: the tool writes
22
+ * there, so nothing in it is trusted (the library bounds and cleans it).
23
+ */
24
+ import { mkdirSync, lstatSync } from 'node:fs';
25
+ import { Docket, WAKE } from 'clavarium-docket/host';
26
+
27
+ export { WAKE };
28
+ export const FOLDER = '.docket';
29
+ export const TICK_MS = 5000;
30
+ /* An event not acknowledged is told again after this long, the tool idle... */
31
+ export const AGAIN_MS = 30 * 60_000;
32
+ /* ...this many times at most (the first included); then its chat says so. */
33
+ export const TOLD_MAX = 3;
34
+
35
+ export class Dockets {
36
+ #resources; #store; #say; #event; #alert; #idle; #awake; #chatOn; #now; #every; #zone;
37
+ #listening = new Map(); #zoned = new Set(); #busy = false;
38
+
39
+ /* `say(name, line)`: types one line into its terminal (true when typed). `event(name, line)`: a line
40
+ in its chat (Talk.event). `alert({title, body, url})`: the owner's devices. `idle(name)`: not in a
41
+ turn (its pulse). `awake()`: the conversations whose machine runs. `chatOn(name)`. `now()`: ms. */
42
+ /* `zone`: the time zone the tool's times are read in -- this server's, as its wake-ups' (a machine runs in UTC). */
43
+ constructor({ store, resources, say, event = () => {}, alert = () => {}, idle = () => true, awake = () => [], chatOn = () => false, now = () => Date.now(), listenEveryMs = 2000,
44
+ zone = Intl.DateTimeFormat().resolvedOptions().timeZone }) {
45
+ this.#zone = zone; this.#store = store; this.#resources = resources; this.#say = say; this.#event = event; this.#alert = alert; this.#idle = idle; this.#awake = awake; this.#chatOn = chatOn; this.#now = now; this.#every = listenEveryMs;
46
+ }
47
+
48
+ #dir(name) { return `${this.#resources.workFolder(name)}/${FOLDER}`; }
49
+ /* Its folder, made when missing; refused when it is anything but a folder of its own (the tool may have put a link there). */
50
+ #ready(name) {
51
+ const dir = this.#dir(name);
52
+ const info = lstatSync(dir, { throwIfNoEntry: false });
53
+ if (info === undefined) mkdirSync(dir);
54
+ else if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`${FOLDER} in its work folder is not a folder of its own`);
55
+ return dir;
56
+ }
57
+ #docket(name) {
58
+ const d = new Docket(this.#ready(name), { now: this.#now, on: (e) => this.#heard(name, e) });
59
+ if (!this.#zoned.has(name)) { try { d.zone(this.#zone); } catch { /* not a zone: the machine's */ } this.#zoned.add(name); }
60
+ return d;
61
+ }
62
+ #line(name, line) { try { this.#event(name, line); } catch { /* its chat may be off */ } }
63
+
64
+ /* Does a wake-up of this conversation go through its docket? */
65
+ on(name) { return this.#chatOn(name) === true; }
66
+
67
+ /* A wake-up: posted, and told at the next tick. Resolves with the event. */
68
+ post(name, { kind, text, data }) {
69
+ const event = this.#docket(name).post({ from: 'clavarium', kind, text, data });
70
+ this.#listen(name);
71
+ return event;
72
+ }
73
+
74
+ /* For the owner: the tool's reminders (each with when it is next due, or taken back) and the newest events. */
75
+ of(name) {
76
+ if (!this.on(name)) return { on: false, plans: [], events: [] };
77
+ let s;
78
+ try { s = this.#docket(name).read(); } catch { return { on: true, plans: [], events: [] }; }
79
+ const told = this.#store.get(name)?.told ?? {};
80
+ return {
81
+ on: true,
82
+ plans: s.plans.filter((p) => !p.off && p.next !== null && !(p.due !== undefined && s.events.some((e) => e.plan === p.id))).map((p) => ({ id: p.id, text: p.text, cron: p.cron ?? null, next: new Date(p.next).toISOString(), tz: p.tz })),
83
+ events: s.events.slice(-20).reverse().map((e) => ({ id: e.id, at: e.at, from: e.from, kind: e.kind, text: e.text, state: e.state, ...(e.ack ? { note: e.ack.note } : {}), told: told[e.id]?.count ?? 0 })),
84
+ waiting: s.waiting,
85
+ };
86
+ }
87
+ /* The owner takes back a reminder of the tool. */
88
+ cancel(name, plan) {
89
+ const d = this.#docket(name);
90
+ if (!d.read().plans.some((p) => p.id === plan)) return false;
91
+ d.cancel(plan);
92
+ return true;
93
+ }
94
+
95
+ #listen(name) { if (!this.#listening.has(name)) { try { this.#listening.set(name, this.#docket(name).listen({ every: this.#every })); } catch { /* not there yet */ } } }
96
+ stop() { for (const off of this.#listening.values()) off(); this.#listening.clear(); }
97
+
98
+ /* What the tool did: said in its chat; a failure alerts its owner. */
99
+ #heard(name, e) {
100
+ if (e.type === 'acked' && e.ack.kind === 'done') this.#line(name, { kind: 'docket-done', text: `Handled: ${e.event.text}${e.ack.note ? ` -- ${e.ack.note}` : ''}`, topic: 'Handled', brief: e.event.text.slice(0, 60) });
101
+ if (e.type === 'acked' && e.ack.kind === 'failed') {
102
+ this.#line(name, { kind: 'docket-failed', text: `Could not be handled: ${e.event.text} -- ${e.ack.note}`, tone: 'warn', topic: 'Not handled' });
103
+ try { this.#alert({ title: `${name}: could not be handled`, body: `${e.event.text}: ${e.ack.note}`, url: `/?c=${name}` }); } catch { /* as said */ }
104
+ }
105
+ if (e.type === 'planned') this.#line(name, { kind: 'docket-reminder', text: `Reminder set by the tool: ${e.plan.text} (${e.plan.cron ? `"${e.plan.cron}", next ` : ''}${new Date(e.plan.next ?? e.plan.due).toISOString().slice(0, 16).replace('T', ' ')} UTC)`, topic: 'Reminder' });
106
+ }
107
+
108
+ /* Every few seconds: the reminders due posted; what waits told, or told again; what was never handled said. */
109
+ async tick() {
110
+ if (this.#busy) return;
111
+ this.#busy = true;
112
+ try {
113
+ const now = this.#now();
114
+ for (const name of this.#awake()) {
115
+ if (!this.on(name)) continue;
116
+ let d;
117
+ try { d = this.#docket(name); } catch { continue; }
118
+ this.#listen(name);
119
+ try { d.tick(now); } catch { /* a folder that cannot be written: nothing posted */ }
120
+ const waiting = d.read().events.filter((e) => e.state === 'waiting');
121
+ const record = this.#store.get(name) ?? { name, told: {} };
122
+ const told = Object.fromEntries(Object.entries(record.told ?? {}).filter(([id]) => waiting.some((e) => e.id === id)));
123
+ const due = waiting.filter((e) => {
124
+ const t = told[e.id];
125
+ return !t || (t.count < TOLD_MAX && now - t.at >= AGAIN_MS);
126
+ });
127
+ /* Told again only while it is not in a turn: a busy tool reads its docket when its turn ends. */
128
+ const fresh = due.filter((e) => !told[e.id]);
129
+ if (due.length && (fresh.length || this.#idle(name))) {
130
+ if (await this.#say(name, WAKE).catch(() => false)) for (const e of due) told[e.id] = { count: (told[e.id]?.count ?? 0) + 1, at: now };
131
+ }
132
+ for (const e of waiting) {
133
+ const t = told[e.id];
134
+ if (t && t.count >= TOLD_MAX && !t.said && now - t.at >= AGAIN_MS) {
135
+ this.#line(name, { kind: 'docket-unhandled', text: `Not handled, told ${t.count} times: ${e.text}`, tone: 'warn', topic: 'Not handled' });
136
+ t.said = true;
137
+ }
138
+ }
139
+ if (JSON.stringify(told) !== JSON.stringify(record.told ?? {})) this.#store.put({ ...record, told });
140
+ }
141
+ } finally { this.#busy = false; }
142
+ }
143
+
144
+ start(everyMs = TICK_MS) {
145
+ const timer = setInterval(() => { void this.tick(); }, everyMs);
146
+ timer.unref?.();
147
+ return timer;
148
+ }
149
+ }
@@ -262,7 +262,8 @@ export class GitKeeper {
262
262
  settings: this.settings(r.name),
263
263
  auto,
264
264
  origin: hasRemote ? { path: `/resources/${folder}`, kept: this.#resources.hasOrigin(r.name), ...(record.mirror ?? {}) } : null,
265
- checks: this.#results.get(r.name) ?? null,
265
+ /* The newest checks of the repository, whatever their target. */
266
+ checks: [...(this.#results.get(r.name)?.values() ?? [])].sort((x, y) => String(y.at ?? '').localeCompare(String(x.at ?? '')))[0] ?? null,
266
267
  last: this.lastChecks(r.name),
267
268
  read: record.lastRead ?? null,
268
269
  blocked: Object.keys(record.blocked ?? {}),
@@ -485,7 +486,10 @@ export class GitKeeper {
485
486
  async #check(name, seen, machine) {
486
487
  const s = this.settings(name);
487
488
  const result = await this.#checks.run(name, { head: seen.head, branch: seen.branch, target: seen.target, remoteTip: seen.remoteTip, remote: this.#review.remoteOf(name), command: s.checkCommand, hook: s.runHook, seconds: s.checkSeconds, ...(machine ? { machine } : {}) });
488
- this.#results.set(name, result);
489
+ /* One result per target: two branches of the repository, checked one after the other, each keep theirs. */
490
+ const byTarget = this.#results.get(name) ?? new Map();
491
+ byTarget.set(String(result.target ?? seen.target ?? ''), result);
492
+ this.#results.set(name, byTarget);
489
493
  this.#keepLast(name, result);
490
494
  return result;
491
495
  }
@@ -524,8 +528,9 @@ export class GitKeeper {
524
528
  async send(name, body) {
525
529
  const r = this.#repository(name);
526
530
  if (this.settings(r.name).requireForSend) {
527
- const last = this.#results.get(r.name);
528
531
  const target = body?.target || undefined;
532
+ const kept = [...(this.#results.get(r.name)?.values() ?? [])];
533
+ const last = target !== undefined ? this.#results.get(r.name)?.get(target) : kept.find((x) => x.head === body?.head);
529
534
  if (!last || last.status !== 'passed' || last.head !== body?.head || (target !== undefined && last.target !== target)) {
530
535
  throw new Refusal(409, 'Passing checks are required before sending: run the checks for this commit first.');
531
536
  }
package/server/guide.mjs CHANGED
@@ -118,6 +118,8 @@ export function ownText({ name, tool, workKept, resources = [], chat, online, se
118
118
  : '- Chat with the person: on. Parley is installed: run parley guide. When you were given Parley as your own tools (MCP: tell, ask, doing, status...), use them to talk to the person, and say with doing what you do at each new step; the parley command does the same.');
119
119
  /* How Parley is used is Parley's to say (parley guide); what is here is this chat's: it renders Markdown. */
120
120
  if (chat) out.push('- The chat shows Markdown (lists, tables, "> [!IMPORTANT]") and pictures of /work: ![before](/work/a.png).');
121
+ /* Its docket (dockets.mjs): what wakes it waits there until it says done or failed. */
122
+ if (chat) out.push('- What wakes you (a file arrived, the clock, a call) waits in your docket: when told "run docket", run it, do each, then docket done ID or docket failed ID "why". To be reminded later: docket remind --at "2026-10-23 09:00" (or --in 2h, --cron "0 9 * * 1") "what for". docket --help says all.');
121
123
  out.push(online === false ? '- Internet: off.' : '- Internet: on.');
122
124
  if (secrets.length) out.push(`- Secrets given, by name only: ${list(secrets.map((s) => plain(s, 40)))}.`);
123
125
  const own = lines.map((l) => plain(l)).filter(Boolean).slice(0, LINES_MAX);
package/server/main.mjs CHANGED
@@ -37,6 +37,8 @@ import { Vault } from './vault.mjs';
37
37
  import { Secrets, RUNNER } from './secrets.mjs';
38
38
  import { Network } from './network.mjs';
39
39
  import { Answerer, answererConfig } from './answerer.mjs';
40
+ import { Dockets } from './dockets.mjs';
41
+ import { PULSE_MS } from 'clavarium-parley/ui';
40
42
  import { Wakeups, CALL_PATH } from './wakeups.mjs';
41
43
  import { Alerts } from './alerts.mjs';
42
44
  import { Talk } from './talk.mjs';
@@ -357,9 +359,18 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
357
359
  /* A tool is told to get to work when something arrives, or by the clock: see wakeups.mjs. */
358
360
  let bridge;
359
361
  /* A wake-up typed is said in its chat (talk, made below: called only once a wake-up fires). */
360
- const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => bridge?.warm(name),
362
+ /* Where its chat is on, what wakes a tool is an event it acknowledges: see dockets.mjs. */
363
+ const dockets = new Dockets({ store: new Store(`${dataDir}/dockets.json`), resources: folders,
364
+ say: (name, line) => wakeups.say(name, line),
365
+ event: (name, line) => talk.event(name, line),
366
+ alert: (message) => { void alerts.tell({ ...message, title: `${instance.name()}: ${message.title}` }); },
367
+ /* Not in a turn: its pulse ended, or is old (Parley's own measure). */
368
+ idle: (name) => { const p = talk.pulse(name); return !(p?.busy === true && Date.now() - Date.parse(p.at) < PULSE_MS); },
369
+ awake: () => all.awake(), chatOn: (name) => talk.isOn(name) });
370
+ const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => bridge?.warm(name), docket: dockets,
361
371
  fired: (name, { text }) => talk.event(name, { kind: 'wakeup', text, topic: 'Wake-up' }) });
362
372
  const wakeTimer = wakeups.start(wakeEveryMs);
373
+ const docketTimer = dockets.start(wakeEveryMs);
363
374
  /* A repository's origin kept up to date, checks run in the machine, and
364
375
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
365
376
  /* What could not be read is told to the agents that write in the repository, where they can act. */
@@ -456,7 +467,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
456
467
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
457
468
  }
458
469
  const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
459
- server.on('close', () => { closing = true; clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
470
+ server.on('close', () => { closing = true; clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
460
471
  let closing = false;
461
472
  bridge = attachBridge(server, {
462
473
  onRejoin: (name) => all.rejoin(name),
package/server/parley.mjs CHANGED
@@ -20,6 +20,14 @@ import { fileURLToPath } from 'node:url';
20
20
  const require = createRequire(import.meta.url);
21
21
  export const APP = fileURLToPath(new URL('..', import.meta.url));
22
22
  export const PARLEY = 'clavarium-parley';
23
+ export const DOCKET = 'clavarium-docket';
24
+ /* THE TOOLS EVERY MACHINE IS GIVEN, each an npm dependency at an exact version, as Parley is:
25
+ installed by this server in every machine (toolbox.mjs), from its archive here. `usage`
26
+ is what /tools/index.json says of it. Adding one is adding a line here and its dependency. */
27
+ export const MACHINE_TOOLS = Object.freeze([
28
+ { name: 'parley', pkg: PARLEY, usage: 'Installed in every machine: parley --help. Talk with the person you work for, on their screen, when their chat is on.' },
29
+ { name: 'docket', pkg: DOCKET, usage: 'Installed in every machine: docket --help. What woke you, waiting until you say done or failed; and reminders you set yourself.' },
30
+ ]);
23
31
 
24
32
  /* Where an installed package is, by the lookup Node itself makes from here
25
33
  (its own node_modules, then each parent's), without asking its "exports":
@@ -39,9 +47,10 @@ export const packageFile = (name, path) => join(packageDir(name), path);
39
47
 
40
48
  export function parleyDir() { return packageDir(PARLEY); }
41
49
  export function parleyVersion(dir = parleyDir()) { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version; }
50
+ export function packageVersion(name, dir = packageDir(name)) { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version; }
42
51
  /* Where its archive for the machines sits, next to the code. */
43
52
  export const ARCHIVES = 'toolbox';
44
- export const archiveName = (version) => `${PARLEY}-${version}.tgz`;
53
+ export const archiveName = (version, pkg = PARLEY) => `${pkg}-${version}.tgz`;
45
54
 
46
55
  /* WHAT NPM RECORDED of a dependency: { version, resolved, integrity } from
47
56
  the lock file of this tree (a working tree, a local install), the
package/server/smoke.mjs CHANGED
@@ -2,7 +2,10 @@
2
2
  * (deploy/updater.mjs), with the Node.js it will run on. It touches no data
3
3
  * and starts nothing: every module loads, the files the page asks for are
4
4
  * there, the terminal module (compiled on this machine) opens a terminal,
5
- * and Parley's archive for the machines is the one npm recorded.
5
+ * and the archive of each machine tool (Parley, Docket) is the one npm
6
+ * recorded. An archive missing is fetched first, checked the same way: an
7
+ * updater older than a tool (0.2.14 fetched Parley's alone) runs this test
8
+ * of the release it makes, so the release is whole whoever made it.
6
9
  *
7
10
  * node server/smoke.mjs exit 0 and "smoke: ok <version>", or 1 and why
8
11
  */
@@ -13,8 +16,14 @@ const fail = (why) => { console.error(`smoke: ${why}`); process.exit(1); };
13
16
  try {
14
17
  const { FILES } = await import('./main.mjs');
15
18
  for (const [path, [file]] of Object.entries(FILES)) for (const f of [file].flat()) if (!existsSync(f.startsWith('/') ? f : new URL(`../${f}`, import.meta.url))) fail(`${path}: ${f} is missing`);
16
- const { parleySource } = await import('./toolbox.mjs');
17
- if (parleySource().length !== 1) fail("Parley's archive for the machines is missing, or not the one npm recorded");
19
+ const { toolSources } = await import('./toolbox.mjs');
20
+ const { MACHINE_TOOLS } = await import('./parley.mjs');
21
+ if (toolSources().length !== MACHINE_TOOLS.length) {
22
+ const { fetchToolArchives } = await import('../deploy/parley-archive.mjs');
23
+ await fetchToolArchives();
24
+ }
25
+ const given = toolSources().map((s) => s.name);
26
+ for (const tool of MACHINE_TOOLS) if (!given.includes(tool.name)) fail(`the archive of ${tool.name} for the machines is missing, or not the one npm recorded`);
18
27
  const pty = createRequire(import.meta.url)('node-pty');
19
28
  await new Promise((done, broken) => {
20
29
  const term = pty.spawn('/bin/sh', ['-c', 'exit 0'], { cols: 80, rows: 24, env: { PATH: '/usr/bin:/bin' } });
package/server/talk.mjs CHANGED
@@ -127,6 +127,11 @@ export const EVENT_LEVELS = Object.freeze({
127
127
  restarted: 'news',
128
128
  /* New tools in its machine that its tool reads only when it starts: a restart recommended (main.mjs). */
129
129
  'tools-updated': 'news',
130
+ /* Its docket (dockets.mjs): what it handled, what it could not, what it never did; a reminder it set itself. */
131
+ 'docket-done': 'news',
132
+ 'docket-failed': 'needs-you',
133
+ 'docket-unhandled': 'needs-you',
134
+ 'docket-reminder': 'trace',
130
135
  });
131
136
  const TONES = ['warn', 'bad'];
132
137
  /* Bounds of a line: its text, its group (topic), what the grouped line says of it (brief), its buttons. */
@@ -289,6 +294,15 @@ export class Talk {
289
294
  } catch { return { waiting: 0, state: null }; }
290
295
  }
291
296
 
297
+ /* Is its chat on? (cheap: the record alone) */
298
+ isOn(name) { return this.#store.get(name)?.on === true; }
299
+
300
+ /* Its tool's pulse (Parley): { busy, at }, or null. Where the chat is off: null. */
301
+ pulse(name) {
302
+ if (this.#store.get(name)?.on !== true) return null;
303
+ try { return this.#parley(name).read().pulse ?? null; } catch { return null; }
304
+ }
305
+
292
306
  async set(name, on) {
293
307
  const c = this.#known(name);
294
308
  if (on === true) {
@@ -2,7 +2,7 @@
2
2
  *
3
3
  * An archive per tool, and an index that says what each one is.
4
4
  *
5
- * PARLEY IS INSTALLED BY THIS SERVER, never by the agent (decided after an
5
+ * PARLEY AND DOCKET (MACHINE_TOOLS, parley.mjs) ARE INSTALLED BY THIS SERVER, never by the agent (decided after an
6
6
  * agent rightly refused to install "code it had not checked"): in every
7
7
  * machine, at each start of its tool when it is missing or not the version
8
8
  * of the index, chat on or off. Its archive's sha256, as the machine reads
@@ -17,7 +17,7 @@
17
17
  * /tools/CLAVARIUM.md where a tool is, the same for every
18
18
  * machine (see guide.mjs): `notes`
19
19
  *
20
- * Adding a tool is putting its archive in SOURCES with one line of usage.
20
+ * Adding a tool is a line of MACHINE_TOOLS and its dependency.
21
21
  *
22
22
  * THE FOLDER IS KEPT BY THIS SERVER and shown in each machine through a
23
23
  * read-only view made by the host program ("tools make": the same bindfs
@@ -29,7 +29,7 @@ import { createHash } from 'node:crypto';
29
29
  import { readFileSync, writeFileSync, readdirSync, renameSync, rmSync, existsSync, mkdirSync } from 'node:fs';
30
30
  import { join } from 'node:path';
31
31
  import { fileURLToPath } from 'node:url';
32
- import { APP, ARCHIVES, PARLEY, archiveName, locked, parleyDir, parleyVersion } from './parley.mjs';
32
+ import { APP, ARCHIVES, MACHINE_TOOLS, archiveName, locked, packageDir, packageVersion } from './parley.mjs';
33
33
 
34
34
  export const TOOLS_PATH = '/tools';
35
35
  export const NOTES = 'CLAVARIUM.md';
@@ -41,17 +41,21 @@ export const LAUNCHERS = fileURLToPath(new URL('../config/launch', import.meta.u
41
41
  parley.mjs), with the integrity npm recorded for the version installed:
42
42
  prepare() refuses an archive that is not that one. Missing, it is said
43
43
  once and nothing is offered: no machine gets a Parley nobody checked. */
44
- export function parleySource({ app = APP, dir } = {}) {
44
+ export function toolSource(tool, { app = APP, dir } = {}) {
45
45
  let version;
46
- try { version = parleyVersion(dir ?? parleyDir()); } catch (error) { console.error(`Parley: ${error.message}`); return []; }
47
- const archive = join(app, ARCHIVES, archiveName(version));
48
- if (!existsSync(archive)) { console.error(`Parley: ${archive} is missing (npm run toolbox): no machine is given Parley`); return []; }
49
- const lock = locked(PARLEY, app);
50
- if (lock?.version !== version) { console.error(`Parley: the lock file does not record version ${version}: no machine is given Parley`); return []; }
51
- return [{ name: 'parley', archive, integrity: lock.integrity, usage: () => 'Installed in every machine: parley --help. Talk with the person you work for, on their screen, when their chat is on.' }];
46
+ try { version = packageVersion(tool.pkg, dir ?? packageDir(tool.pkg)); } catch (error) { console.error(`${tool.name}: ${error.message}`); return []; }
47
+ const archive = join(app, ARCHIVES, archiveName(version, tool.pkg));
48
+ if (!existsSync(archive)) { console.error(`${tool.name}: ${archive} is missing (npm run toolbox): no machine is given it`); return []; }
49
+ const lock = locked(tool.pkg, app);
50
+ if (lock?.version !== version) { console.error(`${tool.name}: the lock file does not record version ${version}: no machine is given it`); return []; }
51
+ return [{ name: tool.name, archive, integrity: lock.integrity, usage: () => tool.usage }];
52
52
  }
53
+ /* Every tool of MACHINE_TOOLS whose archive is here and checked. */
54
+ export const toolSources = (options = {}) => MACHINE_TOOLS.flatMap((tool) => toolSource(tool, options));
55
+ export const parleySource = (options = {}) => toolSource(MACHINE_TOOLS.find((t) => t.name === 'parley'), options);
53
56
 
54
57
  /* "sha512-<base64>", as npm writes an integrity. */
58
+ const NO_NPM = 'there is no npm in this machine';
55
59
  export const integrityOf = (bytes) => `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
56
60
 
57
61
  const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
@@ -69,7 +73,7 @@ export class Toolbox {
69
73
  may be in it: every machine reads it. */
70
74
  /* `launched`: a Store of what each tool was started with (its launchers' fingerprint): see stale(). */
71
75
  /* `launches(name)`: does its tool start through a launcher? (only those read one) */
72
- constructor({ host, vms, mntDir, uid = process.getuid(), gid = process.getgid(), sources = parleySource(), notes = null, launchers = LAUNCHERS, launched = null, launches = () => false }) {
76
+ constructor({ host, vms, mntDir, uid = process.getuid(), gid = process.getgid(), sources = toolSources(), notes = null, launchers = LAUNCHERS, launched = null, launches = () => false }) {
73
77
  this.#launched = launched; this.#launches = launches;
74
78
  this.#host = host; this.#vms = vms; this.#mnt = mntDir; this.#uid = uid; this.#gid = gid; this.#sources = sources; this.#notes = notes; this.#launchers = launchers;
75
79
  }
@@ -162,20 +166,27 @@ export class Toolbox {
162
166
  /* Its machine was built again, or restarted: looked at again at its next opening. */
163
167
  forget(conversation) { this.#installed.delete(conversation); }
164
168
 
169
+ /* Each tool of MACHINE_TOOLS in the index, in turn: '' when all are there, else why the first was not. */
165
170
  async #install(conversation) {
166
- const tool = this.find('parley');
167
- if (!tool) return 'the tools folder is not in place';
171
+ if (!this.ready) return 'the tools folder is not in place';
172
+ const tools = MACHINE_TOOLS.map((t) => this.find(t.name)).filter(Boolean);
173
+ if (tools.length === 0) return 'the tools folder is not in place';
174
+ const sha256 = tools.map((t) => t.sha256).join(' ');
168
175
  const known = this.#installed.get(conversation);
169
- if (known?.sha256 === tool.sha256) return known.why;
176
+ if (known?.sha256 === sha256) return known.why;
177
+ let why = '';
178
+ for (const tool of tools) { why = await this.#installOne(conversation, tool); if (why) break; }
179
+ /* Known once it is said: there, or why not (a machine without npm); a failure on the way is asked again. */
180
+ if (why === '' || why === NO_NPM) this.#installed.set(conversation, { sha256, why });
181
+ return why;
182
+ }
183
+
184
+ async #installOne(conversation, tool) {
170
185
  const exec = (argv, timeoutMs = 30_000) => this.#vms.exec(conversation, argv, { timeoutMs }).catch(() => ({ code: 1, stdout: '', stderr: '' }));
171
- const there = async () => { const v = await exec(['parley', '--version']); return v.code === 0 && v.stdout.trim() === tool.version; };
172
- if (await there()) { this.#installed.set(conversation, { sha256: tool.sha256, why: '' }); return ''; }
173
- if ((await exec(['which', 'npm'])).code !== 0) {
174
- /* A machine without node (a plain shell): said once, until it is built again or restarted. */
175
- const why = 'there is no npm in this machine';
176
- this.#installed.set(conversation, { sha256: tool.sha256, why });
177
- return why;
178
- }
186
+ const there = async () => { const v = await exec([tool.name, '--version']); return v.code === 0 && v.stdout.trim() === tool.version; };
187
+ if (await there()) return '';
188
+ /* A machine without node (a plain shell): said once, until it is built again or restarted. */
189
+ if ((await exec(['which', 'npm'])).code !== 0) return NO_NPM;
179
190
  /* The archive as the machine reads it, against the index; /tools mounted again once if it is not there. */
180
191
  const sum = async () => /^([0-9a-f]{64})\s/.exec((await exec(['sha256sum', '--', tool.path], 60_000)).stdout ?? '')?.[1];
181
192
  let seen = await sum();
@@ -184,8 +195,7 @@ export class Toolbox {
184
195
  if (seen !== tool.sha256) return `${tool.path} in the machine is not the archive of the index (sha256 differs): not installed`;
185
196
  const r = await exec(['sudo', '-n', 'npm', 'install', '-g', '--offline', '--no-audit', '--no-fund', tool.path], 180_000);
186
197
  if (r.code !== 0) return `npm: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`;
187
- if (!(await there())) return 'installed, but "parley --version" does not say the version of the index';
188
- this.#installed.set(conversation, { sha256: tool.sha256, why: '' });
198
+ if (!(await there())) return `installed, but "${tool.name} --version" does not say the version of the index`;
189
199
  return '';
190
200
  }
191
201
 
@@ -14,6 +14,9 @@
14
14
  * What is then done is small: a MESSAGE THE OWNER WROTE is typed into the
15
15
  * tool's terminal, followed by Enter. Nothing is run, nothing is decided
16
16
  * here; the tool does what it would do had its owner typed that line.
17
+ * Where its chat is on, the message is posted to its DOCKET instead, as an
18
+ * event it acknowledges, and it is told so in one line (dockets.mjs): told
19
+ * again until it says done or failed.
17
20
  *
18
21
  * What holds it:
19
22
  * - the message is the owner's. The only thing that is not, the names of
@@ -131,17 +134,36 @@ const FIRED_SHOWN = 120;
131
134
  const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
132
135
 
133
136
  export class Wakeups {
134
- #store; #vms; #conversations; #resources; #warm; #now; #fired; #held = new Map(); #busy = false;
137
+ #store; #vms; #conversations; #resources; #warm; #now; #fired; #docket; #held = new Map(); #busy = false;
135
138
 
136
139
  /* `warm(name)`: opens the terminal of a machine that runs, if it is not open.
137
140
  `fired(name, { text, item })`: a wake-up was typed (its chat says so: Talk.event). */
138
- constructor({ store, vms, conversations, resources, warm = async () => {}, now = () => new Date(), fired = () => {} }) {
139
- this.#store = store; this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#warm = warm; this.#now = now; this.#fired = fired;
141
+ /* `docket`: { on(name), post(name, {kind, text, data}) } (dockets.mjs), or none: typed always. */
142
+ constructor({ store, vms, conversations, resources, warm = async () => {}, now = () => new Date(), fired = () => {}, docket = null }) {
143
+ this.#store = store; this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#warm = warm; this.#now = now; this.#fired = fired; this.#docket = docket;
144
+ }
145
+ /* Where its chat is on, posted to its docket (told at its next tick); else typed. Resolves with what to say of it, and whether it went. */
146
+ async #deliver(name, item, text) {
147
+ if (this.#docket?.on(name)) {
148
+ try { this.#docket.post(name, { kind: item.kind, text, data: { wakeup: item.id } }); return { ok: true, what: `Posted to its docket: ${text}` }; } catch { /* its folder: typed instead */ }
149
+ }
150
+ const typed = await this.#type(name, text).catch(() => false);
151
+ return { ok: typed, what: typed ? `Typed: ${text}` : 'Could not be typed: is its tool running?' };
140
152
  }
141
153
  /* What its chat says of a wake-up that was typed: the line, cut short. Never stops a wake-up. */
142
- #said(name, item, line) {
154
+ #said(name, item, line, posted = false) {
143
155
  const shown = line.length > FIRED_SHOWN ? `${line.slice(0, FIRED_SHOWN - 3)}...` : line;
144
- try { this.#fired(name, { text: `Wake-up "${shown}" typed.`, item: { id: item.id, kind: item.kind } }); } catch { /* as said */ }
156
+ try { this.#fired(name, { text: `Wake-up "${shown}" ${posted ? 'posted to its docket' : 'typed'}.`, item: { id: item.id, kind: item.kind } }); } catch { /* as said */ }
157
+ }
158
+
159
+ /* Its docket, for its owner: the tool's reminders and the newest events (dockets.mjs). */
160
+ docketOf(name) { this.#known(name); return this.#docket?.of(name) ?? { on: false, plans: [], events: [] }; }
161
+ /* The owner takes back a reminder the tool set itself. */
162
+ cancelReminder(name, plan) {
163
+ this.#known(name);
164
+ if (!this.#docket?.on(name)) throw new Refusal(409, 'Its chat is off: it has no docket.');
165
+ if (typeof plan !== 'string' || !this.#docket.cancel(name, plan)) throw new Refusal(404, 'No such reminder.');
166
+ return this.docketOf(name);
145
167
  }
146
168
 
147
169
  #record(name) { return this.#store.get(name) ?? { name, perHour: DEFAULT_PER_HOUR, sent: [], items: [] }; }
@@ -285,11 +307,11 @@ export class Wakeups {
285
307
  const at = this.#now().toISOString();
286
308
  const r = this.#record(record.name);
287
309
  const capped = r.perHour > 0 && this.#recent(r).length >= r.perHour;
288
- const typed = capped ? false : await this.#type(record.name, line).catch(() => false);
289
- const what = capped ? `Not sent: ${r.perHour} wake-up(s) this hour already, the cap you set.` : typed ? `Typed: ${line}` : 'Could not be typed: is its tool running?';
310
+ const went = capped ? { ok: false, what: `Not sent: ${r.perHour} wake-up(s) this hour already, the cap you set.` } : await this.#deliver(record.name, item, line);
311
+ const typed = went.ok; const what = went.what;
290
312
  const again = this.#record(record.name);
291
313
  this.#store.put({ ...again, sent: typed ? [...this.#recent(again), at] : this.#recent(again), items: again.items.map((i) => (i.id === item.id ? { ...i, last: { at, what: what.slice(0, 300), ok: typed } } : i)) });
292
- if (typed) this.#said(record.name, item, line);
314
+ if (typed) this.#said(record.name, item, line, what.startsWith('Posted'));
293
315
  return capped ? 'capped' : typed ? 'typed' : 'failed';
294
316
  }
295
317
  return undefined;
@@ -309,11 +331,11 @@ export class Wakeups {
309
331
  const r = this.#record(record.name);
310
332
  const at = this.#now().toISOString();
311
333
  const capped = r.perHour > 0 && this.#recent(r).length >= r.perHour;
312
- const typed = capped ? false : await this.#type(record.name, text).catch(() => false);
313
- const what = capped ? `Not sent: ${r.perHour} wake-up(s) this hour already, the cap you set.` : typed ? `Typed: ${text}` : 'Could not be typed: is its tool running?';
334
+ const went = capped ? { ok: false, what: `Not sent: ${r.perHour} wake-up(s) this hour already, the cap you set.` } : await this.#deliver(record.name, item, text);
335
+ const typed = went.ok; const what = went.what;
314
336
  const again = this.#record(record.name);
315
337
  this.#store.put({ ...again, sent: typed ? [...this.#recent(again), at] : this.#recent(again), items: again.items.map((i) => (i.id === item.id ? { ...i, last: { at, what: what.slice(0, 300), ok: typed }, ...(i.kind === 'arrival' ? {} : { fired: at }) } : i)) });
316
- if (typed) this.#said(record.name, item, text);
338
+ if (typed) this.#said(record.name, item, text, what.startsWith('Posted'));
317
339
  }
318
340
  }
319
341
  } finally { this.#busy = false; }
package/web/app.js CHANGED
@@ -2550,7 +2550,11 @@
2550
2550
  ['sent-by-hand', 'Sent by hand', 'Sent from the review'],
2551
2551
  ['refused', 'Not sent', 'An automatic sending was refused: what to do'],
2552
2552
  ['origin', 'Origin updated', 'The remote brought commits'],
2553
- ['wakeup', 'Wake-up', 'A wake-up was typed'],
2553
+ ['wakeup', 'Wake-up', 'A wake-up was typed, or posted to its docket'],
2554
+ ['docket-done', 'Handled', 'What woke it, said done by the tool'],
2555
+ ['docket-failed', 'Could not be handled', 'Said failed by the tool, with why'],
2556
+ ['docket-unhandled', 'Not handled', 'Told three times, never said done'],
2557
+ ['docket-reminder', 'Reminder set', 'A reminder the tool set itself'],
2554
2558
  ['machine-problem', 'Machine in trouble', 'Memory, disk, no answer, a failed restart'],
2555
2559
  ['restarted', 'Machine restarted', 'Restarted or built again'],
2556
2560
  ['tools-updated', 'New tools', 'After an update: a restart gives its tool all of them'],
@@ -2671,6 +2675,36 @@
2671
2675
  }
2672
2676
  if (document.activeElement?.id !== 'wakeups-limit') $('wakeups-limit').value = String(mine.perHour);
2673
2677
  $('wakeups-sent').textContent = `${mine.sentThisHour} this hour.`;
2678
+ void paintDocket();
2679
+ }
2680
+ /* Its docket (server/dockets.mjs): the reminders its tool set, which its owner may take back; the newest events. */
2681
+ const DOCKET_STATES = { waiting: 'waits', done: 'done', failed: 'could not be done' };
2682
+ async function paintDocket() {
2683
+ const of = current;
2684
+ const d = DEVICE || !of ? null : await fetch(`${API}/conversations/${encodeURIComponent(of)}/docket`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
2685
+ if (of !== current) return;
2686
+ $('docket-box').hidden = !d?.on;
2687
+ if (!d?.on) return;
2688
+ const plans = $('docket-plans');
2689
+ plans.replaceChildren();
2690
+ for (const p of d.plans) {
2691
+ const row = document.createElement('div'); row.className = 'wakeup'; row.dataset.kind = 'reminder';
2692
+ const what = document.createElement('b'); what.textContent = p.text;
2693
+ const when = document.createElement('p'); when.className = 'hint'; when.textContent = `${p.cron ? `By the clock (${p.cron}), next` : 'Once,'} ${new Date(p.next).toLocaleString()}`;
2694
+ const off = document.createElement('button'); off.type = 'button'; off.textContent = 'Take it back';
2695
+ off.addEventListener('click', async () => { try { await post(`${API}/conversations/${encodeURIComponent(of)}/docket/cancel`, { plan: p.id }); } catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; } void paintDocket(); });
2696
+ const acts = document.createElement('div'); acts.className = 'row'; acts.append(off);
2697
+ row.append(what, when, acts);
2698
+ plans.append(row);
2699
+ }
2700
+ if (d.plans.length === 0) { const none = document.createElement('p'); none.className = 'hint'; none.textContent = 'No reminder set by the tool.'; plans.append(none); }
2701
+ const events = $('docket-events');
2702
+ events.replaceChildren();
2703
+ for (const e of d.events.slice(0, 8)) {
2704
+ const line = document.createElement('p'); line.className = 'hint docket-event'; line.dataset.state = e.state;
2705
+ line.textContent = `${new Date(e.at).toLocaleString()}: ${e.text} -- ${DOCKET_STATES[e.state] ?? e.state}${e.note ? ` (${e.note})` : ''}${e.state === 'waiting' && e.told ? `, told ${e.told} time${e.told > 1 ? 's' : ''}` : ''}`;
2706
+ events.append(line);
2707
+ }
2674
2708
  }
2675
2709
  /* BY THE CLOCK IS ALWAYS A CRON LINE. The few usual choices write it, and
2676
2710
  it stays in sight: what is set is what is shown, and it can be changed. */
@@ -2910,6 +2944,9 @@
2910
2944
  the same target, the same guards). One refused does not hold the
2911
2945
  others back: each says what became of it. */
2912
2946
  const STATE_SAID = { 'up-to-date': 'up to date', diverged: 'behind: its agent must pull first', 'no-remote': 'no remote', unreachable: 'remote not answering', empty: 'empty' };
2947
+ /* How many other branches of a repository are looked at; those moved within this long are ticked at first. */
2948
+ const BRANCHES_MORE = 7;
2949
+ const MOVED_LATELY_MS = 24 * 3600_000;
2913
2950
  async function sendDetail(holder, names) {
2914
2951
  const list = el('div', 'ts-rows'); list.append(el('p', 'hint busy', 'Looking at every repository...'));
2915
2952
  const bar = el('div', 'as-acts ts-bar');
@@ -2919,7 +2956,7 @@
2919
2956
  bar.append(together, go, why);
2920
2957
  const said = el('p', 'ts-said'); said.hidden = true; said.setAttribute('role', 'status');
2921
2958
  const review = el('div', 'ts-review'); review.hidden = true;
2922
- holder.append(el('p', 'hint', 'What its agent committed, in every repository of this conversation. The checks run by themselves.'), list, bar, said, review);
2959
+ holder.append(el('p', 'hint', 'What its agent committed, every branch. Ticked: what it moved lately.'), list, bar, said, review);
2923
2960
  const rows = names.map((name) => ({ name, out: null, keep: null, branch: '', target: '', picked: false, check: null, sent: null }));
2924
2961
  let sending = false;
2925
2962
  let sure = '';
@@ -2933,8 +2970,11 @@
2933
2970
  r.out = out; r.keep = keep; r.branch = out.branch ?? r.branch; r.target = out.target ?? r.target; r.check = null;
2934
2971
  if (out.state !== 'ahead') r.picked = false;
2935
2972
  paint();
2936
- if (out.state === 'ahead') void checkRow(r, out.head, out.target);
2973
+ /* Checked when it is to go: ticked (another branch ticked later is checked then). */
2974
+ if (out.state === 'ahead' && r.picked) void checkRow(r, out.head, out.target);
2937
2975
  }
2976
+ /* Several branches of one repository: named with it. */
2977
+ const label = (r) => (rows.filter((x) => x.name === r.name).length > 1 ? `${r.name} (${r.branch})` : r.name);
2938
2978
  async function checkRow(r, head, target) {
2939
2979
  r.check = { status: 'running' }; paint();
2940
2980
  let result;
@@ -2955,7 +2995,7 @@
2955
2995
  const failed = p.filter((r) => r.check?.status === 'failed');
2956
2996
  const word = p.length > 1 ? `the ${p.length}` : 'it';
2957
2997
  go.disabled = sending || p.length === 0 || running.length > 0 || held.length > 0;
2958
- why.textContent = p.length === 0 ? 'Nothing ticked.' : running.length ? 'Waits for the checks.' : held.length ? `Its owner asked for passing checks: ${held.map((r) => r.name).join(', ')}.` : failed.length ? `Checks failed in ${failed.map((r) => r.name).join(', ')}.` : '';
2998
+ why.textContent = p.length === 0 ? 'Nothing ticked.' : running.length ? 'Waits for the checks.' : held.length ? `Its owner asked for passing checks: ${held.map(label).join(', ')}.` : failed.length ? `Checks failed in ${failed.map(label).join(', ')}.` : '';
2959
2999
  if (sending) { go.textContent = 'Sending...'; return; }
2960
3000
  const all = p.some((r) => r.out?.guards?.confirm);
2961
3001
  go.textContent = sure === 'yes' ? (all ? `Not all of it could be shown here: send ${word}${where} anyway` : `Yes, send ${word}${where}: this cannot be undone`) : sure === 'all' ? `Yes, send ${word}${where}: this cannot be undone` : `Send ${word}${where}${failed.length ? ' anyway' : ''}`;
@@ -2963,23 +3003,16 @@
2963
3003
  function paint() {
2964
3004
  list.replaceChildren();
2965
3005
  for (const r of rows) {
2966
- const row = el('div', 'ts-row'); row.dataset.repo = r.name;
3006
+ const row = el('div', 'ts-row'); row.dataset.repo = r.name; if (r.branch) row.dataset.branch = r.branch;
2967
3007
  const out = r.out;
2968
3008
  const ahead = out?.state === 'ahead';
2969
3009
  row.classList.toggle('off', !ahead);
2970
3010
  const tick = el('input'); tick.type = 'checkbox'; tick.checked = r.picked; tick.disabled = !ahead || sending; tick.setAttribute('aria-label', `Send ${r.name}`);
2971
- tick.addEventListener('change', () => { r.picked = tick.checked; sure = ''; paintButtons(); if (!review.hidden) paintReview(); });
3011
+ tick.addEventListener('change', () => { r.picked = tick.checked; sure = ''; if (r.picked && !r.check && r.out?.state === 'ahead') void checkRow(r, r.out.head, r.out.target); paintButtons(); if (!review.hidden) paintReview(); });
2972
3012
  const who = el('div', 'ts-who'); who.append(el('b', '', r.name), el('small', 'hint', out?.remote ? hostOf(out.remote) : out ? 'no remote' : ''));
2973
3013
  const way = el('div', 'ts-way');
2974
3014
  if (out?.branch) {
2975
- const branches = out.agentBranches ?? [];
2976
- if (branches.length > 1) {
2977
- const pick = el('select'); pick.setAttribute('aria-label', `The branch of ${r.name}`); pick.disabled = sending;
2978
- for (const b of branches) { const o = el('option', '', b.name); o.value = b.name; pick.append(o); }
2979
- pick.value = out.branch;
2980
- pick.addEventListener('change', () => { r.branch = pick.value; r.target = ''; sure = ''; void look(r); });
2981
- way.append(pick);
2982
- } else way.append(el('code', 'ts-branch', out.branch));
3015
+ way.append(el('code', 'ts-branch', out.branch));
2983
3016
  if (['ahead', 'up-to-date', 'diverged'].includes(out.state) && out.target) {
2984
3017
  way.append(el('span', 'ts-arrow', '→'));
2985
3018
  const to = el('select'); to.setAttribute('aria-label', `Where ${r.name} goes`); to.disabled = sending;
@@ -3001,6 +3034,7 @@
3001
3034
  if (r.sent) state.append(el('b', r.sent.ok ? 'ok' : 'bad', r.sent.ok ? r.sent.text : '\u2717 Not sent'));
3002
3035
  else if (!out) state.append('');
3003
3036
  else if (!ahead) state.append(el('span', out.state === 'diverged' || out.state === 'unreachable' || out.state === 'error' ? 'bad' : 'hint', STATE_SAID[out.state] ?? out.message ?? out.state));
3037
+ else if (!r.check && !r.picked) state.append(el('span', 'hint', 'checked once ticked'));
3004
3038
  else if (!r.check || r.check.status === 'running') state.append(el('span', 'warn', 'Checks running...'));
3005
3039
  else {
3006
3040
  const [word, tone] = CHECK_WORDS[r.check.status] ?? [String(r.check.status), ''];
@@ -3039,7 +3073,7 @@
3039
3073
  if (tab === 'changes') {
3040
3074
  const tree = el('div', 'rv-tree ts-tree'); const diffs = el('div', 'rv-diff ts-diffs');
3041
3075
  for (const { r, files } of all) {
3042
- tree.append(el('small', 'ts-tree-repo', r.name));
3076
+ tree.append(el('small', 'ts-tree-repo', label(r)));
3043
3077
  const box = el('div', 'ts-diff'); box.dataset.repo = r.name;
3044
3078
  box.append(el('h4', '', `${r.name}: ${r.out.branch} → ${r.out.target}`));
3045
3079
  const inner = el('div'); box.append(inner);
@@ -3111,10 +3145,17 @@
3111
3145
  paint();
3112
3146
  });
3113
3147
  paint();
3148
+ /* Each repository's branch that moved last, then every other branch of its agent that has something to send. */
3114
3149
  await Promise.all(rows.map(async (r) => { await look(r); }));
3115
- /* Ticked at first: each one with something to send. */
3116
- for (const r of rows) r.picked = r.out?.state === 'ahead';
3150
+ const others = rows.flatMap((r) => (r.out?.agentBranches ?? []).filter((b) => b.name !== r.branch).slice(0, BRANCHES_MORE).map((b) => ({ name: r.name, out: null, keep: r.keep, branch: b.name, target: '', picked: false, check: null, sent: null, movedAt: b.movedAt })));
3151
+ for (const r of rows) r.movedAt = (r.out?.agentBranches ?? []).find((b) => b.name === r.branch)?.movedAt ?? null;
3152
+ await Promise.all(others.map(async (o) => { await look(o); }));
3153
+ for (const o of others) if (o.out?.state === 'ahead') rows.splice(rows.findLastIndex((x) => x.name === o.name) + 1, 0, o);
3154
+ /* Ticked at first: what its agent moved lately -- each repository's newest, and any other moved within a day. */
3155
+ const lately = (r) => r.movedAt && Date.now() - Date.parse(r.movedAt) < MOVED_LATELY_MS;
3156
+ for (const r of rows) r.picked = r.out?.state === 'ahead' && (rows.find((x) => x.name === r.name) === r || lately(r));
3117
3157
  paint();
3158
+ for (const r of rows) if (r.picked) void checkRow(r, r.out.head, r.out.target);
3118
3159
  }
3119
3160
  /* The files of a folder or a mailbox, in a conversation: the Files sheet, moved into the detail. */
3120
3161
  let filesHome = null;
package/web/index.html CHANGED
@@ -274,7 +274,7 @@
274
274
  <div class="chapter-body">
275
275
  <div id="wakeups-box">
276
276
  <div class="panel-top"><b>Wake it by itself</b></div>
277
- <p class="hint">When something arrives in what it has (a file, a mail, a commit), or by the clock, a line you wrote is typed to the tool. A conversation that is asleep is not woken.</p>
277
+ <p class="hint">When something arrives in what it has (a file, a mail, a commit), or by the clock, a line you wrote is typed to the tool. A conversation that is asleep is not woken. Where its chat is on, the line goes to its docket instead: it waits there until the tool says it was done, and the tool is told again until then.</p>
278
278
  <div id="wakeups-rows"></div>
279
279
  <div id="wakeup-address-box" class="notice-box" hidden>
280
280
  <b>Its address, shown this once</b>
@@ -282,6 +282,12 @@
282
282
  <p class="hint">Whoever has this address can wake the tool. Copy it now: it is not kept in a form that can be shown again.</p>
283
283
  <div class="row"><button type="button" id="wakeup-address-copy" class="primary">Copy</button><button type="button" id="wakeup-address-done">I have it</button></div>
284
284
  </div>
285
+ <div id="docket-box" hidden>
286
+ <div class="panel-top"><b>Its docket</b></div>
287
+ <p class="hint">What woke it, and whether it was done; the reminders the tool set itself (it can, with "docket remind"). Take one back if you do not want it.</p>
288
+ <div id="docket-plans"></div>
289
+ <div id="docket-events"></div>
290
+ </div>
285
291
  <details id="wakeups-new-box">
286
292
  <summary>Add a wake-up</summary>
287
293
  <form id="wakeups-new" autocomplete="off">