clavarium 0.2.84-next.1 → 0.2.85-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.
package/config/tools.json CHANGED
@@ -64,6 +64,7 @@
64
64
  {
65
65
  "id": "opencode",
66
66
  "instructions": ".config/opencode/AGENTS.md",
67
+ "logs": [".local/share/opencode/log"],
67
68
  "label": "OpenCode",
68
69
  "command": [
69
70
  "opencode"
@@ -211,6 +211,18 @@ run() { if [ "$SAY" = "yes" ]; then printf '%s\n' "$*"; else exec "$@"; fi; }
211
211
  # with a letter; no trailing hyphen; 32 at most. The same rule as the server.
212
212
  is_name() { [[ "$1" =~ ^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }
213
213
  vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of our VMs: ${1:-<empty>}"; }
214
+ # The qemu process(es) of one of our machines -- a qemu-system whose disk is in
215
+ # that instance, the mapping "server room" also uses. Empty when none is left,
216
+ # which is what a suspend that freed the RAM leaves behind.
217
+ vm_qemu_pids() {
218
+ local want="$1" pid vm
219
+ for pid in $(pgrep qemu-system 2>/dev/null || true); do
220
+ vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
221
+ [ "$vm" = "$want" ] && printf '%s\n' "$pid"
222
+ done
223
+ }
224
+ # No qemu left for this machine after a short grace: its RAM has been freed.
225
+ vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
214
226
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
215
227
  # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
216
228
  # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
@@ -770,9 +782,51 @@ case "$AREA $VERB" in
770
782
  "vm info")
771
783
  [ $# -eq 1 ] || usage; vm_of "$1"
772
784
  run "$MULTIPASS" info "$1" --format json ;;
773
- "vm start"|"vm stop"|"vm suspend")
785
+ "vm start"|"vm stop")
774
786
  [ $# -eq 1 ] || usage; vm_of "$1"
775
787
  run "$MULTIPASS" "$VERB" "$1" ;;
788
+ "vm suspend")
789
+ # Veille: suspend must save the machine's state AND free its RAM by ending
790
+ # its qemu process. Multipass saves the state reliably but at times leaves
791
+ # qemu alive (canonical/multipass #446, #2152, #5432), so the RAM stays
792
+ # taken though the machine shows "Suspended". The state being saved, we make
793
+ # the RAM come back, gentlest first: a second suspend from a clean running
794
+ # state usually ends qemu (and keeps the ~2s resume); failing that, a clean
795
+ # stop frees it for sure (it then wakes by a boot). Normally qemu is already
796
+ # gone after the first suspend and none of this runs.
797
+ [ $# -eq 1 ] || usage; vm_of "$1"
798
+ if [ "$SAY" = "yes" ]; then
799
+ printf '%s\n' "$MULTIPASS suspend $1" \
800
+ "if its qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
801
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
802
+ exit 0
803
+ fi
804
+ "$MULTIPASS" suspend "$1" || refuse "suspend of $1 failed"
805
+ vm_freed "$1" && exit 0
806
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
807
+ vm_freed "$1" && exit 0
808
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
809
+ vm_freed "$1" && exit 0
810
+ refuse "suspended $1 but its memory was not freed (its qemu stayed); the VM manager likely needs a restart" ;;
811
+ "vm reclaim")
812
+ # Free a machine that is ASLEEP but whose qemu still holds the RAM -- a
813
+ # suspend (maybe from before this existed) that did not end the process.
814
+ # Idempotent and safe for an asleep machine (nobody is using it): if its
815
+ # qemu is already gone, nothing happens. Touches only this machine, and
816
+ # never restarts the VM manager.
817
+ [ $# -eq 1 ] || usage; vm_of "$1"
818
+ if [ "$SAY" = "yes" ]; then
819
+ printf '%s\n' "if $1's qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
820
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
821
+ exit 0
822
+ fi
823
+ # Each step that frees the RAM says how, so the server can tell the owner.
824
+ vm_freed "$1" && { echo "freed-already"; exit 0; }
825
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
826
+ vm_freed "$1" && { echo "freed-resleep"; exit 0; }
827
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
828
+ vm_freed "$1" && { echo "freed-stop"; exit 0; }
829
+ refuse "could not free $1's memory (its qemu stayed); the VM manager likely needs a restart" ;;
776
830
  "vm kill")
777
831
  # A stop that does not wait for the system inside: asked only after a
778
832
  # clean stop hung or failed (a restart the owner asked for).
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.84-next.1",
3
+ "version": "0.2.85-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.84-next.1",
9
+ "version": "0.2.85-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
- "clavarium-binder": "0.1.8-next.1",
14
+ "clavarium-binder": "0.1.38-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.11-next.1",
17
- "clavarium-tether": "0.1.0-next.14",
16
+ "clavarium-parley": "0.17.20-next.1",
17
+ "clavarium-tether": "0.1.0-next.32",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -716,9 +716,9 @@
716
716
  }
717
717
  },
718
718
  "node_modules/clavarium-binder": {
719
- "version": "0.1.8-next.1",
720
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.8-next.1.tgz",
721
- "integrity": "sha512-0ZvTgn4z3IzLWjVyt5H82tnrE4g4Zdh0eb0kKrpVYjJ8vEfun6CmzHFclce9lb7vH+CC5ozKETuTAmSVYkk+lg==",
719
+ "version": "0.1.38-next.1",
720
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.38-next.1.tgz",
721
+ "integrity": "sha512-9nhZM/vb1hsXr60vJ354XNWVCojyB9RrrAtl9BWFtaIPO55Dde9D5fgxOylmqTprjmMVq8r6Za2YqvWe+W05ig==",
722
722
  "license": "MIT",
723
723
  "bin": {
724
724
  "binder": "bin/binder.mjs",
@@ -742,9 +742,9 @@
742
742
  }
743
743
  },
744
744
  "node_modules/clavarium-parley": {
745
- "version": "0.17.11-next.1",
746
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.11-next.1.tgz",
747
- "integrity": "sha512-IHGgFbDzHjrNVRcSR/KudWPUfvKxCeu03bNXE8+84lLMGHL7LyaiIg+iuw/cXMq4etz5BVXddVA/DGDoTUFO3A==",
745
+ "version": "0.17.20-next.1",
746
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.20-next.1.tgz",
747
+ "integrity": "sha512-C6v41pABRSPz6zQ/7mJ0miZ+hJfaAg2kXZ3c7v/JYCQtJ1BYVKl8l8wyjZHcTj3NcRSdoFzajU4P8Q6s3lV4aw==",
748
748
  "license": "MIT",
749
749
  "bin": {
750
750
  "parley": "bin/parley.mjs",
@@ -755,9 +755,9 @@
755
755
  }
756
756
  },
757
757
  "node_modules/clavarium-tether": {
758
- "version": "0.1.0-next.14",
759
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.14.tgz",
760
- "integrity": "sha512-QNa5FmgxVi1b2jW0MCMY0hkkqAIl8QDF1qHluwW8j2QbA+h5kwJ1bRW5haT2GomHlX3xxcbah0uYpuSoSZd6dw==",
758
+ "version": "0.1.0-next.32",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.32.tgz",
760
+ "integrity": "sha512-Lkw2EqT79rqDi1q8+nhV1Ll30maopyNvwwHZkXYKp7IPoAUOde9R+Gtf7tCO8X/ArqEoADM7gouWnW+w+h1cXA==",
761
761
  "license": "MIT",
762
762
  "bin": {
763
763
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.84-next.1",
3
+ "version": "0.2.85-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.",
@@ -44,10 +44,10 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-binder": "0.1.8-next.1",
47
+ "clavarium-binder": "0.1.38-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.11-next.1",
50
- "clavarium-tether": "0.1.0-next.14",
49
+ "clavarium-parley": "0.17.20-next.1",
50
+ "clavarium-tether": "0.1.0-next.32",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
@@ -16,13 +16,18 @@
16
16
  * own open-source desktop client, verified for all three: Google over IMAP +
17
17
  * CalDAV/CardDAV, Microsoft over Microsoft Graph (mail, calendar and contacts).
18
18
  *
19
+ * A CLASSIC ACCOUNT (OVH, Infomaniak, Nextcloud... any IMAP/SMTP + CalDAV/CardDAV host)
20
+ * has no token: it signs in with its password. The password is kept the same way, a
21
+ * host-only secret the keeper reveals to the connector alone; each kind is tried live
22
+ * before anything is kept, so a wrong server or password is said at once.
23
+ *
19
24
  * A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
20
25
  * its own level, from the page (Assets > Access) -- like git: one mailbox, many
21
26
  * conversations, each its own rights.
22
27
  */
23
28
  import { Refusal } from './conversations.mjs';
24
29
  import { createHash } from 'node:crypto';
25
- import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState, PROVIDERS } from './oauth.mjs';
30
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, kindsGranted, refreshAccess, pkcePair, newState, PROVIDERS } from './oauth.mjs';
26
31
 
27
32
  /* The loopback the provider sends the code back to; nothing listens there. The
28
33
  person's browser lands on a page that will not load, and they copy the whole
@@ -39,12 +44,20 @@ const PENDING_MAX = 20;
39
44
  Tether kind each becomes, and whether the target needs the email address. */
40
45
  const KIND = {
41
46
  mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
42
- calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
47
+ calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: true },
43
48
  contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
44
49
  };
45
50
  /* What each provider's built-in (Thunderbird) client grants a refresh token for. */
46
51
  const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail', 'calendar', 'contacts'] };
47
52
 
53
+ /* Servers of common classic hosts, by the address's domain (what ISPDB lacks: the
54
+ calendar and contacts addresses). */
55
+ const CLASSIC = {
56
+ 'ovh.net': { imap: 'ssl0.ovh.net', smtp: 'ssl0.ovh.net' },
57
+ 'infomaniak.com': { imap: 'mail.infomaniak.com', smtp: 'mail.infomaniak.com', caldav: 'https://sync.infomaniak.com', carddav: 'https://sync.infomaniak.com' },
58
+ 'ik.me': { imap: 'mail.infomaniak.com', smtp: 'mail.infomaniak.com', caldav: 'https://sync.infomaniak.com', carddav: 'https://sync.infomaniak.com' },
59
+ 'fastmail.com': { imap: 'imap.fastmail.com', smtp: 'smtp.fastmail.com', caldav: 'https://caldav.fastmail.com', carddav: 'https://carddav.fastmail.com' },
60
+ };
48
61
  const emailOk = (s) => /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(s);
49
62
  /* A deterministic, valid secret name for an account's token: a short slug of the
50
63
  address plus a hash of it, so reconnecting the same account reuses the name
@@ -62,10 +75,73 @@ export class Accounts {
62
75
 
63
76
  /* `secrets`: the vault (set host-only, by name). `targets`: { put(spec) } onto
64
77
  the Tether store. `fetch`: injected for tests. */
65
- constructor({ secrets, targets, fetch = globalThis.fetch }) {
78
+ #probe;
79
+ constructor({ secrets, targets, fetch = globalThis.fetch, probe = null }) {
66
80
  if (!secrets?.set) throw new Error('accounts needs the secret store');
67
81
  if (!targets?.put) throw new Error('accounts needs the Tether target store');
68
- this.#secrets = secrets; this.#targets = targets; this.#fetch = fetch;
82
+ this.#secrets = secrets; this.#targets = targets; this.#fetch = fetch; this.#probe = probe;
83
+ }
84
+
85
+ /* The servers of a classic address, as far as they can be known: a few common
86
+ hosts, else the public Thunderbird database of mail providers (ISPDB). What
87
+ is not known stays empty for the person to fill. */
88
+ async lookup({ user } = {}) {
89
+ const address = String(user ?? '').trim();
90
+ if (!emailOk(address)) throw new Refusal(400, 'The account needs its email address.');
91
+ const domain = address.split('@')[1].toLowerCase();
92
+ const known = Object.entries(CLASSIC).find(([d]) => domain === d || domain.endsWith(`.${d}`))?.[1];
93
+ const out = { imap: '', smtp: '', caldav: '', carddav: '', ...(known ?? {}) };
94
+ if (!out.imap || !out.smtp) {
95
+ try {
96
+ const r = await this.#fetch(`https://autoconfig.thunderbird.net/v1.1/${encodeURIComponent(domain)}`);
97
+ if (r.ok) {
98
+ const xml = await r.text();
99
+ const servers = (kind) => [...xml.matchAll(new RegExp(`<(incomingServer|outgoingServer) type="${kind}">([\\s\\S]*?)</\\1>`, 'g'))].map((m) => ({ host: /<hostname>([^<]+)</.exec(m[2])?.[1] ?? '', port: /<port>(\\d+)</.exec(m[2])?.[1] ?? '', socket: /<socketType>([^<]+)</.exec(m[2])?.[1] ?? '' }));
100
+ const imap = servers('imap').find((x) => x.socket === 'SSL') ?? null;
101
+ const smtp = servers('smtp').find((x) => x.socket === 'STARTTLS') ?? null;
102
+ if (!out.imap && imap?.host) out.imap = `${imap.host}${imap.port && imap.port !== '993' ? `:${imap.port}` : ''}`;
103
+ if (!out.smtp && smtp?.host) out.smtp = `${smtp.host}${smtp.port && smtp.port !== '587' ? `:${smtp.port}` : ''}`;
104
+ }
105
+ } catch { /* not known there: the person fills it */ }
106
+ }
107
+ return out;
108
+ }
109
+
110
+ /* Connect a classic account: its password kept host-only, a target per kind,
111
+ each tried live first (nothing is kept if one fails). */
112
+ async classic({ user, password, imap, smtp, caldav, carddav, kinds } = {}) {
113
+ const address = String(user ?? '').trim();
114
+ if (!emailOk(address)) throw new Refusal(400, 'The account needs its email address.');
115
+ const secret = String(password ?? '');
116
+ if (!secret) throw new Refusal(400, 'The account needs its password.');
117
+ const wanted = (Array.isArray(kinds) && kinds.length ? kinds : ['mail']).map(String).filter((k) => KIND[k]);
118
+ if (!wanted.length) throw new Refusal(400, 'Choose at least mail, calendar or contacts.');
119
+ const hostPort = (v, what, port) => {
120
+ const m = /^([a-z0-9.-]+\.[a-z]{2,})(?::(\d{1,5}))?$/i.exec(String(v ?? '').trim());
121
+ if (!m) throw new Refusal(400, `The ${what} server is a name like mail.example.com.`);
122
+ return { host: m[1].toLowerCase(), port: Number(m[2] ?? port) };
123
+ };
124
+ const davUrl = (v, what) => {
125
+ let u; try { u = new URL(/^https?:\/\//i.test(String(v ?? '').trim()) ? String(v).trim() : `https://${String(v ?? '').trim()}`); } catch { u = null; }
126
+ if (!u || u.protocol !== 'https:' || !u.hostname.includes('.')) throw new Refusal(400, `The ${what} address is an https address, like https://dav.example.com.`);
127
+ return u.href;
128
+ };
129
+ const name = secretName('classic', address);
130
+ const specs = [];
131
+ for (const k of wanted) {
132
+ const config = { user: address };
133
+ if (k === 'mail') { const i = hostPort(imap, 'mail (IMAP)', 993); const o = hostPort(smtp, 'sending (SMTP)', 587); Object.assign(config, { host: i.host, port: i.port, smtpHost: o.host, smtpPort: o.port }); }
134
+ if (k === 'calendar') config.caldav = davUrl(caldav, 'calendar (CalDAV)');
135
+ if (k === 'contacts') config.carddav = davUrl(carddav, 'contacts (CardDAV)');
136
+ specs.push({ id: targetId(k, 'classic', address), title: `${KIND[k].title} — ${address}`, kind: KIND[k].kind, connector: KIND[k].connector, config, secrets: { password: name } });
137
+ }
138
+ if (this.#probe) for (const t of specs) {
139
+ try { await this.#probe(t, secret); }
140
+ catch (e) { throw new Refusal(400, `${KIND[t.connector === 'mail' ? 'mail' : t.connector].title}: ${String(e?.message ?? e).replace(/^.*?: /, '')}`); }
141
+ }
142
+ this.#secrets.set({ name, value: secret, hostOnly: true });
143
+ const made = specs.map((t) => { const saved = this.#targets.put(t); return { id: saved?.id ?? t.id, title: saved?.title ?? t.title, kind: t.kind }; });
144
+ return { provider: 'classic', user: address, targets: made, authorized: wanted, denied: [] };
69
145
  }
70
146
 
71
147
  /* Which kinds may be connected, per provider, for the page to offer. */
@@ -103,23 +179,32 @@ export class Accounts {
103
179
  let code;
104
180
  try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
105
181
  const { clientId, clientSecret } = thunderbird(p.provider);
106
- let refreshToken;
107
- try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: redirectFor(p.provider), code, codeVerifier: p.verifier, fetch: this.#fetch })); }
182
+ let refreshToken, grantedScope;
183
+ try { ({ refreshToken, scope: grantedScope } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: redirectFor(p.provider), code, codeVerifier: p.verifier, fetch: this.#fetch })); }
108
184
  catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
109
185
  if (!refreshToken) throw new Refusal(502, 'The account returned no lasting token; allow offline access and try again.');
186
+ /* What was actually allowed. A provider may grant fewer kinds than asked
187
+ (the person unticks one); the token's scope says so, so we make a target
188
+ only for a kind that was really granted, and tell the caller which were
189
+ denied -- no guessing. If the scope is unreadable (matched nothing) we
190
+ trust what was asked, as before. */
191
+ const matched = kindsGranted(p.provider, grantedScope);
192
+ const useScope = matched.length > 0;
193
+ const authorized = useScope ? p.kinds.filter((k) => matched.includes(k)) : p.kinds;
194
+ const denied = useScope ? p.kinds.filter((k) => !matched.includes(k)) : [];
110
195
  /* The token is kept host-only: it can never be attached to a conversation,
111
196
  so it is never delivered to a machine -- the keeper reveals it by name. */
112
197
  const name = secretName(p.provider, p.user);
113
198
  this.#secrets.set({ name, value: refreshToken, hostOnly: true });
114
199
  const label = PROVIDERS[p.provider].label;
115
200
  const made = [];
116
- for (const k of p.kinds) {
201
+ for (const k of authorized) {
117
202
  const spec = KIND[k];
118
203
  /* Pin the client that minted the token onto the target, so the keeper
119
204
  refreshes with the same one -- a refresh token is bound to its client,
120
205
  and this keeps a target working even if the built-in default later
121
206
  moves (the connector prefers config.clientId over its own default). */
122
- const config = { provider: p.provider, clientId };
207
+ const config = { provider: p.provider, clientId, authorizedKinds: authorized };
123
208
  if (spec.needsUser) config.user = p.user;
124
209
  const target = this.#targets.put({
125
210
  id: targetId(k, p.provider, p.user),
@@ -128,7 +213,33 @@ export class Accounts {
128
213
  });
129
214
  made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
130
215
  }
131
- return { provider: p.provider, user: p.user, targets: made };
216
+ return { provider: p.provider, user: p.user, targets: made, authorized, denied };
217
+ }
218
+
219
+ /* Check, live, what a connected account is really authorized for right now --
220
+ not only at connection. A refresh host-side (the token never leaves the
221
+ server) reads the token's current scopes, so the page can say "mail yes,
222
+ calendar no" at any time and reflect a permission removed since. Records the
223
+ result on every target of the account, so it shows without another check. */
224
+ async verify({ id } = {}) {
225
+ const all = this.#targets.all?.() ?? [];
226
+ const target = all.find((t) => t.id === id);
227
+ if (!target) throw new Refusal(404, 'No such connexion.');
228
+ const provider = target.config?.provider;
229
+ if (!PROVIDERS[provider]) throw new Refusal(400, 'This connexion is not an account.');
230
+ const secretRef = target.secrets?.refresh;
231
+ const refreshToken = secretRef && this.#secrets.reveal(secretRef);
232
+ if (!refreshToken) throw new Refusal(404, 'The account token is gone; connect it again.');
233
+ const def = thunderbird(provider);
234
+ const clientId = target.config?.clientId || def.clientId;
235
+ let scope, fresh;
236
+ try { ({ scope, refreshToken: fresh } = await refreshAccess(provider, { clientId, clientSecret: def.clientSecret, refreshToken, fetch: this.#fetch })); }
237
+ catch (e) { throw new Refusal(502, `The account could not be checked: ${e.message}`); }
238
+ /* Keep the token current if the provider rotated it on the refresh. */
239
+ if (fresh && fresh !== refreshToken) this.#secrets.set({ name: secretRef, value: fresh, hostOnly: true });
240
+ const authorized = kindsGranted(provider, scope);
241
+ for (const t of all.filter((x) => x.secrets?.refresh === secretRef)) this.#targets.put({ ...t, config: { ...t.config, authorizedKinds: authorized } });
242
+ return { id, provider, all: SUPPORTED[provider], authorized };
132
243
  }
133
244
 
134
245
  #sweep() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
package/server/api.mjs CHANGED
@@ -12,6 +12,7 @@
12
12
  * GET /api/conversations/<name>/health what was last seen of its machine
13
13
  * POST /api/conversations/<name>/health look now (never wakes a machine)
14
14
  * POST /api/conversations/<name>/health/seen what it says now no longer calls its owner (Needs you)
15
+ * POST /api/conversations/<name>/exit-report why its tool ended: { now (read in its machine, if it runs), last (kept at its end) }
15
16
  * POST /api/conversations/<name>/archive
16
17
  * 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
17
18
  * POST /api/conversations/<name>/resume {on}: its tool takes up its last session when it starts (true), or starts fresh
@@ -19,6 +20,7 @@
19
20
  * POST /api/conversations/<name>/talk {text, answers?, files?, via?}: written in its chat; files from .../talk/file; via 'voice': dictated
20
21
  * POST /api/conversations/<name>/talk/react {to, reaction}: the owner's reaction to a message of the tool (null: taken back)
21
22
  * POST /api/conversations/<name>/chat-name {name}: the name the chat gives its tool ('' : the neutral word of the dictionary)
23
+ * POST /api/conversations/<name>/tasks-binder {binder}: the binder shown beside its chat ('' automatic, '-' none, else an id)
22
24
  * POST /api/conversations/<name>/voice-mark {on}: what is dictated into its terminal starts with a microphone sign (AI tools only)
23
25
  * POST /api/conversations/<name>/talk/file?name=<file name> the body IS a file the person attaches -> {path, name, size}
24
26
  * GET /api/conversations/<name>/talk?last=|days=|before=|from=|since= a part of its chat: the newest messages, those of the
@@ -151,6 +153,9 @@ function readBody(request, max = BODY_MAX) {
151
153
  }
152
154
 
153
155
  /* Returns true when the request was an API request (answered here). */
156
+ /* This run of the server: a page's count of binder changes is of one run, and starts again with the next. */
157
+ const BOOT = Math.random().toString(36).slice(2, 10);
158
+
154
159
  export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups) {
155
160
  const { pathname } = new URL(request.url ?? '/', 'http://local');
156
161
  if (!pathname.startsWith('/api/')) return false;
@@ -299,7 +304,7 @@ export async function handleApi(request, response, conversations, headers, resou
299
304
  if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
300
305
  if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
301
306
  if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
302
- if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: binders.changes() }), true;
307
+ if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
303
308
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
304
309
  /* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
305
310
  if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
@@ -430,6 +435,9 @@ export async function handleApi(request, response, conversations, headers, resou
430
435
  kept host-only, a Tether target made): see accounts.mjs. */
431
436
  if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
432
437
  if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
438
+ if (pathname === '/api/accounts/lookup' && accounts) return send(200, await accounts.lookup(body)), true;
439
+ if (pathname === '/api/accounts/classic' && accounts) { const made = await accounts.classic(body); return send(201, made), true; }
440
+ if (pathname === '/api/accounts/verify' && accounts) { const r = await accounts.verify(body); return send(200, r), true; }
433
441
  /* Assets > Access: the owner sets a conversation's level and rules on a
434
442
  target, decides a call that waited, or removes a target. Each is an op the
435
443
  keeper runs as the owner (person), never as an agent. */
@@ -612,6 +620,15 @@ export async function handleApi(request, response, conversations, headers, resou
612
620
  }
613
621
  const moved = /^\/api\/conversations\/([^/]+)\/work$/.exec(pathname);
614
622
  if (moved) return send(202, await conversations.moveWork(decodeURIComponent(moved[1]), body.to)), true;
623
+ /* Why its tool ended: read now in its machine when it runs, else the last kept at its end. */
624
+ const exitOf = /^\/api\/conversations\/([^/]+)\/exit-report$/.exec(pathname);
625
+ if (exitOf) {
626
+ const conversation = decodeURIComponent(exitOf[1]);
627
+ const c = conversations.list().find((x) => x.name === conversation);
628
+ if (!c) throw new Refusal(404, 'No such conversation.');
629
+ const now = await conversations.exitReport(conversation).catch(() => null);
630
+ return send(200, { now, last: c.lastExit ?? null }), true;
631
+ }
615
632
  /* "Seen": what its machine says now no longer calls its owner (health.mjs). */
616
633
  const seenOf = /^\/api\/conversations\/([^/]+)\/health\/seen$/.exec(pathname);
617
634
  if (seenOf && health) {
@@ -637,6 +654,8 @@ export async function handleApi(request, response, conversations, headers, resou
637
654
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
638
655
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
639
656
  if (naming) return send(200, conversations.setChatName(decodeURIComponent(naming[1]), body.name)), true;
657
+ const beside = /^\/api\/conversations\/([^/]+)\/tasks-binder$/.exec(pathname);
658
+ if (beside) return send(200, conversations.setTasksBinder(decodeURIComponent(beside[1]), body.binder)), true;
640
659
  /* The list: folders and order, the same on every device (conversations.mjs). */
641
660
  if (pathname === '/api/instance' && instance) return send(200, instance.setName(body.name)), true;
642
661
  if (pathname === '/api/dictation' && voice) return send(200, voice.set(body)), true;
@@ -45,7 +45,7 @@ export class Binders {
45
45
  the owner's devices (optional), told of a card a person owns that came due. */
46
46
  constructor({ dataDir, resources, conversations, dockets = null, team = null, alert = null, now = () => Date.now() }) {
47
47
  this.#resources = resources; this.#conversations = conversations; this.#dockets = dockets; this.#team = team; this.#alert = alert;
48
- this.#keeper = keeper(`${dataDir}/binder`, { sides: () => this.#sides(), now });
48
+ this.#keeper = keeper(`${dataDir}/binder`, { sides: () => this.#sides(), now, people: () => this.people() });
49
49
  this.#keeper.store.onChange((line) => { this.#changes++; this.#heard(line); });
50
50
  }
51
51
 
@@ -110,9 +110,12 @@ export class Binders {
110
110
  }
111
111
  /* Who may own a record, or be given a list. */
112
112
  people(identity = '') {
113
+ /* Who signed in, as the store names their ownership ('me' resolves to this). The matrix
114
+ colours a card "à moi" by matching this, so the page is told which entry is the viewer. */
115
+ const meId = `person:${identity || 'owner'}`;
113
116
  const persons = (this.#team?.list?.() ?? []).map((o) => ({ id: `person:${String(o.email ?? o.id ?? '').toLowerCase()}`, kind: 'person', name: String(o.email ?? o.id ?? '') })).filter((p) => p.name);
114
- if (!persons.length) persons.push({ id: `person:${identity || 'owner'}`, kind: 'person', name: identity || 'Owner' });
115
- return [...persons, ...this.#conversations().map((name) => ({ id: `${AGENT}${name}`, kind: 'agent', name }))];
117
+ if (!persons.length) persons.push({ id: meId, kind: 'person', name: identity || 'Owner' });
118
+ return [...persons.map((p) => (p.id === meId ? { ...p, me: true } : p)), ...this.#conversations().map((name) => ({ id: `${AGENT}${name}`, kind: 'agent', name }))];
116
119
  }
117
120
  /* What each conversation was given: { name: { lists, waiting } }, waiting being the
118
121
  records of those lists that wait for a person's tick (a list with a gate, not approved). */
@@ -49,6 +49,13 @@ export const RESERVE_DISK_MAX_MB = 1024 * 1024;
49
49
  export const RESERVE_MEMORY_MAX_MB = 256 * 1024;
50
50
  export const ROOM_MS = 10_000;
51
51
  export const USAGE_MS = 5 * 60_000;
52
+ /* A sleeping machine whose qemu still holds at least this much host memory is a
53
+ suspend that did not free it (see the host program's `vm suspend`); the watch
54
+ reclaims it. */
55
+ export const RECLAIM_MIN_MB = 128;
56
+ /* The same machine is not reclaimed again within this, so a stubborn one (rare,
57
+ needs a VM-manager restart) is reported once, not looped on. */
58
+ export const RECLAIM_EVERY_MS = 30 * 60_000;
52
59
  /* The page shows its small gauge when disk or memory is fuller than this, or
53
60
  when what is free is under this many times the reserve. */
54
61
  export const HIGH_PERCENT = 85;
@@ -92,7 +99,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
92
99
  export class Capacity {
93
100
  /* What the machines take on their disk, as last measured (MB), or undefined. */
94
101
  machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
95
- #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
102
+ #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
96
103
 
97
104
  /* `run(argv)`: the host program. `store`: where the reserve is kept.
98
105
  `conversations`: what each machine was given. `shelf`: how large a
@@ -100,8 +107,8 @@ export class Capacity {
100
107
  /* `roomMs`: how long what is free is taken as known (ROOM_MS). */
101
108
  /* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
102
109
  when what is free falls under the reserve. */
103
- constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null }) {
104
- this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say;
110
+ constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
111
+ this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
105
112
  this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
106
113
  }
107
114
 
@@ -288,9 +295,53 @@ export class Capacity {
288
295
  return done;
289
296
  }
290
297
 
298
+ /* WATCHED too, and on its own: machines that are ASLEEP (not awake) yet whose
299
+ qemu still holds the host RAM -- a suspend that did not end the process,
300
+ including ones left stuck before this ran. Each is freed through the host
301
+ program (`vm reclaim`: wake+resleep, then a clean stop if needed), the owner
302
+ told, and not tried again within reclaimEveryMs, so a stubborn one (rare,
303
+ the VM manager would need a restart) is reported once, not looped on. Only
304
+ asleep machines are touched; the others are never disturbed, and the VM
305
+ manager is never restarted. Resolves with what was reclaimed. */
306
+ async reclaimSleepers() {
307
+ if (!this.#reclaim || this.#sweeping) return [];
308
+ this.#sweeping = true;
309
+ try {
310
+ const f = this.#figures(await this.room({ fresh: true }).catch(() => null));
311
+ if (!f) return [];
312
+ const awake = new Set(this.#conversations.awake?.() ?? []);
313
+ const holding = f.machines.filter((m) => m.name && !m.shelf && !awake.has(m.name) && m.rssMb >= RECLAIM_MIN_MB);
314
+ if (!holding.length) return [];
315
+ const now = this.#now();
316
+ const at = this.#store.get('reclaim')?.at ?? {};
317
+ const done = [];
318
+ for (const m of holding) {
319
+ if (at[m.name] && now - at[m.name] < this.#reclaimEveryMs) continue;
320
+ at[m.name] = now;
321
+ this.#store.put({ name: 'reclaim', at });
322
+ const held = m.rssMb;
323
+ const how = await Promise.resolve(this.#reclaim(m.name)).then((x) => String(x || ''), () => '');
324
+ const by = how.includes('resleep') ? ' by waking it and putting it back to sleep'
325
+ : how.includes('stop') ? ' with a clean stop (it will boot when you open it)'
326
+ : '';
327
+ const after = this.#figures(await this.room({ fresh: true }).catch(() => null));
328
+ const freed = !after?.machines.some((x) => x.name === m.name && !awake.has(x.name) && x.rssMb >= RECLAIM_MIN_MB);
329
+ this.#alert?.(freed
330
+ ? { title: "Reclaimed a sleeping machine's memory", body: `${m.name} was asleep but still held ${gb(held)} (its sleep had not freed it); its memory was reclaimed${by}.`, url: '/?open=settings&at=resources' }
331
+ : { title: 'A sleeping machine still holds memory', body: `${m.name} was asleep but still held ${gb(held)} and could not be freed; the VM manager may need a restart.`, url: '/?open=settings&at=resources' });
332
+ this.#say?.(m.name, freed
333
+ ? `This machine was asleep but still held ${gb(held)} of memory (its sleep had not freed it). Its memory was reclaimed${by}; it still wakes when you open it.`
334
+ : `This machine was asleep but still held ${gb(held)} of memory, and it could not be freed automatically — the VM manager may need a restart.`);
335
+ done.push({ name: m.name, heldMb: held, freed });
336
+ }
337
+ return done;
338
+ } finally { this.#sweeping = false; }
339
+ }
340
+
291
341
  /* Watches every `everyMs`; returns what stops it. */
292
342
  start(everyMs = WATCH_MS) {
293
- const timer = setInterval(() => { void this.watch().catch(() => {}); }, everyMs);
343
+ const tick = () => { void this.watch().catch(() => {}).finally(() => { void this.reclaimSleepers().catch(() => {}); }); };
344
+ const timer = setInterval(tick, everyMs);
294
345
  timer.unref?.();
295
346
  return () => clearInterval(timer);
296
347
  }
@@ -608,6 +608,18 @@ export class Conversations {
608
608
  return this.#store.get(name);
609
609
  }
610
610
 
611
+ /* WHICH BINDER ITS CHAT SHOWS BESIDE IT (the side panel), the same on every device:
612
+ '' for the automatic choice (the first binder of batches it was given), '-' for none,
613
+ else a binder's id. Which binders it was given is Binder's: one it no longer has
614
+ falls back to the automatic choice on the page. */
615
+ setTasksBinder(name, given) {
616
+ const c = this.#store.get(name);
617
+ if (!c) throw new Refusal(404, 'No such conversation.');
618
+ if (typeof given !== 'string' || given.length > 100 || !/^(|-|[a-z0-9][a-z0-9._-]*)$/.test(given)) throw new Refusal(400, 'Give a binder\'s id, "-" for none, or nothing for the automatic choice.');
619
+ this.#store.patch(name, { tasksBinder: given || undefined });
620
+ return this.#store.get(name);
621
+ }
622
+
611
623
  /* THE NAME A PERSON READS, changed at any time; its identifier stays.
612
624
  Kept only when it differs from the identifier: a conversation made
613
625
  before free names is read by its identifier, and nothing is rewritten. */
@@ -1024,6 +1036,11 @@ export class Conversations {
1024
1036
  const alive = await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'has-session', '-t', `=${SESSION}`]);
1025
1037
  /* true: the tool is still there, only the channel to it dropped. */
1026
1038
  if (alive.code === 0) return true;
1039
+ /* Before its machine stops (and its kernel's memory of the night with it): why the tool
1040
+ ended, kept on the conversation and said -- a person without access to the server
1041
+ sees it in Machine, and is told at once when it was cut for lack of memory. */
1042
+ const report = await this.exitReport(name).catch(() => null);
1043
+ if (report) { this.#store.patch(name, { lastExit: report }); try { this.onToolExit?.(name, report); } catch { /* telling is best effort */ } }
1027
1044
  this.#cancelStop(name);
1028
1045
  const timer = setTimeout(() => {
1029
1046
  this.#timers.delete(name);
@@ -1034,6 +1051,28 @@ export class Conversations {
1034
1051
  return false;
1035
1052
  }
1036
1053
 
1054
+ /* WHY ITS TOOL ENDED, read inside the machine while it still runs: the kernel's kills for
1055
+ lack of memory since it started (with the program's name), its memory, and the last
1056
+ lines of the tool's own log (`logs` in config/tools.json). Read as the machine's
1057
+ ordinary user; dmesg through sudo when it may. Nothing is changed. */
1058
+ async exitReport(name) {
1059
+ const c = this.#store.get(name);
1060
+ if (!c) throw new Refusal(404, 'No such conversation.');
1061
+ if (await this.#vms.state(name) !== 'Running') throw new Refusal(409, 'Its machine is not running.');
1062
+ const tool = this.#tools.find((t) => t.id === c.tool);
1063
+ const logs = Array.isArray(tool?.logs) ? tool.logs.filter((d) => /^[A-Za-z0-9._/-]+$/.test(d)) : [];
1064
+ const script = [
1065
+ '( sudo -n dmesg -T 2>/dev/null || dmesg -T 2>/dev/null ) | grep -E "Killed process|Out of memory|Memory cgroup out of memory" | tail -n 4 | sed "s/^/oom /"',
1066
+ 'awk \'/^MemTotal:/{print "memory", int($2/1024)}\' /proc/meminfo',
1067
+ 'for d in "$@"; do f=$(ls -t "$HOME/$d"/*.log 2>/dev/null | head -1); [ -n "$f" ] && { echo "logfile $f"; tail -n 25 "$f" | cut -c1-300 | sed "s/^/log /"; }; done; true',
1068
+ ].join('\n');
1069
+ const r = await this.#vms.exec(name, ['bash', '-c', script, 'report', ...logs], { timeoutMs: 20_000 });
1070
+ const lines = String(r.stdout ?? '').split('\n');
1071
+ const pick = (p) => lines.filter((l) => l.startsWith(`${p} `)).map((l) => l.slice(p.length + 1));
1072
+ const memoryMb = Number(pick('memory')[0]) || null;
1073
+ return { at: new Date().toISOString(), oom: pick('oom'), memoryMb, logFile: pick('logfile')[0] ?? null, log: pick('log') };
1074
+ }
1075
+
1037
1076
  /* ONE FILE OF THE MACHINE'S OWN DISK, read for the person who asked to
1038
1077
  see it (a path on their screen, clicked). Only under /work, only a
1039
1078
  plain path, only a regular file of a modest size; read as the
@@ -696,7 +696,11 @@ export class GitKeeper {
696
696
  /* Its machine did not run them: tried again later, when it may. */
697
697
  if (checks.status !== 'unavailable') held.done.set(b, tip.id);
698
698
  const why = checks.status === 'failed' ? `the checks failed in the machine of ${conversation}` : checks.status === 'none' ? 'automatic sending needs passing checks, and none is set (no pre-push hook, no check command)' : `the checks could not run: the machine of ${conversation} does not run`;
699
- return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent` } : {}) }), false;
699
+ /* On a failure the agent is given the END OF THE CHECK OUTPUT, not only
700
+ that it failed: it is the one that can fix it, and guessing without the
701
+ output wastes its time. */
702
+ const tail = String(checks.output ?? '').trim();
703
+ return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent${tail ? `. The end of the output:\n\n${tail}` : ''}` } : {}) }), false;
700
704
  }
701
705
  }
702
706
  const checked = s.checks ? 'checks passed' : 'no checks asked for';