clavarium 0.2.508-next.1 → 0.2.509-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.508-next.1",
3
+ "version": "0.2.509-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.508-next.1",
9
+ "version": "0.2.509-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.508-next.1",
3
+ "version": "0.2.509-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
@@ -40,6 +40,7 @@
40
40
  * POST /api/conversations/<name>/talk/pin {to, on}: the owner pins a message of the chat (on: false unpins); 5 at most
41
41
  * POST /api/conversations/<name>/talk/split {messages: 500..100000} | {days: 0.5..365} | {off: true}: when its thread is
42
42
  * archived into volumes (nothing deleted) -> {split}; read back as `split` in GET .../talk
43
+ * POST /api/conversations/<name>/tool {tool}: changes its AI, in the same conversation (202: goes on; `toolSwitch`, then `toolSwitchFailed`)
43
44
  * POST /api/conversations/<name>/chat-name {name}: the name the chat gives its tool ('' : the neutral word of the dictionary)
44
45
  * POST /api/conversations/<name>/tasks-binder {binder}: the binder shown beside its chat ('' automatic, '-' none, else an id)
45
46
  * POST /api/conversations/<name>/voice-mark {on}: what is dictated into its terminal starts with a microphone sign (AI tools only)
@@ -1043,6 +1044,8 @@ export async function handleApi(request, response, conversations, headers, resou
1043
1044
  if (linkOf && conversations.signinHelp) return send(200, conversations.signinHelp.showLink(decodeURIComponent(linkOf[1]))), true;
1044
1045
  const asking = /^\/api\/conversations\/([^/]+)\/ask-first$/.exec(pathname);
1045
1046
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
1047
+ const changingAi = /^\/api\/conversations\/([^/]+)\/tool$/.exec(pathname);
1048
+ if (changingAi) return send(202, await conversations.switchTool(decodeURIComponent(changingAi[1]), body.tool)), true;
1046
1049
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
1047
1050
  if (naming) return send(200, conversations.setChatName(decodeURIComponent(naming[1]), body.name)), true;
1048
1051
  const beside = /^\/api\/conversations\/([^/]+)\/tasks-binder$/.exec(pathname);
@@ -20,6 +20,12 @@ import { tmpdir } from 'node:os';
20
20
  import { join, dirname } from 'node:path';
21
21
 
22
22
  export const SESSION = 'main';
23
+ /* A disk just made holds no session of any tool: neither the one it runs nor one it ran before (#404). */
24
+ const NEW_DISK = Object.freeze({ toolStarted: false, toolsStarted: undefined });
25
+ /* An AI a conversation can change to or from (#404): it reads instructions, says where its state is, and can take it up. */
26
+ const canSwitch = (t) => Boolean(t?.instructions && t?.state && t?.resume);
27
+ /* How long a tool just started must stay up to be said started. */
28
+ const SWITCH_SETTLE_MS = 5000;
23
29
  export const STOP_DELAY_MS = 60_000;
24
30
  const STEP_MS = 15 * 60_000;
25
31
  /* A copy reading its original's memory: nothing for this long, and it is ended (and why said). */
@@ -82,7 +88,7 @@ const DOWN = ['polite', 'force', 'term', 'kill', 'check'];
82
88
  const NEXT = Object.freeze({ polite: 'force', force: 'term', term: 'kill' });
83
89
  /* Each step in words, for the journal and the chat (the page has its own, web/app.js). */
84
90
  const STEP_WORDS = Object.freeze({ polite: 'polite stop', force: 'forced stop', term: 'SIGTERM', kill: 'SIGKILL', check: 'check', start: 'start', suspend: 'sleep', resleep: 'wake and sleep again', stop: 'clean stop' });
85
- const KIND_DOING = Object.freeze({ start: 'starting', stop: 'stopping', restart: 'restarting', sleep: 'going to sleep', force: 'being forced off', resize: 'being resized', move: 'moving to a shared machine' });
91
+ const KIND_DOING = Object.freeze({ start: 'starting', stop: 'stopping', restart: 'restarting', sleep: 'going to sleep', force: 'being forced off', resize: 'being resized', move: 'moving to a shared machine', tool: 'changing its AI' });
86
92
  /* THE WATCHDOG of a machine (watchdog.mjs), as its owner set it: on, with how long it may stay mute or
87
93
  full before it is forced off and started again. The defaults, and what may be chosen (minutes). */
88
94
  export const WATCHDOG_DELAY_MIN = 60;
@@ -185,6 +191,8 @@ export class Conversations {
185
191
  if (c.phase === 'building' && c.movingTo) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, sharedMachine: undefined, machineMb: undefined, machineUser: undefined, ...(c.movingFromMb ? { memoryMb: c.movingFromMb } : {}), movingTo: undefined, movingFromMb: undefined, stopped: true, moved: `The server restarted while it was moving to the shared machine ${c.movingTo}: it stays in its own machine, as it was. Move it again when you like.` });
186
192
  else if (c.phase === 'building' && c.movingOutOf) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, ...c.movingOutOf, movingOutOf: undefined, stopped: true, moved: `The server restarted while it was moving out of the shared machine ${c.movingOutOf.sharedMachine}: it stays there. Move it again when you like.` });
187
193
  else if (c.phase === 'building') store.patch(c.name, { phase: 'failed', error: 'The server restarted while this conversation was being built. Build it again, or archive it.' });
194
+ /* A change of AI cut short before its switch: it kept its AI (the record changes in one write). */
195
+ if (c.toolSwitch) store.patch(c.name, { toolSwitch: undefined, toolSwitchFailed: 'The server restarted during the change: it keeps its AI.' });
188
196
  if (c.phase === 'restarting') store.patch(c.name, { phase: 'ready', step: undefined, restartingSince: undefined, restarted: 'The server restarted while this machine was being restarted: look at its state, and restart it again if needed.' });
189
197
  /* An action cut short: said as such, never left running on the page. */
190
198
  if (store.get(c.name)?.machine) store.patch(c.name, { machine: undefined, machineReport: { kind: c.machine.kind, ok: false, cut: true, at: new Date().toISOString(), steps: (c.machine.steps ?? []).filter((x) => x.state !== 'todo').map(({ id, state, s }) => ({ id, result: state === 'run' ? 'cut' : state, ...(s !== undefined ? { s } : {}) })), advice: 'look', said: 'The server restarted during this action: look at its state.' } });
@@ -266,7 +274,8 @@ export class Conversations {
266
274
  /* `resumes`: the tool can take up its last session when it starts (`resume` in config/tools.json). */
267
275
  /* `rights`: it can be started with every right in its machine (`rights` in config/tools.json). */
268
276
  /* `ai`: an agent that reads instructions (`instructions`), not a bare terminal. */
269
- tools() { return this.#tools.map(({ id, label, memoryMb, resume, rights, instructions }) => ({ id, label, memoryMb, resumes: Boolean(resume), rights: Boolean(rights), ai: Boolean(instructions) })); }
277
+ /* `switches`: an existing conversation can change to it, or from it (#404). */
278
+ tools() { return this.#tools.map((t) => ({ id: t.id, label: t.label, memoryMb: t.memoryMb, resumes: Boolean(t.resume), rights: Boolean(t.rights), ai: Boolean(t.instructions), switches: canSwitch(t) })); }
270
279
 
271
280
  /* The sign-in rules of a conversation's tool, or undefined. */
272
281
  signinRules(name) { return this.#tools.find((t) => t.id === this.#store.get(name)?.tool)?.signin; }
@@ -294,7 +303,7 @@ export class Conversations {
294
303
  return this.#store.all().sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name)).map((c) => {
295
304
  const tool = this.#tools.find((t) => t.id === c.tool);
296
305
  /* An AI tool has an instruction file; a shell has none: what is dictated there is never marked. */
297
- return { ...c, ...(c.lentTo && !this.#borrowed.has(c.name) ? { lentTo: undefined } : {}), rank: order.indexOf(c.name), ...(c.group ? { groupRank: groups.indexOf(c.group) } : {}), toolLabel: tool?.label ?? c.tool, memoryMinMb: tool?.memoryMb, resumes: Boolean(tool?.resume), rights: Boolean(tool?.rights), ai: Boolean(tool?.instructions), voiceMark: Boolean(tool?.instructions) && c.voiceMark !== false, cpus: c.cpus ?? 1, hostCpus: availableParallelism() };
306
+ return { ...c, ...(c.lentTo && !this.#borrowed.has(c.name) ? { lentTo: undefined } : {}), rank: order.indexOf(c.name), ...(c.group ? { groupRank: groups.indexOf(c.group) } : {}), toolLabel: tool?.label ?? c.tool, memoryMinMb: tool?.memoryMb, resumes: Boolean(tool?.resume), switches: canSwitch(tool), rights: Boolean(tool?.rights), ai: Boolean(tool?.instructions), voiceMark: Boolean(tool?.instructions) && c.voiceMark !== false, cpus: c.cpus ?? 1, hostCpus: availableParallelism() };
298
307
  });
299
308
  }
300
309
 
@@ -454,8 +463,8 @@ export class Conversations {
454
463
  /* A new disk holds no session of the tool: its first start is a plain
455
464
  one (`false`: known, as opposed to a record made before this was kept). */
456
465
  /* A copy being made (copy): built, but not usable until its work and its state are in. */
457
- if (this.#holding.has(name)) { this.#store.patch(name, { step: 'Copying', toolStarted: false }); this.#fresh.add(name); this.#mountAgain.add(name); return undefined; }
458
- this.#store.patch(name, { phase: 'ready', step: undefined, buildingSince: undefined, toolStarted: false });
466
+ if (this.#holding.has(name)) { this.#store.patch(name, { step: 'Copying', ...NEW_DISK }); this.#fresh.add(name); this.#mountAgain.add(name); return undefined; }
467
+ this.#store.patch(name, { phase: 'ready', step: undefined, buildingSince: undefined, ...NEW_DISK });
459
468
  this.#reach(name, 'folders');
460
469
  /* A machine that has just been built holds nothing of what was put
461
470
  in the one before it: the next opening prepares it from nothing.
@@ -521,8 +530,8 @@ export class Conversations {
521
530
  const r = await this.#vms.exec(name, step.argv, { input: step.input, timeoutMs: STEP_MS });
522
531
  if (r.code !== 0) return fail(`Installing ${tool.label} failed at step ${i + 1}`, r);
523
532
  }
524
- if (this.#holding.has(name)) { this.#store.patch(name, { step: 'Copying', toolStarted: false }); this.#fresh.add(name); this.#mountAgain.add(name); return undefined; }
525
- this.#store.patch(name, { phase: 'ready', step: undefined, buildingSince: undefined, toolStarted: false });
533
+ if (this.#holding.has(name)) { this.#store.patch(name, { step: 'Copying', ...NEW_DISK }); this.#fresh.add(name); this.#mountAgain.add(name); return undefined; }
534
+ this.#store.patch(name, { phase: 'ready', step: undefined, buildingSince: undefined, ...NEW_DISK });
526
535
  this.#reach(name, 'folders');
527
536
  this.#fresh.add(name);
528
537
  this.#mountAgain.add(name);
@@ -542,6 +551,7 @@ export class Conversations {
542
551
  const c = this.#store.get(name);
543
552
  if (!c) throw new Refusal(404, 'No such conversation.');
544
553
  if (c.phase === 'building' && !reset) throw new Refusal(409, 'This conversation is still being built.');
554
+ this.#notChangingAi(name);
545
555
  const tool = this.#tools.find((t) => t.id === c.tool);
546
556
  if (!tool) throw new Refusal(400, 'The tool of this conversation is no longer offered.');
547
557
  const state = await this.#vms.state(name, { fresh: true });
@@ -950,6 +960,121 @@ export class Conversations {
950
960
  return true;
951
961
  }
952
962
 
963
+ /* ---------- CHANGING ITS AI (#404) ---------- */
964
+ /* Set by the server: said in its chat; `line`, on success, told to the new AI. (name, said, line, ok) */
965
+ toolChanged = () => {};
966
+ /* How long a tool just started must stay up (a test shortens it). */
967
+ switchSettleMs = SWITCH_SETTLE_MS;
968
+
969
+ #notChangingAi(name) { if (this.#acts.get(name)?.kind === 'tool') throw this.#busy(name); }
970
+
971
+ /* THE SAME CONVERSATION, ANOTHER AI. Its thread, files, accesses and reminders do not depend on its tool; each
972
+ tool keeps its state in its own folders, so the one left can be gone back to. In order, the old AI working
973
+ until the switch itself: installed if missing (a failure leaves it untouched); then, in one write, the record
974
+ changed, the old session ended, the new one started; a new AI that does not stay up: back to the old one, and
975
+ why said. One at a time, through the one lock of its machine. -> the record, at once; `this.switched`: its end. */
976
+ async switchTool(name, to) {
977
+ const c = this.#busyCheck(name);
978
+ const from = this.#tools.find((t) => t.id === c.tool);
979
+ const target = this.#tools.find((t) => t.id === to);
980
+ if (typeof to !== 'string' || !target) throw new Refusal(400, 'This AI is not offered here.');
981
+ if (to === c.tool) throw new Refusal(409, `It already runs ${target.label}.`);
982
+ if (!canSwitch(from)) throw new Refusal(409, `${from?.label ?? c.tool} cannot be changed for another AI.`);
983
+ if (!canSwitch(target)) throw new Refusal(400, `A conversation cannot change to ${target.label}.`);
984
+ if (c.lentTo || this.#store.all().some((x) => x.copyOf === name && x.phase === 'building')) throw new Refusal(409, 'It is being copied: change its AI after.', { retry: true });
985
+ if ((Number(c.memoryMb) || 0) < target.memoryMb) throw new Refusal(409, `${target.label} needs ${target.memoryMb} MB of memory: give its machine more first.`);
986
+ /* Taken before anything is awaited: a second request sees it. */
987
+ const act = this.#take(name, 'tool');
988
+ try {
989
+ if ((await this.#vms.state(name, { fresh: true }).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
990
+ } catch (error) { this.#give(name, act); throw error; }
991
+ this.#cancelStop(name);
992
+ this.#store.patch(name, { toolSwitch: { to, label: target.label, step: `Installing ${target.label}` }, toolSwitchFailed: undefined });
993
+ this.switched = this.#switching(name, from, target, act).finally(() => this.#give(name, act));
994
+ return this.#store.get(name);
995
+ }
996
+
997
+ async #switching(name, from, target, act) {
998
+ const failed = (why) => {
999
+ if (!this.#store.get(name)) return false;
1000
+ const said = `Its AI stays ${from.label}: ${String(why).replace(/\.?$/, '.')}`;
1001
+ this.#store.patch(name, { toolSwitch: undefined, toolSwitchFailed: said });
1002
+ try { this.toolChanged(name, said, '', false); } catch { /* told, nothing more */ }
1003
+ return false;
1004
+ };
1005
+ try {
1006
+ const missing = await this.#installFor(name, target, act);
1007
+ if (missing) return failed(missing);
1008
+ const now = this.#store.get(name);
1009
+ if (!now) return false; /* archived meanwhile */
1010
+ if (now.phase !== 'ready') return failed('it is busy.');
1011
+ /* What each tool has done on this disk. A record from before this was kept says nothing of the one it
1012
+ leaves: it has run there, and a tool told to resume where it has no session starts a new one. */
1013
+ const started = { ...now.toolsStarted };
1014
+ if (now.toolStarted !== false) started[from.id] = true;
1015
+ const back = started[target.id] === true;
1016
+ delete started[target.id];
1017
+ const was = { tool: now.tool, toolStarted: now.toolStarted, toolsStarted: now.toolsStarted, previousTool: now.previousTool };
1018
+ /* The record first: a screen that reopens meanwhile starts the new AI, never the old. */
1019
+ this.#store.patch(name, { tool: target.id, toolStarted: back, toolsStarted: Object.keys(started).length ? started : undefined, previousTool: from.id, toolSwitch: undefined });
1020
+ /* Its next opening prepares it from nothing: the guide's pointer goes in the new AI's own file. */
1021
+ this.#fresh.add(name);
1022
+ await this.#endTurn(name);
1023
+ await this.ready(name);
1024
+ if (await this.#staysUp(name)) {
1025
+ const said = `Its AI is now ${target.label} (was ${from.label}).`;
1026
+ const line = `You now run this conversation, in place of ${from.label}: read its thread first (parley read --last 100), then carry on.`;
1027
+ try { this.toolChanged(name, said, line, true); } catch { /* told, nothing more */ }
1028
+ return true;
1029
+ }
1030
+ if (!this.#store.get(name)) return false;
1031
+ this.#store.patch(name, was);
1032
+ this.#fresh.add(name);
1033
+ await this.#endTurn(name);
1034
+ await this.ready(name);
1035
+ return failed(`${target.label} did not start.`);
1036
+ } catch (error) { return failed(error?.message ?? error); }
1037
+ }
1038
+
1039
+ /* The tool stopped, and the turn it was in said ended: stopped mid-turn, its « working » would stay for ever
1040
+ under an AI that does not say it (not every tool has a pulse). */
1041
+ async #endTurn(name) {
1042
+ await this.#stopTool(name);
1043
+ await this.#vms.exec(name, ['sh', '-c', 'if [ -f /work/.parley/server.mjs ] && command -v parley >/dev/null 2>&1; then parley pulse --end --dir /work/.parley >/dev/null 2>&1; fi; true'], { timeoutMs: 10_000 }).catch(() => {});
1044
+ }
1045
+
1046
+ /* Its session is still there a moment after it started (a tool that exits ends its session: tmux.mjs). */
1047
+ async #staysUp(name) {
1048
+ await new Promise((r) => { setTimeout(r, this.switchSettleMs).unref?.(); });
1049
+ return (await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'has-session', '-t', `=${SESSION}`], { timeoutMs: 10_000 }).catch(() => ({ code: 1 }))).code === 0;
1050
+ }
1051
+
1052
+ /* ITS RECIPE, the one a build runs (`tool.steps`), for what is missing. On the machine already (another
1053
+ conversation of a shared machine, an earlier change): only its own settings steps, and only when it has no
1054
+ state here -- they write its settings, and what it has is never overwritten. -> what went wrong, or undefined. */
1055
+ async #installFor(name, tool, act) {
1056
+ act.ctl = new AbortController();
1057
+ const run = (argv, options = {}) => this.#vms.exec(name, argv, { ...options, signal: act.ctl.signal });
1058
+ const present = async () => (await run(['sh', '-c', 'command -v "$1"', 'probe', tool.command[0]])).code === 0;
1059
+ let steps = tool.steps;
1060
+ if (tool.steps.length === 0 || await present()) {
1061
+ const r = await run(['sh', '-c', 'for p in "$@"; do [ -e "$HOME/$p" ] && exit 0; done; exit 3', 'probe', ...tool.state.keep]);
1062
+ if (r.code !== 0 && r.code !== 3) return `its machine could not be read (${firstLine(r.stderr) || `exit ${r.code}`})`;
1063
+ steps = r.code === 0 ? [] : tool.steps.filter((s) => s.argv[0] !== 'sudo');
1064
+ }
1065
+ for (const [i, step] of steps.entries()) {
1066
+ if (!this.#store.get(name)) return 'it was archived';
1067
+ if (act.preempted) return 'its machine was forced off';
1068
+ this.#store.patch(name, { toolSwitch: { to: tool.id, label: tool.label, step: `Installing ${tool.label} (${i + 1}/${steps.length})` } });
1069
+ const r = await run(step.argv, { input: step.input, timeoutMs: STEP_MS });
1070
+ if (act.preempted) return 'its machine was forced off';
1071
+ if (r.code !== 0) return `installing ${tool.label} failed at step ${i + 1}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`;
1072
+ }
1073
+ if (act.preempted) return 'its machine was forced off';
1074
+ if (steps.length > 0 && !(await present())) return `${tool.label} is not there after its install`;
1075
+ return undefined;
1076
+ }
1077
+
953
1078
  /* CARRIED ELSEWHERE (11-11, #351): what the conversation is beyond /work -- its tool's state, where its
954
1079
  entry in config/tools.json says it is (`state.keep`, without `state.skip`) -- as one .tar.gz streamed
955
1080
  from its machine, a manifest first (clavarium-conversation.json: its tool, its name, its size). Nothing
@@ -958,9 +1083,11 @@ export class Conversations {
958
1083
  /* `toWork` (14-11): the archive written into its own work folder (/work/.clavarium-carry/<toWork>.tgz), that
959
1084
  the server reads on its side, rather than sent out through the VM manager's output -- which stalled for good
960
1085
  past ~36 KB on the owner's server. Its output is then empty. */
961
- async exportState(name, { toWork } = {}) {
1086
+ /* `others` (#404): a copy or a move carries the state of the AIs it ran before too, so that the way back still holds. */
1087
+ async exportState(name, { toWork, others = false } = {}) {
962
1088
  const c = this.#store.get(name);
963
1089
  if (!c) throw new Refusal(404, 'No such conversation.');
1090
+ this.#notChangingAi(name);
964
1091
  const tool = this.#tools.find((t) => t.id === c.tool);
965
1092
  if (!tool?.state) throw new Refusal(409, `${tool?.label ?? c.tool} does not say where it keeps its state: it cannot be exported.`);
966
1093
  if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
@@ -977,7 +1104,8 @@ export class Conversations {
977
1104
  archive is whole all the same -- what was there, read; only a real error (2) fails. */
978
1105
  + '[ "$rc" -le 1 ]';
979
1106
  const id = typeof toWork === 'string' && /^[a-z0-9-]{1,64}$/.test(toWork) ? toWork : '';
980
- const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, tool.state.skip.join(' '), tool.state.keep.join(' '), id]);
1107
+ const carried = [tool, ...(others ? Object.keys(c.toolsStarted ?? {}).map((id) => this.#tools.find((t) => t.id === id)).filter((t) => t?.state) : [])];
1108
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, carried.flatMap((t) => t.state.skip).join(' '), [...new Set(carried.flatMap((t) => t.state.keep))].join(' '), id]);
981
1109
  const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'pipe'] });
982
1110
  /* What it said when it failed: kept short, for the message that says why (a copy, a move). */
983
1111
  child.said = '';
@@ -992,6 +1120,7 @@ export class Conversations {
992
1120
  async exportWhole(name) {
993
1121
  const c = this.#store.get(name);
994
1122
  if (!c) throw new Refusal(404, 'No such conversation.');
1123
+ this.#notChangingAi(name);
995
1124
  const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
996
1125
  if (!workDir) throw new Refusal(409, 'Its work is on its own machine\'s disk: keep it here first (Its files), then export it.');
997
1126
  if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
@@ -1120,6 +1249,7 @@ export class Conversations {
1120
1249
  async copy(name, { title, machine, machineMb, reminders = false } = {}) {
1121
1250
  const c = this.#store.get(name);
1122
1251
  if (!c) throw new Refusal(404, 'No such conversation.');
1252
+ this.#notChangingAi(name);
1123
1253
  if (c.phase !== 'ready') throw new Refusal(409, 'It is busy: copy it once it is ready.');
1124
1254
  if (c.work !== 'kept') throw new Refusal(409, 'Its work is on its own machine\'s disk: it cannot be copied from here. Keep it here first (Its files), then copy it.');
1125
1255
  const tool = this.#tools.find((t) => t.id === c.tool);
@@ -1185,7 +1315,7 @@ export class Conversations {
1185
1315
  const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
1186
1316
  if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(from, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
1187
1317
  if (inWork && !(await this.#workShown(from, workDir))) throw new Error('its original\'s work folder is not shown in its machine: open the original once, then copy it again');
1188
- const out = await this.exportState(from, inWork ? { toWork: carryId } : {});
1318
+ const out = await this.exportState(from, { others: true, ...(inWork ? { toWork: carryId } : {}) });
1189
1319
  child = out.child;
1190
1320
  let read = 0; let lastAt = Date.now(); let stalled = false;
1191
1321
  const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read`); };
@@ -1254,7 +1384,8 @@ export class Conversations {
1254
1384
  if (reminders && typeof this.copyReminders === 'function') await Promise.resolve().then(() => this.copyReminders(from, to)).catch(() => {});
1255
1385
  this.#holding.delete(to);
1256
1386
  if (!this.#store.get(to)) return undefined;
1257
- this.#store.patch(to, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined });
1387
+ /* The AIs its original ran before came with its state (#404): the way back is the copy's too. */
1388
+ this.#store.patch(to, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, ...(tool.state ? { toolsStarted: c.toolsStarted, previousTool: c.previousTool } : {}) });
1258
1389
  this.ready(to);
1259
1390
  return undefined;
1260
1391
  } catch (error) {
@@ -1328,7 +1459,7 @@ export class Conversations {
1328
1459
  const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
1329
1460
  if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(name, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
1330
1461
  if (inWork && !(await this.#workShown(name, workDir))) return 'its work folder is not shown in its machine: open the conversation once, then move it again.';
1331
- const { stream, child } = await this.exportState(name, inWork ? { toWork: carryId } : {});
1462
+ const { stream, child } = await this.exportState(name, { others: true, ...(inWork ? { toWork: carryId } : {}) });
1332
1463
  let read = 0; let lastAt = Date.now(); let stalled = false;
1333
1464
  const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); this.#store.patch(name, { step: `Taking ${tool.label}'s state along: ${sizeWords(read)}` }); };
1334
1465
  const sizing = setInterval(() => {
@@ -1352,7 +1483,7 @@ export class Conversations {
1352
1483
  const carried = join(dir, 'state.tar.gz');
1353
1484
  const back = (why) => {
1354
1485
  /* Back to its own machine, as it was (stopped: the next opening wakes it). */
1355
- this.#store.patch(name, { sharedMachine: undefined, machineMb: undefined, machineUser: undefined, memoryMb: c.memoryMb, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingTo: undefined, movingFromMb: undefined, moveFailed: `Not moved: ${why}` });
1486
+ this.#store.patch(name, { toolsStarted: c.toolsStarted, sharedMachine: undefined, machineMb: undefined, machineUser: undefined, memoryMb: c.memoryMb, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingTo: undefined, movingFromMb: undefined, moveFailed: `Not moved: ${why}` });
1356
1487
  this.#fresh.add(name); this.#mountAgain.add(name);
1357
1488
  try { this.renewed(name, `Not moved to the shared machine ${machine}: ${why} It stays in its own machine, as it was.`, false); } catch { /* told, nothing more */ }
1358
1489
  };
@@ -1388,7 +1519,7 @@ export class Conversations {
1388
1519
  this.renewed(name, `Moved to the shared machine ${machine}, but ${tool.label}'s state did not come along (${error.message}): it starts afresh. Its old machine is kept, stopped.`, true);
1389
1520
  return undefined;
1390
1521
  }
1391
- this.#store.patch(name, { phase: 'ready', step: undefined });
1522
+ this.#store.patch(name, { phase: 'ready', step: undefined, toolsStarted: c.toolsStarted });
1392
1523
  this.ready(name);
1393
1524
  }
1394
1525
  /* There for good: its own machine can go. */
@@ -1435,7 +1566,7 @@ export class Conversations {
1435
1566
  const back = async (why) => {
1436
1567
  /* Back in its shared machine, as it was: its own machine, if begun, removed; its work shown there again. */
1437
1568
  if (!this.#store.get(name)) return undefined;
1438
- this.#store.patch(name, { sharedMachine: undefined });
1569
+ this.#store.patch(name, { sharedMachine: undefined, toolsStarted: c.toolsStarted });
1439
1570
  if ((await this.#vms.state(name, { fresh: true }).catch(() => undefined)) !== undefined) await this.#vms.removeVm(vmName(name)).catch(() => {});
1440
1571
  this.#store.patch(name, { ...was, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingOutOf: undefined, moveFailed: `Not moved: ${why}` });
1441
1572
  if (left) await this.#vms.workMount(name, this.#uid, this.#gid).catch(() => {});
@@ -1471,7 +1602,7 @@ export class Conversations {
1471
1602
  this.#store.patch(name, { step: `Putting ${tool.label}'s state back` });
1472
1603
  try { await this.#unpack(name, c.tool, carried); } catch (error) { lost = error.message; }
1473
1604
  }
1474
- this.#store.patch(name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, toolStarted: false, movingOutOf: undefined });
1605
+ this.#store.patch(name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, ...NEW_DISK, ...(tool.state && !lost ? { toolsStarted: c.toolsStarted } : {}), movingOutOf: undefined });
1475
1606
  this.ready(name);
1476
1607
  /* There for good: its place in the shared machine goes -- the whole machine with the last one in it. */
1477
1608
  const others = this.#store.all().filter((x) => x.name !== name && x.sharedMachine === shared);
package/server/events.mjs CHANGED
@@ -28,6 +28,7 @@ const SAID = [
28
28
  [/^\/api\/conversations$/, 'conversation', (m, b, a) => `Conversation "${clip(a?.title ?? b.title ?? b.name)}" made (${clip(a?.tool ?? b.tool, 30)})`],
29
29
  [/^\/api\/conversations\/([^/]+)\/archive$/, 'conversation', (m) => `Conversation ${m[1]} archived`],
30
30
  [/^\/api\/conversations\/([^/]+)\/title$/, 'conversation', (m, b) => `Conversation ${m[1]} renamed "${clip(b.title)}"`],
31
+ [/^\/api\/conversations\/([^/]+)\/tool$/, 'conversation', (m, b) => `Conversation ${m[1]}: change of AI to ${clip(b.tool, 30)} asked`],
31
32
  [/^\/api\/conversations\/([^/]+)\/restart$/, 'machine', (m) => `Machine of ${m[1]} restarted`],
32
33
  [/^\/api\/conversations\/([^/]+)\/machine$/, 'machine', (m, b, a) => `Machine of ${m[1]} ${a?.sizeAtWake && a.phase === 'ready' ? 'to be resized as it wakes' : 'resized'}${b.memoryMb ? `: ${b.memoryMb} MB of memory` : ''}${b.diskGb ? `, ${b.diskGb} GB of disk` : ''}${b.cpus ? `, ${b.cpus} core${b.cpus > 1 ? 's' : ''}` : ''}`],
33
34
  [/^\/api\/conversations\/([^/]+)\/machine\/cancel$/, 'machine', (m) => `Machine of ${m[1]}: the size kept for its wake given up`],
package/server/main.mjs CHANGED
@@ -619,6 +619,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
619
619
  if (!dockets.on(name)) return false;
620
620
  try { dockets.post(name, { kind: 'restarted', text: `Your machine was restarted${why ? ` (${String(why).replace(/\.$/, '')})` : ''}. What ran in the background stopped with it: pick up where you were.` }); return true; } catch { return false; }
621
621
  };
622
+ /* ITS AI CHANGED (#404), or not: said in its chat and the journal. The new AI is told through its docket, once
623
+ free; without one, the line that makes it reread the thread goes with the person's next message. */
624
+ all.toolChanged = (name, said, line, ok) => {
625
+ events.add({ kind: 'conversation', text: `${name}: ${said}`, conversation: name });
626
+ try { talk.event(name, ok ? { kind: 'restarted', text: said, topic: 'Restarted' } : { kind: 'machine-problem', text: said, tone: 'bad', topic: 'Machine' }); } catch { /* its chat is off */ }
627
+ if (!ok) return;
628
+ try { if (dockets.on(name)) { dockets.post(name, { kind: 'ai-changed', text: line }); return; } } catch { /* the other way */ }
629
+ talk.renewed(name, '', true);
630
+ };
622
631
  /* What an owner did to a machine (start, stop, sleep, force, restart): in the journal, and a line in its chat. */
623
632
  all.machineSaid = (name, text, ok, chat) => {
624
633
  /* What runs changed (a start, a stop, a sleep): the rules follow at once, not at the next watch. */
@@ -1039,7 +1048,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
1039
1048
  shown in it first (after a rebuild there are some), and its health is
1040
1049
  looked at (folders that did not come back are put back): both on the
1041
1050
  way, as steps of its start (`mounted` above, conversations.mjs). */
1042
- all.ready = (name) => { toolbox.forget(name); void bridge.warm(name); };
1051
+ /* Resolves once its terminal is open (a change of AI waits for it); `warm` never rejects. */
1052
+ all.ready = (name) => { toolbox.forget(name); return bridge.warm(name); };
1043
1053
  /* Their health too: after a restart of the host, a folder may not have come back. */
1044
1054
  /* The tools are shown in them first: a machine made before /tools existed gets it now, not as "a folder that came loose". */
1045
1055
  /* After the quiet start, one machine after another (QUIET_STEP_MS apart). */
@@ -265,6 +265,7 @@ export const SETTINGS_WORDS_FR = {
265
265
  'set-secret-next-on': '{name} : remis à son outil au prochain démarrage', 'set-secret-next-off': '{name} : plus remis dès son prochain démarrage',
266
266
  'set-files-list': 'Liste', 'set-files-icons': 'Icônes', 'set-files-empty': 'Ce dossier est vide.',
267
267
  'set-files-read-only': 'Lecture seule : rien ne peut y être changé.',
268
+ 'set-ai': 'IA', 'set-ai-back': 'Revenir à {name}', 'set-ai-ask': 'Passer à {name} ? Elle relira ce fil.', 'set-ai-go': 'Changer', 'set-ai-no': 'Annuler',
268
269
  'set-this-conv': 'Cette conversation · {name}', 'set-ask-first': 'Demander avant d\'agir',
269
270
  'set-online': 'En ligne', 'set-offline-btn': 'Hors ligne', 'set-sleep': 'Endormir',
270
271
  'set-room-name': 'Nom', 'set-room-welcomes': 'Accueille', 'set-room-ais': 'Ses IA',
package/web/app.js CHANGED
@@ -3155,6 +3155,7 @@
3155
3155
  paintWatchdog(here);
3156
3156
  /* Whether its tool asks before acting -- for a tool that can be given every right in its machine. */
3157
3157
  $('rights-box').hidden = DEVICE || !here?.rights;
3158
+ paintAi(here);
3158
3159
  for (const b of $('ask-first').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.askFirst === true)));
3159
3160
  void paintConvHand(here);
3160
3161
  paintConvStates(here);
@@ -3211,6 +3212,53 @@
3211
3212
  chapterNow('health', here.asleep ? uiSaid('set-asleep', 'Asleep') : !hl ? uiSaid('set-not-looked', 'Not looked at yet') : join(wrong.length ? wrong[0].text : hl.state === 'Running' ? uiSaid('set-running-well', 'Running · nothing wrong') : hl.state, hl.at ? agoSaid(hl.at) : ''));
3212
3213
  chapterNow('advanced', uiSaid('set-conv-advanced', 'Archive · reset · delete'));
3213
3214
  }
3215
+ /* ITS AI (#404): one list, the one before offered to go back, a confirmation before anything changes. */
3216
+ function paintAi(here) {
3217
+ const box = $('ai-box');
3218
+ box.hidden = DEVICE || here?.switches !== true;
3219
+ if (box.hidden) { box.wanted = ''; $('ai-sure').hidden = true; return; }
3220
+ if (!box.tools && !box.asking) {
3221
+ box.asking = true;
3222
+ void fetch(`${API}/tools`).then((r) => (r.ok ? r.json() : null)).catch(() => null).then((list) => {
3223
+ box.asking = false;
3224
+ if (!Array.isArray(list)) return;
3225
+ box.tools = list.filter((t) => t.switches);
3226
+ paintAi(conversations.find((x) => x.name === current));
3227
+ });
3228
+ }
3229
+ const tools = box.tools ?? [{ id: here.tool, label: here.toolLabel ?? here.tool }];
3230
+ const choice = $('ai-choice');
3231
+ const of = `${here.name}/${here.tool}/${tools.map((t) => t.id).join()}`;
3232
+ if (choice.dataset.of !== of && document.activeElement !== choice) {
3233
+ choice.dataset.of = of;
3234
+ choice.replaceChildren(...tools.map((t) => { const o = document.createElement('option'); o.value = t.id; o.textContent = t.label; return o; }));
3235
+ box.wanted = '';
3236
+ }
3237
+ /* Nothing being chosen: it shows the AI it runs (a change that failed included). */
3238
+ if (!box.wanted && document.activeElement !== choice) choice.value = here.tool;
3239
+ const busy = Boolean(here.toolSwitch) || here.phase !== 'ready';
3240
+ choice.disabled = busy;
3241
+ const back = tools.find((t) => t.id === here.previousTool && t.id !== here.tool);
3242
+ $('ai-back').hidden = !back || busy;
3243
+ if (back) { $('ai-back').dataset.to = back.id; $('ai-back').textContent = uiSaid('set-ai-back', 'Back to {name}', { name: back.label }); }
3244
+ const asked = !busy && tools.find((t) => t.id === box.wanted);
3245
+ $('ai-sure').hidden = !asked;
3246
+ if (asked) $('ai-ask').textContent = uiSaid('set-ai-ask', 'Change to {name}? It will read this chat.', { name: asked.label });
3247
+ else box.wanted = '';
3248
+ const said = here.toolSwitch?.step ?? here.toolSwitchFailed ?? '';
3249
+ $('ai-said').textContent = said; $('ai-said').hidden = !said;
3250
+ }
3251
+ const aiHere = () => conversations.find((x) => x.name === current);
3252
+ $('ai-choice').addEventListener('change', () => { const here = aiHere(); $('ai-box').wanted = $('ai-choice').value === here?.tool ? '' : $('ai-choice').value; paintAi(here); });
3253
+ $('ai-back').addEventListener('click', () => { $('ai-box').wanted = $('ai-back').dataset.to; $('ai-choice').value = $('ai-back').dataset.to; paintAi(aiHere()); });
3254
+ $('ai-no').addEventListener('click', () => { const here = aiHere(); $('ai-box').wanted = ''; $('ai-choice').value = here?.tool ?? ''; paintAi(here); });
3255
+ $('ai-go').addEventListener('click', async () => {
3256
+ const to = $('ai-box').wanted; if (!to) return;
3257
+ $('panel-error').hidden = true; $('ai-box').wanted = '';
3258
+ try { await post(`${API}/conversations/${encodeURIComponent(current)}/tool`, { tool: to }); await refresh(); }
3259
+ catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; $('ai-choice').value = aiHere()?.tool ?? ''; }
3260
+ paintMachine(aiHere());
3261
+ });
3214
3262
  for (const b of $('ask-first').children) {
3215
3263
  b.addEventListener('click', async () => {
3216
3264
  $('panel-error').hidden = true;
package/web/index.html CHANGED
@@ -167,6 +167,12 @@
167
167
  <summary><span class="chapter-title" data-said="set-ch-general">General</span><span class="chapter-about">Name, group, chat.</span></summary>
168
168
  <div class="chapter-body">
169
169
  <dl id="general-facts" class="facts"></dl>
170
+ <!-- ITS AI, changed in the same conversation (#404), the one before offered to go back. -->
171
+ <div id="ai-box" hidden>
172
+ <div class="set-row"><div class="set-what"><label for="ai-choice" data-said="set-ai">AI</label></div><div class="set-control"><select id="ai-choice"></select><button type="button" id="ai-back" hidden></button></div></div>
173
+ <div class="set-row" id="ai-sure" hidden><div class="set-what"><span id="ai-ask"></span></div><div class="set-control"><button type="button" id="ai-go" class="primary" data-said="set-ai-go">Change</button><button type="button" id="ai-no" data-said="set-ai-no">Cancel</button></div></div>
174
+ <p class="hint" id="ai-said" role="status" hidden></p>
175
+ </div>
170
176
  <div id="title-box" hidden>
171
177
  <form id="title-form" class="set-row" autocomplete="off"><div class="set-what"><label for="title-name">Name</label></div><div class="set-control"><input id="title-name" maxlength="60" spellcheck="false"><button type="submit">Save</button></div></form>
172
178
  </div>