clavarium 0.2.244-beta.1 → 0.2.245-beta.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.
@@ -12,8 +12,9 @@
12
12
  * keys:PATTERN=K a question with one answer always: the keys K typed (Enter, Down, Up, Escape, 1, y...),
13
13
  * once per screen. Only what its launcher wrote: nothing else is ever typed.
14
14
  * type:PATTERN=TEXT the same with a few words (a command such as /login), then Enter; once per screen.
15
- * code:PATTERN the tool waits for a code the person gets after signing in: the next message they write
16
- * in the chat that looks like one (no space, 10 to 300 signs) is typed there, then Enter.
15
+ * code:PATTERN the tool waits for a code the person gets after signing in. Nothing here acts on it: the
16
+ * server reads the same rule, offers a field in the chat and types what is pasted there (#405).
17
+ * A chat message is never typed as a code.
17
18
  * Only the last LINES lines are read: what the tool prints of its own work above never counts.
18
19
  *
19
20
  * THE RULES FROM THE TOOLS' CONFIGURATION (15-11, #362): `--tool ID` reads the rules of that tool from
@@ -31,7 +32,7 @@
31
32
  */
32
33
  import { spawnSync } from 'node:child_process';
33
34
  import { randomUUID } from 'node:crypto';
34
- import { existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
35
36
  import { dirname, join } from 'node:path';
36
37
  import { fileURLToPath } from 'node:url';
37
38
 
@@ -47,7 +48,7 @@ export function rulesOf(args) {
47
48
  try { return [{ kind: m[1], re: new RegExp(pattern, 'i'), value }]; } catch { return []; }
48
49
  });
49
50
  }
50
- /* What the person pastes, or the companion gives back, that may be typed as a code: no space, 10 to 300 signs. */
51
+ /* What the person pastes in the sign-in field, or the companion gives back, that may be typed as a code: no space, 10 to 300 signs. */
51
52
  export const CODE = /^[A-Za-z0-9_#.~+/=-]{10,300}$/;
52
53
  export const RULES_FILE = 'screen-rules.json';
53
54
  const SIGNIN_KINDS = new Set(['link', 'keys', 'type', 'code']);
@@ -85,27 +86,22 @@ export function actionsOn(screen, rules, seen) {
85
86
  }
86
87
 
87
88
  /* Where a sign-in link goes, step by step (15-11, #362): what to do, as a list of effects the caller runs --
88
- { do: 'ask', ask } (write signin-ask.json), 'tell-link' { a } (the link in the person's chat), 'arm' (the next
89
- code the person pastes is typed), 'tell-paste' (say so). `route()`: signin-route.json as read, or null. */
89
+ { do: 'ask', ask } (write signin-ask.json), 'tell-link' { a } (the link in the person's chat). `field: true` in
90
+ the ask: this watcher reads no code from the chat (#405; an older one does, see SigninHelp.oldWatcherArmed).
91
+ `route()`: signin-route.json as read, or null. */
90
92
  export const HAND_MS = 20_000;
91
93
  export class Relay {
92
94
  #ask = null; #now; #id; #route; #chat;
93
95
  constructor({ route = () => null, chat = () => true, now = () => Date.now(), id = () => randomUUID() } = {}) { this.#route = route; this.#chat = chat; this.#now = now; this.#id = id; }
94
96
  /* Told to the person: the ask says so too (`told`), so that a server that reads it late hands it to nobody. */
95
- #person() { const a = this.#ask; a.route = 'person'; return [{ do: 'ask', ask: { ...a.file, told: true } }, { do: 'tell-link', a: a.a }, ...(a.codeSeen ? [{ do: 'arm' }, { do: 'tell-paste' }] : [])]; }
97
+ #person() { const a = this.#ask; a.route = 'person'; return [{ do: 'ask', ask: { ...a.file, told: true } }, { do: 'tell-link', a: a.a }]; }
96
98
  link(a) {
97
99
  /* No chat folder: nowhere to hand it over, nobody but the person (and the chat is off anyway). */
98
100
  if (!this.#chat()) return [{ do: 'tell-link', a }];
99
101
  const id = this.#id(); const at = this.#now();
100
- this.#ask = { id, at, a, route: null, codeSeen: false, file: { id, at: new Date(at).toISOString(), link: a.match, around: a.around ?? '' } };
102
+ this.#ask = { id, at, a, route: null, file: { id, at: new Date(at).toISOString(), link: a.match, around: a.around ?? '', field: true } };
101
103
  return [{ do: 'ask', ask: this.#ask.file }];
102
104
  }
103
- code() {
104
- const a = this.#ask;
105
- if (!a || a.route === 'person') return [{ do: 'arm' }, { do: 'tell-paste' }];
106
- /* Handed over, or not known yet: the person is not asked to paste, unless it comes back to them. */
107
- a.codeSeen = true; return [];
108
- }
109
105
  step() {
110
106
  const a = this.#ask; if (!a || a.route === 'person') return [];
111
107
  const r = this.#route(); const mine = r && r.id === a.id ? r.route : null;
@@ -125,25 +121,6 @@ if (main) {
125
121
  const pane = process.env.SCREEN_WATCH_PANE ?? '=main:';
126
122
  const chat = process.env.PARLEY_DIR ?? '/work/.parley';
127
123
  const seen = new Set();
128
- /* Waiting for a code: the person's chat, from where it stood when the tool asked (to-agent.jsonl). */
129
- let awaiting = null;
130
- const inbox = `${chat}/to-agent.jsonl`;
131
- const codeFrom = () => { try { return statSync(inbox).size; } catch { return 0; } };
132
- const typeCode = () => {
133
- if (awaiting === null) return;
134
- let text = ''; try { const b = readFileSync(inbox); text = b.subarray(awaiting).toString('utf8'); } catch { return; }
135
- for (const line of text.split('\n').filter(Boolean)) {
136
- let m; try { m = JSON.parse(line); } catch { continue; }
137
- const code = String(m?.text ?? '').trim();
138
- if (CODE.test(code)) {
139
- spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, '-l', '--', code], { timeout: 5000 });
140
- spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, 'Enter'], { timeout: 5000 });
141
- /* Typed: the ask is over, so the next message that looks like a code is a secret again (#394). */
142
- try { rmSync(`${chat}/signin-ask.json`, { force: true }); } catch { /* left: it runs out on the server's side */ }
143
- awaiting = null; return;
144
- }
145
- }
146
- };
147
124
  /* The sign-in link's way (Relay): asked in the chat folder, routed by the server. */
148
125
  const readRoute = () => { try { return JSON.parse(readFileSync(`${chat}/signin-route.json`, 'utf8')); } catch { return null; } };
149
126
  const relay = new Relay({ route: readRoute, chat: () => existsSync(chat) });
@@ -151,12 +128,9 @@ if (main) {
151
128
  for (const e of effects) {
152
129
  if (e.do === 'ask') { try { writeFileSync(`${chat}/.signin-ask.json.new`, JSON.stringify(e.ask)); renameSync(`${chat}/.signin-ask.json.new`, `${chat}/signin-ask.json`); } catch { /* not written: no answer comes, told to the person after HAND_MS */ } }
153
130
  if (e.do === 'tell-link') spawnSync('parley', ['tell', `Your tool asks you to open this link: ${e.a.match}${e.a.around && e.a.around !== e.a.match ? `\n\n\`\`\`\n${e.a.around}\n\`\`\`` : ''}`, '--dir', chat], { timeout: 10_000 });
154
- if (e.do === 'arm') awaiting = codeFrom();
155
- if (e.do === 'tell-paste') spawnSync('parley', ['tell', 'Once signed in, paste here the code the page gives you.', '--dir', chat], { timeout: 10_000 });
156
131
  }
157
132
  };
158
133
  const look = () => {
159
- typeCode();
160
134
  run(relay.step());
161
135
  const r = spawnSync('tmux', [...tmux, 'capture-pane', '-p', '-t', pane], { encoding: 'utf8', timeout: 5000 });
162
136
  if (r.status !== 0) return;
@@ -165,7 +139,6 @@ if (main) {
165
139
  if (a.kind === 'notice') spawnSync('docket', ['remind', '--in', '1m', a.value, '--dir', process.env.DOCKET_DIR ?? '/work/.docket'], { timeout: 10_000 });
166
140
  if (a.kind === 'keys') for (const k of a.value) spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, k], { timeout: 5000 });
167
141
  if (a.kind === 'type') { spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, '-l', '--', a.value], { timeout: 5000 }); spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, 'Enter'], { timeout: 5000 }); }
168
- if (a.kind === 'code') run(relay.code());
169
142
  }
170
143
  };
171
144
  /* Its life is the tool's: started just before the launcher becomes the tool (exec), it ends with it. */
package/config/tools.json CHANGED
@@ -78,7 +78,8 @@
78
78
  "keys:Select login method:=Enter",
79
79
  "link:https://(claude\\.ai|claude\\.com|console\\.anthropic\\.com)/\\S*oauth\\S*",
80
80
  "code:Paste code here"
81
- ]
81
+ ],
82
+ "refused": "OAuth error"
82
83
  }
83
84
  },
84
85
  {
@@ -298,6 +299,7 @@
298
299
  "install",
299
300
  "-q",
300
301
  "--disable-pip-version-check",
302
+ "--force-reinstall",
301
303
  "mistral-vibe"
302
304
  ],
303
305
  [
package/deploy/install.sh CHANGED
@@ -32,7 +32,7 @@
32
32
  # asap: as soon as a version is out; ask: says so in
33
33
  # Settings and waits; off. Changed later in Settings.
34
34
  # --update-window HH:MM-HH:MM when "auto" may update (default 02:00-05:00)
35
- # --channel C latest (default) or next (versions with a "-": tests)
35
+ # --channel C latest (default), beta (proven by tests) or next (versions to try)
36
36
  # --keep-release keep the release that runs (change the settings only:
37
37
  # what `clavarium online` does to go from local mode to
38
38
  # server mode)
@@ -116,7 +116,7 @@ DEX_LAYER="680f1119fdbcdd7f0ad8985b2534ded871b08b5b77c40f337c38aebd062b59c2"
116
116
  DEX_SHA256="217aa675738d1cbaf25fe8d7bc04cb00dbc60f91d8465b76b8d8af963d571337"
117
117
  HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
118
118
 
119
- bad() { echo "install: $*" >&2; echo "usage: install.sh --domain NAME --operator EMAIL [--operator EMAIL...] [--port N] [--relay HOST [--relay-port N]] [--core-only] [--version X.Y.Z | --from-dir DIR] [--updates auto|asap|ask|off] [--update-window HH:MM-HH:MM] [--channel latest|next] [--name NAME] [--client-id ID] [--dry-run]" >&2; echo " or: install.sh --local [--port N] [same options] [--dry-run] to try it on this machine, with no domain" >&2; exit 64; }
119
+ bad() { echo "install: $*" >&2; echo "usage: install.sh --domain NAME --operator EMAIL [--operator EMAIL...] [--port N] [--relay HOST [--relay-port N]] [--core-only] [--version X.Y.Z | --from-dir DIR] [--updates auto|asap|ask|off] [--update-window HH:MM-HH:MM] [--channel latest|beta|next] [--name NAME] [--client-id ID] [--dry-run]" >&2; echo " or: install.sh --local [--port N] [same options] [--dry-run] to try it on this machine, with no domain" >&2; exit 64; }
120
120
  refuse() { echo "install: REFUSED: $*" >&2; exit 78; }
121
121
  step() { echo "== $*"; }
122
122
 
@@ -183,7 +183,7 @@ if [ -z "$VERSION" ] && [ -z "$FROM_DIR" ]; then
183
183
  fi
184
184
  [ -z "$UPDATES" ] || [[ "$UPDATES" =~ ^(auto|asap|ask|off)$ ]] || bad "--updates is auto, asap, ask or off"
185
185
  [ -z "$WINDOW" ] || { [[ "$WINDOW" =~ ^([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9]$ ]] && [ "${WINDOW%-*}" != "${WINDOW#*-}" ]; } || bad "--update-window is two times, like 02:00-05:00"
186
- [ -z "$CHANNEL" ] || [[ "$CHANNEL" =~ ^(latest|next)$ ]] || bad "--channel is latest or next"
186
+ [ -z "$CHANNEL" ] || [[ "$CHANNEL" =~ ^(latest|beta|next)$ ]] || bad "--channel is latest, beta or next"
187
187
  # It goes in the unit file, between quotes: plain characters only (any other is chosen in Settings).
188
188
  [ -z "$APP_NAME" ] || [[ "$APP_NAME" =~ ^[A-Za-z0-9]([A-Za-z0-9\ ._-]{0,28}[A-Za-z0-9.])?$ ]] || bad "--name is letters, digits, spaces, dots and hyphens, 30 at most, like \"Home lab\""
189
189
  # The OAuth client id, seen in the open when a browser is sent to sign in. Default:
@@ -194,7 +194,7 @@ fi
194
194
  had() { { sed -n "s/^$1=//p" "$UPDATE_CONF" 2>/dev/null || true; } | head -1; }
195
195
  SHOW_MODE="${UPDATES:-$(had MODE)}"; SHOW_MODE="${SHOW_MODE:-auto}"
196
196
  SHOW_WINDOW="${WINDOW:-$(had WINDOW)}"; SHOW_WINDOW="${SHOW_WINDOW:-02:00-05:00}"
197
- case "$VERSION" in *-*) default_channel="next" ;; *) default_channel="latest" ;; esac
197
+ case "$VERSION" in *-beta.*) default_channel="beta" ;; *-*) default_channel="next" ;; *) default_channel="latest" ;; esac
198
198
  SHOW_CHANNEL="${CHANNEL:-$(had CHANNEL)}"; SHOW_CHANNEL="${SHOW_CHANNEL:-$default_channel}"
199
199
 
200
200
  # The Node.js the server runs on: the same pinned version, with the same
@@ -203,6 +203,11 @@ NODE_VERSION="$(sed -n "s/^export const NODE_VERSION = '\(v[0-9.]*\)';$/\1/p" "$
203
203
  NODE_SHA256="$(sed -n "s/^export const NODE_SHA256 = '\([0-9a-f]\{64\}\)';$/\1/p" "$HERE/server/tools.mjs")"
204
204
  [ -n "$NODE_VERSION" ] && [ -n "$NODE_SHA256" ] || refuse "the pinned Node.js version was not found in $HERE/server/tools.mjs"
205
205
 
206
+ # ALREADY ONLINE (22-11, #409): local mode would rewrite the service without its operators.
207
+ if [ "$LOCAL" = "yes" ] && [ "$DRY" != "yes" ] && grep -q -- ' --operators ' "$UNIT" 2>/dev/null; then
208
+ refuse "this Clavarium is online: it updates itself. Installing in local mode would remove its sign-in. Nothing was changed."
209
+ fi
210
+
206
211
  if [ "$DRY" = "yes" ]; then
207
212
  cat <<PLAN
208
213
  would install Clavarium:
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.244-beta.1",
3
+ "version": "0.2.245-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.244-beta.1",
9
+ "version": "0.2.245-beta.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.244-beta.1",
3
+ "version": "0.2.245-beta.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
@@ -32,6 +32,7 @@
32
32
  * POST /api/signin-companion {companion}: the conversation that signs the others' tools in with its browser ('' none; 15-11); {clicks}: it clicks Authorize itself
33
33
  * POST /api/conversations/<name>/signin-companion {companion}: its own (a conversation, "none"), or null for the general one; never itself
34
34
  * POST /api/conversations/<name>/signin-link its sign-in handed to a companion: shown to the person instead
35
+ * POST /api/conversations/<name>/signin-code {code}: typed into its tool at its code prompt; kept nowhere (#405)
35
36
  * POST /api/conversations/<name>/ask-first {on}: its tool asks before acting (true), or acts without asking in its machine (false, the default), from its next start
36
37
  * POST /api/conversations/<name>/resume {on}: its tool takes up its last session when it starts (true), or starts fresh
37
38
  * POST /api/conversations/<name>/terminal/repair its terminal does not come though its machine runs: repaired
@@ -40,6 +41,7 @@
40
41
  * POST /api/conversations/<name>/talk/pin {to, on}: the owner pins a message of the chat (on: false unpins); 5 at most
41
42
  * POST /api/conversations/<name>/talk/split {messages: 500..100000} | {days: 0.5..365} | {off: true}: when its thread is
42
43
  * archived into volumes (nothing deleted) -> {split}; read back as `split` in GET .../talk
44
+ * POST /api/conversations/<name>/tool {tool}: changes its AI, in the same conversation (202: goes on; `toolSwitch`, then `toolSwitchFailed`)
43
45
  * POST /api/conversations/<name>/chat-name {name}: the name the chat gives its tool ('' : the neutral word of the dictionary)
44
46
  * POST /api/conversations/<name>/tasks-binder {binder}: the binder shown beside its chat ('' automatic, '-' none, else an id)
45
47
  * POST /api/conversations/<name>/voice-mark {on}: what is dictated into its terminal starts with a microphone sign (AI tools only)
@@ -589,6 +591,9 @@ export async function handleApi(request, response, conversations, headers, resou
589
591
  return send(403, { error: 'This request does not come from this site.' }), true;
590
592
  }
591
593
  const body = await readBody(request, pathname === '/api/setup/preview' || pathname === '/api/setup/import' ? SETUP_BODY_MAX : BODY_MAX);
594
+ /* A SIGN-IN CODE (#405): answered before anything below can see this body (the journal, say). */
595
+ const codeOf = /^\/api\/conversations\/([^/]+)\/signin-code$/.exec(pathname);
596
+ if (codeOf && conversations.signinHelp) return send(200, await conversations.signinHelp.enterCode(decodeURIComponent(codeOf[1]), body?.code)), true;
592
597
  /* What was done, once it was done: said in What happened (events.mjs), for those worth saying. */
593
598
  if (events) { const answer = send; send = (status, out) => { if (status < 300) { try { events.fromRequest(pathname, body, identity, out); } catch { /* never in the way */ } } answer(status, out); }; }
594
599
  if (rooms && pathname.startsWith('/api/rooms')) {
@@ -1043,6 +1048,8 @@ export async function handleApi(request, response, conversations, headers, resou
1043
1048
  if (linkOf && conversations.signinHelp) return send(200, conversations.signinHelp.showLink(decodeURIComponent(linkOf[1]))), true;
1044
1049
  const asking = /^\/api\/conversations\/([^/]+)\/ask-first$/.exec(pathname);
1045
1050
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
1051
+ const changingAi = /^\/api\/conversations\/([^/]+)\/tool$/.exec(pathname);
1052
+ if (changingAi) return send(202, await conversations.switchTool(decodeURIComponent(changingAi[1]), body.tool)), true;
1046
1053
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
1047
1054
  if (naming) return send(200, conversations.setChatName(decodeURIComponent(naming[1]), body.name)), true;
1048
1055
  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) && !c.sharedMachine, 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,133 @@ 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
+ /* Not tried on a real shared machine yet (22-11): refused rather than promised. */
983
+ if (c.sharedMachine) throw new Refusal(409, 'Changing its AI needs its own machine.');
984
+ if (!canSwitch(from)) throw new Refusal(409, `${from?.label ?? c.tool} cannot be changed for another AI.`);
985
+ if (!canSwitch(target)) throw new Refusal(400, `A conversation cannot change to ${target.label}.`);
986
+ 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 });
987
+ if ((Number(c.memoryMb) || 0) < target.memoryMb) throw new Refusal(409, `${target.label} needs ${target.memoryMb} MB of memory: give its machine more first.`);
988
+ /* Taken before anything is awaited: a second request sees it. */
989
+ const act = this.#take(name, 'tool');
990
+ try {
991
+ 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 });
992
+ } catch (error) { this.#give(name, act); throw error; }
993
+ this.#cancelStop(name);
994
+ this.#store.patch(name, { toolSwitch: { to, label: target.label, step: `Installing ${target.label}` }, toolSwitchFailed: undefined });
995
+ this.switched = this.#switching(name, from, target, act).finally(() => this.#give(name, act));
996
+ return this.#store.get(name);
997
+ }
998
+
999
+ async #switching(name, from, target, act) {
1000
+ const failed = (why) => {
1001
+ if (!this.#store.get(name)) return false;
1002
+ const said = `Its AI stays ${from.label}: ${String(why).replace(/\.?$/, '.')}`;
1003
+ this.#store.patch(name, { toolSwitch: undefined, toolSwitchFailed: said });
1004
+ try { this.toolChanged(name, said, '', false); } catch { /* told, nothing more */ }
1005
+ return false;
1006
+ };
1007
+ try {
1008
+ const missing = await this.#installFor(name, target, act);
1009
+ if (missing) return failed(missing);
1010
+ const now = this.#store.get(name);
1011
+ if (!now) return false; /* archived meanwhile */
1012
+ if (now.phase !== 'ready') return failed('it is busy.');
1013
+ /* What each tool has done on this disk. A record from before this was kept says nothing of the one it
1014
+ leaves: it has run there, and a tool told to resume where it has no session starts a new one. */
1015
+ const started = { ...now.toolsStarted };
1016
+ if (now.toolStarted !== false) started[from.id] = true;
1017
+ const back = started[target.id] === true;
1018
+ delete started[target.id];
1019
+ const was = { tool: now.tool, toolStarted: now.toolStarted, toolsStarted: now.toolsStarted, previousTool: now.previousTool };
1020
+ /* The record first: a screen that reopens meanwhile starts the new AI, never the old. */
1021
+ this.#store.patch(name, { tool: target.id, toolStarted: back, toolsStarted: Object.keys(started).length ? started : undefined, previousTool: from.id, toolSwitch: undefined });
1022
+ /* Its next opening prepares it from nothing: the guide's pointer goes in the new AI's own file. */
1023
+ this.#fresh.add(name);
1024
+ await this.#endTurn(name);
1025
+ await this.ready(name);
1026
+ if (await this.#staysUp(name)) {
1027
+ const said = `Its AI is now ${target.label} (was ${from.label}).`;
1028
+ const line = `You now run this conversation, in place of ${from.label}: read its thread first (parley read --last 100), then carry on.`;
1029
+ try { this.toolChanged(name, said, line, true); } catch { /* told, nothing more */ }
1030
+ return true;
1031
+ }
1032
+ if (!this.#store.get(name)) return false;
1033
+ this.#store.patch(name, was);
1034
+ this.#fresh.add(name);
1035
+ await this.#endTurn(name);
1036
+ await this.ready(name);
1037
+ /* Its tools folder came loose (the VM manager's mount died): only a restart of the machine puts it back (health.mjs, STUCK_MOUNT). */
1038
+ const loose = (await this.#vms.exec(name, ['timeout', '5', 'ls', `${TOOLS_PATH}/${LAUNCH}`], { timeoutMs: 10_000 }).catch(() => ({ code: 1 }))).code !== 0;
1039
+ return failed(loose ? `${target.label} did not start: its tools folder came loose. Restart its machine, then try again.` : `${target.label} did not start.`);
1040
+ } catch (error) { return failed(error?.message ?? error); }
1041
+ }
1042
+
1043
+ /* The tool stopped, and the turn it was in said ended: stopped mid-turn, its « working » would stay for ever
1044
+ under an AI that does not say it (not every tool has a pulse). */
1045
+ async #endTurn(name) {
1046
+ await this.#stopTool(name);
1047
+ 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(() => {});
1048
+ }
1049
+
1050
+ /* Its session is still there a moment after it started (a tool that exits ends its session: tmux.mjs). */
1051
+ async #staysUp(name) {
1052
+ await new Promise((r) => { setTimeout(r, this.switchSettleMs).unref?.(); });
1053
+ return (await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'has-session', '-t', `=${SESSION}`], { timeoutMs: 10_000 }).catch(() => ({ code: 1 }))).code === 0;
1054
+ }
1055
+
1056
+ /* ITS RECIPE, the one a build runs (`tool.steps`), for what is missing. On the machine already (another
1057
+ conversation of a shared machine, an earlier change): only its own settings steps, and only when it has no
1058
+ state here -- they write its settings, and what it has is never overwritten. -> what went wrong, or undefined. */
1059
+ async #installFor(name, tool, act) {
1060
+ act.ctl = new AbortController();
1061
+ const run = (argv, options = {}) => this.#vms.exec(name, argv, { ...options, signal: act.ctl.signal });
1062
+ /* AN INSTALL CUT OFF (22-11, seen on a real machine: forced off in the middle, its program left EMPTY, which
1063
+ starts and exits at once): marked while it runs, written to disk before the mark goes. Marked or empty: not there. */
1064
+ const mark = `.clavarium-installing-${tool.id}`;
1065
+ const present = async () => (await run(['sh', '-c', 'command -v "$1" >/dev/null && [ -s "$(readlink -f "$(command -v "$1")")" ] && [ ! -e "$HOME/$2" ]', 'probe', tool.command[0], mark])).code === 0;
1066
+ let steps = tool.steps;
1067
+ if (tool.steps.length === 0 || await present()) {
1068
+ const r = await run(['sh', '-c', 'for p in "$@"; do [ -e "$HOME/$p" ] && exit 0; done; exit 3', 'probe', ...tool.state.keep]);
1069
+ if (r.code !== 0 && r.code !== 3) return `its machine could not be read (${firstLine(r.stderr) || `exit ${r.code}`})`;
1070
+ steps = r.code === 0 ? [] : tool.steps.filter((s) => s.argv[0] !== 'sudo');
1071
+ }
1072
+ if (steps.length > 0) {
1073
+ const r = await run(['sh', '-c', 'touch "$HOME/$1" && sync', 'probe', mark]);
1074
+ if (r.code !== 0) return `its machine could not be written (${firstLine(r.stderr) || `exit ${r.code}`})`;
1075
+ }
1076
+ for (const [i, step] of steps.entries()) {
1077
+ if (!this.#store.get(name)) return 'it was archived';
1078
+ if (act.preempted) return 'its machine was forced off';
1079
+ this.#store.patch(name, { toolSwitch: { to: tool.id, label: tool.label, step: `Installing ${tool.label} (${i + 1}/${steps.length})` } });
1080
+ const r = await run(step.argv, { input: step.input, timeoutMs: STEP_MS });
1081
+ if (act.preempted) return 'its machine was forced off';
1082
+ if (r.code !== 0) return `installing ${tool.label} failed at step ${i + 1}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`;
1083
+ }
1084
+ if (act.preempted) return 'its machine was forced off';
1085
+ if (steps.length > 0) await run(['sh', '-c', 'sync; rm -f "$HOME/$1"; sync', 'probe', mark]);
1086
+ if (steps.length > 0 && !(await present())) return `${tool.label} is not there after its install`;
1087
+ return undefined;
1088
+ }
1089
+
953
1090
  /* CARRIED ELSEWHERE (11-11, #351): what the conversation is beyond /work -- its tool's state, where its
954
1091
  entry in config/tools.json says it is (`state.keep`, without `state.skip`) -- as one .tar.gz streamed
955
1092
  from its machine, a manifest first (clavarium-conversation.json: its tool, its name, its size). Nothing
@@ -958,9 +1095,11 @@ export class Conversations {
958
1095
  /* `toWork` (14-11): the archive written into its own work folder (/work/.clavarium-carry/<toWork>.tgz), that
959
1096
  the server reads on its side, rather than sent out through the VM manager's output -- which stalled for good
960
1097
  past ~36 KB on the owner's server. Its output is then empty. */
961
- async exportState(name, { toWork } = {}) {
1098
+ /* `others` (#404): a copy or a move carries the state of the AIs it ran before too, so that the way back still holds. */
1099
+ async exportState(name, { toWork, others = false } = {}) {
962
1100
  const c = this.#store.get(name);
963
1101
  if (!c) throw new Refusal(404, 'No such conversation.');
1102
+ this.#notChangingAi(name);
964
1103
  const tool = this.#tools.find((t) => t.id === c.tool);
965
1104
  if (!tool?.state) throw new Refusal(409, `${tool?.label ?? c.tool} does not say where it keeps its state: it cannot be exported.`);
966
1105
  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 +1116,8 @@ export class Conversations {
977
1116
  archive is whole all the same -- what was there, read; only a real error (2) fails. */
978
1117
  + '[ "$rc" -le 1 ]';
979
1118
  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]);
1119
+ const carried = [tool, ...(others ? Object.keys(c.toolsStarted ?? {}).map((id) => this.#tools.find((t) => t.id === id)).filter((t) => t?.state) : [])];
1120
+ 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
1121
  const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'pipe'] });
982
1122
  /* What it said when it failed: kept short, for the message that says why (a copy, a move). */
983
1123
  child.said = '';
@@ -992,6 +1132,7 @@ export class Conversations {
992
1132
  async exportWhole(name) {
993
1133
  const c = this.#store.get(name);
994
1134
  if (!c) throw new Refusal(404, 'No such conversation.');
1135
+ this.#notChangingAi(name);
995
1136
  const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
996
1137
  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
1138
  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 +1261,7 @@ export class Conversations {
1120
1261
  async copy(name, { title, machine, machineMb, reminders = false } = {}) {
1121
1262
  const c = this.#store.get(name);
1122
1263
  if (!c) throw new Refusal(404, 'No such conversation.');
1264
+ this.#notChangingAi(name);
1123
1265
  if (c.phase !== 'ready') throw new Refusal(409, 'It is busy: copy it once it is ready.');
1124
1266
  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
1267
  const tool = this.#tools.find((t) => t.id === c.tool);
@@ -1185,7 +1327,7 @@ export class Conversations {
1185
1327
  const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
1186
1328
  if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(from, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
1187
1329
  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 } : {});
1330
+ const out = await this.exportState(from, { others: true, ...(inWork ? { toWork: carryId } : {}) });
1189
1331
  child = out.child;
1190
1332
  let read = 0; let lastAt = Date.now(); let stalled = false;
1191
1333
  const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read`); };
@@ -1254,7 +1396,8 @@ export class Conversations {
1254
1396
  if (reminders && typeof this.copyReminders === 'function') await Promise.resolve().then(() => this.copyReminders(from, to)).catch(() => {});
1255
1397
  this.#holding.delete(to);
1256
1398
  if (!this.#store.get(to)) return undefined;
1257
- this.#store.patch(to, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined });
1399
+ /* The AIs its original ran before came with its state (#404): the way back is the copy's too. */
1400
+ this.#store.patch(to, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, ...(tool.state ? { toolsStarted: c.toolsStarted, previousTool: c.previousTool } : {}) });
1258
1401
  this.ready(to);
1259
1402
  return undefined;
1260
1403
  } catch (error) {
@@ -1277,6 +1420,7 @@ export class Conversations {
1277
1420
  own disk is refused (its files would stay behind): kept first (its settings, Its files).
1278
1421
  -> the record, at once; `this.built`: the end of it. */
1279
1422
  async moveToShared(name, { machine, machineMb } = {}) {
1423
+ if (this.#store.get(name)?.offline === true) throw new Refusal(409, 'It is offline, which needs its own machine: put it online first.');
1280
1424
  const c = this.#busyCheck(name);
1281
1425
  if (c.sharedMachine) throw new Refusal(409, `It lives in the shared machine ${c.sharedMachine} already.`);
1282
1426
  if (typeof machine !== 'string' || !isConversationName(machine)) throw new Refusal(400, 'A machine name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter.');
@@ -1328,7 +1472,7 @@ export class Conversations {
1328
1472
  const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
1329
1473
  if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(name, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
1330
1474
  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 } : {});
1475
+ const { stream, child } = await this.exportState(name, { others: true, ...(inWork ? { toWork: carryId } : {}) });
1332
1476
  let read = 0; let lastAt = Date.now(); let stalled = false;
1333
1477
  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
1478
  const sizing = setInterval(() => {
@@ -1352,7 +1496,7 @@ export class Conversations {
1352
1496
  const carried = join(dir, 'state.tar.gz');
1353
1497
  const back = (why) => {
1354
1498
  /* 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}` });
1499
+ 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
1500
  this.#fresh.add(name); this.#mountAgain.add(name);
1357
1501
  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
1502
  };
@@ -1388,7 +1532,7 @@ export class Conversations {
1388
1532
  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
1533
  return undefined;
1390
1534
  }
1391
- this.#store.patch(name, { phase: 'ready', step: undefined });
1535
+ this.#store.patch(name, { phase: 'ready', step: undefined, toolsStarted: c.toolsStarted });
1392
1536
  this.ready(name);
1393
1537
  }
1394
1538
  /* There for good: its own machine can go. */
@@ -1435,7 +1579,7 @@ export class Conversations {
1435
1579
  const back = async (why) => {
1436
1580
  /* Back in its shared machine, as it was: its own machine, if begun, removed; its work shown there again. */
1437
1581
  if (!this.#store.get(name)) return undefined;
1438
- this.#store.patch(name, { sharedMachine: undefined });
1582
+ this.#store.patch(name, { sharedMachine: undefined, toolsStarted: c.toolsStarted });
1439
1583
  if ((await this.#vms.state(name, { fresh: true }).catch(() => undefined)) !== undefined) await this.#vms.removeVm(vmName(name)).catch(() => {});
1440
1584
  this.#store.patch(name, { ...was, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingOutOf: undefined, moveFailed: `Not moved: ${why}` });
1441
1585
  if (left) await this.#vms.workMount(name, this.#uid, this.#gid).catch(() => {});
@@ -1471,7 +1615,7 @@ export class Conversations {
1471
1615
  this.#store.patch(name, { step: `Putting ${tool.label}'s state back` });
1472
1616
  try { await this.#unpack(name, c.tool, carried); } catch (error) { lost = error.message; }
1473
1617
  }
1474
- this.#store.patch(name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, toolStarted: false, movingOutOf: undefined });
1618
+ this.#store.patch(name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, ...NEW_DISK, ...(tool.state && !lost ? { toolsStarted: c.toolsStarted } : {}), movingOutOf: undefined });
1475
1619
  this.ready(name);
1476
1620
  /* There for good: its place in the shared machine goes -- the whole machine with the last one in it. */
1477
1621
  const others = this.#store.all().filter((x) => x.name !== name && x.sharedMachine === shared);
@@ -2236,7 +2380,10 @@ export class Conversations {
2236
2380
 
2237
2381
  /* Online or offline: remembered here, enforced by network.mjs. */
2238
2382
  setOffline(name, offline) {
2239
- if (!this.#store.get(name)) throw new Refusal(404, 'No such conversation.');
2383
+ const c = this.#store.get(name);
2384
+ if (!c) throw new Refusal(404, 'No such conversation.');
2385
+ /* A shared machine has one network for all its agents: the rules, by machine, could not cut this one (#410). */
2386
+ if (offline === true && c.sharedMachine) throw new Refusal(409, 'Offline needs its own machine.');
2240
2387
  this.#store.patch(name, { offline: offline === true });
2241
2388
  }
2242
2389
 
package/server/door.mjs CHANGED
@@ -27,6 +27,7 @@
27
27
  * POST /c/api/<pairing>/conversations/<any>/talk/react {to, reaction}: a reaction to a message of the tool (null: taken back)
28
28
  * POST /c/api/<pairing>/conversations/<any>/talk/file?name= a file attached to a message
29
29
  * POST /c/api/<pairing>/terminal/repair its terminal does not come (see conversations.mjs)
30
+ * POST /c/api/<pairing>/conversations/<any>/signin-code?c=<any> {code}: only a device given its terminal, which could type it there (#405)
30
31
  * the chat of its conversation, where it talks through the app (see
31
32
  * talk.mjs): read, written to, reminded. Turning it on and inviting
32
33
  * the tool stay the owner's.
@@ -86,7 +87,7 @@ export function devicePairing(devices, headers, pairing) {
86
87
  }
87
88
 
88
89
  /* Returns true when the request was under /c/api/ (answered here). */
89
- export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes }) {
90
+ export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode }) {
90
91
  const url = new URL(request.url ?? '/', 'http://local');
91
92
  if (!url.pathname.startsWith('/c/api/')) return false;
92
93
  /* "/<pairing>/me" -> the pairing and "/me"; "/pair" has no pairing yet. */
@@ -190,6 +191,13 @@ export async function handleDoor(request, response, { devices, conversations, re
190
191
  }
191
192
  if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request); return send(201, await talk.say(name, body.text, body.answers, body.files, body.via, { quick: body.quick === true })); }
192
193
  }
194
+ /* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
195
+ const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
196
+ if (request.method === 'POST' && codeFor && signinCode) {
197
+ need(part.terminal, 'the terminal');
198
+ if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
199
+ return send(200, await signinCode(name, (await readJson(request)).code));
200
+ }
193
201
  /* Its terminal does not come: only a device given it asks for it to be repaired. */
194
202
  if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
195
203
  /* The device takes itself out: this pairing is removed, here and on the server. */