clavarium 0.2.462-next.1 → 0.2.464-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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.462-next.1",
3
+ "version": "0.2.464-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.462-next.1",
9
+ "version": "0.2.464-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.462-next.1",
3
+ "version": "0.2.464-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.",
package/server/api.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  * POST /api/conversations {name, tool, memoryMb?}
7
7
  * POST /api/conversations/<name>/sleep
8
8
  * POST /api/conversations/<name>/restart a clean stop (by force if it hangs), then a start
9
- * GET /api/conversations/<name>/export[?all=1] its tool's state, or everything of it, one archive (#351) POST .../import[?replaceWork=1] put back (same tool)
9
+ * GET /api/conversations/<name>/export[?all=1] its tool's state, or everything of it, one archive (#351) POST .../import[?replaceWork=1&reminders=1] put back (same tool)
10
10
  * POST /api/conversations/<name>/machine {memoryMb?, diskGb?, cpus?}: stopped, set, started again (202);
11
11
  * asleep: checked and kept for its wake, as `sizeAtWake` (200)
12
12
  * POST /api/conversations/<name>/machine {action: start|stop|restart|sleep|force|force-now}: done on its machine,
@@ -321,7 +321,7 @@ export async function handleApi(request, response, conversations, headers, resou
321
321
  if (carry && request.method === 'POST' && carry[2] === 'import') {
322
322
  if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
323
323
  /* ?replaceWork=1: a whole export may replace the work folder that holds files (asked first, on the page). */
324
- return send(200, await conversations.importState(decodeURIComponent(carry[1]), request, { replaceWork: query.get('replaceWork') === '1' })), true;
324
+ return send(200, await conversations.importState(decodeURIComponent(carry[1]), request, { replaceWork: query.get('replaceWork') === '1', reminders: query.get('reminders') === '1' })), true;
325
325
  }
326
326
  if (pathname.startsWith('/api/files/')) {
327
327
  if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' }), true;
package/server/carry.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  machine's part (its home) is in conversations.mjs (exportWhole, importState).
5
5
 
6
6
  The archive, in this order:
7
- clavarium-conversation.json its manifest (version 2, `whole`): its tool, its title, its sizes, its accesses
7
+ clavarium-conversation.json its manifest (version 2, `whole`): its tool, its title, its sizes, its accesses, its wake-ups
8
8
  home/... its home, without what is rebuilt or thrown away (HOME_LEFT_OUT)
9
9
  work/... its work folder, read here (it is kept on this server) */
10
10
  import { spawn } from 'node:child_process';
@@ -92,12 +92,14 @@ export function unpackHere(file, into) {
92
92
  }
93
93
 
94
94
  /* ITS WORK PUT BACK, here: what it holds now thrown away only when asked (`replace`), then each entry of the
95
- export's work/ moved in (the same disk: a rename). */
95
+ export's work/ moved in (the same disk: a rename). Its docket (.docket) is neither: the one here stays its
96
+ own, and the export's reminders come only when asked (`reminders`, conversations.mjs importState). */
97
+ const DOCKET_DIR = '.docket';
96
98
  export function restoreWork(from, workDir, replace) {
97
- if (replace) for (const e of readdirSync(workDir)) if (e !== CARRY) rmSync(join(workDir, e), { recursive: true, force: true });
99
+ if (replace) for (const e of readdirSync(workDir)) if (e !== CARRY && e !== DOCKET_DIR) rmSync(join(workDir, e), { recursive: true, force: true });
98
100
  let entries = [];
99
101
  try { entries = readdirSync(from); } catch { return; }
100
- for (const e of entries) if (e !== CARRY) renameSync(join(from, e), join(workDir, e));
102
+ for (const e of entries) if (e !== CARRY && e !== DOCKET_DIR) renameSync(join(from, e), join(workDir, e));
101
103
  }
102
104
 
103
105
  /* WHAT IT WAS GIVEN, for a whole export, each by its id: a folder, a repository or a mailbox by its asset
@@ -160,6 +160,10 @@ export class Conversations {
160
160
  only (never its value); and the same given again on an import, where it exists here -> { linked, missing }. */
161
161
  accessesOf = async () => ({});
162
162
  relink = async () => ({ linked: [], missing: [] });
163
+ /* Set by the server: its wake-ups, for a whole export; and on its import, when asked, its reminders (from the
164
+ export's work folder) and those wake-ups given again (15-11, as a copy does). */
165
+ wakeupsOf = () => undefined;
166
+ importReminders = async () => {};
163
167
 
164
168
  /* `uid`/`gid`: the account this server runs as; files the tool writes in
165
169
  its kept work folder belong to it on the host. */
@@ -989,7 +993,7 @@ export class Conversations {
989
993
  if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
990
994
  const tool = this.#tools.find((t) => t.id === c.tool);
991
995
  const accesses = await this.accessesOf(name);
992
- const manifest = JSON.stringify({ kind: 'clavarium-conversation', version: 2, whole: true, tool: c.tool, name: c.name, ...(c.title ? { title: c.title } : {}), memoryMb: c.memoryMb, cpus: c.cpus ?? 1, diskGb: c.diskGb ?? DISK_GB, at: new Date().toISOString(), accesses });
996
+ const manifest = JSON.stringify({ kind: 'clavarium-conversation', version: 2, whole: true, tool: c.tool, name: c.name, ...(c.title ? { title: c.title } : {}), memoryMb: c.memoryMb, cpus: c.cpus ?? 1, diskGb: c.diskGb ?? DISK_GB, at: new Date().toISOString(), accesses, wakeups: this.wakeupsOf(name) });
993
997
  const id = `whole-${Date.now()}`;
994
998
  /* In its machine: the manifest, then its home as home/ (a link's target left as it is), one block per record
995
999
  so that its work can follow it (carry.mjs). Globs off: the words left out are given to tar as they are. */
@@ -1014,8 +1018,9 @@ export class Conversations {
1014
1018
  /* PUT BACK an exported state in this conversation (same tool): its tool stopped, the archive unpacked in
1015
1019
  its home, its tool started again, taking up its last session. -> { tool, from } */
1016
1020
  /* A WHOLE export (exportWhole) puts back its home, its work folder and its accesses: its work only into an empty
1017
- one, unless `replaceWork` -- what is there is never thrown away silently. -> { tool, from, whole, linked, toLink } */
1018
- async importState(name, input, { replaceWork = false } = {}) {
1021
+ one, unless `replaceWork` -- what is there is never thrown away silently; its reminders and wake-ups only when
1022
+ asked (`reminders`). -> { tool, from, whole, linked, toLink } */
1023
+ async importState(name, input, { replaceWork = false, reminders = false } = {}) {
1019
1024
  const c = this.#busyCheck(name);
1020
1025
  const tool = this.#tools.find((t) => t.id === c.tool);
1021
1026
  if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
@@ -1049,6 +1054,7 @@ export class Conversations {
1049
1054
  if (r.code !== 0) throw new Refusal(502, `Not imported: ${firstLine(r.stderr) || `exit ${r.code}`}`);
1050
1055
  restoreWork(join(stage, 'work'), workDir, replaceWork);
1051
1056
  const { linked, missing } = await this.relink(name, manifest.accesses ?? {});
1057
+ if (reminders) await Promise.resolve().then(() => this.importReminders(name, join(stage, 'work'), manifest.wakeups)).catch(() => {});
1052
1058
  return { tool: c.tool, from: { name: manifest.name, at: manifest.at }, whole: true, linked, toLink: missing };
1053
1059
  } finally { this.ready(name); }
1054
1060
  } finally {
package/server/guide.mjs CHANGED
@@ -129,7 +129,7 @@ export function ownText({ name, tool, shared, workKept, resources = [], chat, on
129
129
  /* The thread is kept whole: after a restart, its end is read, and further back on demand. */
130
130
  if (chat && reread) out.push(`- After a restart: ${plain(reread, 60)}, the end of the chat; it says how to read further back.`);
131
131
  /* 02-11: the one command a tool may ask of the server. */
132
- if (chat) out.push('- To be restarted (new tools to take up, or anything stuck): finish what runs, then `touch /work/.parley/restart-asked`; the server restarts you once your turn ends, and your work picks up where it was.');
132
+ if (chat) out.push('- To be restarted (new tools to take up, or anything stuck): finish what runs, then `touch /work/.parley/restart-asked`; the server restarts you once your turn ends, and your work picks up where it was. /work itself fails ("not connected"): `cd / && touch /var/tmp/clavarium-restart-asked` instead.');
133
133
  /* Its docket (dockets.mjs): what wakes it waits there until it says done or failed. */
134
134
  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.');
135
135
  /* Its lists (binders.mjs): kept on the server, asked for through .binder; a person approves. */
package/server/health.mjs CHANGED
@@ -25,6 +25,14 @@
25
25
  shell. It prints one fact per line; the server reads only these lines. */
26
26
  import { SHARING_STEP } from './vm.mjs';
27
27
  import { WHY } from './linkguard.mjs';
28
+ import { SOCKET } from './tmux.mjs';
29
+ import { SESSION } from './conversations.mjs';
30
+
31
+ /* A FILE OUTSIDE /work where its tool may ask to be restarted when /work itself is dead (16-11): the
32
+ one in its chat's folder (talk.mjs, RESTART_ASKED) cannot be written then. Read by the probe. */
33
+ export const RESTART_OUTSIDE = '/var/tmp/clavarium-restart-asked';
34
+ /* What a folder that came loose looks like on a terminal (the kernel's words for ENOTCONN). */
35
+ const LOOSE_WORDS = 'transport endpoint is not connected|socket is not connected|ENOTCONN';
28
36
 
29
37
  /* How long installing the shared-folder helper in a machine may take (it comes from the snap store). */
30
38
  export const SHARING_MS = 180_000;
@@ -41,6 +49,15 @@ export const PROBE = [
41
49
  ' else echo "mount missing $p"; fi',
42
50
  'done',
43
51
  'if [ -d /work ] && awk \'$2=="/work"{f=1} END{exit !f}\' /proc/mounts; then timeout 5 df -Pm /work 2>/dev/null | awk \'NR==2{print "disk /work", $4, $2}\'; fi',
52
+ /* ITS TOOL STILL IN A FOLDER THAT WENT (16-11). A folder put back is a NEW mount: a program that was
53
+ in the old one stays in it, dead ("Transport endpoint is not connected"), until it is started
54
+ again -- the folder looks well, its tool does not. So each program of its tool's session whose
55
+ folder is ours to read (readlink) and cannot be entered is said; the first one is enough. */
56
+ `t=$(tmux -L ${SOCKET} list-panes -t '=${SESSION}:' -F '#{pane_pid}' 2>/dev/null | head -n 1)`,
57
+ 'case "$t" in ""|*[!0-9]*) ;; *) timeout 5 sh -c \'for p in $(ps -o pid= -s "$1" 2>/dev/null); do l=$(readlink "/proc/$p/cwd" 2>/dev/null) || continue; [ -n "$l" ] || continue; [ -d "/proc/$p/cwd/." ] || { echo "stale $p"; exit 0; }; done\' stale "$t";; esac',
58
+ /* What its terminal shows now: a folder that is not connected, said by its tool (a symptom, not a proof). */
59
+ `tmux -L ${SOCKET} capture-pane -p -t '=${SESSION}:' 2>/dev/null | grep -c -i -E '${LOOSE_WORDS}' | awk '{print "screen", $1+0}'`,
60
+ `if [ -f ${RESTART_OUTSIDE} ]; then echo "restart asked"; fi`,
44
61
  ].join('\n');
45
62
  export const PROBE_NAME = 'clavarium-health';
46
63
 
@@ -76,6 +93,9 @@ export function readProbe(text, paths = []) {
76
93
  if (parts[0] === 'oomkinds' && parts.length === 3 && a !== undefined && b !== undefined) facts.oomKinds = { machine: a, limit: b };
77
94
  if (parts[0] === 'disk' && parts.length === 4 && disks.has(parts[1]) && b !== undefined && c !== undefined) facts.disks[parts[1]] = { availableMb: b, sizeMb: c };
78
95
  if (parts[0] === 'mount' && parts.length === 3 && expected.has(parts[2]) && MOUNT_STATES.has(parts[1])) facts.mounts[parts[2]] = parts[1];
96
+ if (parts[0] === 'stale' && parts.length === 2 && a !== undefined) facts.stale = true;
97
+ if (parts[0] === 'screen' && parts.length === 2 && a !== undefined) facts.screenLoose = a;
98
+ if (line.trim() === 'restart asked') facts.restartAsked = true;
79
99
  }
80
100
  return facts;
81
101
  }
@@ -123,6 +143,9 @@ export function judge(record) {
123
143
  for (const path of record.remounted ?? []) add('info', 'mount', `remounted:${path}`, `${path} had come loose in the machine: it was mounted again.`);
124
144
  for (const { path, why } of record.failed ?? []) add('bad', 'mount', `failed:${path}`, `${path} is not reachable in the machine and could not be mounted again${why ? `: ${why}` : ''}.`);
125
145
  for (const path of record.missing ?? []) if (!(record.failed ?? []).some((f) => f.path === path)) add('warn', 'mount', `missing:${path}`, `${path} is not reachable in the machine.`);
146
+ if (record.stale) add('bad', 'mount', 'stale-tool', 'Its tool is still in a folder that came loose: it is restarted, its work picks up where it was.');
147
+ /* Its terminal says so while its folders look well: said, nothing done (its tool may only be quoting it). */
148
+ else if (record.screenLoose > 0 && !(record.missing ?? []).length) add('warn', 'mount', 'screen-loose', 'Its terminal says a folder is not connected, though its folders look well.');
126
149
  }
127
150
  /* Links its folders hold that the share cannot serve (linkguard.mjs): looked at on this server, whatever its machine does. */
128
151
  for (const l of record.links?.removed ?? []) add('info', 'link', `link-removed:${l.folder}/${l.path}`, `/resources/${l.folder}/${l.path} was a broken link (${WHY[l.kind] ?? l.kind}): it was removed on the server, what it pointed to left as it was.`);
@@ -226,6 +249,7 @@ export class Health {
226
249
  return this.#keep(name, {
227
250
  at, state, answering: true, memory: facts.memory, oomKills: facts.oomKills ?? 0, ...(facts.oomKinds ? { oomKinds: facts.oomKinds } : {}), disks: facts.disks,
228
251
  paths, missing: loose(), ...(remounted.length ? { remounted } : {}), ...(failed.length ? { failed } : {}), ...(links ? { links } : {}),
252
+ ...(facts.stale ? { stale: true } : {}), ...(facts.screenLoose ? { screenLoose: facts.screenLoose } : {}), ...(facts.restartAsked ? { restartAsked: true } : {}),
229
253
  /* What was put back stays said until a later look finds nothing to put back. */
230
254
  });
231
255
  }
package/server/main.mjs CHANGED
@@ -59,7 +59,8 @@ import { GitChecks } from './gitchecks.mjs';
59
59
  import { GitKeeper } from './gitkeeper.mjs';
60
60
  import { GitRunner } from './gitrunner.mjs';
61
61
  import { Shelf } from './shelf.mjs';
62
- import { Health } from './health.mjs';
62
+ import { Health, RESTART_OUTSIDE } from './health.mjs';
63
+ import { Revive } from './revive.mjs';
63
64
  import { LinkGuard, removedLine, toolLine } from './linkguard.mjs';
64
65
  import { Setup } from './setup.mjs';
65
66
  import { Capacity } from './capacity.mjs';
@@ -613,7 +614,27 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
613
614
  /* A TOOL THAT ASKS TO BE RESTARTED (02-11: to take up its tools, after an update): its tool restarted by this server
614
615
  once its turn has ended (its pulse no longer busy), said in its chat; once per ten minutes at most. */
615
616
  const restartedAt = new Map();
617
+ /* ITS TOOL STILL IN A FOLDER THAT CAME LOOSE, or asking from outside /work (16-11, revive.mjs): restarted
618
+ by the server, its tool only; told through its docket first (read as it starts), its chat after. */
619
+ const revive = new Revive({
620
+ restart: (name) => all.restartTool(name),
621
+ busy: (name) => talk.pulse(name)?.busy === true,
622
+ taken: (name) => vms.exec(name, ['rm', '-f', RESTART_OUTSIDE], { timeoutMs: 10_000 }),
623
+ tell: (name, why, step) => {
624
+ const loose = why === 'stale';
625
+ if (step === 'before') {
626
+ if (loose) try { if (dockets.on(name)) dockets.post(name, { kind: 'restarted', text: 'Your work folder came loose in your machine and was put back: your tool was restarted to see it again (what was in the old one could not be reached). Your work picks up where it was; what ran in the background stopped.' }); } catch { /* its docket may be off */ }
627
+ return;
628
+ }
629
+ const text = step === 'done'
630
+ ? (loose ? 'Its work folder had come loose: its tool was restarted to see it again. Its work picks up where it was.' : 'Its tool was restarted as it asked: its work picks up where it was.')
631
+ : 'Its tool could not be restarted: open its terminal and type exit, it starts again.';
632
+ try { talk.event(name, { kind: step === 'done' ? 'restarted' : 'machine-problem', text, topic: step === 'done' ? 'Restarted' : 'Machine', ...(step === 'done' ? {} : { tone: 'warn' }) }); } catch { /* its chat is off */ }
633
+ if (step === 'failed') events.add({ kind: 'machine', text: `${name}: ${text}`, conversation: name });
634
+ },
635
+ });
616
636
  const restartTimer = setInterval(() => {
637
+ void revive.tick().catch(() => {});
617
638
  for (const name of all.awake()) {
618
639
  if (!talk.restartAsked(name)) continue;
619
640
  if (talk.pulse(name)?.busy) continue;
@@ -646,7 +667,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
646
667
  /* Where its chat is on, its agent is given an event when its disk or memory crosses a level (healthdocket.mjs);
647
668
  not where its owner turned on its own reaction (above): one way of telling it, not two. */
648
669
  const healthDocket = new HealthDocket({ store: new Store(`${dataDir}/health-docket.json`), dockets, reacting: (name) => reacting.settings(name).on });
649
- health.forgotten = (name) => { healthDocket.forget(name); watchdog.forget(name); };
670
+ health.forgotten = (name) => { healthDocket.forget(name); watchdog.forget(name); revive.forget(name); };
650
671
  /* A machine's problems worth keeping in What happened: said once, until they went away. */
651
672
  const problemsSaid = new Map();
652
673
  /* ITS WATCHDOG (watchdog.mjs): mute or full for as long as its owner set, forced off then started, once;
@@ -662,6 +683,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
662
683
  alert: (payload) => { events.add({ kind: 'machine', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload)?.catch?.(() => {}); } });
663
684
  health.judged = (name, record) => {
664
685
  void watchdog.judged(name, record).catch(() => {});
686
+ try { revive.judged(name, record); } catch { /* its tool: nothing more */ }
665
687
  talk.machine(name, record); void reacting.judged(name, record).catch(() => {});
666
688
  /* A folder that came loose and was put back: said once, in its chat (the look that put it back). */
667
689
  for (const path of record?.remounted ?? []) { try { talk.event(name, { kind: 'machine-ok', text: `Le dossier ${path} s'était détaché de la machine : il a été remonté.`, topic: 'Machine', brief: 'Shared folder' }); } catch { /* its chat is off */ } }
@@ -721,6 +743,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
721
743
  mailbox by its asset, a secret by its name only (never its value), its Tether targets and its lists by theirs. */
722
744
  all.accessesOf = async (name) => accessesOf({ folders, secrets, tethers, binders, talk, guide }, name);
723
745
  /* ITS IMPORT: each given again where the same id exists here, with the same level (as copyRights does). */
746
+ all.wakeupsOf = (name) => wakeups.exportOf(name);
747
+ all.importReminders = (name, work, given) => { copyPlans(work, folders.workFolder(name)); wakeups.importTo(name, given); };
724
748
  all.relink = (name, given) => relinkAccesses({ folders, secrets, tethers, binders, talk, guide, gitKeeper }, name, given);
725
749
  /* A tool that ended cut for lack of memory: said in the events, to the owner, and in its chat. */
726
750
  all.onToolExit = (name, report) => {
@@ -0,0 +1,66 @@
1
+ /* ITS TOOL STARTED AGAIN WHEN A FOLDER IT WAS IN CAME LOOSE (16-11).
2
+ *
3
+ * Seen in production: /work of a conversation came loose ("socket is not connected"). Putting the
4
+ * folder back (health.mjs, resources.mjs repair) makes a NEW mount; its tool, and every program it
5
+ * started (its shell, Parley, Docket), stays in the old one, dead, until it is started again. It cannot
6
+ * even ask to be restarted: that request is a file in /work. Its owner typed exit by hand; this does it.
7
+ *
8
+ * Told by health.mjs, each look (`judged`):
9
+ * - `stale`: a program of its tool's session is in a folder that cannot be entered;
10
+ * - `restartAsked`: its tool asked from outside /work (health.mjs, RESTART_OUTSIDE).
11
+ * Then, at the next tick: its tool only is restarted (conversations.mjs restartTool, never its
12
+ * machine), once its turn has ended -- or after WAIT_MS anyway when stale: a tool stuck in a dead
13
+ * folder cannot say its turn ended (its pulse is in /work). Never a loop: not again within AGAIN_MS.
14
+ * Its tool told through its docket before it starts again, its owner through What happened.
15
+ */
16
+ export const WAIT_MS = 5 * 60_000;
17
+ export const AGAIN_MS = 30 * 60_000;
18
+
19
+ export class Revive {
20
+ #restart; #busy; #tell; #taken; #now; #wanted = new Map(); #lastAt = new Map(); #going = new Set();
21
+
22
+ /* `restart(name)`: its tool restarted, resolves with whether it was. `busy(name)`: its turn goes on.
23
+ `tell(name, why, step)`: said where it should be, step 'before' (its docket), then 'done' or 'failed' (main.mjs).
24
+ `taken(name)`: the request outside /work removed (in its machine). */
25
+ constructor({ restart, busy = () => false, tell = () => {}, taken = async () => {}, now = Date.now }) {
26
+ this.#restart = restart; this.#busy = busy; this.#tell = tell; this.#taken = taken; this.#now = now;
27
+ }
28
+
29
+ /* What one look found. A look that finds it well forgets a stale one not yet acted on. */
30
+ judged(name, record) {
31
+ if (!record || record.state !== 'Running' || record.answering !== true) return;
32
+ if (record.restartAsked) { void Promise.resolve().then(() => this.#taken(name)).catch(() => {}); this.#want(name, 'asked'); }
33
+ if (record.stale) this.#want(name, 'stale');
34
+ else if (this.#wanted.get(name)?.why === 'stale') this.#wanted.delete(name);
35
+ }
36
+
37
+ #want(name, why) {
38
+ const had = this.#wanted.get(name);
39
+ /* A stale tool outranks a plain request: it is acted on even while it looks busy. */
40
+ if (!had || (why === 'stale' && had.why !== 'stale')) this.#wanted.set(name, { why, since: had?.since ?? this.#now() });
41
+ }
42
+
43
+ wanted(name) { return this.#wanted.get(name)?.why ?? null; }
44
+ forget(name) { this.#wanted.delete(name); this.#lastAt.delete(name); }
45
+
46
+ /* One pass: each one wanted, restarted when it may be. Resolves with the names restarted. */
47
+ async tick() {
48
+ const done = [];
49
+ for (const [name, { why, since }] of [...this.#wanted]) {
50
+ if (this.#going.has(name)) continue;
51
+ const busy = (() => { try { return this.#busy(name); } catch { return false; } })();
52
+ if (busy && !(why === 'stale' && this.#now() - since >= WAIT_MS)) continue;
53
+ this.#wanted.delete(name);
54
+ if (this.#now() - (this.#lastAt.get(name) ?? -Infinity) < AGAIN_MS) continue;
55
+ this.#lastAt.set(name, this.#now());
56
+ this.#going.add(name);
57
+ try {
58
+ try { this.#tell(name, why, 'before'); } catch { /* told, nothing more */ }
59
+ const ok = await this.#restart(name).catch(() => false);
60
+ if (ok) done.push(name);
61
+ try { this.#tell(name, why, ok ? 'done' : 'failed'); } catch { /* told, nothing more */ }
62
+ } finally { this.#going.delete(name); }
63
+ }
64
+ return done;
65
+ }
66
+ }
@@ -186,7 +186,7 @@ export const SETTINGS_WORDS_FR = {
186
186
  'set-carry': 'Exporter / Importer', 'set-carry-hint': 'Mémoire de son IA, ou tout : à emporter.',
187
187
  'set-carry-export': 'Mémoire de son IA', 'set-carry-all': 'Tout (dossier perso, travail, accès)', 'set-carry-all-off': 'Son travail doit être gardé ici.',
188
188
  'set-carry-replace': 'Son travail a des fichiers. Tout remplacer ?', 'set-carry-replace-go': 'Remplacer son travail',
189
- 'set-carry-tolink': 'À relier à la main :', 'set-carry-import': 'Importer…', 'set-carry-go': 'Importer',
189
+ 'set-carry-tolink': 'À relier à la main :', 'set-carry-import': 'Importer…', 'set-carry-reminders': 'Importer aussi ses rappels et réveils', 'set-carry-go': 'Importer',
190
190
  'set-carry-ask': '« {file} » dans « {name} » ? Mémoire remplacée.', 'set-carry-done': 'Importé depuis « {from} ».',
191
191
  'set-mcp-drop': 'Collez ici la configuration du service', 'set-mcp-drop-hint': 'le bloc { "mcpServers": … } de sa page d\'aide',
192
192
  'set-mcp-hand': 'Remplir à la main', 'set-mcp-add-n': 'Ajouter les {n}', 'set-mcp-nokey': 'aucune',
@@ -28,6 +28,7 @@
28
28
  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
+ import { NODE_STEPS } from './tools.mjs';
31
32
  import { fileURLToPath } from 'node:url';
32
33
  import { APP, ARCHIVES, MACHINE_TOOLS, archiveName, locked, packageDir, packageVersion } from './parley.mjs';
33
34
 
@@ -58,6 +59,7 @@ export const parleySource = (options = {}) => toolSource(MACHINE_TOOLS.find((t)
58
59
 
59
60
  /* "sha512-<base64>", as npm writes an integrity. */
60
61
  const NO_NPM = 'there is no npm in this machine';
62
+ const NODE_STEP_MS = 15 * 60_000;
61
63
  export const integrityOf = (bytes) => `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
62
64
 
63
65
  const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
@@ -192,8 +194,13 @@ export class Toolbox {
192
194
  const exec = (argv, timeoutMs = 30_000) => this.#vms.exec(conversation, argv, { timeoutMs }).catch(() => ({ code: 1, stdout: '', stderr: '' }));
193
195
  const there = async () => { const v = await exec([tool.name, '--version']); return v.code === 0 && v.stdout.trim() === tool.version; };
194
196
  if (await there()) return '';
195
- /* A machine without node (a plain shell): said once, until it is built again or restarted. */
196
- if ((await exec(['which', 'npm'])).code !== 0) return NO_NPM;
197
+ /* A machine without node (a plain shell, a tool whose recipe has none): node first, as a tool's "node"
198
+ step gives it; still none, said once, until it is built again or restarted. */
199
+ if ((await exec(['which', 'npm'])).code !== 0) {
200
+ const why = await this.#node(conversation);
201
+ if (why) return why;
202
+ if ((await exec(['which', 'npm'])).code !== 0) return NO_NPM;
203
+ }
197
204
  /* The archive as the machine reads it, against the index; /tools mounted again once if it is not there. */
198
205
  const sum = async () => /^([0-9a-f]{64})\s/.exec((await exec(['sha256sum', '--', tool.path], 60_000)).stdout ?? '')?.[1];
199
206
  let seen = await sum();
@@ -206,6 +213,15 @@ export class Toolbox {
206
213
  return '';
207
214
  }
208
215
 
216
+ /* NODE IN A MACHINE WITHOUT IT: the steps of tools.mjs (its checksum checked before it is unpacked). '' or why not. */
217
+ async #node(conversation) {
218
+ for (const [i, step] of NODE_STEPS.entries()) {
219
+ const r = await this.#vms.exec(conversation, step.argv, { input: step.input, timeoutMs: NODE_STEP_MS }).catch(() => ({ code: 1, stdout: '', stderr: '' }));
220
+ if (r.code !== 0) return `node could not be installed (step ${i + 1}): ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`;
221
+ }
222
+ return '';
223
+ }
224
+
209
225
  /* THE LAUNCHER OF A TOOL, there in its machine before the tool starts: when /tools is
210
226
  missing or came loose, it is repaired (below) and looked at again. '' or why not --
211
227
  then the tool does not start: never a start in a half-made state. */
@@ -246,6 +246,27 @@ export class Wakeups {
246
246
  return this.of(to);
247
247
  }
248
248
 
249
+ /* A WHOLE EXPORT'S WAKE-UPS (15-11): what each is, never its id, its clock or a call from outside (its address
250
+ is the original's). Given again on its import when asked, each through add(): checked as one written here;
251
+ one that is not (its folder not attached here) is left out. -> how many */
252
+ exportOf(name) {
253
+ const r = this.#record(name);
254
+ return { perHour: r.perHour, items: r.items.filter((i) => i.kind !== 'call').map(({ kind, on, message, resource, onlyNew, quiet, minutes, at, line }) => ({ kind, on, message, resource, onlyNew, quiet, minutes, at, line })) };
255
+ }
256
+ importTo(name, given) {
257
+ let n = 0;
258
+ try { if (given?.perHour !== undefined) this.setLimit(name, given.perHour); } catch { /* not a cap */ }
259
+ for (const i of (Array.isArray(given?.items) ? given.items : []).slice(0, ITEMS_MAX)) {
260
+ if (!i || typeof i !== 'object' || i.kind === 'call') continue;
261
+ try {
262
+ const made = this.add(name, i).items.at(-1);
263
+ if (i.on === false) this.turn(name, made.id, false);
264
+ n++;
265
+ } catch { /* not one this conversation can have */ }
266
+ }
267
+ return n;
268
+ }
269
+
249
270
  #change(name, id, change) {
250
271
  this.#known(name);
251
272
  const r = this.#record(name);
package/web/app.js CHANGED
@@ -2695,6 +2695,7 @@
2695
2695
  $('carry-export-all').title = here?.work !== 'kept' ? uiSaid('set-carry-all-off', 'Its work must be kept here.') : '';
2696
2696
  $('carry-export-all').onclick = allOff ? (event) => { event.preventDefault(); } : null;
2697
2697
  $('carry-import').disabled = down;
2698
+ $('carry-reminders').checked = false; $('carry-reminders').disabled = down;
2698
2699
  $('carry-said').hidden = !down;
2699
2700
  if (down) {
2700
2701
  const start = Object.assign(document.createElement('button'), { type: 'button', className: 'inline', textContent: here.asleep === true ? uiSaid('set-wake-it', 'Wake it') : uiSaid('set-m-start', 'Start') });
@@ -2704,13 +2705,14 @@
2704
2705
  $('carry-import').onclick = () => $('carry-file').click();
2705
2706
  /* Sent; a whole export into a work folder that holds files asks first, then is sent again to replace it.
2706
2707
  What it was given that does not exist here is listed after, to link by hand. */
2707
- const carryImport = async (name, file, replaceWork) => {
2708
+ const carryImport = async (name, file, replaceWork, reminders) => {
2708
2709
  try {
2709
- const r = await fetch(`${API}/conversations/${encodeURIComponent(name)}/import${replaceWork ? '?replaceWork=1' : ''}`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
2710
+ const query = [replaceWork ? 'replaceWork=1' : '', reminders ? 'reminders=1' : ''].filter(Boolean).join('&');
2711
+ const r = await fetch(`${API}/conversations/${encodeURIComponent(name)}/import${query ? `?${query}` : ''}`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
2710
2712
  const said = await r.json().catch(() => ({}));
2711
2713
  if (!r.ok && said.kind === 'work-not-empty') {
2712
2714
  show(uiSaid('set-carry-replace', 'Its work folder has files. Replace them all?'), uiSaid('set-carry-replace-go', 'Replace its work'),
2713
- () => carryImport(name, file, true), () => { notice.hidden = true; focusTerminal(); });
2715
+ () => carryImport(name, file, true, reminders), () => { notice.hidden = true; focusTerminal(); });
2714
2716
  return;
2715
2717
  }
2716
2718
  if (!r.ok) throw new Error(said.error ?? `HTTP ${r.status}`);
@@ -2722,10 +2724,10 @@
2722
2724
  $('carry-file').onchange = () => {
2723
2725
  const file = $('carry-file').files?.[0]; $('carry-file').value = '';
2724
2726
  if (!file) return;
2725
- const name = current;
2727
+ const name = current; const reminders = $('carry-reminders').checked;
2726
2728
  leavePanel();
2727
2729
  show(uiSaid('set-carry-ask', '« {file} » into « {name} »? Its memory is replaced.', { file: file.name, name }),
2728
- uiSaid('set-carry-go', 'Import'), () => carryImport(name, file, false), () => { notice.hidden = true; focusTerminal(); });
2730
+ uiSaid('set-carry-go', 'Import'), () => carryImport(name, file, false, reminders), () => { notice.hidden = true; focusTerminal(); });
2729
2731
  };
2730
2732
  void paintAnswerer(); paintWakeups(); void paintTalkBox(); void paintShareHere();
2731
2733
  paintMachine(here);
package/web/index.html CHANGED
@@ -247,6 +247,7 @@
247
247
  <div class="panel-top"><b data-said="set-carry">Export / Import</b></div>
248
248
  <p class="hint" data-said="set-carry-hint">Its AI's memory, or everything: to take elsewhere.</p>
249
249
  <div class="row"><a id="carry-export" class="button" download data-said="set-carry-export">Its AI's memory</a><a id="carry-export-all" class="button" download data-said="set-carry-all">Everything (home, work, accesses)</a><button type="button" id="carry-import" data-said="set-carry-import">Import...</button><input type="file" id="carry-file" accept=".gz,application/gzip" hidden></div>
250
+ <label class="cm-tick"><input type="checkbox" id="carry-reminders"> <span data-said="set-carry-reminders">Import its reminders and wake-ups too</span></label>
250
251
  <p id="carry-said" class="hint" role="status" hidden></p>
251
252
  </div>
252
253
  <!-- WHEN ITS MACHINE IS SHORT (server/healthreact.mjs): you are told either way. -->
package/web/voice-core.js CHANGED
@@ -144,3 +144,26 @@ export function toWav(blocks, rate = RATE) {
144
144
  }
145
145
  return new Uint8Array(bytes);
146
146
  }
147
+
148
+ /* PHRASES IN THE ORDER THEY WERE SPOKEN: each is transcribed on its own, and a short one comes back before a
149
+ long one said before it. `order()` takes a place when a phrase ends; that place is later given what to do
150
+ with its result (or nothing: failed, empty), and runs only once every place before it was given its own. */
151
+ export function inOrder() {
152
+ let taken = 0;
153
+ let next = 0;
154
+ const held = new Map();
155
+ return () => {
156
+ const place = taken++;
157
+ let given = false;
158
+ return (run) => {
159
+ if (given) return;
160
+ given = true;
161
+ held.set(place, run);
162
+ while (held.has(next)) {
163
+ const done = held.get(next);
164
+ held.delete(next); next++;
165
+ try { done?.(); } catch { /* one that throws never holds the rest */ }
166
+ }
167
+ };
168
+ };
169
+ }
package/web/voice.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /* DICTATION IN THE PAGE: the microphone stays open, each spoken phrase is
2
2
  transcribed and handed to whoever listens. The page types it into the
3
3
  terminal. See voice-core.js for how a phrase is found. */
4
- import { RATE, BLOCK, BLOCK_MS, Detector, Segmenter, loudness, levelOf, levelBars, toWav } from './voice-core.js';
4
+ import { RATE, BLOCK, BLOCK_MS, Detector, Segmenter, loudness, levelOf, levelBars, toWav, inOrder } from './voice-core.js';
5
5
 
6
6
  /* The operator's pages ask /api; a paired device asks /c/api/<its pairing>,
7
7
  known once it has signed in (the page writes it on the document). */
@@ -28,17 +28,19 @@ async function listen(on, { to } = {}) {
28
28
  const detector = new Detector();
29
29
  let pending = 0;
30
30
  let closed = false;
31
+ const order = inOrder();
31
32
  const tell = () => { if (!closed) on.state(pending > 0 ? 'transcribing' : segmenter.speaking ? 'hearing' : detector.ready() ? 'listening' : 'calibrating'); };
32
33
  const segmenter = new Segmenter({
33
34
  onStart: () => { on.speech?.(); tell(); },
34
35
  onPhrase: async (blocks) => {
35
36
  pending++; tell();
37
+ const place = order();
36
38
  try {
37
39
  const r = await fetch(withLanguage(to ?? `${api()}/voice`), { method: 'POST', headers: { 'content-type': 'audio/wav' }, body: toWav(blocks) });
38
40
  const j = await r.json().catch(() => ({}));
39
41
  if (!r.ok) throw new Error(j.error || 'The phrase could not be transcribed.');
40
- if (!closed && j.text) on.phrase(j.text);
41
- } catch (error) { if (!closed) on.error(error.message); }
42
+ place(j.text ? () => { if (!closed) on.phrase(j.text); } : null);
43
+ } catch (error) { place(null); if (!closed) on.error(error.message); }
42
44
  pending--; tell();
43
45
  },
44
46
  });